@0perator/operator 0.2.1 → 0.2.2-next.1

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 (66) hide show
  1. package/README.md +1 -1
  2. package/dist/auth/byo.js +1 -1
  3. package/dist/auth/commands.js +8 -2
  4. package/dist/autonomy/agent-cli.js +1 -1
  5. package/dist/autonomy/headless.js +30 -6
  6. package/dist/autonomy/pr-isolation.js +92 -0
  7. package/dist/autonomy/pr-preflight.js +474 -0
  8. package/dist/autonomy/session-factory.js +2 -0
  9. package/dist/browser/capture.js +505 -0
  10. package/dist/browser/engine.js +4 -3
  11. package/dist/browser/page-capture.js +167 -0
  12. package/dist/browser/png.js +116 -0
  13. package/dist/browser/visual-compare.js +229 -0
  14. package/dist/bus/beam-drop.js +55 -0
  15. package/dist/bus/inbox.js +7 -1
  16. package/dist/cli.js +130 -26
  17. package/dist/config/managed.js +40 -1
  18. package/dist/config/persona.js +86 -41
  19. package/dist/config/product-hosts.js +2 -0
  20. package/dist/config/settings.js +30 -13
  21. package/dist/config/skills-index.js +37 -14
  22. package/dist/engine/agent.js +1 -1
  23. package/dist/engine/aurora.js +18 -9
  24. package/dist/engine/continuation.js +36 -0
  25. package/dist/engine/identity.js +42 -0
  26. package/dist/engine/moa.js +7 -0
  27. package/dist/engine/net-error.js +15 -0
  28. package/dist/engine/rolling-summary.js +142 -93
  29. package/dist/engine/waterfall.js +33 -0
  30. package/dist/gateway-cli.js +10 -1
  31. package/dist/memory/session-index.js +3 -3
  32. package/dist/permissions/index.js +2 -1
  33. package/dist/permissions/policy.js +9 -2
  34. package/dist/permissions/tier.js +9 -1
  35. package/dist/products/craft.js +90 -1
  36. package/dist/products/temple.js +20 -1
  37. package/dist/products/voice.js +112 -0
  38. package/dist/router/free-models.js +5 -9
  39. package/dist/router/models.js +58 -14
  40. package/dist/router/provider-models.js +78 -0
  41. package/dist/router/router.js +15 -3
  42. package/dist/selfimprove/lessons.js +23 -0
  43. package/dist/session.js +192 -87
  44. package/dist/skills/catalogue.js +5 -2
  45. package/dist/skills/finder.js +4 -4
  46. package/dist/skills/install-guard.js +1 -1
  47. package/dist/tools/beam.js +246 -0
  48. package/dist/tools/craft.js +23 -0
  49. package/dist/tools/deferred.js +7 -3
  50. package/dist/tools/doc-text.js +1 -1
  51. package/dist/tools/registry.js +55 -9
  52. package/dist/tools/sandbox.js +6 -6
  53. package/dist/ui/App.js +3 -3
  54. package/dist/ui/ApprovalPrompt.js +1 -1
  55. package/dist/ui/Composer.js +44 -2
  56. package/dist/ui/StatusRule.js +2 -1
  57. package/dist/ui/Transcript.js +5 -0
  58. package/dist/ui/modelPicker.js +10 -6
  59. package/dist/ui/phase.js +4 -2
  60. package/dist/ui/slashCommands.js +1 -0
  61. package/dist/ui/voice.js +185 -0
  62. package/dist/update.js +1 -2
  63. package/dist/util/audio-io.js +82 -0
  64. package/dist/util/slash.js +2 -2
  65. package/dist/vision/pairs.js +239 -0
  66. package/package.json +1 -1
