@0perator/operator 0.2.0 → 0.2.2-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +5 -4
  2. package/dist/auth/byo.js +1 -1
  3. package/dist/auth/commands.js +15 -5
  4. package/dist/auth/identity.js +1 -0
  5. package/dist/auth/staff.js +55 -0
  6. package/dist/autonomy/agent-cli.js +1 -1
  7. package/dist/autonomy/delegate-mode.js +2 -2
  8. package/dist/autonomy/delegate.js +41 -14
  9. package/dist/autonomy/headless.js +37 -10
  10. package/dist/autonomy/index.js +2 -4
  11. package/dist/autonomy/pr-isolation.js +92 -0
  12. package/dist/autonomy/pr-preflight.js +474 -0
  13. package/dist/autonomy/session-factory.js +13 -12
  14. package/dist/autonomy/subagent-model.js +17 -7
  15. package/dist/background/capacity.js +136 -0
  16. package/dist/background/evidence.js +42 -0
  17. package/dist/background/index.js +311 -44
  18. package/dist/background/lane-phase.js +60 -0
  19. package/dist/background/lane-summary.js +151 -0
  20. package/dist/background/notices.js +12 -3
  21. package/dist/background/synthesis.js +25 -0
  22. package/dist/browser/capture.js +505 -0
  23. package/dist/browser/engine.js +4 -3
  24. package/dist/browser/page-capture.js +167 -0
  25. package/dist/browser/png.js +116 -0
  26. package/dist/browser/visual-compare.js +229 -0
  27. package/dist/bus/beam-drop.js +55 -0
  28. package/dist/bus/inbox.js +157 -7
  29. package/dist/cli.js +316 -120
  30. package/dist/config/features.js +3 -3
  31. package/dist/config/managed.js +40 -1
  32. package/dist/config/persona.js +80 -29
  33. package/dist/config/product-hosts.js +2 -0
  34. package/dist/config/settings.js +289 -31
  35. package/dist/config/skills-index.js +37 -14
  36. package/dist/config/staff-prompt.js +12 -0
  37. package/dist/engine/agent.js +52 -41
  38. package/dist/engine/aurora.js +54 -13
  39. package/dist/engine/batch-scheduler.js +4 -13
  40. package/dist/engine/compaction.js +1 -1
  41. package/dist/engine/continuation.js +66 -32
  42. package/dist/engine/decision-points.js +2 -3
  43. package/dist/engine/fanout.js +16 -0
  44. package/dist/engine/identity.js +42 -0
  45. package/dist/engine/loop-guard.js +26 -83
  46. package/dist/engine/messages.js +2 -2
  47. package/dist/engine/moa.js +23 -1
  48. package/dist/engine/native-vision-node.js +72 -0
  49. package/dist/engine/native-vision.js +103 -0
  50. package/dist/engine/net-error.js +15 -0
  51. package/dist/engine/rolling-summary.js +142 -93
  52. package/dist/engine/verify-gate.js +37 -7
  53. package/dist/engine/waterfall.js +33 -0
  54. package/dist/gateway-cli.js +24 -4
  55. package/dist/memory/live-progress.js +4 -5
  56. package/dist/memory/session-index.js +3 -3
  57. package/dist/moa/codeact-lane.js +98 -0
  58. package/dist/moa/codeact-sandbox.js +409 -0
  59. package/dist/moa/codeact.js +140 -0
  60. package/dist/permissions/artifact-visibility.js +10 -0
  61. package/dist/permissions/index.js +2 -1
  62. package/dist/permissions/policy.js +9 -2
  63. package/dist/permissions/tier.js +13 -3
  64. package/dist/products/craft.js +92 -3
  65. package/dist/products/temple.js +20 -1
  66. package/dist/products/voice.js +112 -0
  67. package/dist/remote/grants.js +119 -0
  68. package/dist/remote/host.js +33 -5
  69. package/dist/router/free-models.js +5 -9
  70. package/dist/router/models.js +80 -26
  71. package/dist/router/provider-models.js +78 -0
  72. package/dist/router/router.js +15 -3
  73. package/dist/selfimprove/index.js +8 -6
  74. package/dist/selfimprove/lessons.js +23 -0
  75. package/dist/services/preflight.js +35 -91
  76. package/dist/session.js +316 -125
  77. package/dist/skills/catalogue.js +5 -2
  78. package/dist/skills/finder.js +4 -4
  79. package/dist/skills/install-guard.js +68 -0
  80. package/dist/skills/install.js +67 -0
  81. package/dist/toolchain/manifest.json +13 -13
  82. package/dist/tools/background-result.js +1 -1
  83. package/dist/tools/beam.js +246 -0
  84. package/dist/tools/classes.js +103 -0
  85. package/dist/tools/contract.js +1 -1
  86. package/dist/tools/craft.js +36 -2
  87. package/dist/tools/deferred.js +7 -3
  88. package/dist/tools/doc-text.js +1 -1
  89. package/dist/tools/executor.js +25 -15
  90. package/dist/tools/generation-gateway.js +94 -0
  91. package/dist/tools/registry.js +135 -158
  92. package/dist/tools/sandbox.js +6 -6
  93. package/dist/ui/App.js +17 -6
  94. package/dist/ui/ApprovalPrompt.js +1 -1
  95. package/dist/ui/BgPanel.js +15 -10
  96. package/dist/ui/Composer.js +44 -2
  97. package/dist/ui/Header.js +1 -6
  98. package/dist/ui/StatusRule.js +20 -8
  99. package/dist/ui/ToolStep.js +3 -3
  100. package/dist/ui/Transcript.js +41 -14
  101. package/dist/ui/batchLine.js +4 -4
  102. package/dist/ui/editdiff.js +2 -4
  103. package/dist/ui/format.js +4 -20
  104. package/dist/ui/liveTools.js +3 -3
  105. package/dist/ui/modelPicker.js +10 -6
  106. package/dist/ui/opsMode.js +20 -0
  107. package/dist/ui/phase.js +4 -2
  108. package/dist/ui/slashCommands.js +1 -0
  109. package/dist/ui/types.js +0 -2
  110. package/dist/ui/voice.js +185 -0
  111. package/dist/update-check.js +17 -6
  112. package/dist/update.js +1 -2
  113. package/dist/util/audio-io.js +82 -0
  114. package/dist/util/slash.js +2 -2
  115. package/dist/vision/pairs.js +239 -0
  116. package/package.json +1 -1
  117. package/dist/tools/mutating.js +0 -15
