@0perator/operator 0.1.222 → 0.1.261

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 (110) hide show
  1. package/README.md +6 -5
  2. package/dashboard/server.mjs +1 -1
  3. package/dist/acp/agent.js +320 -53
  4. package/dist/acp/auth.js +44 -0
  5. package/dist/acp/config-options.js +34 -0
  6. package/dist/acp/prompt.js +41 -0
  7. package/dist/acp/run.js +116 -10
  8. package/dist/acp/tool-map.js +48 -0
  9. package/dist/auth/byo.js +125 -0
  10. package/dist/auth/client.js +12 -6
  11. package/dist/auth/commands.js +71 -3
  12. package/dist/auth/identity.js +136 -0
  13. package/dist/auth/store.js +7 -5
  14. package/dist/autonomy/board.js +3 -2
  15. package/dist/autonomy/cron.js +332 -0
  16. package/dist/autonomy/delegate.js +168 -0
  17. package/dist/autonomy/dream.js +1 -1
  18. package/dist/autonomy/index.js +16 -2
  19. package/dist/autonomy/media-robot.js +137 -0
  20. package/dist/autonomy/profile.js +77 -0
  21. package/dist/autonomy/routines.js +5 -4
  22. package/dist/autonomy/session-factory.js +19 -10
  23. package/dist/background/index.js +8 -1
  24. package/dist/browser/cdp.js +266 -0
  25. package/dist/browser/session.js +286 -0
  26. package/dist/cli.js +207 -106
  27. package/dist/compose/client.js +56 -0
  28. package/dist/config/brand.js +3 -3
  29. package/dist/config/home.js +70 -0
  30. package/dist/config/managed.js +230 -0
  31. package/dist/config/persona.js +243 -21
  32. package/dist/config/scaffold.js +142 -0
  33. package/dist/config/settings.js +87 -20
  34. package/dist/config/skills-index.js +175 -0
  35. package/dist/consolidation/scheduler.js +10 -7
  36. package/dist/consolidation/sleep.js +17 -3
  37. package/dist/engine/agent.js +231 -21
  38. package/dist/engine/aurora.js +79 -14
  39. package/dist/engine/batch-scheduler.js +128 -0
  40. package/dist/engine/compaction.js +129 -2
  41. package/dist/engine/computer-event.js +139 -0
  42. package/dist/engine/continuation.js +55 -0
  43. package/dist/engine/contract.js +3 -1
  44. package/dist/engine/grandmaster.js +13 -3
  45. package/dist/engine/json-repair.js +105 -0
  46. package/dist/engine/messages.js +52 -5
  47. package/dist/engine/redact.js +25 -0
  48. package/dist/engine/rolling-summary.js +28 -11
  49. package/dist/engine/router-adapter.js +2 -0
  50. package/dist/engine/unrestricted.js +51 -0
  51. package/dist/engine/verify-gate.js +6 -0
  52. package/dist/enterprise/cli.js +137 -0
  53. package/dist/flywheel/processor.js +30 -2
  54. package/dist/flywheel/secret-gate.js +123 -0
  55. package/dist/index.browser.js +4 -0
  56. package/dist/index.js +4 -0
  57. package/dist/mcp/index.js +18 -24
  58. package/dist/memory/index.js +0 -0
  59. package/dist/memory/session-index.js +324 -0
  60. package/dist/memory/session-rewind.js +92 -0
  61. package/dist/memory/state-maintenance.js +441 -0
  62. package/dist/observability/index.js +3 -3
  63. package/dist/permissions/audit.js +4 -1
  64. package/dist/permissions/index.js +24 -12
  65. package/dist/permissions/policy.js +4 -3
  66. package/dist/permissions/tier.js +31 -14
  67. package/dist/remote/host.js +9 -2
  68. package/dist/router/models.js +62 -2
  69. package/dist/selfimprove/index.js +9 -7
  70. package/dist/session.js +129 -42
  71. package/dist/skills/catalogue.js +167 -0
  72. package/dist/telemetry/audit-verify.js +94 -0
  73. package/dist/telemetry/events.js +92 -7
  74. package/dist/telemetry/lifecycle.js +18 -0
  75. package/dist/tools/computer.js +1 -1
  76. package/dist/tools/deferred.js +117 -0
  77. package/dist/tools/executor.js +27 -23
  78. package/dist/tools/memory.js +117 -0
  79. package/dist/tools/mutating.js +6 -0
  80. package/dist/tools/registry.js +1022 -46
  81. package/dist/tools/sandbox.js +63 -17
  82. package/dist/tools/searxng.js +2 -2
  83. package/dist/tools/shell-session.js +36 -1
  84. package/dist/tools/tool-output-spill.js +4 -4
  85. package/dist/ui/ActivitySpinner.js +17 -6
  86. package/dist/ui/App.js +36 -14
  87. package/dist/ui/ArtifactPicker.js +109 -0
  88. package/dist/ui/Composer.js +39 -8
  89. package/dist/ui/Markdown.js +5 -3
  90. package/dist/ui/MouseProvider.js +99 -19
  91. package/dist/ui/QuestionPrompt.js +24 -3
  92. package/dist/ui/ThinkingSpinner.js +9 -5
  93. package/dist/ui/ToolStep.js +17 -12
  94. package/dist/ui/Transcript.js +28 -9
  95. package/dist/ui/capabilities.js +0 -9
  96. package/dist/ui/listhit.js +23 -0
  97. package/dist/ui/mouse.js +22 -0
  98. package/dist/ui/osc.js +7 -4
  99. package/dist/ui/progressbar.js +46 -0
  100. package/dist/ui/shimmer.js +43 -0
  101. package/dist/ui/theme.js +2 -0
  102. package/dist/ui/tick.js +48 -0
  103. package/dist/ui/toolicons.js +69 -0
  104. package/dist/ui/useInputHistory.js +3 -3
  105. package/dist/util/slash.js +1 -0
  106. package/dist/vault/cli.js +48 -0
  107. package/dist/vault/store.js +157 -0
  108. package/dist/vault/tool.js +50 -0
  109. package/package.json +3 -5
  110. package/CHANGELOG.md +0 -1629