@@ -0,0 +1,42 @@
1
+ // How model, leg and host identity reads in text a user sees (2026-11-30-neutral-harness-names). The serving model is
2
+ // confidential unless the owner opted in (settings.identity.discloseModel → KODE_DISCLOSE_MODEL=1): then every formatter
3
+ // here returns its input unchanged. Otherwise a model reads as a role, a host or a box is left out, and a server's own
4
+ // words become a short cause. Telemetry, events.jsonl and the audit keep the real names; only user-facing text comes
5
+ // through here. Dependency-free leaf (agent.ts is also bundled for the browser).
6
+ export const BRAND = "Operator";
7
+ export function discloseModel() {
8
+ return globalThis.process?.env?.KODE_DISCLOSE_MODEL === "1";
9
+ }
10
+ const ROLE = { primary: "the primary model", backup: "a backup model", selected: "the selected model" };
11
+ /** A model named in a sentence: its name when disclosed, else its role ("the primary model"). */
12
+ export function shownModel(name, role) {
13
+ return discloseModel() ? name : ROLE[role];
14
+ }
15
+ /** The model on the status line, the phase line and receipts: its label when disclosed, else the brand. */
16
+ export function shownModelLabel(label) {
17
+ return discloseModel() ? label : BRAND;
18
+ }
19
+ /** A failure's cause as a user reads it: the full cause when disclosed (it may carry a box, an upstream id or a
20
+ * router's error body), else one of busy, timed out, unavailable, empty reply or server error. */
21
+ export function shownCause(cause) {
22
+ return discloseModel() ? cause : neutralCause(cause);
23
+ }
24
+ export function neutralCause(cause) {
25
+ if (/nothing in them|empty repl|no content/i.test(cause))
26
+ return "empty reply";
27
+ if (/busy|maxInflight|\b429\b|rate.?limit|overloaded|capacity|too many/i.test(cause))
28
+ return "busy";
29
+ if (/timed? ?out|timeout|stall|too slow|no response/i.test(cause))
30
+ return "timed out";
31
+ if (/refused|not found|unreachable|DNS|reset|dropped|\b50[234]\b|\b404\b|unavailable|\bdown\b|loading|offline|closed/i.test(cause))
32
+ return "unavailable";
33
+ return "server error";
34
+ }
35
+ /** Several legs' causes as one: each shown, without repeats ("busy; timed out"). */
36
+ export function shownCauses(causes) {
37
+ return [...new Set(causes.filter(Boolean).map(shownCause))].join("; ");
38
+ }
39
+ /** Capitalize the first letter: a role opens a sentence ("The primary model's server…"). */
40
+ export function sentence(s) {
41
+ return s ? s[0].toUpperCase() + s.slice(1) : s;
42
+ }
@@ -19,6 +19,12 @@ const CODEACT_LINES = [
19
19
  " call per item. Never for edits, commits, pushes, network or messages: those stay normal steps. A step the check",
20
20
  " refuses runs on tools and the report says why.",
21
21
  ];
22
+ /** The external lane's lines in the brief (Waterfall teams): steps that need the open web go to a remote agent. */
23
+ const EXTERNAL_LINES = [
24
+ "- A step that needs the live web, a browser, an outside site or long outside research: delegate_task it with model",
25
+ " \"external-executor\" (a remote agent with its own browser and sandbox). It takes minutes and is metered: only when",
26
+ " the open web is required, never for repo, file or fleet work, and give it the full context it needs.",
27
+ ];
22
28
  /** The planner's standing brief. Identical every turn for a given team, so it stays in the prompt cache. */
23
29
  export function plannerBrief(team) {
24
30
  if (team.prompt)
@@ -37,6 +43,7 @@ export function plannerBrief(team) {
37
43
  " as many as it has free lanes; a brief it hands back, do yourself. Keep decisions, edits and the synthesis here.",
38
44
  "- No fan-out for one step, a step quicker than ~20 s inline, or a chain where each step needs the last.",
39
45
  ...(team.codeact ? CODEACT_LINES : []),
46
+ ...(team.external ? EXTERNAL_LINES : []),
40
47
  "- Do yourself: a single quick tool call, anything that needs reading an image (only you read images), and the final",
41
48
  " answer.",
42
49
  "- Check every report before marking the step done (task_update); fix or redo a wrong one instead of passing it on.",
@@ -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
  }
@@ -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
+ }
@@ -78,8 +78,17 @@ function gatewayBinary(home) {
78
78
  catch { /* no link */ }
79
79
  return { line: dangling ? `not linked (${link} → ${readlinkSync(link)} dangles)` : "not linked", toolchain: "unmanaged (legacy resolution: the gateway's PATH)" };
80
80
  }
81
- /** The executable image a live pid has mapped: the first txt entry lsof reports (-a: lsof ORs its selectors without it). */
81
+ /** The executable image a live pid has mapped: /proc/<pid>/exe on Linux, else the first txt entry lsof reports (-a: lsof
82
+ * ORs its selectors without it). */
82
83
  function mappedExecutable(pid) {
84
+ if (process.platform === "linux") {
85
+ try {
86
+ return readlinkSync(`/proc/${pid}/exe`);
87
+ }
88
+ catch {
89
+ return undefined;
90
+ }
91
+ }
83
92
  const r = spawnSync("/usr/sbin/lsof", ["-nP", "-a", "-p", String(pid), "-d", "txt", "-Fn"], { encoding: "utf8", timeout: 5000 });
84
93
  return r.status === 0 ? r.stdout.split("\n").find((l) => l.startsWith("n"))?.slice(1) : undefined;
85
94
  }
