@0perator/operator 0.1.359-next.0 → 0.1.360-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 (64) hide show
  1. package/dashboard/index.html +2 -2
  2. package/dist/autonomy/cloud-agent.js +2 -2
  3. package/dist/autonomy/headless.js +15 -6
  4. package/dist/autonomy/session-factory.js +2 -1
  5. package/dist/background/notices.js +1 -1
  6. package/dist/browser/session.js +7 -0
  7. package/dist/cli.js +94 -52
  8. package/dist/config/features.js +6 -5
  9. package/dist/config/persona.js +57 -40
  10. package/dist/config/settings.js +39 -55
  11. package/dist/engine/agent.js +72 -33
  12. package/dist/engine/aurora.js +24 -2
  13. package/dist/engine/compaction.js +27 -7
  14. package/dist/engine/decision-points.js +16 -4
  15. package/dist/engine/kv-slot.js +87 -0
  16. package/dist/engine/loop-guard.js +49 -18
  17. package/dist/engine/messages.js +8 -1
  18. package/dist/engine/progress-deadline.js +37 -0
  19. package/dist/engine/verify-gate.js +134 -9
  20. package/dist/enterprise/cli.js +13 -1
  21. package/dist/mcp/craft-server.js +5 -3
  22. package/dist/memory/live-progress.js +35 -6
  23. package/dist/permissions/policy.js +8 -0
  24. package/dist/permissions/signature.js +9 -0
  25. package/dist/products/artifact-library.js +47 -0
  26. package/dist/products/craft.js +58 -94
  27. package/dist/products/temple.js +230 -0
  28. package/dist/remote/host.js +28 -1
  29. package/dist/router/discovery.js +23 -6
  30. package/dist/router/models.js +29 -70
  31. package/dist/services/preflight.js +3 -41
  32. package/dist/session.js +121 -38
  33. package/dist/skills/catalogue.js +2 -0
  34. package/dist/skills/finder.js +1 -1
  35. package/dist/tools/background-result.js +26 -0
  36. package/dist/tools/chauffeur-native.js +6 -0
  37. package/dist/tools/craft.js +17 -6
  38. package/dist/tools/deferred.js +64 -30
  39. package/dist/tools/executor.js +4 -2
  40. package/dist/tools/paths.js +3 -3
  41. package/dist/tools/read-ledger.js +44 -0
  42. package/dist/tools/registry.js +218 -264
  43. package/dist/tools/sandbox.js +52 -39
  44. package/dist/tools/shell-context.js +5 -0
  45. package/dist/tools/shell-session.js +61 -29
  46. package/dist/tools/vision-gateway.js +79 -34
  47. package/dist/tools/wave-tools.js +2 -2
  48. package/dist/tools/wave2-tools.js +6 -6
  49. package/dist/ui/ArtifactPicker.js +2 -2
  50. package/dist/ui/Composer.js +9 -2
  51. package/dist/ui/StatusRule.js +1 -1
  52. package/dist/ui/modelPicker.js +1 -1
  53. package/dist/ui/nextStep.js +1 -0
  54. package/dist/ui/pending.js +10 -0
  55. package/dist/update.js +78 -4
  56. package/dist/util/retry.js +34 -0
  57. package/dist/util/slash.js +2 -1
  58. package/dist/vault/tool.js +3 -1
  59. package/mcp/powertools-toolbox.mjs +166 -1
  60. package/package.json +9 -13
  61. package/dashboard/README.md +0 -62
  62. package/dist/compose/client.js +0 -56
  63. package/mcp/README.md +0 -88
  64. package/mcp/powertools.md +0 -210
@@ -10,17 +10,26 @@
10
10
  // keep returning the same result; per-turn caps on web searches and sub-agent spawns. Warnings never block.
11
11
  // A hard stop is on by default for unattended runs and opt-in for an interactive owner; before it ends a turn the
12
12
  // engine offers bounded recovery (LoopRecovery).
13
+ import { unwrapToolCall } from "./decision-points.js";
13
14
  export const LOOP_GUARD_DEFAULTS = {
14
15
  warnIdentical: 3, warnExactFailure: 2, warnSameToolFailure: 3, warnNoProgress: 2, warnInvestigateLoop: 8,
15
16
  stopIdentical: 5, stopExactFailure: 5, stopSameToolFailure: 8, stopNoProgress: 5, stopInvestigateLoop: 15,
17
+ terminalStop: 25,
16
18
  maxWebSearches: 50, maxSubagents: 50,
17
19
  };
18
20
  const intAtLeast = (v, dflt, min) => typeof v === "number" && Number.isFinite(v) && Math.floor(v) >= min ? Math.floor(v) : dflt;