@@ -0,0 +1,128 @@
1
+ // BTX — the shared batch-execution scheduler (mission spec: _ai-docs/features/2026-10-07-batch-exec-v2.md).
2
+ // ONE pure, node-free DAG executor that ToolExecutor, withPermissions and withMcp all delegate to, so
3
+ // batch ordering holds at EVERY layer of the composition (the race this kills: withPermissions used to
4
+ // Promise.all per-call execute(), bypassing the walk the 0.1.225 fix introduced).
5
+ //
6
+ // Semantics (superset of the old walk):
7
+ // • Results land in INPUT ORDER in slots; onSettle(index, result) fires the moment each call finishes.
8
+ // • Each call declares resource keys (path-ish args) or a device class. Two calls CONFLICT when a
9
+ // key equals or is a path prefix of the other (dir vs child), when either is a device barrier, or
10
+ // both are unknown-name writes with no keys (conservative: no keys + mutating = device-class).
11
+ // • READS (pure ops) run alongside anything that cannot change what they observe: they wait only for
12
+ // prior WRITES on conflicting keys. WRITES wait for everything conflicting (read-after-write is a
13
+ // read's concern; write-after-write and write-after-read are this write's concern) — serialized
14
+ // per-resource in INPUT ORDER via the resource's tail promise.
15
+ // • Barrier tools (bash/shell_exec/git_command/checkpoint/computer_*/browser*/browser_vault/…) can
16
+ // touch ANYTHING and share one persistent shell — they run alone, in input order.
17
+ // • A rejected/denied run resolves as a string (executor contract: resolve-not-reject); one call's
18
+ // failure never strands its dependents — the chain advances regardless.
19
+ // Pure JS: no node builtins, no asyncLocalStorage — safe for the neutral engine bundle (run-jsc).
20
+ const BARRIER_EXACT = new Set([
21
+ "bash", "shell_exec", "shell_background", "bash_kill",
22
+ "git_command", "checkpoint", "tool_call",
23
+ "delegate_task", // a whole sub-agent session with the full tool set: it can touch anything, so it runs alone like bash
24
+ "app_open", "app_activate", "computer_applescript", "computer_type", "computer_key", "computer_click", "computer_screenshot",
25
+ ]);
26
+ const BARRIER_PREFIX = ["computer_", "browser", "shell", "mcp__"]; // browser_vault included: it drives the same browser device
27
+ export function defaultClassify(name, isSafe) {
28
+ return (n) => {
29
+ if (BARRIER_EXACT.has(n))
30
+ return "barrier";
31
+ for (const p of BARRIER_PREFIX)
32
+ if (n.startsWith(p) || n.includes("__" + p))
33
+ return "barrier";
34
+ return isSafe(n) ? "read" : "write";
35
+ };
36
+ }
37
+ /** Path-ish arg keys: any string value under a path-named arg, normalized to a comparable key.
38
+ * A MUTATING call with no path keys gets a per-name lock — injected by runBatch (which knows the
39
+ * class), never here: reads must not acquire locks or they could never pair with their writes. */
40
+ export function defaultKeys(_name, args) {
41
+ const out = [];
42
+ for (const [k, v] of Object.entries(args ?? {})) {
43
+ if (typeof v === "string" && v && /path|dir|file|cwd|target|token|handle/i.test(k))
44
+ out.push(normKey(v));
45
+ }
46
+ return out;
47
+ }
48
+ function normKey(p) {
49
+ const t = p.replace(/\\/g, "/").replace(/\/{2,}/g, "/");
50
+ const trimmed = t.replace(/\/+$/, "");
51
+ return trimmed || "/";
52
+ }
53
+ function conflicts(a, b) {
54
+ if (a === b)
55
+ return true;
56
+ if (a.startsWith("lock:") || b.startsWith("lock:"))
57
+ return a === b;
58
+ return a.startsWith(b + "/") || b.startsWith(a + "/");
59
+ }
60
+ /** Schedule a whole batch; resolves when every slot has its result (input order). */
61
+ export function runBatch(calls, opts) {
62
+ const results = new Array(calls.length);
63
+ const done = [];
64
+ const writeTails = new Map(); // resource key -> last WRITE on it
65
+ const inflight = new Set(); // everything not yet settled (barrier gate)
66
+ let afterBarrier = Promise.resolve(); // every op must clear the last barrier
67
+ for (let i = 0; i < calls.length; i++) {
68
+ const c = calls[i];
69
+ const kind = opts.classify(c.name);
70
+ let keys = kind === "barrier" ? [] : opts.keys(c.name, c.args);
71
+ // no-path MUTATIONS (memory_store, task_add, cron create…): serialize per tool-name lock.
72
+ // Reads never take the lock — a path-less read pairs with nothing and is safe to overlap.
73
+ if (kind === "write" && keys.length === 0)
74
+ keys = ["lock:" + c.name];
75
+ const gate = [];
76
+ if (kind === "barrier") {
77
+ gate.push(afterBarrier);
78
+ for (const p of inflight)
79
+ gate.push(p); // a barrier runs ALONE: waits for everything prior
80
+ }
81
+ else if (kind === "read") {
82
+ gate.push(afterBarrier); // barriers can change anything a read observes
83
+ if (!keys.length) {
84
+ for (const t2 of writeTails.values())
85
+ gate.push(t2); // path-less read: any prior write may target it
86
+ }
87
+ for (const k of keys) {
88
+ // A read waits only for PRIOR WRITES on overlapping resources. Prior READS never matter
89
+ // (nothing to serialize), and a write after a read must NOT wait for the read: the model
90
+ // consumes results next turn; any pre/post read value is a valid serialization.
91
+ for (const [wk, wt] of writeTails)
92
+ if (conflicts(k, wk))
93
+ gate.push(wt);
94
+ }
95
+ }
96
+ else {
97
+ gate.push(afterBarrier);
98
+ for (const k of keys) {
99
+ for (const [wk, wt] of writeTails)
100
+ if (conflicts(k, wk))
101
+ gate.push(wt);
102
+ }
103
+ }
104
+ const run = Promise.all(gate).then(async () => {
105
+ let r;
106
+ try {
107
+ r = await opts.runOne(c);
108
+ }
109
+ catch (e) {
110
+ r = `error running ${c.name}: ${e?.message ?? String(e)}`;
111
+ }
112
+ results[i] = r;
113
+ try {
114
+ opts.onSettle?.(i, r);
115
+ }
116
+ catch { /* UI never breaks execution */ }
117
+ });
118
+ if (kind === "barrier")
119
+ afterBarrier = run; // everything later waits behind this barrier
120
+ else if (kind === "write")
121
+ for (const k of keys)
122
+ writeTails.set(k, run);
123
+ inflight.add(run);
124
+ run.then(() => inflight.delete(run));
125
+ done.push(run);
126
+ }
127
+ return Promise.all(done).then(() => results);
128
+ }
@@ -187,6 +187,126 @@ function dropLeadingOrphanTools(messages) {
187
187
  * Call this proactively when needsCompaction() is true, or directly (forced) on a 400 with
188
188
  * no bigger endpoint to route to (SPEC §4 self-heal) or on `/compact`.
189
189
  */
190
+ // ── GW-31 · CONTEXT SURGERY — deterministic anchors + verbatim user voice ─────────────────────────
191
+ // The summarizer's prompt already DEMANDS verbatim identifiers (the "load-bearing rule") and the
192
+ // 9-section contract asks for the user's own asks. Both are model-discretion promises — an honest
193
+ // one, but a promise is not a guarantee. These functions add the HARD backstop: mechanically
194
+ // extracted, model-independent, appended to every compaction. Rationale (measured this week):
195
+ // a lossy summarizer that mangles one SHA/flag/PR poisons the next 100 turns (and becomes a
196
+ // training-set corruption vector through the flywheel capture) — while re-prefilling the whole
197
+ // evicted span to "be safe" costs minutes at depth. Extraction costs microseconds. It also makes
198
+ // anchor LOSS AUDITABLE: anchorLossAudit() is the primitive the canary/flywheel gates use.
199
+ // Pure + browser-safe (no node imports) — compaction.ts must stay in the neutral engine bundle.
200
+ const ANCHOR_CATS = [
201
+ ["git-sha", /\b(?=[0-9a-f]{7,40}\b)(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b/g], // hex, >=7, needs a letter (kills bare-number false hits)
202
+ ["uuid", /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/g],
203
+ ["issue-ref", /(?:\b[a-zA-Z0-9_.\/-]+)?#\d{1,7}\b/g], // PR/issue refs (repo-scoped form kept intact)
204
+ ["version", /\bv?\d+\.\d+\.\d+(?:[-+][\w.]+)?\b/g],
205
+ ["cli-flag", /(?:^|[\s,"'`])(--?[a-z][\w-]*(?:=[\S]{1,40})?)/g],
206
+ ["path", /(?:[\w.\-~]+\/)+[\w.\-]+(?:\.[A-Za-z]\w{0,9})?/g],
207
+ ["url", /\bhttps?:\/\/[^\s"'<>\])]+/g],
208
+ ["unit-number", /\b\d[\d,._]*\s?(?:tok\/s|tokens|ms|MB|GB|KB|K\b|%)(?=[\s,.;:)\]}"]|$)/gi],
209
+ ];
210
+ const ANCHOR_CAP_PER_CAT = 40; // each category's ceiling
211
+ const ANCHOR_CAP_TOTAL_CHARS = 2400; // the whole block's ceiling — bounded so fold costs stay trivial
212
+ function anchorSource(m) {
213
+ const parts = [];
214
+ if (typeof m.content === "string" && m.content)
215
+ parts.push(m.content);
216
+ const tcs = m.tool_calls;
217
+ for (const tc of tcs ?? [])
218
+ parts.push(`${tc.function?.name ?? ""} ${tc.function?.arguments ?? ""}`);
219
+ return parts.join("\n");
220
+ }
221
+ function extractAnchorsCapped(span, capPerCat) {
222
+ const out = new Map();
223
+ for (const [cat, re] of ANCHOR_CATS) {
224
+ const seen = new Set();
225
+ for (const m of span) {
226
+ const text = anchorSource(m);
227
+ if (!text)
228
+ continue;
229
+ re.lastIndex = 0;
230
+ let mm;
231
+ while ((mm = re.exec(text)) && seen.size < capPerCat) {
232
+ const v = (mm[1] ?? mm[0]).replace(/[,.;:]$/, "");
233
+ if (v.length > 100 || /^\/{2,}/.test(v) || v === "./" || v === "../")
234
+ continue;
235
+ seen.add(v);
236
+ }
237
+ }
238
+ if (seen.size)
239
+ out.set(cat, [...seen]);
240
+ }
241
+ return out;
242
+ }
243
+ /** Extract every high-value identifier from a message span, per category, first-seen order, soft-capped
244
+ * at ANCHOR_CAP_PER_CAT — the RENDER budget for the index block inside a summary. */
245
+ export function extractAnchors(span) {
246
+ return extractAnchorsCapped(span, ANCHOR_CAP_PER_CAT);
247
+ }
248
+ // The AUDIT view is 25x wider than the render view. The old coupling — audit sharing the render cap —
249
+ // made identifier-dense spans report a FALSE GREEN: everything past 40/category was invisible to both
250
+ // sides of the comparison. N1 (verified compaction): measure wide, render bounded, REPAIR the overflow.
251
+ const AUDIT_CAP_PER_CAT = 1000;
252
+ const REPAIR_CAP = 200;
253
+ /** Render the anchor index as a compact, labeled block ("" when nothing found). */
254
+ export function renderAnchorIndex(span) {
255
+ const cats = extractAnchors(span);
256
+ if (!cats.size)
257
+ return "";
258
+ let s = "";
259
+ for (const [cat, vals] of cats)
260
+ s += `<${cat}> ${vals.join(", ")}\n`;
261
+ if (s.length > ANCHOR_CAP_TOTAL_CHARS)
262
+ s = s.slice(0, ANCHOR_CAP_TOTAL_CHARS) + " [truncated]\n";
263
+ return "\n\nANCHORS (mechanically extracted — verbatim, model-independent):\n" + s;
264
+ }
265
+ /** The audit primitive: anchors present in `pre` but NOT in `post` — i.e. lost through compaction.
266
+ * [] = the transformation preserved every identifier. Used by tests, the update canary, and the
267
+ * flywheel integrity gate (a trajectory whose turn crossed compaction loses its anchor set). */
268
+ export function anchorLossAudit(pre, post) {
269
+ const postText = post.map(anchorSource).join("\n");
270
+ const missing = [];
271
+ for (const vals of extractAnchorsCapped(pre, AUDIT_CAP_PER_CAT).values())
272
+ for (const v of vals)
273
+ if (!postText.includes(v))
274
+ missing.push(v);
275
+ return missing;
276
+ }
277
+ /** N1 as a REUSABLE guarantee: audit the summary against the evicted span (WIDE view), force-append
278
+ * spilled anchors deterministically, report the honest residual. compact() calls it; session.ts's
279
+ * INSTANT (pre-written) compaction path calls it too — the fast path must not skip the safety net
280
+ * it exists to provide (audit-engine finding H2: the instant branch inserted the raw blob). */
281
+ export function applyAnchorVerification(summaryMsg, evicted, outAll) {
282
+ let missing = anchorLossAudit(evicted, outAll);
283
+ let repaired = 0;
284
+ if (missing.length) {
285
+ const carry = missing.slice(0, REPAIR_CAP);
286
+ repaired = carry.length;
287
+ summaryMsg.content += `\n\nANCHOR REPAIR (${missing.length} spilled past the index caps — verbatim): ${carry.join(", ")}`
288
+ + (missing.length > REPAIR_CAP ? ` [+${missing.length - REPAIR_CAP} uncarried — identifier-dense span; offload before training]` : "");
289
+ missing = anchorLossAudit(evicted, outAll);
290
+ }
291
+ return { repaired, residual: missing.length };
292
+ }
293
+ /** Verbatim user-voice: the FIRST user message (the original mission — the thing most often lost and
294
+ * most catastrophic to lose: instruction drift is how long autonomous runs go off rails, this week's
295
+ * 76-min Pando marathon is the cautionary tale) PLUS the last k user messages (current intent). Middle
296
+ * follow-ups are NOT duplicated here — the summarizer's FACTS/STATE already carries them; head+tail is
297
+ * exactly the shape frontier compaction uses (objective pinned at head, recency at tail) and keeps the
298
+ * block bounded regardless of span depth. */
299
+ export function verbatimUserTail(span, k = 3, capPerMsg = 400) {
300
+ const users = span.filter((m) => m.role === "user" && typeof m.content === "string" && m.content.trim().length > 0);
301
+ if (!users.length)
302
+ return "";
303
+ const head = users[0];
304
+ const tail = users.slice(-k);
305
+ const chosen = [...new Set([head, ...tail])]; // first + last k, deduped, in order (<=k+1 messages)
306
+ const lines = chosen.map((m) => `> ${m.content.replace(/\s+/g, " ").slice(0, capPerMsg)}`);
307
+ const label = chosen.length === 1 ? "original request" : `original + last ${chosen.length - 1} request(s)`;
308
+ return "\n\nUSER VOICE (verbatim, " + label + "):\n" + lines.join("\n");
309
+ }
190
310
  export async function compact(conversation, opts) {
191
311
  const minKeep = opts.minKeepTurns ?? 4;
192
312
  const starts = turnStarts(conversation);
@@ -216,9 +336,16 @@ export async function compact(conversation, opts) {
216
336
  // real history with a bare "[Compacted summary of N]" header. The caller retries; nothing is lost.
217
337
  if (!summaryText)
218
338
  return [...conversation];
339
+ // GW-31: the deterministic backstop rides with the model's note — identifiers and the user's own
340
+ // words are preserved by CODE, not by asking nicely. Dedup logic: the prompt rule stays (a good
341
+ // summary embeds specifics in prose); these blocks guarantee nothing critical was dropped.
219
342
  const summaryMsg = {
220
343
  role: "user", // never a 2nd system message — SPEC §1/§5
221
- content: `[Compacted summary of ${evicted.length} earlier message(s)]\n${summaryText}`,
344
+ content: `[Compacted summary of ${evicted.length} earlier message(s)]\n${summaryText}${renderAnchorIndex(evicted)}${verbatimUserTail(evicted)}`,
222
345
  };
223
- return [summaryMsg, ...kept];
346
+ // N1 VERIFIED COMPACTION: proof-of-preservation rides with the summary (shared helper now — the
347
+ // instant/prewritten path in session.ts MUST get the same guarantee, audit-engine §2).
348
+ const outAll = [summaryMsg, ...kept];
349
+ opts.onVerification?.(applyAnchorVerification(summaryMsg, evicted, outAll));
350
+ return outAll;
224
351
  }
@@ -0,0 +1,139 @@
1
+ // The 0perator Computer event stream (ENGINE_CONTRACT ≥ 1.4). A TYPED, RETAINED record of the agent's
2
+ // observable actions, so a surface — the desktop "Computer" pane, the web follower, a mobile watcher —
3
+ // can attach at ANY time, replay what already happened, then follow live. This is the gap the existing
4
+ // host callbacks leave: onToolStart / onToolResult / onToolBatch are ephemeral UI-render hints (flip
5
+ // this row, show this spinner) scoped to ONE attached renderer — a surface that connects late has
6
+ // already missed everything. The Computer stream is the opposite: a durable, normalized activity log
7
+ // keyed by a monotonic `seq`, so a reconnecting surface says "I have through seq N, give me N+1…".
8
+ //
9
+ // Layering: the ENGINE owns the shape (this file — type + stream + normalizer); the HOST owns the
10
+ // facts it alone knows (which `env` it runs in) and does the wiring, feeding the stream FROM the
11
+ // callback seams it already receives. That keeps the engine's hot path (agent.ts runTurn) untouched —
12
+ // there is still exactly one source of truth for "a tool ran" (the callbacks); this just classifies
13
+ // and retains them. The text/reasoning stream (onDelta / onReasoning) is a SEPARATE, complementary
14
+ // channel: this log is the ACTIONS, that one is the words.
15
+ /**
16
+ * A retained, replayable event stream over a bounded ring buffer. Deliberately NOT an EventEmitter: a
17
+ * plain emitter's late listener misses the backlog, which defeats the whole point ("let me watch — what
18
+ * has it done so far?"). subscribe() replays from a chosen seq, THEN follows live, in one call.
19
+ */
20
+ export class ComputerEventStream {
21
+ cap;
22
+ buf = [];
23
+ seqCounter = 0;
24
+ subs = new Set();
25
+ /** `cap` = max events retained for replay. A surface offline longer than this sees a gap, signalled
26
+ * by the first replayed event's seq being greater than its (have + 1). Default 1000. */
27
+ constructor(cap = 1000) {
28
+ this.cap = cap;
29
+ }
30
+ /** Record an event: assigns the next seq + ts, buffers it (evicting the oldest past cap), fans out to
31
+ * live subscribers, and returns the completed event. A throwing subscriber never breaks the turn. */
32
+ push(e) {
33
+ const full = { ...e, seq: ++this.seqCounter, ts: e.ts ?? Date.now() };
34
+ this.buf.push(full);
35
+ if (this.buf.length > this.cap)
36
+ this.buf.shift();
37
+ for (const fn of this.subs) {
38
+ try {
39
+ fn(full);
40
+ }
41
+ catch { /* isolate bad subscribers */ }
42
+ }
43
+ return full;
44
+ }
45
+ /** The highest seq assigned so far (0 = nothing yet). A surface reports this back to resume. */
46
+ get head() { return this.seqCounter; }
47
+ /** Everything still retained, oldest first — for a fresh surface that wants the whole backlog at once. */
48
+ snapshot() { return this.buf.slice(); }
49
+ /**
50
+ * Replay every retained event with seq > `afterSeq`, then follow live. Returns an unsubscribe fn.
51
+ * Pass 0 to replay the whole backlog. If the backlog no longer reaches afterSeq (aged out), replay
52
+ * starts at the oldest retained event — the caller detects the gap because its seq > afterSeq + 1.
53
+ */
54
+ subscribe(afterSeq, fn) {
55
+ for (const e of this.buf)
56
+ if (e.seq > afterSeq) {
57
+ try {
58
+ fn(e);
59
+ }
60
+ catch { /* isolate */ }
61
+ }
62
+ this.subs.add(fn);
63
+ return () => { this.subs.delete(fn); };
64
+ }
65
+ }
66
+ // ── Normalizer: engine tool name → Computer taxonomy ──────────────────────────────────────────────
67
+ // The engine's tool names are stable (registry.ts), so classification is a cheap name match with a
68
+ // sane default (file) for the long tail. A host that knows better (e.g. a browser-driving MCP tool)
69
+ // can always push a fully-formed event itself instead of going through the tracker.
70
+ /** Classify a tool call into { tool, action-hint } by name. Best-effort + total: never throws. */
71
+ export function classifyTool(name) {
72
+ const n = name.toLowerCase();
73
+ if (n === "bash" || n === "shell" || n.includes("exec") || n.includes("terminal") || n.includes("command"))
74
+ return "terminal";
75
+ if (n.includes("edit") || n === "write" || n.includes("str_replace") || n.includes("notebook"))
76
+ return "editor";
77
+ if (n.startsWith("browser") || n.includes("navigate") || n === "computer" || n.includes("chrome") || n.includes("page"))
78
+ return "browser";
79
+ // read / glob / grep / ls / file ops and everything else → the file lane
80
+ return "file";
81
+ }
82
+ /** Pull the most meaningful argument into a one-line title ("npm run build", "edit agent.ts", "GET url"). */
83
+ export function titleFor(name, args) {
84
+ const pick = (k) => (typeof args[k] === "string" ? args[k] : undefined);
85
+ const primary = pick("command") ?? pick("cmd") ?? pick("file_path") ?? pick("path") ?? pick("url") ??
86
+ pick("pattern") ?? pick("query") ?? pick("old_string");
87
+ const label = primary ? primary.replace(/\s+/g, " ").trim().slice(0, 120) : "";
88
+ return label ? `${name}: ${label}` : name;
89
+ }
90
+ /** Build the "start" event for a tool call (before it runs). `env` is the host's environment fact. */
91
+ export function startEvent(env, call) {
92
+ return {
93
+ env,
94
+ tool: classifyTool(call.name),
95
+ action: "start",
96
+ title: titleFor(call.name, call.args),
97
+ payload: { id: call.id, name: call.name, args: call.args, batchId: call.batchId },
98
+ };
99
+ }
100
+ /** Build the "end" event once a call resolves. Flags an error by the engine's "unknown → error string"
101
+ * convention (a result that begins "Error" / "error:"), so a surface can tint the row without parsing. */
102
+ export function resultEvent(env, call, result) {
103
+ const isError = /^\s*(error\b|error:)/i.test(result);
104
+ return {
105
+ env,
106
+ tool: classifyTool(call.name),
107
+ action: "end",
108
+ title: titleFor(call.name, call.args),
109
+ payload: { id: call.id, name: call.name, ok: !isError, resultChars: result.length, batchId: call.batchId },
110
+ };
111
+ }
112
+ /**
113
+ * Correlates the engine's start/result callbacks into paired Computer events. onToolResult only carries
114
+ * (id, result) — the name/args come from the matching onToolStart — so the tracker remembers the batch's
115
+ * pending calls by id. Wire it once to a stream; feed it the two callbacks. Two lines at the host:
116
+ * onToolStart: calls => tracker.onToolStart(calls)
117
+ * onToolResult: (id, result) => tracker.onToolResult(id, result)
118
+ */
119
+ export class ComputerEventTracker {
120
+ stream;
121
+ env;
122
+ pending = new Map();
123
+ constructor(stream, env = "sandbox") {
124
+ this.stream = stream;
125
+ this.env = env;
126
+ }
127
+ onToolStart(calls) {
128
+ for (const c of calls) {
129
+ this.pending.set(c.id, c);
130
+ this.stream.push(startEvent(this.env, c));
131
+ }
132
+ }
133
+ onToolResult(id, result) {
134
+ const c = this.pending.get(id);
135
+ this.pending.delete(id);
136
+ if (c)
137
+ this.stream.push(resultEvent(this.env, c, result));
138
+ }
139
+ }
@@ -0,0 +1,55 @@
1
+ // Turn-continuation (0.1.228). A turn's loop continues only while the model returns tool calls — a TEXT-ONLY
2
+ // response finalizes it. So when a model ends a round with an action ANNOUNCEMENT ("Let me implement these
3
+ // now.", "Now I'll run the tests.") and no tool call, the turn stops with the work undone and the owner has to
4
+ // type "continue". detectUnfinishedAction() recognises that shape from the TAIL of the text; the engine then
5
+ // injects ONE user-role nudge and keeps the loop going (bounded — see ANNOUNCE_NUDGE_MAX), instead of finalizing.
6
+ //
7
+ // Deliberately conservative: a false negative costs one "continue" the owner already types today; a false
8
+ // positive burns one extra round (and is bounded to ANNOUNCE_NUDGE_MAX per turn). So it only fires when the
9
+ // FINAL sentence is a first-person announcement of a tool-shaped action, and never on a question, a hand-back
10
+ // ("let me know…"), a deferral ("…in a follow-up"), a contingency ("if that fails, I'll…"), or a summary report.
11
+ // Dependency-free leaf (agent.ts is also bundled for the browser).
12
+ /** At most this many continuation nudges per turn — the model can never be forced into an unbounded turn. */
13
+ export const ANNOUNCE_NUDGE_MAX = 2;
14
+ export const ANNOUNCE_NUDGE = "You described the next action but didn't perform it — proceed now: call the tool(s) to do it.";
15
+ const LEAD = `(?:let me|let['’]s|let us|i['’]ll|i will|i['’]m going to|i am going to|i['’]m gonna|i['’]m about to|i am about to)`;
16
+ const FILL = String.raw `(?:(?:now|just|first|also|then|next|quickly|immediately|actually|directly|really|go ahead and|ahead and|proceed to|need to|have to|want to|start by|begin by)\s+){0,3}`;
17
+ // Tool-shaped actions only. Deliberately EXCLUDES text-delivery verbs (explain, summarize, show, walk through,
18
+ // think, outline, describe): "Let me explain…" is the model's own prose, not a missing tool call.
19
+ const VERB = `(?:create|implement|build|add|write|run|do|fix|check|update|read|look|see|open|inspect|search|find|test|verify|edit|make|start|begin|apply|refactor|install|fetch|examine|review|grep|list|view|try|wire|patch|modify|change|remove|delete|rename|move|generate|compile|execute|launch|restart|deploy|commit|set|take|dig|investigate|explore|scan|trace|debug|validate|save|copy|replace|rewrite|merge|call|use|load|print|pull|push|re-?run|re-?read|re-?check)`;
20
+ /** First-person lead-in + (optional filler) + a tool-shaped verb, e.g. "Let me implement", "Now I'll run",
21
+ * "Next, I'm going to add", "I'll first check". */
22
+ const ANNOUNCE_RE = new RegExp(String.raw `\b${LEAD}\s+${FILL}${VERB}\b`, "i");
23
+ // The model is handing control BACK (asking, offering, waiting) — a legitimate stop, never nudged.
24
+ const HANDBACK_RE = /\b(?:let me know|want me to|would you like|do you want|shall i|should i|if you(?:['’]d)? (?:want|like|prefer|need|say|confirm|approve|agree)|feel free|your call|up to you|waiting (?:for|on)|when you['’]re ready|once you|after you|before i|need your|your (?:go-?ahead|approval|confirmation|permission|input|decision)|please (?:confirm|approve|let me)|just say|say the word|tell me)\b/i;
25
+ // A closing statement ("all done", "nothing else to do") — the work is declared finished.
26
+ const CLOSING_RE = /\b(?:all (?:done|set|green)|that['’]s (?:it|all)|nothing (?:else|more)|(?:task|work|everything|it) (?:is|was) (?:now )?(?:done|complete|finished|ready)|no (?:further|more) (?:changes|action|work))\b/i;
27
+ // Explicitly deferred / optional work — mentioned, not announced for right now.
28
+ const DEFER_RE = /\b(?:follow-?up|later|afterwards?|separately|in the future|future (?:work|session|pass)|next (?:session|time|pass|turn|week|sprint)|optionally|if needed|as needed|if desired|someday|eventually|at some point|when (?:needed|necessary))\b/i;
29
+ // A contingency, not a commitment: "If that fails, I'll roll back." / "Once deployed, let me know…".
30
+ const CONDITIONAL_RE = /\b(?:if|unless|once|should|in case)\b[^.!?:]*\b(?:i['’]ll|i will|let me|let['’]s)\b/i;
31
+ // A summary/report section anywhere in the text — a deliberate "Next steps: I'll…" line closing a report
32
+ // is a plan for the reader, not a missing tool call.
33
+ const SUMMARY_RE = /^(?:#{1,4}\s*|\*\*)(?:summary|results?|changes(?: made)?|what (?:changed|i did|was done)|done|complete|findings|conclusion|recap|outcome)\b/im;
34
+ /** True when `content` — a text-only (no tool call) model response — reads as an unfinished action
35
+ * announcement: its final sentence says the model is about to DO a tool-shaped thing, in the first person,
36
+ * right now, and the text is not a question, a hand-back, a deferral, a contingency, or a summary report. */
37
+ export function detectUnfinishedAction(content) {
38
+ const text = (content ?? "").trim();
39
+ if (!text || /```\s*$/.test(text))
40
+ return false; // empty, or ends inside/after a code block
41
+ const tail = text.replace(/[\s*_~`"'”’)\]]+$/, ""); // drop trailing emphasis / quotes / brackets
42
+ if (/[??]$/.test(tail))
43
+ return false; // asking the user something — a genuine hand-back
44
+ if (SUMMARY_RE.test(text))
45
+ return false; // a report, not an interrupted action
46
+ const lines = (tail.split(/\n\s*\n/).pop() ?? "").split("\n").map((l) => l.trim()).filter(Boolean);
47
+ const last = lines[lines.length - 1] ?? "";
48
+ if (!last || HANDBACK_RE.test(last) || CLOSING_RE.test(last))
49
+ return false;
50
+ // The announcement must be in the last two sentences of the last line — or be the lead-in of a trailing
51
+ // list ("I'll do the following:\n1. …\n2. …"), whose first line ends with a colon.
52
+ const window = last.split(/(?<=[.!?:…])\s+/).slice(-2);
53
+ const head = lines.length > 1 && lines[0].endsWith(":") ? [lines[0]] : [];
54
+ return [...head, ...window].some((s) => ANNOUNCE_RE.test(s) && !HANDBACK_RE.test(s) && !DEFER_RE.test(s) && !CONDITIONAL_RE.test(s));
55
+ }
@@ -5,4 +5,6 @@
5
5
  // PATCH internal fix, no contract change (e.g. clampMaxTokens)
6
6
  // Bump MAJOR only when a host must change how it calls the engine. This is the single source of truth;
7
7
  // both barrels (index.ts, index.browser.ts) re-export it, and the SPEC conformance fixtures pin it.
8
- export const ENGINE_CONTRACT = "1.3.0"; // 1.3.0: + permissions surface (withPermissions, PermissionPolicy, ApproveFn) for client-side gating (additive)
8
+ export const ENGINE_CONTRACT = "1.5.0"; // 1.5.0: + AgentOpts.onComputerEvent / computerEnv — runTurn now EMITS each typed ComputerEvent (start/end) through an optional host callback, so a prebuilt host that only sees bridge callbacks (the mobile JSCore bundle) gets the stream without wiring a tracker; additive (opt-in, default off)
9
+ // 1.4.0: + 0perator Computer event stream (ComputerEvent, ComputerEventStream, ComputerEventTracker) — a typed, retained, replayable action log a surface feeds from the existing tool callbacks; runTurn/AgentOpts unchanged, so additive (older hosts ignore it)
10
+ // 1.3.0: + permissions surface (withPermissions, PermissionPolicy, ApproveFn) for client-side gating (additive)
@@ -153,8 +153,9 @@ export function detectShallowTest(path, content) {
153
153
  /** Verify the child's claim WITHOUT trusting its say-so (mechanism 3). Orchestrator-side, cheap + real:
154
154
  * a code-edit's claimed files_changed must actually exist on disk (read-after-write), the declared
155
155
  * verify_command must actually be RUN with a real passing exit code (never the child's self-report), and
156
- * any changed test file must not be hollow (detectShallowTest). Non-code tasks pass structurally. */
157
- export async function verifyFinalAnswer(value, type, cwd) {
156
+ * any changed test file must not be hollow (detectShallowTest). Non-code tasks pass structurally.
157
+ * @param opts.diffSha Optional HEAD sha before the turn — used for mutation check to catch vacuous tests. */
158
+ export async function verifyFinalAnswer(value, type, cwd, opts) {
158
159
  if (type !== "code-edit")
159
160
  return { verified: true, detail: "no file-level verify for this task type" };
160
161
  const files = Array.isArray(value.files_changed) ? value.files_changed.map(String) : [];
@@ -187,7 +188,7 @@ export async function verifyFinalAnswer(value, type, cwd) {
187
188
  try {
188
189
  const { execFile } = await nodeImport("node:child_process");
189
190
  const { promisify } = await nodeImport("node:util");
190
- const out = await promisify(execFile)("bash", ["-lc", vc], { cwd, timeout: 180_000, maxBuffer: 10 * 1024 * 1024 });
191
+ const out = await promisify(execFile)("bash", ["-lc", "set -o pipefail; " + vc], { cwd, timeout: 180_000, maxBuffer: 10 * 1024 * 1024 }); // H3: verified:true must be unfakeable by `cmd | tail` — GW-35 semantics extend to THIS exec
191
192
  const text = String(out.stdout ?? "") + String(out.stderr ?? "");
192
193
  if (ranButFailed(text))
193
194
  return { verified: false, detail: `verify_command reported failure: ${vc.slice(0, 60)}` };
@@ -207,6 +208,15 @@ export async function verifyFinalAnswer(value, type, cwd) {
207
208
  if (shallow)
208
209
  return { verified: false, detail: `verify_command passed, but ${shallow} — assert on real output/state, not just presence` };
209
210
  }
211
+ // If we have a diffSha, run the mutation check — re-verify against a reverted diff.
212
+ // If the suite still passes after reverting the change, the tests are likely vacuous.
213
+ if (opts?.diffSha) {
214
+ const mutResult = await verifyMutation(cwd, vc, opts.diffSha);
215
+ if (mutResult.passed) {
216
+ return { verified: false, detail: `verify_command passed, but mutation check suggests vacuous tests: ${mutResult.detail}` };
217
+ }
218
+ // mutation check failed (good — tests are real) — log the detail for diagnostics
219
+ }
210
220
  return { verified: true, detail: `verify_command passed (exit 0): ${vc.slice(0, 60)}` };
211
221
  }
212
222
  catch (e) {
@@ -0,0 +1,105 @@
1
+ // json-repair — one-shot, conservative argument-JSON repair for model-emitted tool calls.
2
+ // WHY: models frequently emit tool-call arguments with RAW newlines/tabs inside string values
3
+ // (multi-line bash/python -c scripts — the escape gets emitted as the literal control char, which
4
+ // strict JSON.parse rejects as "Bad control character"), or get CUT mid-string at the output token
5
+ // limit ("Unterminated string"). Both failure modes showed live (Spectre autonomous review turn,
6
+ // 2026-10-07): the generic error left the model guessing, and it burned 69 tool calls hunting a
7
+ // phantom "btx binary" instead of shortening its command. Fix: repair what is SAFE to repair
8
+ // (control chars — the command semantics survive), never guess at what is not (a truncated
9
+ // argument is a HALF-WRITTEN COMMAND; executing a repaired-by-closing-brace version could run
10
+ // something the model never finished deciding). For truncation we return guidance the model can
11
+ // actually act on. Pure JS: no node builtins — loaded inside the engine bundle.
12
+ /** Escape raw control chars that appear INSIDE string literals. Outside-string whitespace is
13
+ * legitimate JSON whitespace and untouched. Backslash state is honored, so an existing
14
+ * sequence like \\" or a proper \\n escape passes through unchanged. */
15
+ export function escapeControlChars(raw) {
16
+ let out = "";
17
+ let inStr = false;
18
+ let esc = false;
19
+ for (const ch of raw) {
20
+ if (!inStr) {
21
+ if (ch === '"')
22
+ inStr = true;
23
+ out += ch;
24
+ continue;
25
+ }
26
+ if (esc) {
27
+ out += ch;
28
+ esc = false;
29
+ continue;
30
+ }
31
+ if (ch === "\\") {
32
+ out += ch;
33
+ esc = true;
34
+ continue;
35
+ }
36
+ switch (ch) {
37
+ case "\n":
38
+ out += "\\n";
39
+ break;
40
+ case "\r":
41
+ out += "\\r";
42
+ break;
43
+ case "\t":
44
+ out += "\\t";
45
+ break;
46
+ default:
47
+ out += ch.codePointAt(0) < 0x20 ? "\\u" + ch.codePointAt(0).toString(16).padStart(4, "0") : ch;
48
+ }
49
+ }
50
+ return out;
51
+ }
52
+ /** Does the JSON look CUT OFF (truncation) rather than merely malformed? Signals: ends inside an
53
+ * unterminated string, ends mid-escape, ends on an open structure with missing closers. */
54
+ export function looksTruncated(raw) {
55
+ let inStr = false;
56
+ let esc = false;
57
+ const stack = [];
58
+ for (const ch of raw) {
59
+ if (!inStr && (ch === "{" || ch === "["))
60
+ stack.push(ch);
61
+ else if (!inStr && (ch === "}" || ch === "]"))
62
+ stack.pop();
63
+ else if (inStr && esc)
64
+ esc = false;
65
+ else if (inStr && ch === "\\")
66
+ esc = true;
67
+ else if (ch === '"')
68
+ inStr = !inStr;
69
+ }
70
+ return inStr || esc || stack.length > 0;
71
+ }
72
+ /** Parse model-emitted tool-call arguments with one conservative repair pass. Empty/whitespace =
73
+ * {} (zero-arg tools emit "" constantly — already tolerated upstream, kept identical). */
74
+ export function parseToolArgs(raw) {
75
+ if (!raw || raw.trim() === "")
76
+ return { ok: true, args: {}, repaired: false };
77
+ let lastErr = "";
78
+ try {
79
+ const v = JSON.parse(raw);
80
+ if (v && typeof v === "object" && !Array.isArray(v))
81
+ return { ok: true, args: v, repaired: false };
82
+ lastErr = "arguments did not parse to an object";
83
+ }
84
+ catch (e) {
85
+ lastErr = e instanceof Error ? e.message : String(e);
86
+ }
87
+ // repair pass (control chars inside strings)
88
+ const fixed = escapeControlChars(raw);
89
+ if (fixed !== raw) {
90
+ try {
91
+ const v = JSON.parse(fixed);
92
+ if (v && typeof v === "object" && !Array.isArray(v))
93
+ return { ok: true, args: v, repaired: true };
94
+ lastErr = "repaired arguments did not parse to an object";
95
+ }
96
+ catch (e) {
97
+ lastErr = e instanceof Error ? e.message : String(e);
98
+ }
99
+ }
100
+ const truncated = looksTruncated(raw);
101
+ const guidance = truncated
102
+ ? "the arguments were CUT OFF mid-generation (output token limit hit inside the JSON). Do NOT retry the same giant call: for long or multi-line scripts, file_write the script first, then bash a short command that runs the file; or split into several smaller calls. Keep arguments under ~4KB."
103
+ : `malformed JSON in arguments (${lastErr}). Re-emit valid JSON: escape quotes/newlines inside strings, close all braces.`;
104
+ return { ok: false, truncated, error: guidance };
105
+ }