@@ -204,13 +204,12 @@ class JsonBackend {
204
204
  // ---------------------------------------------------------------------------
205
205
  let _backend = null;
206
206
  let _backendHome = null;
207
- async function openSqlite(fs) {
207
+ async function openSqlite() {
208
208
  try {
209
209
  const sqlite = await nodeImport("node:sqlite");
210
210
  if (!sqlite?.DatabaseSync)
211
211
  return null;
212
212
  const dbPath = operatorPath("state", "state.db");
213
- fs.mkdirSync(operatorPath("state"), { recursive: true });
214
213
  const db = new sqlite.DatabaseSync(dbPath);
215
214
  db.exec("CREATE TABLE IF NOT EXISTS sessions_meta (id TEXT PRIMARY KEY, mtime REAL NOT NULL)");
216
215
  db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS sessions_fts USING fts5(id UNINDEXED, body)");
@@ -229,7 +228,8 @@ async function backend() {
229
228
  _backend = null;
230
229
  }
231
230
  const { fs } = await fsp();
232
- _backend = (await openSqlite(fs)) ?? new JsonBackend(operatorPath("state", "session-index.json"), fs);
231
+ fs.mkdirSync(operatorPath("state"), { recursive: true });
232
+ _backend = (await openSqlite()) ?? new JsonBackend(operatorPath("state", "session-index.json"), fs);
233
233
  _backendHome = home;
234
234
  return _backend;
235
235
  }
@@ -93,7 +93,8 @@ export function withPermissions(inner, policy, opts = {}) {
93
93
  else {
94
94
  if (line)
95
95
  sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name}` } });
96
- approved = opts.approve ? await opts.approve(name, args) : false; // no approver ⇒ fail-safe deny
96
+ const ctx = policy.asksEachCall(name) ? { line: `${policy.currentTier()} seat`, once: true } : undefined;
97
+ approved = opts.approve ? await opts.approve(name, args, ctx) : false; // no approver ⇒ fail-safe deny
97
98
  if (!approved) {
98
99
  tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch }, argHash);
99
100
  return refuse(DENIED(name, opts.approve ? "user" : "no-approver"));
@@ -3,7 +3,7 @@
3
3
  // zero gates, zero overhead — programmatic/embedded callers opt in explicitly), but the SHIPPED
4
4
  // settings default is "gated" (2026-10-23): mutating tools ask the user to Allow/Deny on spawn,
5
5
  // Claude Code-style; shift+tab or settings leave it (permissions/modes.ts). "audit" allows-but-records.
6
- import { registrySafeTools, tierAllows } from "./tier.js";
6
+ import { registrySafeTools, tierAllows, tierAsks } from "./tier.js";
7
7
  import { signatureLine } from "./signature.js";
8
8
  // Read-only tools (registry `safe: true`) — never gated unless a rule says otherwise. DERIVED from the
9
9
  // registry, never hand-copied: the old 5-item copy drifted and gated/plan/dream/manual denied 12 safe tools.
@@ -90,6 +90,10 @@ export class PermissionPolicy {
90
90
  allowsTool(name) {
91
91
  return tierAllows(this.tier, name);
92
92
  }
93
+ /** True iff this seat may call `name` only with a fresh approval each time: the approval is never remembered. */
94
+ asksEachCall(name) {
95
+ return tierAsks(this.tier, name);
96
+ }
93
97
  /** Which human-signature line a call crosses (money/prod/destructive), or null. Live only while
94
98
  * enforcing (never for the fully-inert local owner). The wrapper reports this on an approval. */
95
99
  signatureLineFor(name, args) {
@@ -105,12 +109,15 @@ export class PermissionPolicy {
105
109
  }
106
110
  /** The decision for one tool call. Precedence: tier ceiling (a denied tool can't be granted by any
107
111
  * rule) → human-signature line (money/prod/destructive always ask, beating a rule/mode; under plan
108
- * review the approved plan answers — see planAnswer) → per-tool rule → allowlist pattern match → mode. */
112
+ * review the approved plan answers — see planAnswer) → tier ask (a seat's approval-only tools) → per-tool rule →
113
+ * allowlist pattern match → mode. */
109
114
  decide(name, args) {
110
115
  if (!this.allowsTool(name))
111
116
  return "deny"; // tier ceiling — absolute, above rules and mode
112
117
  if (this.signatureLineFor(name, args))
113
118
  return "ask"; // human-signature line — always a human, beats rules
119
+ if (tierAsks(this.tier, name))
120
+ return "ask"; // granted to this seat only with approval, each call
114
121
  const rule = this.rules[name];
115
122
  if (rule)
116
123
  return rule; // explicit override within the tier
@@ -26,7 +26,11 @@ const ENTERPRISE_MUTATING = [
26
26
  "memory_store", "skill_save",
27
27
  "artifact_create", "craft_update", "craft_delete",
28
28
  ];
29
- const ENTERPRISE_ALLOW = new Set([...SAFE_TOOLS, ...ENTERPRISE_MUTATING]);
29
+ // Enterprise seat, granted only with approval: every call asks, whatever the mode, rules or allow patterns
30
+ // (policy.ts decide). The Beam drop tools fetch over the LAN and write ~/Beam/in (open, get) or send a signed receipt
31
+ // (ack); owner decision 2026-11-30. beam_send (file egress) stays outside the seat, like file_upload.
32
+ const ENTERPRISE_ASK = ["beam_open", "beam_get", "beam_ack"];
33
+ const ENTERPRISE_ALLOW = new Set([...SAFE_TOOLS, ...ENTERPRISE_MUTATING, ...ENTERPRISE_ASK]);
30
34
  // Readonly seat: inspection only = the registry-safe tools minus READONLY_SAFE_EXCLUDED. Every member is
31
35
  // registry `safe: true`, so no workspace-mutating tool can be in it — widening it means marking a tool safe
32
36
  // in the registry, which a dedicated permissions test holds to account.
@@ -45,3 +49,7 @@ export function tierAllows(tier, tool) {
45
49
  default: return false;
46
50
  }
47
51
  }
52
+ /** Whether `tier` may call `tool` only with a fresh approval each time. */
53
+ export function tierAsks(tier, tool) {
54
+ return tier === "enterprise" && ENTERPRISE_ASK.includes(tool);
55
+ }
@@ -97,5 +97,94 @@ export async function craftDelete(args, auth) {
97
97
  const r = await temple.remove(id, auth);
98
98
  return r.ok ? `deleted craft ${id}` : `error: ${r.error}`;
99
99
  }
100
+ // ── rooms: working on one craft with other agents and its owner (temple.room) ──────────────────────────────────────
101
+ const ROOM_ACTIONS = ["join", "get", "post", "task_add", "claim", "release", "task_state", "edit", "wait", "link"];
102
+ function roomText(r, recent = 12) {
103
+ const tasks = r.tasks.map((t) => `- ${t.id} [${t.state}] ${t.title}${t.target ? ` · ${t.target}` : ""}${t.owner_handle ? ` · ${t.owner_handle}${t.lease_until ? ` (lease until ${t.lease_until})` : ""}` : ""} · rev ${t.rev}`);
104
+ const said = r.events.filter((e) => e.kind === "message" || e.kind === "conflict").slice(-recent)
105
+ .map((e) => ` #${e.seq} ${e.handle ?? "?"}${e.author_kind === "human" ? " (person)" : ""}: ${e.kind === "conflict" ? `conflict on ${str(e.data.path)}` : e.body}`);
106
+ return [`room of ${r.artifact.id} · "${r.artifact.title}" · v${r.artifact.version} · you can ${r.access} · cursor ${r.cursor}`,
107
+ `people: ${r.participants.map((p) => `${p.handle} (${p.kind})`).join(", ") || "none yet"}`,
108
+ `tasks:\n${tasks.join("\n") || " none"}`, said.length ? `recent:\n${said.join("\n")}` : "recent: nothing said yet",
109
+ `page for people: ${temple.room.link(r.artifact.id)}`].join("\n");
110
+ }
111
+ /** One tool for the room: join/get/post/task_add/claim/release/task_state/edit/wait/link. */
112
+ export async function craftRoom(args, auth) {
113
+ const action = str(args.action);
114
+ const id = str(args.id);
115
+ if (!ROOM_ACTIONS.includes(action))
116
+ return `error: craft_room needs \`action\`: ${ROOM_ACTIONS.join(" | ")}`;
117
+ if (!id)
118
+ return "error: craft_room needs `id` (the craft's id)";
119
+ if (action === "link")
120
+ return temple.room.link(id);
121
+ const denied = gate(auth);
122
+ if (denied)
123
+ return `error: ${denied}`;
124
+ const handle = str(args.handle) || "operator";
125
+ const taskId = str(args.task_id);
126
+ const need = (k) => `error: craft_room ${action} needs \`${k}\``;
127
+ switch (action) {
128
+ case "join":
129
+ case "get": {
130
+ const r = action === "join" ? await temple.room.join(id, handle, auth) : await temple.room.get(id, undefined, auth);
131
+ return r.ok ? roomText(r.value) : `error: ${r.error}`;
132
+ }
133
+ case "post": {
134
+ if (!str(args.body))
135
+ return need("body");
136
+ const r = await temple.room.post(id, handle, str(args.body), auth);
137
+ return r.ok ? `posted #${r.value.seq} as ${handle}` : `error: ${r.error}`;
138
+ }
139
+ case "task_add": {
140
+ if (!str(args.title))
141
+ return need("title");
142
+ const r = await temple.room.taskAdd(id, handle, { title: str(args.title), detail: str(args.detail) || undefined, target: str(args.target) || undefined }, auth);
143
+ return r.ok ? `added task ${r.value.id}${r.value.target ? ` on ${r.value.target}` : ""}` : `error: ${r.error}`;
144
+ }
145
+ case "claim":
146
+ case "release": {
147
+ if (!taskId)
148
+ return need("task_id");
149
+ const r = action === "claim" ? await temple.room.claim(id, handle, taskId, auth) : await temple.room.release(id, handle, taskId, auth);
150
+ if (!r.ok)
151
+ return r.code === "claimed" ? `error: ${r.error} — pick another task, or wait (craft_room wait) and try again` : `error: ${r.error}`;
152
+ return action === "claim" ? `you hold ${r.value.target ?? `task ${r.value.id}`} until ${r.value.lease_until ?? "you release it"} (rev ${r.value.rev}); each edit renews it` : `released task ${r.value.id}`;
153
+ }
154
+ case "task_state": {
155
+ const state = str(args.state);
156
+ if (!taskId || !/^(review|done|blocked|open)$/.test(state))
157
+ return need("task_id` and `state` (review | done | blocked | open)");
158
+ const r = await temple.room.taskState(id, handle, taskId, state, Number(args.rev), str(args.note) || undefined, auth);
159
+ if (!r.ok)
160
+ return r.code === "stale_task" ? `error: ${r.error} — craft_room get, then retry with the task's current rev` : `error: ${r.error}`;
161
+ return `task ${r.value.id} is ${r.value.state} (rev ${r.value.rev})`;
162
+ }
163
+ case "edit": {
164
+ const path = str(args.path);
165
+ const base = Number(args.base_version);
166
+ if (!path || typeof args.content !== "string" || !Number.isInteger(base))
167
+ return need("path`, `content` and `base_version");
168
+ const r = await temple.room.edit(id, handle, path, args.content, base, auth);
169
+ if (r.ok)
170
+ return `saved ${path} as v${r.value.artifact.version}${r.value.rebased_from ? ` (applied on top of others' changes since v${r.value.rebased_from})` : ""}`;
171
+ if (r.code === "version_conflict") {
172
+ const live = (r.live ?? {});
173
+ return `conflict: ${path} changed in v${live.changed_in ?? "?"}${live.by ? ` by ${live.by}` : ""} after your base v${base}. Nothing was written. ` +
174
+ `Merge your change into the live file below and edit again with base_version ${live.version}.\n--- live ${path} (v${live.version}) ---\n${live.content ?? "(not shown: binary or over 256 KB; read it from the craft)"}`;
175
+ }
176
+ return `error: ${r.error}`;
177
+ }
178
+ case "wait": {
179
+ const r = await temple.room.wait(id, Number(args.after) || 0, Math.min(Math.max(Number(args.timeout_secs) || 20, 1), 25), auth);
180
+ if (!r.ok)
181
+ return `error: ${r.error}`;
182
+ if (!r.value.events.length)
183
+ return `nothing new (cursor ${r.value.cursor})`;
184
+ return r.value.events.map((e) => `#${e.seq} ${e.kind} ${e.handle ?? ""}: ${e.body || JSON.stringify(e.data)}`).join("\n") + `\ncursor ${r.value.cursor}`;
185
+ }
186
+ }
187
+ return `error: unknown action ${action}`;
188
+ }
100
189
  // Exposed for tests (pure helpers that don't touch the network).
101
- export const _internal = { resolveScopes };
190
+ export const _internal = { resolveScopes, roomText };