21
+ /** process.env where it exists, {} in the neutral/JSCore bundle (typeof never throws). */
22
+ const safeEnv = () => (typeof process !== "undefined" && process?.env) ? process.env : {};
23
+ const envOff = (v) => v === "0" || v === "false";
19
24
  /** Fold user settings over the defaults. `unattended` = no owner watching (headless run/loop/board/routine):
20
- * the hard stop defaults ON there and OFF for an interactive session unless `hardStop` says otherwise. */
21
- export function resolveLoopGuardConfig(raw, ctx) {
25
+ * the hard stop defaults ON there and OFF for an interactive session unless `hardStop` says otherwise.
26
+ * `env` lets a fleet/owner opt out of the hard stops without a settings file: `KODE_LOOP_NO_WRITE_STOP=0`
27
+ * disables the mode-gated headless no-write stop, `KODE_LOOP_TERMINAL_STOP=<n>` tunes (0 disables) the
28
+ * mode-independent read-only no-progress terminal. */
29
+ export function resolveLoopGuardConfig(raw, ctx, env = safeEnv()) {
22
30
  const s = raw ?? {};
23
31
  const d = LOOP_GUARD_DEFAULTS;
32
+ const terminalEnv = env.KODE_LOOP_TERMINAL_STOP;
24
33
  return {
25
34
  enabled: s.enabled !== false,
26
35
  hardStop: typeof s.hardStop === "boolean" ? s.hardStop : ctx.unattended,
@@ -28,7 +37,8 @@ export function resolveLoopGuardConfig(raw, ctx) {
28
37
  recoveryAttempts: Math.min(5, intAtLeast(s.recovery?.maxAttempts, 2, 0)),
29
38
  finishDirective: s.finishDirective !== false,
30
39
  methodSwitches: Math.min(5, intAtLeast(s.methodSwitches, 3, 0)),
31
- stopOnNoWrite: s.stopOnNoWrite === true,
40
+ stopOnNoWrite: envOff(env.KODE_LOOP_NO_WRITE_STOP) ? false : s.stopOnNoWrite !== false,
41
+ terminalStop: terminalEnv !== undefined ? intAtLeast(Number(terminalEnv), d.terminalStop, 0) : intAtLeast(s.terminalStop, d.terminalStop, 0),
32
42
  warnIdentical: intAtLeast(s.warnAfter?.identicalCall, d.warnIdentical, 2),
33
43
  warnExactFailure: intAtLeast(s.warnAfter?.exactFailure, d.warnExactFailure, 1),
34
44
  warnSameToolFailure: intAtLeast(s.warnAfter?.sameToolFailure, d.warnSameToolFailure, 1),
@@ -79,6 +89,7 @@ const FAILURE_PREFIX_RE = /^(?:error|permission denied|cancelled)\b/i;
79
89
  const EXIT_TRAILER_RE = /(?:\[exit (\d+)\]|^\(no output; exit (\d+|\?)\))\s*$/;
80
90
  /** True when a poll-style call is legitimately repeated while waiting (never a loop). */
81
91
  export function isRepeatable(name, args) {
92
+ ({ name, args } = unwrapToolCall(name, args));
82
93
  if (POLLER_TOOLS.has(name))
83
94
  return true;
84
95
  // A known allowance: generated/MCP poller naming conventions are legitimately re-invoked with identical args.
@@ -174,12 +185,20 @@ export class LoopGuard {
174
185
  this.haltDecision ??= d;
175
186
  return d;
176
187
  }
177
- /** Before a call runs: per-turn caps (always), then, with the hard stop on, a replay of a call that already
178
- * failed with no change since, or a read-only call that keeps returning the same thing. */
188
+ /** The stop threshold for a read-only no-progress / identical-result loop. hardStop TUNES it, never switches
189
+ * it off: the low mode-gated count when hardStop is on, the high MODE-INDEPENDENT terminal when it is off
190
+ * (attended TUI) — so a read-only loop still halts, just much later. 0 (terminalStop off, hardStop off) = no stop. */
191
+ noProgressStopAt(low) {
192
+ return this.config.hardStop ? low : this.config.terminalStop;
193
+ }
194
+ /** Before a call runs: per-turn caps (always), then a read-only call that keeps returning the same thing
195
+ * (MODE-INDEPENDENT at the terminal count — FIX 1), and, with the hard stop on, a replay of a call that
196
+ * already failed with no change since. */
179
197
  beforeCall(name, args) {
180
198
  const c = this.config;
181
199
  if (!c.enabled)
182
200
  return ALLOW(name);
201
+ ({ name, args } = unwrapToolCall(name, args)); // a deferred tool is judged by its own name, not the wrapper's
183
202
  if (name === "web_search" && c.maxWebSearches > 0) {
184
203
  if (this.webSearches >= c.maxWebSearches) {
185
204
  return this.stop("web_search_cap", name, this.webSearches, `this turn already made ${c.maxWebSearches} web searches, the per-turn limit — that looks like a runaway search loop`);
@@ -192,17 +211,21 @@ export class LoopGuard {
192
211
  }
193
212
  this.spawns++;
194
213
  }
214
+ const sig = name + "\0" + canonical(args);
215
+ // Read-only no-progress: the SAME idempotent read returning the SAME result. hardStop on → stop at the low
216
+ // count; hardStop off → at the high terminal (so an attended read-only loop still halts). Varied reads never
217
+ // reach this (different sig each time), so legitimate research is untouched.
218
+ const rec = IDEMPOTENT_TOOLS.has(name) ? this.noProgress.get(sig) : undefined;
219
+ const noProgStop = this.noProgressStopAt(c.stopNoProgress);
220
+ if (rec && noProgStop > 0 && rec.count >= noProgStop) {
221
+ return this.stop("no_progress", name, rec.count, `${name} returned the same result ${rec.count} times`);
222
+ }
195
223
  if (!c.hardStop)
196
224
  return ALLOW(name);
197
- const sig = name + "\0" + canonical(args);
198
225
  const exact = this.progressSinceFailure.has(sig) ? 0 : (this.exactFailures.get(sig) ?? 0);
199
226
  if (exact >= c.stopExactFailure) {
200
227
  return this.stop("exact_failure", name, exact, `the same ${name} call failed ${exact} times with identical arguments and nothing changed in between`);
201
228
  }
202
- const rec = IDEMPOTENT_TOOLS.has(name) ? this.noProgress.get(sig) : undefined;
203
- if (rec && rec.count >= c.stopNoProgress) {
204
- return this.stop("no_progress", name, rec.count, `${name} returned the same result ${rec.count} times`);
205
- }
206
229
  return ALLOW(name);
207
230
  }
208
231
  /** After a call settled. Returns the text to record as the tool result (the original, a duplicate-result
@@ -212,6 +235,7 @@ export class LoopGuard {
212
235
  const c = this.config;
213
236
  if (!c.enabled)
214
237
  return { result, decision: ALLOW(name) };
238
+ ({ name, args } = unwrapToolCall(name, args));
215
239
  const sig = name + "\0" + canonical(args);
216
240
  if (opts.shortCircuited) {
217
241
  const last = this.lastHash.get(sig);
@@ -304,10 +328,13 @@ export class LoopGuard {
304
328
  this.history.shift();
305
329
  let note;
306
330
  let decision = ALLOW(name, this.streak.count);
331
+ // hardStop ON → stop at `stopIdentical`; OFF → at the high mode-independent terminal (FIX 1), so an attended
332
+ // identical-call / cycle loop still halts. Only identical results reach here, so varied work never trips it.
333
+ const identicalStop = this.noProgressStopAt(c.stopIdentical);
307
334
  if (!repeatable && this.streak.count >= c.warnIdentical) {
308
335
  note = `this is the ${ordinal(this.streak.count)} consecutive identical call to ${name} with identical arguments returning the same result. Do not repeat it — change arguments, use a different tool, or proceed with what you have.`;
309
336
  decision = { action: "warn", code: "identical_call", message: note, tool: name, count: this.streak.count };
310
- if (c.hardStop && this.streak.count >= c.stopIdentical)
337
+ if (identicalStop > 0 && this.streak.count >= identicalStop)
311
338
  decision = this.stop("identical_call", name, this.streak.count, `the same ${name} call returned the same result ${this.streak.count} times in a row`);
312
339
  }
313
340
  else {
@@ -315,7 +342,7 @@ export class LoopGuard {
315
342
  if (cycle) {
316
343
  note = `the last ${cycle.laps} rounds repeated the same cycle of ${cycle.period} tool calls (ending with ${name}) with identical arguments and identical results. Do not repeat the batch — change arguments, use a different tool, or proceed with what you have.`;
317
344
  decision = { action: "warn", code: "identical_cycle", message: note, tool: name, count: cycle.laps };
318
- if (c.hardStop && cycle.laps >= c.stopIdentical)
345
+ if (identicalStop > 0 && cycle.laps >= identicalStop)
319
346
  decision = this.stop("identical_cycle", name, cycle.laps, `the same cycle of ${cycle.period} tool calls repeated ${cycle.laps} times with identical results`);
320
347
  }
321
348
  }
@@ -373,7 +400,7 @@ export const AUTOPOST_POLLERS = new Set(["agent_status"]);
373
400
  export const POLL_SPIN_DEFAULTS = { nudgeAfter: 2, stopAfter: 3 };
374
401
  export const POLL_SPIN_NUDGE = "agent_status will not change faster by asking again — each report, and a STUCK notice if one stalls, arrives " +
375
402
  "as a message on its own. Act on what it shows: steer an agent that is stuck or off its brief (message_agent), " +
376
- "or stop it (stop_agent) and do its step yourself. Otherwise do the work that does not depend on them, or close " +
403
+ "or stop it (stop_agent) and do its step yourself (both on demand). Otherwise do the work that does not depend on them, or close " +
377
404
  "the turn for the owner: one status line per agent (round, files written) and 2-3 options.";
378
405
  export const POLL_SPIN_STOP = "[stopped — waiting on sub-agents: agent_status was polled repeatedly with no change. Their reports, and a notice if " +
379
406
  "one gets stuck, arrive on their own. Nothing was lost.]";
@@ -504,17 +531,20 @@ export const INVESTIGATE_LOOP_STOP = "[stopped — no write-progress in {n} cons
504
531
  "Pick a direction and act on it, or end the turn.]";
505
532
  /** Watches settled tool rounds for zero write-progress. Fed one round at a time via observe(); a
506
533
  * mutating call resets the streak. Side-effect-free: the engine acts on the returned action.
507
- * Hard-stop is unattended-only (warn for interactive). */
534
+ * The hard stop is MODE-GATED (`hardStop`): the unattended / stopOnNoWrite default (FIX 2) — warn-only
535
+ * otherwise. (The attended read-only-loop backstop is the LoopGuard's identical/no-progress terminal, FIX 1,
536
+ * which keys on identical RESULTS and so never chokes a varied-output research turn the way a no-WRITE
537
+ * counter would.) */
508
538
  export class NoWriteProgressGuard {
509
539
  warnAfter;
510
540
  stopAfter;
511
- unattended;
541
+ hardStop;
512
542
  streak = 0;
513
543
  warned = false;
514
- constructor(warnAfter, stopAfter, unattended) {
544
+ constructor(warnAfter, stopAfter, hardStop) {
515
545
  this.warnAfter = warnAfter;
516
546
  this.stopAfter = stopAfter;
517
- this.unattended = unattended;
547
+ this.hardStop = hardStop;
518
548
  }
519
549
  reset() { this.streak = 0; this.warned = false; }
520
550
  /** One settled round: the tools it ran (names) and their results, index-aligned. */
@@ -525,7 +555,8 @@ export class NoWriteProgressGuard {
525
555
  return { action: "allow", streak: 0 };
526
556
  }
527
557
  this.streak += 1;
528
- if (this.streak >= this.stopAfter && this.unattended) {
558
+ // Mode-gated hard stop (unattended / stopOnNoWrite): the generous stopAfter.
559
+ if (this.streak >= this.stopAfter && this.hardStop) {
529
560
  return { action: "halt", streak: this.streak, message: INVESTIGATE_LOOP_STOP.replace("{n}", String(this.streak)) };
530
561
  }
531
562
  if (this.streak >= this.warnAfter && !this.warned) {
@@ -1,5 +1,6 @@
1
1
  // Message types + conversation builder — SPEC §1, §3. Single source of truth for `Msg` so
2
2
  // aurora.ts, toolcalls.ts, agent.ts and compaction.ts all agree on shape.
3
+ import { forgetViews } from "../tools/read-ledger.js"; // pure, node-free: this file stays in the neutral graph
3
4
  /**
4
5
  * Guards the one invariant llama.cpp's chat template 400s on (SPEC §1):
5
6
  * two system messages, or a system message immediately followed by an assistant message.
@@ -96,6 +97,10 @@ export function sanitizeToolCallArgs(messages) {
96
97
  // byte-identical across sessions on the same model and stays in the server's prompt cache.
97
98
  export const SESSION_CONTEXT_OPEN = "\n<session-context>\n";
98
99
  export const SESSION_CONTEXT_CLOSE = "\n</session-context>";
100
+ /** The block's last line, the one nearest the owner's words. The block sits in the USER message, so without it a small
101
+ * model takes the facts above for the request: "hello" from the home folder got a tour of the disk (11/25). */
102
+ export const SESSION_CONTEXT_REQUEST_LINE = "\nThe lines above are facts about this session, not a request. The owner's " +
103
+ "message follows; it alone is the task. A greeting or a question gets a direct reply, with no tools.";
99
104
  /** Moves the tagged session context out of the system prompt and in front of the first user message. Text
100
105
  * appended after the closing tag (a think directive, a turn directive, MOA drafts) stays in the system prompt.
101
106
  * With no user message to carry it, the system prompt is returned untouched. */
@@ -145,9 +150,11 @@ export class Conversation {
145
150
  tool(toolCallId, content) {
146
151
  this.messages.push({ role: "tool", content, tool_call_id: toolCallId });
147
152
  }
148
- /** Used by compaction to splice in [summary, ...keptTurns]. */
153
+ /** Used by compaction to splice in [summary, ...keptTurns]. The one way history is ever rewritten, so the read
154
+ * ledger forgets its views here: the text a repeat read would point at may no longer be above. */
149
155
  replaceAll(messages) {
150
156
  this.messages = messages;
157
+ forgetViews();
151
158
  }
152
159
  build(systemPrompt) {
153
160
  return buildMessages(systemPrompt, this.messages);
@@ -0,0 +1,37 @@
1
+ // A deadline that tells a slow request from a dead one. A fixed wall clock cannot: 120 s killed a summarizer that was
2
+ // still reading its prompt (2026-11-24). This one aborts when NOTHING has been reported for `idleMs`, or at `ceilingMs`
3
+ // whatever was reported, and the abort reason names the limit that was hit.
4
+ export class DeadlineError extends Error {
5
+ limit;
6
+ ms;
7
+ constructor(limit, ms) {
8
+ const s = Math.round(ms / 1000);
9
+ super(limit === "idle" ? `no progress for ${s} s (idle limit)` : `still running at the ${s} s ceiling`);
10
+ this.limit = limit;
11
+ this.ms = ms;
12
+ this.name = "DeadlineError";
13
+ }
14
+ }
15
+ /** A limit of 0 (or less, or not a number) is off. */
16
+ export function progressDeadline(idleMs, ceilingMs) {
17
+ const ctrl = new AbortController();
18
+ const arm = (limit, ms) => (ms > 0 ? setTimeout(() => ctrl.abort(new DeadlineError(limit, ms)), ms) : undefined);
19
+ let idle = arm("idle", idleMs);
20
+ const ceiling = arm("ceiling", ceilingMs);
21
+ return {
22
+ signal: ctrl.signal,
23
+ progress: () => { clearTimeout(idle); if (!ctrl.signal.aborted)
24
+ idle = arm("idle", idleMs); },
25
+ clear: () => { clearTimeout(idle); clearTimeout(ceiling); },
26
+ };
27
+ }
28
+ // The slowest summarizer the ceiling still waits for: a third of the read rate and of the write rate measured on a
29
+ // loaded local box (≈300 tok/s reading, ≈17 tok/s writing). Idle catches a dead request; this only bounds a live one.
30
+ const READ_FLOOR_TPS = 100;
31
+ const WRITE_FLOOR_TPS = 5;
32
+ const MIN_CEILING_MS = 10 * 60_000;
33
+ /** The overall limit for one summarize request, scaled to what it has to read and may write:
34
+ * promptTokens / 100 + maxTokens / 5 seconds, never under 10 minutes. 50K + 1800 → 14 min; 241K + 1800 → 46 min. */
35
+ export function summaryCeilingMs(promptTokens, maxTokens) {
36
+ return Math.max(MIN_CEILING_MS, Math.ceil((promptTokens / READ_FLOOR_TPS + maxTokens / WRITE_FLOOR_TPS) * 1000));
37
+ }
@@ -74,8 +74,8 @@ export function ranButFailed(result) {
74
74
  return Number(m[1]) !== 0;
75
75
  if (/timed out after \d+ms/.test(result))
76
76
  return true;
77
- if (/^moved to background as /.test(result.trim()))
78
- return true; // ctrl+b: the command had not finished, so nothing was verified
77
+ if (stillInBackground(result))
78
+ return true; // ctrl+b or a known-long command: it had not finished, so nothing was verified
79
79
  if (/^error running command:/i.test(result.trim()))
80
80
  return true;
81
81
  return false;
@@ -105,11 +105,59 @@ export function checksRun(cmd) {
105
105
  }
106
106
  return [...out];
107
107
  }
108
+ // A STRONG verify (FIX 3 — the unattended hard precondition): the command actually BUILDS, TYPE-CHECKS, TESTS
109
+ // or RUNS what changed — not merely a command behind an allowlisted head. `npm ls`, `go env`, `cargo tree`,
110
+ // `pip list` and version probes pass isVerifyCmd (allowlisted) but check NOTHING, so they must NOT satisfy the
111
+ // hard gate. This keeps the advisory path (isVerifyCmd) unchanged and tightens only the enforced one.
112
+ const DIRECT_STRONG_HEADS = new Set([
113
+ ...TYPECHECK_HEADS, ...TEST_HEADS,
114
+ "make", "cmake", "gradle", "mvn", "dotnet", "rake", "xcodebuild",
115
+ "eslint", "ruff", "markdownlint", "markdownlint-cli2", "lychee", "markdown-link-check",
116
+ "vale", "yamllint", "shellcheck", "hadolint", "pre-commit",
117
+ ]);
118
+ // Runner subcommands that build/test/run/check (vs ls/view/list/info/env/metadata/tree/audit/outdated/install —
119
+ // state reports or dependency work that verifies nothing).
120
+ const RUNNER_STRONG_SUB = new Set(["test", "build", "run", "check", "clippy", "vet", "bench", "compile", "e2e", "lint", "typecheck", "exec", "x"]);
121
+ function segmentVerifiesStrong(args) {
122
+ const words = args.map((w) => w.replace(/^.*\//, "")); // basename every token
123
+ const head = words[0];
124
+ const rest = words.slice(1);
125
+ if (rest.length === 1 && /^(?:-v|-V|--version|version|-h|--help|help)$/.test(rest[0]))
126
+ return false;
127
+ if (DIRECT_STRONG_HEADS.has(head))
128
+ return true;
129
+ if (head === "docker")
130
+ return dockerVerifies(rest);
131
+ // A test / type-check via a runner (npm test, npm run typecheck, npx vitest, go test, python -m pytest, …).
132
+ if (checksRun(args.join(" ")).length > 0)
133
+ return true;
134
+ const named = rest.filter((w) => !w.startsWith("-"));
135
+ // node / deno / bun / python / ruby / php RUNNING a script file (a path) is a real run of what changed.
136
+ if ((head === "node" || head === "deno" || head === "bun" || head === "python" || head === "python3" || head === "ruby" || head === "php") &&
137
+ named.some((w) => /[/.]/.test(w)))
138
+ return true;
139
+ // go/cargo build|run|test|check, deno/bun run, npm/pnpm/yarn run <script>, poetry/uv run <x>.
140
+ if (RUNNERS.has(head))
141
+ return RUNNER_STRONG_SUB.has(named[0] ?? "");
142
+ return false;
143
+ }
144
+ /** True when `cmd` actually builds / type-checks / tests / runs what changed — a STRONG verify. Stricter than
145
+ * isVerifyCmd, which accepts any allowlisted head (so `npm ls` passes it). Used for the unattended hard
146
+ * precondition: a mutating turn must run one of these before it may claim "done". */
147
+ export function isStrongVerifyCmd(cmd) {
148
+ if (!cmd || /\$\(|`/.test(cmd))
149
+ return false;
150
+ if (segmentArgs(cmd).some(segmentVerifiesStrong))
151
+ return true;
152
+ // Running a local script/binary is a real run: ./x, bash x.sh, sh x.sh — but not `bash -c '...'`.
153
+ return /(?:^|\|\||&&|[;|&]\s*)\s*\.?\/\S/.test(cmd) || /\b(?:bash|sh|zsh)\s+[^-]\S*/.test(cmd);
154
+ }
108
155
  /** The checks `text` reports as clean (a passing type-check, passing tests). */
109
156
  export function reportedChecks(text) {
110
157
  return REPORTED.filter(([, re]) => re.test(text)).map(([k]) => k);
111
158
  }
112
159
  import { MUTATING_TOOLS } from "../tools/mutating.js"; // single source of truth (see tools/mutating.ts)
160
+ import { backgroundJobId, finishedJob, stillInBackground } from "../tools/background-result.js";
113
161
  const VERIFY_TOOLS = new Set(["bash", "shell_exec"]);
114
162
  /** Turn-local ledger. The loop calls observe() after each tool batch, then gate() at the done-exit.
115
163
  * Turn-scoped (one runTurn = one task): a verify from an earlier turn must not satisfy this turn's new
@@ -117,35 +165,106 @@ const VERIFY_TOOLS = new Set(["bash", "shell_exec"]);
117
165
  export class TaskVerification {
118
166
  mutated = false;
119
167
  verified = false;
168
+ verifiedStrong = false; // a STRONG verify ran+passed (test/build/typecheck/run) — the enforced-gate signal
120
169
  ran = new Set(); // run at all this turn: a piped `tsc | head` exits 0 whatever it found
170
+ latest = new Map(); // each check's LAST result this turn: null = it passed
171
+ background = new Map(); // job id → the check it runs, started after the last change, result unread
121
172
  /** names[i] / commands[i] / results[i] are index-aligned: a batch of tool calls and their result
122
173
  * strings. `commands[i]` is the shell command for bash/shell_exec calls, "" otherwise. */
123
174
  observe(names, commands, results) {
124
175
  for (let i = 0; i < names.length; i++) {
125
176
  const name = names[i];
126
- const res = results[i] ?? "";
127
- if (MUTATING_TOOLS.has(name) && !/^error/i.test(res.trim()))
177
+ let res = results[i] ?? "";
178
+ let cmd = (commands[i] ?? "").trim();
179
+ let shell = VERIFY_TOOLS.has(name);
180
+ // 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())) {
128
182
  this.mutated = true;
129
- if (VERIFY_TOOLS.has(name) && isVerifyCmd(commands[i] ?? "") && !ranButFailed(res))
130
- this.verified = true;
131
- if (VERIFY_TOOLS.has(name) && !/^(?:error running command:|moved to background as )/i.test(res.trim()))
132
- for (const k of checksRun(commands[i] ?? ""))
183
+ this.verified = this.verifiedStrong = false;
184
+ this.background.clear();
185
+ }
186
+ const jobId = shell || name === "shell_background" ? backgroundJobId(res) : undefined;
187
+ if (jobId && isVerifyCmd(cmd))
188
+ this.background.set(jobId, cmd);
189
+ // bash_output on a finished job is that check's result: its command, its real exit code
190
+ const done = name === "bash_output" ? finishedJob(res) : undefined;
191
+ const held = done && this.background.get(done.id);
192
+ if (done && held) {
193
+ this.background.delete(done.id);
194
+ shell = true;
195
+ cmd = held;
196
+ res = `[exit ${done.exit}]`;
197
+ }
198
+ if (shell && !ranButFailed(res)) {
199
+ if (isVerifyCmd(cmd))
200
+ this.verified = true;
201
+ if (isStrongVerifyCmd(cmd))
202
+ this.verifiedStrong = true;
203
+ }
204
+ if (shell && !/^error running command:/i.test(res.trim()) && !stillInBackground(res))
205
+ for (const k of checksRun(cmd))
133
206
  this.ran.add(k);
207
+ if (shell && isStrongVerifyCmd(cmd) && !stillInBackground(res)) {
208
+ const keys = checksRun(cmd);
209
+ const failed = ranButFailed(res) ? { command: cmd, exit: res.match(/\[exit (-?\d+)\]|\(no output; exit (-?\d+)\)/)?.slice(1).find(Boolean) ?? "?" } : null;
210
+ for (const key of keys.length ? keys : [cmd])
211
+ this.latest.set(key, failed);
212
+ }
134
213
  }
135
214
  }
215
+ /** The background job holding a check started after the last change whose result has not been read, if any. */
216
+ backgroundCheck() {
217
+ return this.background.keys().next().value;
218
+ }
219
+ /** Checks whose latest run this turn failed (a later clean run of the same check clears it). */
220
+ failing() {
221
+ return [...new Set([...this.latest.values()].filter((f) => !!f))];
222
+ }
223
+ /** The failing checks `answer` does not plainly own up to: it never says the check failed, or it explains the
224
+ * failure away ("expected", "normal", "can be ignored"). Empty when every check's latest run passed. */
225
+ unreportedFailures(answer) {
226
+ const failing = this.failing();
227
+ if (!failing.length)
228
+ return [];
229
+ return ownsFailure(answer) ? [] : failing;
230
+ }
136
231
  /** True once a mutating tool succeeded this turn. */
137
232
  changedFiles() {
138
233
  return this.mutated;
139
234
  }
140
- /** True ⇒ this turn changed code but never ran a passing check ⇒ nudge, then annotate. */
235
+ /** True ⇒ this turn changed code but never ran a passing check ⇒ nudge, then annotate (ADVISORY path). */
141
236
  gate() {
142
237
  return this.mutated && !this.verified;
143
238
  }
239
+ /** 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). */
241
+ gateStrong() {
242
+ return this.mutated && !this.verifiedStrong;
243
+ }
144
244
  /** The checks `answer` reports as clean that never ran this turn ⇒ nudge, then annotate. */
145
245
  unrun(answer) {
146
246
  return reportedChecks(answer).filter((k) => !this.ran.has(k));
147
247
  }
148
248
  }
249
+ // An answer owns a failure when it says a check failed and does not excuse it. 11/23: a two-file edit ended "The test
250
+ // runs failed because npm can't find a package.json … that's expected … The task is complete" — the tests had run from ~.
251
+ const SAYS_FAILED = /\b(?:fail(?:ed|s|ing|ure)?|did(?: not|n't) pass|does(?: not|n't) pass|not (?:yet )?(?:passing|verified|green)|unverified|still (?:red|broken|erroring))\b/i;
252
+ const EXCUSES = /\b(?:(?:is |was |are |were |that'?s |it'?s )?(?:expected|normal|harmless|fine)\b|can be (?:safely )?ignored|safe to ignore|not (?:a |an )?(?:real |actual )?(?:problem|issue|concern)|just because|only because|nothing to worry)/i;
253
+ export function ownsFailure(answer) {
254
+ return SAYS_FAILED.test(answer) && !EXCUSES.test(answer);
255
+ }
256
+ /** Injected for ONE extra round when the answer leaves a failing check unreported or explains it away. */
257
+ export function failedCheckReminder(failed) {
258
+ const list = failed.map((f) => `\`${f.command.length > 160 ? f.command.slice(0, 159) + "…" : f.command}\` (exit ${f.exit})`).join(", ");
259
+ return `[verify-before-done] A check failed and your answer does not report it as failing: ${list}. A failing check is never ` +
260
+ `"expected". Find out why it failed — a check run from the wrong folder (no package.json, pyproject.toml, Cargo.toml or go.mod ` +
261
+ `there) checked nothing — then fix it or re-run it the right way. If it still fails, say so plainly with its output; do not call ` +
262
+ `the work done.`;
263
+ }
264
+ /** Prefixed to the final answer when a failing check is still unreported (reminder spent). */
265
+ export function failedCheckBanner(failed) {
266
+ return `⚠ A check failed and was not re-run clean: ${failed.map((f) => `\`${f.command.length > 80 ? f.command.slice(0, 79) + "…" : f.command}\` (exit ${f.exit})`).join(", ")}.\n\n`;
267
+ }
149
268
  const CHECK_COMMAND = { "type-check": "the type-check (for TypeScript: `npx tsc --noEmit`)", tests: "the test suite" };
150
269
  /** Injected for ONE extra round when the answer reports a check that never ran this turn. */
151
270
  export function unrunCheckReminder(checks) {
@@ -177,5 +296,11 @@ export const VERIFY_REMINDER = "[verify-before-done] You changed files this turn
177
296
  "command or CLI you changed — and report what it printed. If there is genuinely nothing runnable to " +
178
297
  "check, say so in one line and name what stays unverified. Don't apologize or re-explain; just run it, " +
179
298
  "or state plainly why you can't.";
299
+ /** VERIFY_REMINDER's form when the check did run but went to a background job: re-running it bare only backgrounds it again. */
300
+ export function backgroundCheckReminder(jobId) {
301
+ return `[verify-before-done] You changed files and the check is still running in the background (job ${jobId}), or has finished unread. ` +
302
+ `Read its result with bash_output {"id":"${jobId}"}, or re-run it in the foreground with timeout_ms. It counts once it exits 0; ` +
303
+ `until then do not call the work done.`;
304
+ }
180
305
  /** Prefixed to the final answer when a turn changed files but never ran a passing check (nudge spent). */
181
306
  export const NOT_VERIFIED_BANNER = "⚠ Not verified — I changed files but did not run a passing check this turn.\n\n";
@@ -15,6 +15,7 @@ import { auditFilesFor, verifyAuditFiles } from "../telemetry/audit-verify.js";
15
15
  import { defaultEventsFile } from "../telemetry/events.js";
16
16
  import { loadCredentials } from "../auth/store.js";
17
17
  import { PermissionPolicy } from "../permissions/index.js";
18
+ import { osSandboxAvailable } from "../tools/sandbox.js";
18
19
  const activeFile = (flag) => {
19
20
  const raw = flag ?? defaultEventsFile();
20
21
  return raw.startsWith("~/") ? join(process.env.HOME ?? "", raw.slice(2)) : raw;
@@ -137,7 +138,18 @@ export async function collectChecks(settings, ctx) {
137
138
  add("seat", seat?.source === "lockdown" ? "warn" : "ok", `tier=${tier} source=${seat?.source ?? "local-owner"}${seat?.sub ? ` sub=${seat.sub}` : ""}${seat?.reasons?.length ? ` (${seat.reasons.join("; ")})` : ""}`);
138
139
  add("permissions", settings.permissions.mode === "bypass" && tier === "admin" ? "info" : "ok", `mode=${settings.permissions.mode} tier=${tier} rules=${Object.keys(settings.permissions.rules ?? {}).length}`);
139
140
  const narrowed = tier !== "admin" || m?.status === "ok";
140
- add("sandbox", settings.sandbox.mode === "off" && narrowed ? "warn" : "ok", `mode=${settings.sandbox.mode}${settings.sandbox.mode === "off" && narrowed ? " — the agent can write outside the workspace; with the sandbox on it also cannot touch its own settings/credentials/audit log" : ""}`);
141
+ const sbMode = settings.sandbox.mode;
142
+ if (sbMode === "off") {
143
+ add("sandbox", narrowed ? "warn" : "ok", `mode=off${narrowed ? " — the agent can write outside the workspace; with the sandbox on it also cannot touch its own settings/credentials/audit log" : ""}`);
144
+ }
145
+ else {
146
+ // Reflect the EFFECTIVE enforcement, not just the configured mode: with no OS sandbox layer present
147
+ // (sandbox-exec / bwrap), wrapShell runs plain bash and the shell is UNCONFINED — only the JS file-guards apply.
148
+ const osOk = await osSandboxAvailable();
149
+ add("sandbox", osOk ? "ok" : "warn", osOk
150
+ ? `mode=${sbMode} — shell writes confined to the workspace${sbMode === "strict" ? ", network cut" : ""}`
151
+ : `mode=${sbMode} configured, but no OS sandbox (${process.platform === "darwin" ? "sandbox-exec" : process.platform === "linux" ? "bwrap" : process.platform}) on this host — the shell runs UNCONFINED; only the file-write guards apply`);
152
+ }
141
153
  add("computer", settings.computer.enabled ? "warn" : "ok", settings.computer.enabled ? "computer control ENABLED" : "computer control off");
142
154
  add("mcp", "info", settings.mcp ? "fleet MCP tools enabled" : "fleet MCP off");
143
155
  add("flywheel", settings.selfImprove.flywheel && narrowed ? "warn" : "info", settings.selfImprove.flywheel ? "training-flywheel capture ON (prompts + answers, secret-masked, 0600)" : "training-flywheel capture off");
@@ -7,17 +7,18 @@
7
7
  // this handler is async and passes the CALLER'S own bearer + authz scopes through (ownership = the caller's account
8
8
  // server-side, never the process env token). It reuses products/craft.ts — zero reimplementation; account-ownership,
9
9
  // ACL, versioning + the change-feed/revoke guarantee live server-side on the hosted surface.
10
- import { craftCreate, craftUpdate, craftList, craftGet } from "../products/craft.js";
10
+ import { craftCreate, craftUpdate, craftList, craftGet, craftDelete } from "../products/craft.js";
11
11
  const PROTOCOL_VERSION = "2025-06-18";
12
12
  const asText = (text) => ({ content: [{ type: "text", text }], ...(text.startsWith("error:") ? { isError: true } : {}) });
13
13
  function toolDefs() {
14
14
  return [
15
- { name: "craft_create", description: "Create a hosted, shareable craft (page/deck/doc/board/dashboard/app) and get its view URL.",
16
- inputSchema: { type: "object", required: ["content"], properties: { content: { type: "string", description: "HTML, SVG, or markdown body" }, type: { type: "string", description: "page|deck|doc|board|dashboard|app|svg|markdown|canvas|html" }, title: { type: "string" } } } },
15
+ { name: "craft_create", description: "Create a hosted, shareable craft (page/deck/doc/board/dashboard/app/image/video) and get its 0perator.co share link.",
16
+ inputSchema: { type: "object", properties: { content: { type: "string", description: "HTML, markdown, SVG, or text body" }, type: { type: "string", description: "page|deck|doc|board|dashboard|app|image|video" }, content_type: { type: "string", description: "html|markdown|svg|text|canvas" }, title: { type: "string" }, visibility: { type: "string", description: "link|private|public" } } } },
17
17
  { name: "craft_update", description: "Update a craft by id (content/title/visibility); optimistic concurrency via expected_version.",
18
18
  inputSchema: { type: "object", required: ["id"], properties: { id: { type: "string" }, content: { type: "string" }, title: { type: "string" }, visibility: { type: "string" }, expected_version: { type: "string" } } } },
19
19
  { name: "craft_list", description: "List the caller's crafts.", inputSchema: { type: "object", properties: { limit: { type: "number" } } } },
20
20
  { name: "craft_get", description: "Read a craft by id (current version + view URL).", inputSchema: { type: "object", required: ["id"], properties: { id: { type: "string" } } } },
21
+ { name: "craft_delete", description: "Delete a craft you own by id.", inputSchema: { type: "object", required: ["id"], properties: { id: { type: "string" } } } },
21
22
  ];
22
23
  }
23
24
  /** Dispatch one MCP JSON-RPC request against the Craft product, as the caller. Async (brokered). The surface gate
@@ -45,6 +46,7 @@ export async function handleCraftMcp(req, ctx) {
45
46
  case "update": return ok(asText(await craftUpdate(a, auth)));
46
47
  case "list": return ok(asText(await craftList(a, auth)));
47
48
  case "get": return ok(asText(await craftGet(a, auth)));
49
+ case "delete": return ok(asText(await craftDelete(a, auth)));
48
50
  default: return err(-32601, `unknown tool: ${name}`);
49
51
  }
50
52
  }
@@ -6,8 +6,10 @@
6
6
  // the request, the task list with its states, the files touched and the last thing the model said are already on
7
7
  // disk. The block is keyed by session (two tabs in one directory keep their own), rewritten atomically (tmp +
8
8
  // rename, so ENOSPC or a kill mid-write never truncates the owner's handoff), budgeted to fit the 6000-char tail the
9
- // persona loads, and settled ("turn completed") when the turn ends normally so a finished turn is never offered as
10
- // something to resume.
9
+ // persona loads, and settled when the turn ends: "turn completed" normally, "stopped by the owner" on an interrupt, so
10
+ // only a turn that died mid-flight is offered as something to resume. A turn that only planned (task_* calls, no file
11
+ // writes) settles too: on 11/20 such a block said "resume from this" for three days, and every new session in ~ chased
12
+ // its plan over what the owner typed. freshHandoff drops live blocks past LIVE_MAX_AGE_MS as a second guard.
11
13
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
12
14
  import { dirname, relative, isAbsolute } from "node:path";
13
15
  export const LIVE_START = "<!-- live-progress:start";
@@ -35,7 +37,9 @@ export function liveProgressBlock(p) {
35
37
  const at = (p.at ?? new Date()).toISOString();
36
38
  const head = p.completed
37
39
  ? `## Live progress — turn completed ${at} (nothing to resume from here)`
38
- : `## Live progress (auto-saved ${at}) — the turn may have been cut off here; resume from this`;
40
+ : p.stopped
41
+ ? `## Live progress — turn stopped by the owner ${at} (resume only if the owner asks)`
42
+ : `## Live progress (auto-saved ${at}) — the turn may have been cut off here; resume from this`;
39
43
  const tasks = p.tasks.length
40
44
  ? p.tasks.map((t) => `${MARK[t.status] ?? "[ ]"} #${t.id} ${clip(t.text.replace(/\s+/g, " "), MAX_TASK_CHARS)} (${t.status})`).join("\n")
41
45
  : "(no task list this turn)";
@@ -77,7 +81,32 @@ export function recordLiveProgress(file, p) {
77
81
  return false;
78
82
  }
79
83
  }
80
- /** The turn ended normally: mark the block completed so the next session is not told to resume a finished turn. */
81
- export function settleLiveProgress(file, p) {
82
- return recordLiveProgress(file, { ...p, completed: true });
84
+ /** The turn ended: mark the block completed (or stopped by the owner) so the next session is not told to resume it. */
85
+ export function settleLiveProgress(file, p, how = "completed") {
86
+ return recordLiveProgress(file, how === "stopped" ? { ...p, stopped: true } : { ...p, completed: true });
87
+ }
88
+ /** The handoff text without settled live blocks (turn completed, or stopped by the owner), and how many were dropped.
89
+ * A settled block still carries the old REQUEST and task list, and a model reads those as work to do whatever the
90
+ * heading says (11/23: "hello" restarted a finished three-step task), so the next session gets a pointer instead. */
91
+ export function withoutSettled(text) {
92
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
93
+ const block = new RegExp(`${esc(LIVE_START)}[^\\n]*-->[\\s\\S]*?(?:${esc(LIVE_END)}|$)`, "g");
94
+ let settled = 0;
95
+ const kept = text.replace(block, (b) => (/## Live progress — turn (completed|stopped by the owner)/.test(b) ? (settled++, "") : b));
96
+ return { text: kept.replace(/\n{3,}/g, "\n\n").trim(), settled };
97
+ }
98
+ export const LIVE_MAX_AGE_MS = 12 * 3600_000;
99
+ const STAMP = /\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z/;
100
+ /** The handoff text without live blocks older than maxAgeMs (an unreadable stamp counts as old): a block that outlived
101
+ * its turn is history, and an unsettled one would otherwise tell every later session to resume it. */
102
+ export function freshHandoff(text, now = new Date(), maxAgeMs = LIVE_MAX_AGE_MS) {
103
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
104
+ const block = new RegExp(`${esc(LIVE_START)}[^\\n]*-->[\\s\\S]*?(?:${esc(LIVE_END)}|$)`, "g");
105
+ return text
106
+ .replace(block, (b) => {
107
+ const t = Date.parse(b.match(STAMP)?.[0] ?? "");
108
+ return Number.isFinite(t) && now.getTime() - t <= maxAgeMs ? b : "";
109
+ })
110
+ .replace(/\n{3,}/g, "\n\n")
111
+ .trim();
83
112
  }
@@ -18,6 +18,14 @@ const DANGEROUS = [
18
18
  /:\(\)\s*\{.*\}\s*;/, // fork bomb
19
19
  /\bchmod\s+-R\s+0?00\b/i,
20
20
  />\s*\/dev\/sd[a-z]/i,
21
+ // Broader irreversible-delete + obfuscated-shell shapes (kept in sync with permissions/signature.ts).
22
+ /\bfind\b[^|;&\n]*\s-delete\b/i, // find … -delete
23
+ /\bshred\b/i, // secure-erase a file
24
+ /\btruncate\b[^|;&\n]*-s\s*0\b/i, // truncate -s0 (empties a file)
25
+ /(^|[\n;&|])\s*:?\s*>\s*[^>\s&]/, // truncating redirect at command start: `> f`, `: > f`
26
+ /\bgit\s+clean\b[^|;&\n]*\s-{1,2}[a-z]*f/i, // git clean -f… / -fdx
27
+ /\beval\s+["'`$({]/i, // eval executing a (possibly obfuscated) string
28
+ /\bbase64\b[^\n]*\|\s*\w*\b(sh|bash|zsh|python[0-9.]*|perl|node)\b/i, // base64 … | sh
21
29
  ];
22
30
  function looksDangerous(_name, args) {
23
31
  const cmd = typeof args.command === "string" ? args.command : "";
@@ -35,6 +35,15 @@ const DESTRUCTIVE_CMD = [
35
35
  /\bchmod\s+-R\s+0?00\b/i,
36
36
  />\s*\/dev\/sd[a-z]/i,
37
37
  /\b(drop\s+(database|table|schema)|truncate\s+table|delete\s+from)\b/i, // SQL data loss
38
+ // Defense-in-depth on top of the sandbox floor (hints, not the floor): more irreversible-delete shapes.
39
+ /\bfind\b[^|;&\n]*\s-delete\b/i, // find … -delete (bulk irreversible delete)
40
+ /\bshred\b/i, // secure-erase a file (unrecoverable)
41
+ /\btruncate\b[^|;&\n]*-s\s*0\b/i, // truncate -s0 / -s 0 (empties a file in place)
42
+ /(^|[\n;&|])\s*:?\s*>\s*[^>\s&]/, // truncating redirect at command start: `> f`, `: > f` (empties f)
43
+ /\bgit\s+clean\b[^|;&\n]*\s-{1,2}[a-z]*f/i, // git clean -f… / -fdx (delete untracked, incl. ignored)
44
+ // Obfuscated shells — hidden/dynamic code is treated as ask/hold, since the payload can't be read:
45
+ /\beval\s+["'`$({]/i, // eval executing a (possibly obfuscated) string
46
+ /\bbase64\b[^\n]*\|\s*\w*\b(sh|bash|zsh|python[0-9.]*|perl|node)\b/i, // base64 … | sh — decode-and-run
38
47
  ];
39
48
  function blob(name, args) {
40
49
  const cmd = typeof args.command === "string" ? args.command : "";