Web pages: a page without headings is arranged by itself, and a typed address becomes a titled link

A page cut into parts by length is now arranged into titled sections by a
model when it is first read, through the same gates as s (a model, the
daily budget, the plan's limits, one request per text), once per text per
server run. EX_PAGES_ARRANGE=manual keeps it to s. The pane shows the
parts at once, says that it is arranging or why it did not, and swaps the
sections in when they arrive.

A bare http(s) address typed into a node's text is linked when the edit
ends, then replaced by the page's title once that is read; u brings the
address back. A node whose whole text is one address becomes a section
that is only a link. See docs/pages.md.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
thalladaandClaude Fable 5.2 committed 2026-11-18 14:19:21 -05:00
1 parent f8c6576ea1
commit 57b605e13c
19 files changed
+1095 -92

No files matched your search

+9 -8
View File
@@ -27,7 +27,7 @@ import { usage, withMockUsage } from "./usage";
import { HttpError, ROOT as root, abortOnClose, dataDir, readJson, sendJson as json } from "./util";
import { PageClient, pages } from "./page";
import { makeMockPageFetch } from "./pageMock";
import { Arranger, serverBudget } from "./pageArrange";
import { Arranger, arrangeMode, serverBudget } from "./pageArrange";
import { pageOff, pageRoutes } from "./pageRoutes";
import { applyWebPolicy, webConfig } from "./web";
import { WikiClient, validContact, wiki, wikiLang } from "./wiki";
@@ -109,12 +109,13 @@ const pageMode: PageMode = pagesWanted === "live" || pagesWanted === "mock" ? pa
if (pageMode !== pagesWanted) console.warn(`EX_PAGES=${pagesWanted} is not live, mock or off; reading web pages is off.`);
// The mock keeps its snapshots in memory only, so each run starts from nothing read.
const mockPages = pageMode === "mock" ? new PageClient({ fetch: makeMockPageFetch(), spacingMs: 0, persist: false }) : null;
// Arranging a page with a model (s on a page) is always the reader's own request, through the
// shared model, within EX_PAGE_CALLS calls a day for the whole server (default 20, counted in
// <EX_DATA>/page-calls.json), and never while the plan's limits are nearly used. EX_PAGES_ARRANGE=off
// turns it off.
const arrangeOn = process.env.EX_PAGES_ARRANGE !== "off";
const arranger = new Arranger({ pages: () => mockPages ?? pages(), llm: () => llm, on: arrangeOn, budget: serverBudget(process.env, DATA), plan: () => usage.summary().plan });
// Arranging a page with a model: at the reader's request (s on a page), and by itself, once, for a
// page with no headings of its own (divided by length) when it is first read. Through the shared
// model, within EX_PAGE_CALLS calls a day for the whole server (default 20, counted in
// <EX_DATA>/page-calls.json), and never while the plan's limits are nearly used.
// EX_PAGES_ARRANGE=manual leaves it to s alone; EX_PAGES_ARRANGE=off turns it off.
const { on: arrangeOn, auto: arrangeAuto } = arrangeMode(process.env);
const arranger = new Arranger({ pages: () => mockPages ?? pages(), llm: () => llm, on: arrangeOn, auto: arrangeAuto, budget: serverBudget(process.env, DATA), plan: () => usage.summary().plan });
const handlePages = pageMode === "off" ? pageOff : pageRoutes(() => mockPages ?? pages(), () => arranger);
/** A short reason for a failed model call, whichever provider made it. */
@@ -350,5 +351,5 @@ createServer(async (req, res) => {
console.log(
`wikipedia: ${wikiMode === "live" ? `live (${wikiState.lang}.wikipedia.org, ${wikiState.contact ? "with" : "without"} a contact)` : wikiMode === "mock" ? "mock (fixtures, no network)" : "off"}`,
);
console.log(`web pages: ${pageMode === "live" ? "live (only pages you open)" : pageMode === "mock" ? "mock (fixtures, no network)" : "off"}${pageMode !== "off" ? `; arranged by a model: ${arrangeOn && llm ? `on request, at most ${arranger.budgetMax} calls a day` : "off"}` : ""}`);
console.log(`web pages: ${pageMode === "live" ? "live (only pages you open)" : pageMode === "mock" ? "mock (fixtures, no network)" : "off"}${pageMode !== "off" ? `; arranged by a model: ${arrangeOn && llm ? `${arranger.automatic ? "pages without headings by themselves, and " : ""}on request, at most ${arranger.budgetMax} calls a day` : "off"}` : ""}`);
});
+9 -1
View File
@@ -80,11 +80,19 @@ export interface WebArticle {
words: number;
attribution: WebAttribution;
/**
* What a model added at the reader's request (POST /api/page/arrange), never the page's own
* What a model added (POST /api/page/arrange, or by itself: server/pageArrange.ts), never the page's own
* words: a summary, and whether the sections are the model's (outline "model").
*/
model?: { summary: string; sections: boolean; by?: string; at: string; note?: string };
/**
* For a page divided by length that a model has not arranged: whether it is being arranged by
* itself now, or why it was not (server/pageArrange.ts `auto`). Added by the routes to the page
* they send; never kept in the snapshot.
*/
auto?: AutoArrange;
}
/** A page divided by length, arranged by itself after it is read: under way, or why not (a refusal's reason and words). */
export type AutoArrange = { state: "running" } | { state: "skipped"; reason: string; message: string };
export type WebUnusableReason = "robots" | "refused" | "type" | "empty" | "too-large" | "offline" | "error" | "off";
/** A page that is not shown: the reader is offered the original, with the reason in plain words. */
export interface WebUnusable {
+78 -8
View File
@@ -1,6 +1,7 @@
/**
* Arranging a web page with a model, at the reader's request (POST /api/page/arrange): a short
* summary, and for a page divided only by length, sections at the places the model chooses. See
* Arranging a web page with a model (POST /api/page/arrange): a short summary, and for a page
* divided only by length, sections at the places the model chooses. At the reader's request (s), and
* by itself once for a page divided by length when it is first read (`auto`, below). See
* docs/pages.md §10 for why it is shaped as it is.
*
* What is sent: the page's title and the opening of each of its units, numbered (at most
@@ -23,11 +24,19 @@
* the server's daily budget of calls (EX_PAGE_CALLS, default 20) is spent. One call per content hash
* however many ask at once, and none for a page already arranged as it now reads. The call goes
* through the server's shared model, so it is counted in the usage like every other.
*
* By itself (`auto`, started by the routes when a page is read or opened, or read for a link's
* title): only a page divided by length (outline "chunks"; a page with headings or pseudo-headings,
* one short enough to be a lead, and one that cannot be shown never are), not yet arranged as it
* now reads, with the same gate, the same call and the same flight as the reader's s, plus
* EX_PAGES_ARRANGE=manual, which leaves arranging to s alone. One attempt per content hash in a
* server's run: one refused or failed is not tried again by itself (s still may), so nothing loops;
* a Reload that changes the text gives it a new hash, and so one more attempt.
*/
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import type { ArrangeReply, JsonReq, LLM } from "../src/llm/types";
import type { ModelWork, PageClient, PageMaterial, WebArticle, WebSection } from "./page";
import type { AutoArrange, ModelWork, PageClient, PageMaterial, WebArticle, WebSection } from "./page";
import { clipText, type PageUnit } from "./pageHtml";
import type { UsageSummary } from "./usage";
import { dataDir, writeAtomic } from "./util";
@@ -214,7 +223,7 @@ export class DailyBudget {
// ---- the arranger ----
export type ArrangeRefusal = "uncached" | "old" | "no-model" | "off" | "plan" | "budget" | "too-long" | "failed";
export type ArrangeRefusal = "uncached" | "old" | "no-model" | "off" | "manual" | "plan" | "budget" | "too-long" | "failed" | "idle";
export type ArrangeResult =
| {
ok: true;
@@ -233,11 +242,22 @@ export interface ArrangerOptions {
llm: () => LLM | null;
/** False when EX_PAGES_ARRANGE=off. */
on?: boolean;
/** False when EX_PAGES_ARRANGE=manual (or off): a page is arranged only at the reader's request. */
auto?: boolean;
budget: DailyBudget;
/** The usage tracker's view of the plan (server/usage.ts summary().plan). */
plan?: () => UsageSummary["plan"];
}
/** What EX_PAGES_ARRANGE says: off (never), manual (at the reader's request only), anything else both that and by itself. */
export function arrangeMode(env: NodeJS.ProcessEnv = process.env): { on: boolean; auto: boolean } {
const v = (env.EX_PAGES_ARRANGE ?? "").trim().toLowerCase();
return { on: v !== "off", auto: v !== "off" && v !== "manual" };
}
/** Pages remembered as tried by themselves, at most (the oldest forgotten first). */
const TRIED_MAX = 2000;
/** The budget the server keeps: EX_PAGE_CALLS calls a day, counted in <EX_DATA>/page-calls.json. */
export function serverBudget(env: NodeJS.ProcessEnv = process.env, dir = dataDir()): DailyBudget {
const n = Number(env.EX_PAGE_CALLS);
@@ -246,6 +266,8 @@ export function serverBudget(env: NodeJS.ProcessEnv = process.env, dir = dataDir
export class Arranger {
private flying = new Map<string, Promise<ArrangeResult>>();
/** Content hashes tried by themselves in this run: null while the call is made, else why it came to nothing. */
private tried = new Map<string, { reason: ArrangeRefusal; message: string } | null>();
constructor(private o: ArrangerOptions) {}
@@ -254,8 +276,18 @@ export class Arranger {
return this.o.budget.max;
}
/** Arrange (or summarise) a page already read here. Never reads the page; never throws. */
async arrange(url: string): Promise<ArrangeResult> {
/** Whether pages divided by length are arranged by themselves (a model, and EX_PAGES_ARRANGE neither off nor manual). */
get automatic(): boolean {
return this.o.on !== false && this.o.auto !== false && !!this.o.llm();
}
/**
* Arrange (or summarise) a page already read here. Never reads the page; never throws. `join`:
* only wait for an arrangement already under way (or answer with the one kept, or why the
* automatic attempt came to nothing), never start a call: what the browser asks while a page
* is being arranged by itself, so that asking can never spend a call.
*/
async arrange(url: string, o: { join?: boolean } = {}): Promise<ArrangeResult> {
const m = this.o.pages().material(url);
if (!m) return { ok: false, reason: "uncached", message: "Only a page already read here can be arranged: open it first." };
const done = this.kept(m);
@@ -263,6 +295,10 @@ export class Arranger {
// One call per content hash, however many ask.
const k = m.article.hash;
let p = this.flying.get(k);
if (!p && o.join) {
const was = this.tried.get(k);
return { ok: false, ...(was ?? { reason: "idle", message: "This page is not being arranged now: s arranges it." }) };
}
if (!p) {
p = this.call(url, m).finally(() => this.flying.delete(k));
this.flying.set(k, p);
@@ -270,16 +306,50 @@ export class Arranger {
return p;
}
/**
* Arrange a page by itself, after it was read or opened: only a page divided by length, not yet
* arranged as it now reads, and not tried by itself before in this run. Starts the call (the same
* one s makes, in the same flight) and does not wait for it. Returns where that stands for the
* page as now kept: under way, or why it is not done; undefined when there is nothing to say (a
* page with sections of its own, one already arranged, one not kept here). Never throws.
*/
auto(url: string): AutoArrange | undefined {
const m = this.o.pages().material(url);
if (!m || m.article.outline !== "chunks" || this.kept(m)) return undefined;
const k = m.article.hash;
if (this.flying.has(k)) return { state: "running" };
const was = this.tried.get(k);
if (was) return { state: "skipped", ...was };
if (was === null) return undefined; // tried, and kept or gone since
// Refusals that hold for the whole run are not attempts: they are said each time, never remembered.
const always = this.refusal(true);
if (always && (always.reason === "no-model" || always.reason === "off" || always.reason === "manual")) return { state: "skipped", ...always };
const now = always ?? (m.units ? null : { reason: "old" as const, message: "This copy of the page was read before pages could be arranged: R reads it again, and it is arranged then." });
this.remember(k, now);
if (now) return { state: "skipped", ...now };
void this.arrange(url).then((r) => {
if (!r.ok) this.remember(k, { reason: r.reason, message: r.message });
});
return { state: "running" };
}
private remember(k: string, v: { reason: ArrangeRefusal; message: string } | null) {
this.tried.delete(k);
this.tried.set(k, v);
if (this.tried.size > TRIED_MAX) this.tried.delete(this.tried.keys().next().value as string);
}
/** The result kept for the page as it now reads, if there is one. */
private kept(m: PageMaterial): ArrangeResult | null {
if (m.model?.hash !== m.article.hash) return null;
return { ok: true, article: m.view, called: false, arranged: m.model.sections ? "sections" : "summary", ...(m.model.note ? { note: m.model.note } : {}) };
}
/** Why no call may be made now, or null. */
private refusal(): { reason: ArrangeRefusal; message: string } | null {
/** Why no call may be made now, or null. `auto`: for an attempt by itself, which EX_PAGES_ARRANGE=manual refuses too. */
private refusal(auto = false): { reason: ArrangeRefusal; message: string } | null {
if (!this.o.llm()) return { reason: "no-model", message: "No model is configured on this server, so pages cannot be arranged." };
if (this.o.on === false) return { reason: "off", message: "Arranging pages with a model is turned off on this server (EX_PAGES_ARRANGE=off)." };
if (auto && this.o.auto === false) return { reason: "manual", message: "This server arranges pages only when asked (EX_PAGES_ARRANGE=manual)." };
const plan = this.o.plan?.();
if (plan?.limited) return { reason: "plan", message: `The plan is refusing requests now${plan.limitLabel ? ` (its ${plan.limitLabel} limit)` : ""}${plan.limitResetsAt ? `, until ${plan.limitResetsAt.slice(0, 16).replace("T", " ")} UTC` : ""}; pages are not arranged until it lifts.` };
if (plan?.warning) return { reason: "plan", message: `The plan's limits are nearly used${plan.remainingPercent !== null ? ` (${plan.remainingPercent}% left)` : ""}; pages are not arranged until they reset, so the calls are kept for writing.` };
+14
View File
@@ -6,6 +6,10 @@
*
* tracing a blog post whose sections are all h3, with <meta name=author> and a <time>
* essay a long headingless essay in a layout table, paragraphs made of <br><br>, no metadata
* drift a headingless page of plain paragraphs whose title says "mockfail": the mock model
* fails to arrange it (an automatic attempt that comes to nothing, then s)
* slow a headingless page whose title says "mockslow": the mock model takes 1.5 s over it
* (the "arranging…" line, and a pane on a part by length when the sections arrive)
* letters sections opened by <p>I.</p>, <p>II.</p>…, author and date in JSON-LD
* rules <p><strong>1. …</strong></p> sections, a sidebar full of h2s, a byline class
* phare French, h2 and h3 sections, with junk ones (Sommaire, Voir aussi, Notes et références)
@@ -36,6 +40,8 @@
export const MOCK_PAGES = {
tracing: "https://tracing.example.org/posts/following-a-request",
essay: "https://essays.example.com/hundred.html",
drift: "https://notes.example.net/field/unsorted",
slow: "https://tides.example.net/slow-water",
letters: "https://letters.example.net/p/on-maps",
rules: "https://software.example.com/2003/10/twelve-rules/",
phare: "https://encyclopedie.example.org/fr/Phare_de_la_Pointe",
@@ -130,6 +136,12 @@ const tracing = page(
</article></main>${FOOTER}`,
);
/** A page of plain paragraphs and nothing else: no headings, no metadata but its title. */
const headingless = (title: string, from: number) =>
page(`<title>${title}</title>`, `<article>${Array.from({ length: 12 }, (_, i) => `<p>${prose(125, from + i * 2)}</p>`).join("")}</article>`);
const drift = headingless("Field notes, unsorted (mockfail)", 3);
const slow = headingless("Slow water (mockslow)", 7);
const essayParas = Array.from({ length: 14 }, (_, i) => prose(120 + (i % 3) * 15, i * 2));
const essay = `<html><head><title>A Hundred Small Maps</title></head><body bgcolor="#ffffff">
<table border="0" cellspacing="0" cellpadding="0"><tr valign="top"><td><img src="/nav.gif" width="69" height="357" alt=""></td><td width="26"></td>
@@ -290,6 +302,8 @@ const redirect = (to: string, status = 302) => new Response(null, { status, head
const PAGES: Record<string, () => Response> = {
[MOCK_PAGES.tracing]: () => html(tracing),
[MOCK_PAGES.essay]: () => html(essay, 200, { "content-type": "text/html" }),
[MOCK_PAGES.drift]: () => html(drift),
[MOCK_PAGES.slow]: () => html(slow),
[MOCK_PAGES.letters]: () => html(letters),
[MOCK_PAGES.rules]: () => html(rules, 200, { "last-modified": "Tue, 01 Nov 2022 10:00:00 GMT" }),
[MOCK_PAGES.phare]: () => html(phare),
+30 -10
View File
@@ -5,7 +5,7 @@
* GET /api/page/summary?url=https://…[&cached=1] title, site, author, date, first sentence
* GET /api/page/media?u=https://… an image a page read here shows
* POST /api/page/reload { url } read the page again (the reader's Reload)
* POST /api/page/arrange { url } summarise it with a model, and arrange a page
* POST /api/page/arrange { url[, auto: true] } summarise it with a model, and arrange a page
* divided by length into sections (pageArrange.ts)
*
* summary &cached=1 answers from the snapshot cache only, never reading the page: 404
@@ -27,12 +27,18 @@
* arranging existed), 422 too-long, 429 budget or plan, 502 failed (the call failed), 503 no-model
* or off (EX_PAGES_ARRANGE=off).
*
* Arranging by itself: article, reload and summary (not &cached=1) start it for a page divided by
* length that a model has not arranged (Arranger.auto), and article and reload send where it stands
* in the page's `auto`: { state: "running" } or { state: "skipped", reason, message }. While it runs
* the browser asks arrange with `auto: true`, which only waits for the call under way (or answers
* with what it came to: 409 idle when nothing is under way) and never starts one.
*
* Every route refuses a request another site's page makes (Sec-Fetch-Site, else Origin, against
* the request's own Host). Requests with neither header (curl, the tests) are allowed. The two
* that act (reload reads a site, arrange spends model budget) are POST only; the others GET only.
*/
import type { IncomingMessage, ServerResponse } from "node:http";
import type { MediaResult, PageClient, PageResult, WebUnusable } from "./page";
import type { MediaResult, PageClient, PageResult, WebArticle, WebUnusable } from "./page";
import type { ArrangeRefusal, Arranger } from "./pageArrange";
import { HttpError, abortOnClose, readJson, sendJson as send } from "./util";
import type { Uncached } from "./wiki";
@@ -94,7 +100,7 @@ export function sendMedia(res: ServerResponse, r: MediaResult | { ok: false; rea
/** The routes that act, and are POST only; the rest are GET only. */
const POSTS = new Set(["reload", "arrange"]);
const REFUSED: Record<ArrangeRefusal, number> = { uncached: 404, old: 409, "too-long": 422, budget: 429, plan: 429, failed: 502, "no-model": 503, off: 503 };
const REFUSED: Record<ArrangeRefusal, number> = { uncached: 404, old: 409, idle: 409, "too-long": 422, budget: 429, plan: 429, failed: 502, "no-model": 503, off: 503, manual: 503 };
function reply<V>(res: ServerResponse, r: PageResult<V> | Uncached | { ok: false; reason: "aborted" }, key: string) {
if (r.ok) return send(res, 200, { ok: true, cached: r.cached, [key]: r.value });
@@ -118,36 +124,50 @@ export function pageRoutes(client: () => PageClient, arranger?: () => Arranger)
send(res, 405, { ok: false, message: `use ${method}` }, { allow: method });
return true;
}
// A page read or opened: arranged by itself if it is divided by length (never throws, never waits).
const auto = (u: string) => arranger?.().auto(u);
const withAuto = <R extends { ok: true; value: WebArticle }>(u: string, r: R): R => {
const a = auto(u);
return a ? { ...r, value: { ...r.value, auto: a } } : r;
};
try {
const p = client();
const signal = abortOnClose(res);
switch (route) {
case "reload": {
const body = await readJson<{ url?: unknown }>(req, 16 * 1024);
const r = await p.reload(checked(body.url, "url"), { signal });
if (r.ok) send(res, 200, { ok: true, cached: false, article: r.value, ...(r.stale ? { stale: r.stale } : {}) });
const u = checked(body.url, "url");
const r = await p.reload(u, { signal });
if (r.ok) send(res, 200, { ok: true, cached: false, article: withAuto(u, r).value, ...(r.stale ? { stale: r.stale } : {}) });
else reply(res, r, "article");
return true;
}
case "arrange": {
const body = await readJson<{ url?: unknown }>(req, 16 * 1024);
const body = await readJson<{ url?: unknown; auto?: unknown }>(req, 16 * 1024);
const u = checked(body.url, "url");
if (!arranger) {
send(res, 503, { ok: false, reason: "off", message: "Arranging pages with a model is not available on this server." });
return true;
}
// Not abandoned when the browser goes: the call is made once, and its result kept for the next ask.
const r = await arranger().arrange(u);
const r = await arranger().arrange(u, { join: body.auto === true });
if (r.ok) send(res, 200, r);
else send(res, REFUSED[r.reason], r);
return true;
}
case "article":
reply(res, await p.article(address(url, "url"), { signal }), "article");
case "article": {
const u = address(url, "url");
const r = await p.article(u, { signal });
reply(res, r.ok ? withAuto(u, r) : r, "article");
return true;
}
case "summary": {
const u = address(url, "url");
reply(res, await p.summary(u, { signal, cacheOnly: url.searchParams.get("cached") === "1" }), "summary");
const cacheOnly = url.searchParams.get("cached") === "1";
const r = await p.summary(u, { signal, cacheOnly });
// Read for a link's title (not a card's look at the cache): arranged by itself as when opened.
if (r.ok && !cacheOnly) auto(u);
reply(res, r, "summary");
return true;
}
case "media":