@@ -0,0 +1,72 @@
1
+ // Node side of native vision (engine/native-vision.ts): finding the image files a message names and encoding one for the
2
+ // wire. Kept apart because the engine itself is also bundled for the browser, where fs does not exist.
3
+ import { existsSync, statSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { resolve } from "node:path";
6
+ import { NATIVE_IMAGE_LIMITS } from "./native-vision.js";
7
+ /** Largest file read for an attachment at all (matches the screenshot snapshot cap). */
8
+ const MAX_IMAGE_FILE_BYTES = 64 * 1024 * 1024;
9
+ const IMG_EXT = "(?:png|jpe?g|gif|bmp|webp)";
10
+ // A quoted path may hold spaces; a bare one is a run of non-space characters (shell-escaped spaces allowed). Both must
11
+ // start at an absolute or ~/ root, so an http(s) url — whose path follows "//" — never matches.
12
+ const QUOTED_PATH_RE = new RegExp(`(["'\`])((?:~|/)[^"'\`\\n]*?\\.${IMG_EXT})\\1`, "gi");
13
+ const BARE_PATH_RE = new RegExp(`(?:^|[\\s(\\[])((?:~|/)(?:\\\\ |[^\\s"'\`<>|()\\[\\]])+?\\.${IMG_EXT})(?=$|[\\s)\\],.;:!?])`, "gi");
14
+ /** The local image files a message names, in order, deduplicated, existing and readable, at most `max`. */
15
+ export function extractImagePaths(text, max = NATIVE_IMAGE_LIMITS.maxImages) {
16
+ if (!text)
17
+ return [];
18
+ const found = [];
19
+ for (const m of text.matchAll(QUOTED_PATH_RE))
20
+ found.push({ at: m.index ?? 0, raw: m[2] });
21
+ for (const m of text.matchAll(BARE_PATH_RE))
22
+ found.push({ at: m.index ?? 0, raw: m[1].replace(/\\ /g, " ") });
23
+ found.sort((a, b) => a.at - b.at);
24
+ const out = [];
25
+ for (const { raw } of found) {
26
+ const p = resolve(raw.startsWith("~/") ? `${homedir()}/${raw.slice(2)}` : raw);
27
+ if (out.includes(p))
28
+ continue;
29
+ try {
30
+ if (!existsSync(p))
31
+ continue;
32
+ const st = statSync(p);
33
+ if (!st.isFile() || st.size === 0 || st.size > MAX_IMAGE_FILE_BYTES)
34
+ continue;
35
+ }
36
+ catch {
37
+ continue;
38
+ }
39
+ out.push(p);
40
+ if (out.length >= max)
41
+ break;
42
+ }
43
+ return out;
44
+ }
45
+ /** One image file as a data url at the wire limits, or null when it cannot be read (gone since the message was sent) or
46
+ * is blank. Cached by path, size and mtime. */
47
+ const encoded = new Map();
48
+ export async function encodeImage(path) {
49
+ let key;
50
+ try {
51
+ const st = statSync(path);
52
+ key = `${path}|${st.size}|${st.mtimeMs}`;
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ if (encoded.has(key))
58
+ return encoded.get(key) ?? null;
59
+ let url = null;
60
+ try {
61
+ const { visionImageDataUrl } = await import("../tools/registry.js");
62
+ const r = await visionImageDataUrl(path, NATIVE_IMAGE_LIMITS);
63
+ url = "url" in r ? r.url : null;
64
+ }
65
+ catch {
66
+ url = null;
67
+ }
68
+ if (encoded.size >= 8)
69
+ encoded.delete(encoded.keys().next().value);
70
+ encoded.set(key, url);
71
+ return url;
72
+ }
@@ -0,0 +1,103 @@
1
+ /** What goes on the wire for an attached image. 1568 px keeps a screenshot's text legible; a file heavier than
2
+ * `maxBytes` at that size is re-encoded as JPEG. At most `maxImages` per message. `keepBlank`: a flat picture is still
3
+ * the owner's picture, so the tool's "image is blank" refusal does not apply. */
4
+ export const NATIVE_IMAGE_LIMITS = { maxEdge: 1568, maxBytes: 1_500_000, maxImages: 4, keepBlank: true };
5
+ // ── capability ────────────────────────────────────────────────────────────────────────────────────────────
6
+ /** llama.cpp `GET /props`: `modalities.vision` is true only when the server was started with a multimodal projector. */
7
+ export function visionFromProps(props) {
8
+ const v = props?.modalities?.vision;
9
+ return typeof v === "boolean" ? (v ? "yes" : "no") : "unknown";
10
+ }
11
+ /** A model row from `GET /v1/models/<id>` on a gateway or vendor. Understands the shapes in use (`modalities.vision`,
12
+ * `capabilities.vision`, `vision`, `input_modalities`/`architecture.input_modalities` listing "image"); anything
13
+ * else is unknown, never a guess. */
14
+ export function visionFromModelRow(row) {
15
+ const r = row;
16
+ if (!r || typeof r !== "object")
17
+ return "unknown";
18
+ for (const v of [r.modalities?.vision, r.capabilities?.vision, r.vision])
19
+ if (typeof v === "boolean")
20
+ return v ? "yes" : "no";
21
+ const list = r.input_modalities ?? r.architecture?.input_modalities;
22
+ if (Array.isArray(list))
23
+ return list.includes("image") ? "yes" : "no";
24
+ return "unknown";
25
+ }
26
+ const SUPPORT_TTL_MS = 10 * 60_000;
27
+ const support = new Map();
28
+ const supportKey = (base, model) => `${base.replace(/\/+$/, "").replace(/\/v1$/, "")}|${model}`;
29
+ async function getJson(url, timeoutMs, f) {
30
+ try {
31
+ const r = await f(url, { signal: AbortSignal.timeout(timeoutMs) });
32
+ return r.ok ? await r.json() : null;
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ }
38
+ /** Whether the endpoint serves a model that takes images. llama.cpp's own `/props` first, then the model's row on a
39
+ * gateway; "unknown" when neither says. Cached per endpoint and model (10 minutes); a rejected image flips it to "no". */
40
+ export async function detectVision(base, model, opts = {}) {
41
+ const key = supportKey(base, model);
42
+ const now = opts.now ?? Date.now();
43
+ const hit = support.get(key);
44
+ if (hit && now - hit.at < SUPPORT_TTL_MS)
45
+ return hit.v;
46
+ const f = opts.fetchImpl ?? fetch;
47
+ const timeoutMs = opts.timeoutMs ?? 1500;
48
+ const bare = key.split("|")[0];
49
+ let v = visionFromProps(await getJson(`${bare}/props`, timeoutMs, f));
50
+ if (v === "unknown")
51
+ v = visionFromModelRow(await getJson(`${bare}/v1/models/${encodeURIComponent(model)}`, timeoutMs, f));
52
+ support.set(key, { v, at: now });
53
+ return v;
54
+ }
55
+ /** The server turned an image down: remember it, so the rest of the session sends no more. */
56
+ export function markVisionRejected(base, model) {
57
+ support.set(supportKey(base, model), { v: "no", at: Date.now() });
58
+ }
59
+ export function resetVisionCache() { support.clear(); }
60
+ /** The error an endpoint raises for an image it cannot take (llama.cpp without a projector: "image input is not
61
+ * supported"; vendors: "does not support image"/"multimodal"). Only a client or server error that names it. */
62
+ const IMAGE_REJECT_RE = /\bimage(?:_url|s)?\b.*\b(?:not supported|unsupported|not support|invalid|cannot|can't|does not|doesn't)\b|\b(?:not supported|unsupported|does not support|doesn't support)\b.*\b(?:image|multimodal|vision)|\bmmproj\b|\bmultimodal\b/i;
63
+ export function imageRejected(err) {
64
+ const status = err?.status;
65
+ if (typeof status !== "number" || status < 400)
66
+ return false;
67
+ return IMAGE_REJECT_RE.test(err instanceof Error ? err.message : String(err));
68
+ }
69
+ // ── message construction ──────────────────────────────────────────────────────────────────────────────────
70
+ const SEEN_NOTE = "[The image(s) above are attached to this message and you can see them directly: describe or read them from the picture, with no image_analyze call.]";
71
+ /** The request's messages with each message's `images` turned into image_url parts after its text. An image that
72
+ * cannot be encoded is left out (its path is still in the text). `images` itself never reaches the wire. */
73
+ export async function toWireMessages(messages, encode) {
74
+ const out = [];
75
+ for (const m of messages) {
76
+ const { images, ...rest } = m;
77
+ if (!images?.length) {
78
+ out.push(rest);
79
+ continue;
80
+ }
81
+ const parts = [];
82
+ for (const p of images) {
83
+ const url = await encode(p);
84
+ if (url)
85
+ parts.push({ type: "image_url", image_url: { url } });
86
+ }
87
+ out.push(parts.length ? { ...rest, content: [{ type: "text", text: `${m.content}\n\n${SEEN_NOTE}` }, ...parts] } : rest);
88
+ }
89
+ return out;
90
+ }
91
+ /** The conversation with every message's images taken back off: the owner's text gains a line pointing at each file,
92
+ * so the model can still look at it with image_analyze. Returns how many images were taken off. */
93
+ export function withoutImages(messages) {
94
+ let removed = 0;
95
+ const out = messages.map((m) => {
96
+ if (!m.images?.length)
97
+ return m;
98
+ removed += m.images.length;
99
+ const { images, ...rest } = m;
100
+ return { ...rest, content: `${m.content}\n\n[Attached image${images.length > 1 ? "s" : ""} not sent to the model directly: ${images.join(", ")}. Look at ${images.length > 1 ? "them" : "it"} with image_analyze.]` };
101
+ });
102
+ return { messages: out, removed };
103
+ }
@@ -2,7 +2,9 @@
2
2
  // unreachable. For network-level failures (the request never got an HTTP answer) this appends the active
3
3
  // model's label and the endpoint hosts that were tried, plus the one action that helps. The original message is
4
4
  // never swallowed, and any other error renders exactly as before.
5
+ import { discloseModel, neutralCause } from "./identity.js";
5
6
  const NET_RE = /fetch failed|ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|EHOSTUNREACH|ENETUNREACH|EAI_AGAIN|socket hang up|network (?:error|request failed)/i;
7
+ const SERVER_RE = /\bHTTP \d{3}\b|backend|upstream|maxInflight/i;
6
8
  export function isNetworkFailure(message) {
7
9
  return NET_RE.test(message);
8
10
  }
@@ -15,7 +17,20 @@ export function hostOf(base) {
15
17
  return base.replace(/^https?:\/\//, "").replace(/\/.*$/, "");
16
18
  }
17
19
  }
20
+ /** An error message as a user reads it. With the serving model confidential, a network failure or a server's error
21
+ * (a router's body names legs, upstreams and boxes) becomes one neutral phrase; anything else is unchanged. */
22
+ export function shownFailure(message) {
23
+ if (discloseModel())
24
+ return message;
25
+ if (isNetworkFailure(message))
26
+ return "the model's server is unreachable";
27
+ if (SERVER_RE.test(message))
28
+ return `the model's server failed (${neutralCause(message)})`;
29
+ return message;
30
+ }
18
31
  export function describeTurnError(message, ctx = {}) {
32
+ if (shownFailure(message) !== message)
33
+ return `[turn error: ${shownFailure(message)}; /model to switch]`;
19
34
  if (!isNetworkFailure(message))
20
35
  return `[turn error: ${message}]`;
21
36
  const hosts = [...new Set((ctx.bases ?? []).map(hostOf))];
@@ -1,115 +1,164 @@
1
- // Rolling session summary — the "instant compaction" mechanism.
2
- // A background summarizer runs during lulls (when a round ends without tool calls)
3
- // and maintains a structured session-memory/summary.md. When compact() fires,
4
- // it loads this pre-computed summary instead of making a live summarize call,
5
- // turning a 48s–5min stall into zero user-visible latency.
6
- //
7
- // Also pre-builds the living-memory block for Pillar B's journal index.
8
- import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
1
+ // Rolling session summary — compaction whose cost is bounded by construction.
2
+ // The conversation is summarized AS IT GOES, in bounded passes: each pass reads the next chunk of messages nothing has
3
+ // covered yet and writes a short note for that chunk alone. The notes
4
+ // are appended, never rewritten, so a fact is digested once — measured 11/24: a chain that REWROTE one summary per
5
+ // pass kept 3 of 8 planted facts in its prose after 11 passes on a 2B model; one request over the same span kept 8.
6
+ // A pass never reads the whole conversation, so its cost is set by the chunk, not by how long the session is, which
7
+ // model runs it, or whether the server still holds the conversation in its prompt cache. Passes run in the background
8
+ // between turns; at compaction the notes are the summary, and only the uncovered tail is read live, in one request.
9
+ // When the notes outgrow their cap (a long session, or several compactions) one pass folds their older half into a
10
+ // single summary; the newer half is left as written.
11
+ // The watermark is a message count (how many leading messages the notes cover) plus a fingerprint of that prefix, so
12
+ // a conversation that was replaced under it (a resumed session) is never trusted.
13
+ import { writeFileSync, existsSync, mkdirSync } from "node:fs";
9
14
  import { join, dirname } from "node:path";
10
15
  import { operatorPath } from "../config/home.js";
11
- const SESSION_MEMORY_DIR = operatorPath("session-memory");
12
- const SUMMARY_FILE = join(SESSION_MEMORY_DIR, "summary.md");
13
- const DEFAULTS = {
14
- minTokensSinceUpdate: 5000,
15
- minToolBatches: 3,
16
- maxSummaryChars: 4000,
17
- enabled: true,
18
- };
16
+ import { SUMMARY_INSTRUCTION, applyAnchorVerification } from "./compaction.js";
17
+ const SUMMARY_FILE = join(operatorPath("session-memory"), "summary.md");
18
+ const CHARS_PER_TOKEN = 4; // the same prior as estimateTokensHeuristic: sizes here are bounds on a prompt, not a meter
19
+ export function rollingBudget(ctxWindow, summaryTokens) {
20
+ const chunkTokens = Math.max(2000, Math.min(16_000, Math.floor(ctxWindow / 16)));
21
+ return {
22
+ chunkTokens, dueTokens: Math.floor(chunkTokens / 2), liveTokens: Math.max(chunkTokens, Math.floor(ctxWindow / 2)),
23
+ noteTokens: Math.floor(summaryTokens / 4), capTokens: Math.max(2 * summaryTokens, Math.min(8192, Math.floor(ctxWindow / 32))), summaryTokens,
24
+ };
25
+ }
26
+ const clip = (s, cap) => s.length <= cap ? s : `${s.slice(0, Math.floor(cap * 0.7))}\n[… ${s.length - cap} chars clipped …]\n${s.slice(-(Math.floor(cap * 0.3) - 40))}`;
27
+ /** One message as the summarizer reads it. No message takes more than a quarter of a chunk: one huge tool output
28
+ * cannot be the whole pass (its identifiers still reach the compacted note through compact()'s anchor index). */
29
+ function renderMsg(m, b) {
30
+ let s = `${m.role}: ${m.content ?? ""}`;
31
+ for (const tc of m.tool_calls ?? [])
32
+ s += `\n→ ${tc.function?.name ?? ""}(${tc.function?.arguments ?? ""})`;
33
+ return clip(s, b.chunkTokens * CHARS_PER_TOKEN / 4);
34
+ }
35
+ /** The next chunk of `conversation[from, to)`: at least one message, then as many as fit `capTokens` (a background
36
+ * pass: one chunk; a live one: b.liveTokens). */
37
+ export function takeChunk(conversation, from, to, b, capTokens = b.chunkTokens) {
38
+ const cap = capTokens * CHARS_PER_TOKEN;
39
+ const parts = [];
40
+ let used = 0;
41
+ let end = from;
42
+ while (end < to) {
43
+ const r = renderMsg(conversation[end], b);
44
+ if (parts.length && used + r.length + 1 > cap)
45
+ break;
46
+ parts.push(r);
47
+ used += r.length + 1;
48
+ end++;
49
+ }
50
+ return { end, text: parts.join("\n"), tokens: Math.ceil(used / CHARS_PER_TOKEN) };
51
+ }
52
+ /** Tokens of `conversation[from, to)` as the summarizer would read them (every message clipped as in a chunk). */
53
+ export function uncoveredTokens(conversation, from, to, b) {
54
+ let chars = 0;
55
+ for (let i = from; i < to; i++)
56
+ chars += renderMsg(conversation[i], b).length + 1;
57
+ return Math.ceil(chars / CHARS_PER_TOKEN);
58
+ }
59
+ /** The notes inside an earlier compaction's message (compact(): header line, the summary, then the mechanical anchor
60
+ * / user-voice blocks, which compact() derives again from the span). They are adopted as the notes so far instead of
61
+ * being digested again. Undefined when `head` is not a compacted summary. */
62
+ export function adoptedNotes(head) {
63
+ if (!head?.startsWith("[Compacted summary"))
64
+ return undefined;
65
+ return head.slice(head.indexOf("\n") + 1).split(/\n\n(?:ANCHORS \(mechanically extracted|USER VOICE \(verbatim)/)[0];
66
+ }
67
+ /** Whether the notes have outgrown their cap and the next pass folds them. */
68
+ export const notesOverCap = (notes, b) => notes.length > b.capTokens * CHARS_PER_TOKEN;
69
+ /** What turns the summary contract compaction has always used (SUMMARY_INSTRUCTION, nine sections) into the contract
70
+ * for ONE chunk's note. Reused, not rewritten, and the chunk is all the model is shown — both measured 11/24 on a 2B
71
+ * model: a purpose-made FACTS-first format transcribed tool logs until its budget ran out (1 of 8 planted facts
72
+ * kept), and with the earlier notes shown as context it wrote the same note again for every later chunk. */
73
+ export const NOTE_SCOPE = " The conversation above is ONE PART of a longer one that is summarized part by part: write the note for these " +
74
+ "messages alone. A tool result is evidence, not content: keep from it what the assistant used or a later turn will " +
75
+ "need (the path, the version, the failing line), never a transcript of a log, a listing or a file body.";
76
+ /** A note pass's whole request: the chunk and the contract — nothing whose size depends on the session. */
77
+ export function notePrompt(chunkText, b, noteTokens = b.noteTokens) {
78
+ return `${chunkText}\n\n${SUMMARY_INSTRUCTION}${NOTE_SCOPE} Keep the note under ${Math.floor(noteTokens / 2)} words.`;
79
+ }
80
+ /** What a fold rewrites and what it leaves alone: the older half of the notes (cut between two notes) is folded, the
81
+ * newer half — what the next turns depend on, and the current state — is never touched by the model. */
82
+ export function foldSplit(notes) {
83
+ const cut = notes.lastIndexOf("\n\n", Math.floor(notes.length / 2));
84
+ const i = cut > 0 ? cut : Math.floor(notes.length / 2);
85
+ return [notes.slice(0, i), notes.slice(i).trimStart()];
86
+ }
87
+ /** A fold pass's whole request: the older half of the notes, as the '[Compacted summary …]' SUMMARY_INSTRUCTION
88
+ * already says to carry every concrete value forward from. Bounded: half the cap plus one live note. */
89
+ export function foldPrompt(old, b) {
90
+ return `[Compacted summary — the running notes of the conversation so far, oldest first]\n${clip(old, (b.capTokens + b.summaryTokens) * CHARS_PER_TOKEN)}\n\n` +
91
+ `${SUMMARY_INSTRUCTION} Keep the whole note under ${Math.floor(b.summaryTokens / 2)} words: tighten prose, never drop a concrete value.`;
92
+ }
93
+ /** The notes after a fold: [what the model made of the older half] + [the newer half, as it was]. The fold is held to
94
+ * compaction's own proof (applyAnchorVerification): every identifier the older notes held and the fold dropped is
95
+ * appended verbatim, by code — measured 11/24, a 2B model folded 14K chars of notes into 1K and kept none of 8
96
+ * planted facts. Always under the cap (the oldest text goes first), so a fold is never due again at once. */
97
+ export function foldedNotes(old, folded, recent, b) {
98
+ const [durable, state] = splitState(folded.slice(0, b.summaryTokens * CHARS_PER_TOKEN));
99
+ const m = { role: "user", content: durable.trim() };
100
+ applyAnchorVerification(m, [{ role: "user", content: old }], [m, { role: "user", content: recent }]);
101
+ return appendNote(`${m.content}\n\n${state}`, recent).slice(-b.capTokens * CHARS_PER_TOKEN);
102
+ }
103
+ /** A note's durable sections, and its state: from the last PENDING heading (however the model dresses it) to the end. */
104
+ function splitState(s) {
105
+ const heads = [...s.matchAll(/^[\s#*\d.)]*PENDING\b/gm)];
106
+ const i = heads.length ? heads[heads.length - 1].index : -1;
107
+ return i < 0 ? [s, ""] : [s.slice(0, i), s.slice(i)];
108
+ }
109
+ /** The notes after one more: the new note's durable sections (1-6) are appended; its state — from the PENDING heading
110
+ * to the end: PENDING, CURRENT, NEXT STEP — replaces the old state, so the notes always end with the conversation as
111
+ * it now stands and never carry a stale "still open". A note with no PENDING heading leaves the old state in place. */
112
+ export function appendNote(notes, note) {
113
+ const [durable, state] = splitState(notes);
114
+ const [added, now] = splitState(note);
115
+ return [durable, added, now || state].map((p) => p.trim()).filter(Boolean).join("\n\n");
116
+ }
19
117
  export class RollingSummarizer {
20
- opts;
21
- lastUpdateTokens = 0;
22
- lastUpdateBatches = 0;
23
- summaryCache = "";
24
- dirty = false;
25
- // GW-27-U2: how many user-turns the CURRENT cached summary covers (turnCount at fire time).
26
- // Without this, /compact cannot tell a summary that covers the whole evicted span from one that
27
- // predates the newest N quiet turns — and silently drops the uncovered ones.
28
- coveredThroughTurns = 0;
118
+ summary = "";
119
+ covered = 0;
120
+ mark = "";
29
121
  path;
30
122
  constructor(opts = {}) {
31
- this.opts = { ...DEFAULTS, ...opts };
32
123
  this.path = opts.summaryPath ?? SUMMARY_FILE;
33
- // Load existing summary if present
34
- if (existsSync(this.path)) {
35
- this.summaryCache = readFileSync(this.path, "utf8");
36
- }
37
124
  }
38
- /** Feed token/batch counts from a completed round. Returns true if a summary should be triggered. */
39
- feedRound(outputTokens, toolBatches) {
40
- if (!this.opts.enabled)
41
- return false;
42
- this.lastUpdateTokens += outputTokens;
43
- this.lastUpdateBatches += toolBatches;
44
- // Check if we should trigger a summary
45
- const minTokens = this.opts.minTokensSinceUpdate ?? DEFAULTS.minTokensSinceUpdate ?? 5000;
46
- const minBatches = this.opts.minToolBatches ?? DEFAULTS.minToolBatches ?? 3;
47
- const tokensOk = this.lastUpdateTokens >= minTokens;
48
- const batchesOk = this.lastUpdateBatches >= minBatches;
49
- if (tokensOk && batchesOk) {
50
- this.dirty = true;
51
- // Reset counters — the caller fires the actual summarize
52
- this.lastUpdateTokens = 0;
53
- this.lastUpdateBatches = 0;
54
- return true;
55
- }
56
- return false;
125
+ static fingerprint(conversation, n) {
126
+ return `${n}:${conversation[0]?.content.slice(0, 80) ?? ""}:${conversation.slice(Math.max(0, n - 32), n).map((m) => m.role[0]).join("")}`;
57
127
  }
58
- /** Mark that a summary was fired (called by the session after summarizing). Pass the number of
59
- * user-turns the produced summary covers so /compact can verify coverage before trusting it
60
- * (GW-27-U2). Omitted => coverage unknown => treated as covering nothing: safe, just falls back
61
- * to the live summarize path. */
62
- markSummaryFired(turnsCovered) {
63
- this.dirty = false;
64
- this.coveredThroughTurns = typeof turnsCovered === "number" ? turnsCovered : 0;
65
- }
66
- /** The fire-watermark: user-turns covered by the cached summary (0 = never fired / unknown). */
67
- getCoveredThrough() {
68
- return this.coveredThroughTurns;
69
- }
70
- /** Get the current cached summary (for /compact to use). Empty string if none. */
128
+ /** The notes on the first coveredCount(conversation) messages ("" when there are none). */
71
129
  getSummary() {
72
- return this.summaryCache;
130
+ return this.summary;
73
131
  }
74
- /** Set the summary content (called by the session after a summary is generated). */
75
- setSummary(content) {
76
- this.summaryCache = content;
77
- this.writeSummary();
78
- this.dirty = false;
132
+ /** How many leading messages of THIS conversation the notes cover. 0 — and the notes dropped — when the
133
+ * conversation is not the one it was written from. */
134
+ coveredCount(conversation) {
135
+ if (!this.covered)
136
+ return 0;
137
+ if (this.covered > conversation.length || RollingSummarizer.fingerprint(conversation, this.covered) !== this.mark)
138
+ this.clear();
139
+ return this.covered;
79
140
  }
80
- /** Whether a summary is stale and should be refreshed. */
81
- isStale() {
82
- return this.dirty;
83
- }
84
- /** Whether to persist the summary to disk. */
85
- writeSummary() {
141
+ /** A pass finished: `summary` (the notes) now covers the first `n` messages of `conversation`. */
142
+ advance(summary, conversation, n) {
143
+ this.summary = summary;
144
+ this.covered = n;
145
+ this.mark = RollingSummarizer.fingerprint(conversation, n);
86
146
  try {
87
- // dirname(this.path), not the global dir: a per-session path (ACP, bots, delegate) lives elsewhere and the write
88
- // used to fail silently there. The summary is a digest of the conversation, so owner-only.
147
+ // dirname(this.path), not the global dir: a per-session path (ACP, bots, delegate) lives elsewhere. The summary
148
+ // is a digest of the conversation, so owner-only.
89
149
  mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
90
- writeFileSync(this.path, this.summaryCache, { encoding: "utf8", mode: 0o600 });
150
+ writeFileSync(this.path, summary, { encoding: "utf8", mode: 0o600 });
91
151
  }
92
152
  catch { /* best-effort — summary persistence never blocks a turn */ }
93
153
  }
94
- /** Truncate summary to max chars, keeping the most recent content. */
95
- truncate(maxChars) {
96
- const cap = maxChars || (this.opts?.maxSummaryChars ?? DEFAULTS.maxSummaryChars) || 4000;
97
- if (this.summaryCache.length <= cap)
98
- return this.summaryCache;
99
- // Keep the tail — newer info is more relevant
100
- return this.summaryCache.slice(-(cap - 50)) + "\n\n[summary truncated — older context in live conversation]";
101
- }
102
- /** Clear the rolling summary (for /new session). */
154
+ /** Forget the summary (a new session, or a compaction that folded it into the conversation). */
103
155
  clear() {
104
- this.summaryCache = "";
105
- this.dirty = false;
106
- this.coveredThroughTurns = 0;
107
- this.lastUpdateTokens = 0;
108
- this.lastUpdateBatches = 0;
156
+ this.summary = "";
157
+ this.covered = 0;
158
+ this.mark = "";
109
159
  try {
110
- if (existsSync(this.path)) {
160
+ if (existsSync(this.path))
111
161
  writeFileSync(this.path, "", "utf8");
112
- }
113
162
  }
114
163
  catch { /* best-effort */ }
115
164
  }
@@ -156,9 +156,20 @@ export function isStrongVerifyCmd(cmd) {
156
156
  export function reportedChecks(text) {
157
157
  return REPORTED.filter(([, re]) => re.test(text)).map(([k]) => k);
158
158
  }
159
- import { MUTATING_TOOLS } from "../tools/mutating.js"; // single source of truth (see tools/mutating.ts)
159
+ import { FILE_WRITE, SHELL_FOREGROUND } from "../tools/classes.js";
160
160
  import { backgroundJobId, finishedJob, stillInBackground } from "../tools/background-result.js";
161
- const VERIFY_TOOLS = new Set(["bash", "shell_exec"]);
161
+ // A prose / document deliverable (markdown, a report, plain text) is verified by a CONTENT or DOC check,
162
+ // never a code test/build — so a research write-up must not read as "not verified" just because no test ran.
163
+ const PROSE_EXT_RE = /\.(?:md|markdown|mdx|mdc|txt|text|rst|adoc|asciidoc)$/i;
164
+ /** A content check of a written file — read it back (wc/cat/head/tail/sed -n/grep) or lint the prose
165
+ * (markdownlint, markdown-link-check, vale, …). This is what verifies a document deliverable. */
166
+ function isContentCheckCmd(cmd) {
167
+ if (!cmd || /\$\(|`/.test(cmd))
168
+ return false;
169
+ return /(?:^|\|\||&&|[;|]\s*)\s*(?:wc|cat|head|tail|less|more|nl|bat|fold|markdownlint|markdownlint-cli2|markdown-link-check|lychee|vale|mdl|textlint|cspell)\b/.test(cmd) ||
170
+ /(?:^|\|\||&&|[;|]\s*)\s*sed\s+-n\b/.test(cmd) ||
171
+ /(?:^|\|\||&&|[;|]\s*)\s*grep\b[^|]*\.(?:md|txt|markdown|rst)\b/i.test(cmd);
172
+ }
162
173
  /** Turn-local ledger. The loop calls observe() after each tool batch, then gate() at the done-exit.
163
174
  * Turn-scoped (one runTurn = one task): a verify from an earlier turn must not satisfy this turn's new
164
175
  * changes — the same reason grandmaster re-derives `verified` per result and never trusts prior state. */
@@ -166,6 +177,8 @@ export class TaskVerification {
166
177
  mutated = false;
167
178
  verified = false;
168
179
  verifiedStrong = false; // a STRONG verify ran+passed (test/build/typecheck/run) — the enforced-gate signal
180
+ codeMutated = false; // a NON-prose (code/config) file changed → a real test/build is the verify
181
+ contentChecked = false; // a content/doc check ran (read the file back, or a prose linter) — verifies a doc deliverable
169
182
  ran = new Set(); // run at all this turn: a piped `tsc | head` exits 0 whatever it found
170
183
  latest = new Map(); // each check's LAST result this turn: null = it passed
171
184
  background = new Map(); // job id → the check it runs, started after the last change, result unread
@@ -176,12 +189,16 @@ export class TaskVerification {
176
189
  const name = names[i];
177
190
  let res = results[i] ?? "";
178
191
  let cmd = (commands[i] ?? "").trim();
179
- let shell = VERIFY_TOOLS.has(name);
192
+ let shell = SHELL_FOREGROUND.has(name);
180
193
  // a change makes every earlier check stale, a job started before it included: only a check that runs after the last change verifies it
181
- if (MUTATING_TOOLS.has(name) && !/^error/i.test(res.trim())) {
194
+ if (FILE_WRITE.has(name) && !/^error/i.test(res.trim())) {
182
195
  this.mutated = true;
183
- this.verified = this.verifiedStrong = false;
196
+ this.verified = this.verifiedStrong = this.contentChecked = false;
184
197
  this.background.clear();
198
+ // file_edit/file_write report "edited <path>" / "wrote <path>"; a non-prose (or unknown) path needs a real test/build.
199
+ const path = /^(?:edited|wrote|created|updated)\s+(\S+)/i.exec(res.trim())?.[1] ?? "";
200
+ if (!path || !PROSE_EXT_RE.test(path))
201
+ this.codeMutated = true;
185
202
  }
186
203
  const jobId = shell || name === "shell_background" ? backgroundJobId(res) : undefined;
187
204
  if (jobId && isVerifyCmd(cmd))
@@ -200,6 +217,8 @@ export class TaskVerification {
200
217
  this.verified = true;
201
218
  if (isStrongVerifyCmd(cmd))
202
219
  this.verifiedStrong = true;
220
+ if (isContentCheckCmd(cmd))
221
+ this.contentChecked = true;
203
222
  }
204
223
  if (shell && !/^error running command:/i.test(res.trim()) && !stillInBackground(res))
205
224
  for (const k of checksRun(cmd))
@@ -232,13 +251,24 @@ export class TaskVerification {
232
251
  changedFiles() {
233
252
  return this.mutated;
234
253
  }
235
- /** True ⇒ this turn changed code but never ran a passing check ⇒ nudge, then annotate (ADVISORY path). */
254
+ /** A document/prose deliverable: files changed but NONE were code/config — it is verified by a content or
255
+ * doc check, not a code test. (Falls back to "treat as code" when a mutation's path can't be read.) */
256
+ proseOnly() {
257
+ return this.mutated && !this.codeMutated;
258
+ }
259
+ /** True ⇒ this turn changed code but never ran a passing check ⇒ nudge, then annotate (ADVISORY path).
260
+ * A prose/doc deliverable is instead cleared by a content/doc check — so a verified report never reads "not verified". */
236
261
  gate() {
262
+ if (this.proseOnly())
263
+ return !this.contentChecked;
237
264
  return this.mutated && !this.verified;
238
265
  }
239
266
  /** True ⇒ changed code but never ran a STRONG (test/build/typecheck/run) check ⇒ the ENFORCED hard
240
- * precondition for unattended turns (an allowlisted-but-empty command like `npm ls` does NOT clear it). */
267
+ * precondition for unattended turns (an allowlisted-but-empty command like `npm ls` does NOT clear it).
268
+ * A prose/doc deliverable has no code to strong-verify, so it is never held for a test/build. */
241
269
  gateStrong() {
270
+ if (this.proseOnly())
271
+ return false;
242
272
  return this.mutated && !this.verifiedStrong;
243
273
  }
244
274
  /** The checks `answer` reports as clean that never ran this turn ⇒ nudge, then annotate. */
@@ -0,0 +1,33 @@
1
+ import { inferType } from "./grandmaster.js";
2
+ export const WATERFALL_MODEL_ID = "waterfall";
3
+ export const EXTERNAL_EXECUTOR = "external-executor";
4
+ export const WATERFALL_SEATS = {
5
+ operator: { planner: "operator-planner", executor: "operator-executor" },
6
+ dexter: { planner: "dexter-planner", executor: "dexter-executor" },
7
+ moa: { planner: "moa-planner", executor: "moa-executor" },
8
+ };
9
+ /** A message this short with no work verb reads as conversation: one model answers it. */
10
+ const DIRECT_MAX_CHARS = 280;
11
+ /** The tier for a turn. The turn router decides when it answered (direct → operator; work: code edits → dexter,
12
+ * anything else → moa). Without it (a customer's box has no local router, or it was down/slow), the keyword rules
13
+ * decide, so a tier is always chosen and the turn never waits on a missing service. */
14
+ export function waterfallTier(text, route) {
15
+ if (route) {
16
+ if (route.route === "direct")
17
+ return { tier: "operator", by: "router" };
18
+ return { tier: route.role === "code-edit" ? "dexter" : "moa", by: "router" };
19
+ }
20
+ const kind = inferType(text);
21
+ if (kind === "code-edit")
22
+ return { tier: "dexter", by: "keywords" };
23
+ if (kind === "generic" && text.trim().length <= DIRECT_MAX_CHARS)
24
+ return { tier: "operator", by: "keywords" };
25
+ return { tier: "moa", by: "keywords" };
26
+ }
27
+ /** The planner team for a tier, or undefined for operator (one model, no plan). */
28
+ export function waterfallTeam(tier, opts = {}) {
29
+ if (tier === "operator")
30
+ return undefined;
31
+ const seats = WATERFALL_SEATS[tier];
32
+ return { planner: { id: seats.planner }, specialist: seats.executor, external: true, ...(opts.codeact ? { codeact: true } : {}) };
33
+ }