@0perator/operator 0.1.351 → 0.1.353

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 (92) hide show
  1. package/dist/acp/agent.js +2 -2
  2. package/dist/acp/tool-map.js +5 -4
  3. package/dist/autonomy/delegate.js +54 -1
  4. package/dist/autonomy/headless.js +2 -0
  5. package/dist/autonomy/session-factory.js +1 -0
  6. package/dist/background/index.js +86 -10
  7. package/dist/background/notices.js +16 -4
  8. package/dist/cli.js +1073 -177
  9. package/dist/config/home.js +6 -0
  10. package/dist/config/memory-sections.js +92 -0
  11. package/dist/config/persona.js +144 -26
  12. package/dist/config/settings.js +15 -4
  13. package/dist/consolidation/scheduler.js +9 -2
  14. package/dist/consolidation/sleep.js +39 -278
  15. package/dist/engine/agent.js +444 -76
  16. package/dist/engine/anthropic-chat.js +13 -2
  17. package/dist/engine/aurora.js +66 -19
  18. package/dist/engine/batch-scheduler.js +27 -3
  19. package/dist/engine/compaction.js +12 -5
  20. package/dist/engine/continuation.js +14 -12
  21. package/dist/engine/contract.js +1 -1
  22. package/dist/engine/decision-points.js +7 -1
  23. package/dist/engine/front-door.js +59 -0
  24. package/dist/engine/grandmaster.js +13 -1
  25. package/dist/engine/loop-guard.js +694 -0
  26. package/dist/engine/owner-act.js +52 -0
  27. package/dist/engine/verify-gate.js +52 -0
  28. package/dist/flywheel/processor.js +3 -1
  29. package/dist/flywheel/srft.js +8 -4
  30. package/dist/hooks/index.js +12 -8
  31. package/dist/mcp/index.js +9 -4
  32. package/dist/permissions/index.js +32 -11
  33. package/dist/permissions/modes.js +42 -0
  34. package/dist/permissions/plan-review.js +100 -0
  35. package/dist/permissions/policy.js +16 -5
  36. package/dist/permissions/signature.js +8 -3
  37. package/dist/remote/safe-commands.js +1 -1
  38. package/dist/router/read-rates.js +152 -0
  39. package/dist/selfimprove/backfill.js +174 -0
  40. package/dist/selfimprove/index.js +146 -57
  41. package/dist/selfimprove/lessons.js +429 -0
  42. package/dist/selfimprove/sync.js +58 -0
  43. package/dist/session.js +362 -33
  44. package/dist/skills/finder.js +219 -0
  45. package/dist/toolchain/toolchain.py +528 -112
  46. package/dist/tools/deferred.js +28 -18
  47. package/dist/tools/executor.js +7 -3
  48. package/dist/tools/registry.js +68 -7
  49. package/dist/tools/result-cap.js +1 -1
  50. package/dist/ui/ActivitySpinner.js +21 -12
  51. package/dist/ui/App.js +107 -30
  52. package/dist/ui/ApprovalPrompt.js +5 -3
  53. package/dist/ui/ArtifactPicker.js +3 -3
  54. package/dist/ui/BgPanel.js +105 -5
  55. package/dist/ui/Composer.js +85 -9
  56. package/dist/ui/PlanPane.js +72 -8
  57. package/dist/ui/QuestionPrompt.js +6 -4
  58. package/dist/ui/SecretPrompt.js +8 -3
  59. package/dist/ui/SessionPicker.js +2 -2
  60. package/dist/ui/SkillFinder.js +153 -0
  61. package/dist/ui/StatusRule.js +5 -2
  62. package/dist/ui/SummaryCard.js +3 -1
  63. package/dist/ui/ThinkingSpinner.js +11 -2
  64. package/dist/ui/ToolBatch.js +11 -2
  65. package/dist/ui/ToolStep.js +36 -13
  66. package/dist/ui/Transcript.js +13 -2
  67. package/dist/ui/actNow.js +61 -0
  68. package/dist/ui/batchLine.js +165 -0
  69. package/dist/ui/conversations.js +154 -0
  70. package/dist/ui/decodeHealth.js +77 -0
  71. package/dist/ui/expand.js +17 -0
  72. package/dist/ui/fit.js +40 -0
  73. package/dist/ui/fitTail.js +14 -0
  74. package/dist/ui/fold.js +149 -0
  75. package/dist/ui/format.js +46 -2
  76. package/dist/ui/liveTools.js +163 -13
  77. package/dist/ui/modelPicker.js +78 -6
  78. package/dist/ui/nextStep.js +103 -0
  79. package/dist/ui/pending.js +57 -0
  80. package/dist/ui/phase.js +105 -0
  81. package/dist/ui/planExit.js +0 -5
  82. package/dist/ui/progressbar.js +4 -26
  83. package/dist/ui/readForecast.js +44 -0
  84. package/dist/ui/readProgress.js +119 -0
  85. package/dist/ui/reportLine.js +62 -0
  86. package/dist/ui/slashCommands.js +1 -1
  87. package/dist/ui/theme.js +1 -0
  88. package/dist/ui/turnFlow.js +72 -0
  89. package/dist/ui/turnLedger.js +121 -0
  90. package/dist/ui/turnScope.js +11 -0
  91. package/dist/util/slash.js +18 -0
  92. package/package.json +1 -1
@@ -0,0 +1,52 @@
1
+ // "Use what you have" (TUI A3.3, ctrl+y): the owner cuts a long reasoning stream short and asks for an answer — or the one
2
+ // next call — built from what the model already has, instead of waiting it out or throwing it away with Esc. A latch the
3
+ // Session sets and runTurn acts on. Requested while a reply streams: the stream is cut at once and its partial is kept
4
+ // in context. While the server is still reading the prompt: it arms, and trips on the first token, so the read is not
5
+ // wasted. During a tool batch: it applies before the next request. The rest of the turn runs think-off; the system
6
+ // prompt and the tools array never change, so the cached prefix holds. Browser-safe: no node imports.
7
+ export const OWNER_ACT_MESSAGE = "use what you have now — answer, or make the one next call";
8
+ /** The tool result for a call the model makes after its one next call. */
9
+ export const OWNER_ACT_REFUSED = "Blocked: the owner asked for your answer now, so this call did not run. Answer from what you have.";
10
+ /** The engine stop when the model keeps calling tools after the owner asked for its answer (continuation.ts "owner"). */
11
+ export const OWNER_ACT_STOP = "[stopped — the owner asked for an answer with what I had, and I kept reaching for tools instead.]";
12
+ /** How much of a cut reasoning stream is kept in context (its tail): enough to answer from, never the 400K-char spiral. */
13
+ export const OWNER_ACT_REASONING_KEEP = 8000;
14
+ /** The pause between cutting a stream and sending the act round. llama.cpp frees the cut request's slot only when its
15
+ * next token write fails; a request sent at once can land on another slot that holds none of this prefix. Measured on
16
+ * JL2's 4-slot Aurora (11/04): an immediate follow-up re-read the whole 9.4K prompt in 1 of 2 tries (16.5 s; the live
17
+ * drive's 23K re-read took 48.9 s), a 600 ms pause hit the cache in 2 of 2 (0.6 s). */
18
+ export const OWNER_ACT_SETTLE_MS = 600;
19
+ export class OwnerAct {
20
+ requested = false;
21
+ open = false; // the turn's first request is out: before it there is nothing to use (review F7)
22
+ spent = false; // acted on: one act per turn, so a second press never re-opens the one next call
23
+ listener;
24
+ /** ctrl+y. The live stream, if any, hears it at once. False when there is nothing to act on — before the turn's first
25
+ * request, or once it acted — so the shell shows no arming for a press the engine ignores. */
26
+ request() {
27
+ if (!this.open || this.spent)
28
+ return false;
29
+ this.requested = true;
30
+ this.listener?.();
31
+ return true;
32
+ }
33
+ /** The engine: a request of this turn is going out (from the first one on, ctrl+y has something to use). */
34
+ opened() { this.open = true; }
35
+ /** The engine acted on it: later presses this turn change nothing. */
36
+ acted() { this.spent = true; this.requested = false; }
37
+ pending() { return this.requested; }
38
+ /** True once per request: the engine has acted on it. */
39
+ consume() { const r = this.requested; this.requested = false; return r; }
40
+ /** The stream in flight listens while it runs (one at a time); undefined stops listening. */
41
+ listen(fn) { this.listener = fn; }
42
+ /** A new turn starts clean: a ctrl+y that landed as the last turn ended applies to nothing. */
43
+ reset() { this.requested = false; this.open = false; this.spent = false; this.listener = undefined; }
44
+ }
45
+ /** The assistant message a cut stream leaves in context: the tail of its reasoning, marked as cut, then any answer text
46
+ * it had begun. Empty when nothing had streamed. */
47
+ export function keptPartial(reasoning, text) {
48
+ const r = reasoning.trim();
49
+ const t = text.trim();
50
+ const tail = r.length > OWNER_ACT_REASONING_KEEP ? `…${r.slice(-OWNER_ACT_REASONING_KEEP)}` : r;
51
+ return [tail ? `(my reasoning so far, cut short when the owner asked for an answer)\n${tail}` : "", t].filter(Boolean).join("\n\n");
52
+ }
@@ -80,6 +80,35 @@ export function ranButFailed(result) {
80
80
  return true;
81
81
  return false;
82
82
  }
83
+ const REPORTED = [
84
+ ["type-check", /\b(?:no|0|zero) (?:typescript|type|tsc|ts|type-?check) errors?\b|\b(?:type-?check(?:ing|s)?|tsc)\b(?: (?:is|are|now|still|run|runs|ran|fully|completely))* (?:passe[sd]|passing|clean|succeed(?:s|ed))\b/i],
85
+ ["tests", /\b(?:all (?:the )?)?tests? (?:pass(?:ed|es|ing)?\b|are (?:passing|green)\b|green\b)/i],
86
+ ];
87
+ const TYPECHECK_HEADS = new Set(["tsc", "vue-tsc", "pyright", "mypy"]);
88
+ const TEST_HEADS = new Set(["vitest", "jest", "mocha", "pytest", "rspec", "phpunit", "ctest", "tox", "nox", "bats"]);
89
+ const RUNNERS = new Set(["npm", "pnpm", "yarn", "bun", "npx", "bunx", "deno", "node", "python", "python3", "go", "cargo", "make", "poetry", "uv"]);
90
+ /** The checks one shell command runs: a type-checker, or a test runner (directly, via npx / a package script named for it,
91
+ * `go test`, `cargo test`, `python -m pytest`, `node --test`, `make test`). */
92
+ export function checksRun(cmd) {
93
+ const out = new Set();
94
+ for (const args of segmentArgs(cmd)) {
95
+ const words = args.map((w) => w.replace(/^.*\//, ""));
96
+ const head = words[0];
97
+ const rest = words.slice(1);
98
+ const named = RUNNERS.has(head) ? rest.filter((w) => !w.startsWith("-")) : [];
99
+ const script = (named[0] === "run" || named[0] === "exec" ? named[1] : named[0]) ?? "";
100
+ if (TYPECHECK_HEADS.has(head) || TYPECHECK_HEADS.has(script) || /^(?:type-?check|check-?types|types|lint:types)(?::|$)/.test(script))
101
+ out.add("type-check");
102
+ if (TEST_HEADS.has(head) || TEST_HEADS.has(script) || /^(?:test|t)(?::|$)/.test(script) || (head === "node" && rest.includes("--test")) ||
103
+ ((head === "python" || head === "python3") && rest[0] === "-m" && (rest[1] === "pytest" || rest[1] === "unittest")))
104
+ out.add("tests");
105
+ }
106
+ return [...out];
107
+ }
108
+ /** The checks `text` reports as clean (a passing type-check, passing tests). */
109
+ export function reportedChecks(text) {
110
+ return REPORTED.filter(([, re]) => re.test(text)).map(([k]) => k);
111
+ }
83
112
  import { MUTATING_TOOLS } from "../tools/mutating.js"; // single source of truth (see tools/mutating.ts)
84
113
  const VERIFY_TOOLS = new Set(["bash", "shell_exec"]);
85
114
  /** Turn-local ledger. The loop calls observe() after each tool batch, then gate() at the done-exit.
@@ -88,6 +117,7 @@ const VERIFY_TOOLS = new Set(["bash", "shell_exec"]);
88
117
  export class TaskVerification {
89
118
  mutated = false;
90
119
  verified = false;
120
+ ran = new Set(); // run at all this turn: a piped `tsc | head` exits 0 whatever it found
91
121
  /** names[i] / commands[i] / results[i] are index-aligned: a batch of tool calls and their result
92
122
  * strings. `commands[i]` is the shell command for bash/shell_exec calls, "" otherwise. */
93
123
  observe(names, commands, results) {
@@ -98,12 +128,34 @@ export class TaskVerification {
98
128
  this.mutated = true;
99
129
  if (VERIFY_TOOLS.has(name) && isVerifyCmd(commands[i] ?? "") && !ranButFailed(res))
100
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] ?? ""))
133
+ this.ran.add(k);
101
134
  }
102
135
  }
136
+ /** True once a mutating tool succeeded this turn. */
137
+ changedFiles() {
138
+ return this.mutated;
139
+ }
103
140
  /** True ⇒ this turn changed code but never ran a passing check ⇒ nudge, then annotate. */
104
141
  gate() {
105
142
  return this.mutated && !this.verified;
106
143
  }
144
+ /** The checks `answer` reports as clean that never ran this turn ⇒ nudge, then annotate. */
145
+ unrun(answer) {
146
+ return reportedChecks(answer).filter((k) => !this.ran.has(k));
147
+ }
148
+ }
149
+ const CHECK_COMMAND = { "type-check": "the type-check (for TypeScript: `npx tsc --noEmit`)", tests: "the test suite" };
150
+ /** Injected for ONE extra round when the answer reports a check that never ran this turn. */
151
+ export function unrunCheckReminder(checks) {
152
+ return `[verify-before-done] Your answer reports ${checks.map((k) => (k === "tests" ? "passing tests" : "a clean type-check")).join(" and ")}, ` +
153
+ `but ${checks.length > 1 ? "neither" : "it never"} ran this turn${checks.includes("type-check") ? " — a bundle/build step (vite, esbuild) does not type-check" : ""}. Run ` +
154
+ `${checks.map((k) => CHECK_COMMAND[k]).join(" and ")} now and report what it printed, or say plainly that it is unverified.`;
155
+ }
156
+ /** Prefixed to the final answer when it still reports a check that never ran (reminder spent). */
157
+ export function unrunCheckBanner(checks) {
158
+ return `⚠ Not verified — this answer reports ${checks.map((k) => (k === "tests" ? "passing tests" : "a clean type-check")).join(" and ")}, but ${checks.length > 1 ? "neither" : "it never"} ran this turn.\n\n`;
107
159
  }
108
160
  /** Injected as a user-role message for the ONE extra round. Prefixed so its provenance is unmistakably the
109
161
  * harness, not the user. Authorizes an honest escape so a docs edit / no-test repo ends cleanly, not stuck. */
@@ -7,6 +7,7 @@ import { join, dirname } from "node:path";
7
7
  // SRFT (Step Rejection Fine-Tuning) — per-step masking for trajectories
8
8
  // ---------------------------------------------------------------------------
9
9
  import { applySRFTMask, isPromotable, DEFAULT_SCORE_THRESHOLD } from "./srft.js";
10
+ import { rowLooped } from "../engine/loop-guard.js";
10
11
  export { applySRFTMask, isPromotable } from "./srft.js"; // one import surface for existing consumers
11
12
  /** The reward-score promotion threshold in effect: KODE_FLYWHEEL_SCORE_THRESHOLD if set, else the default. */
12
13
  export function scoreThreshold() {
@@ -218,7 +219,8 @@ export class FlywheelProcessor {
218
219
  const row = JSON.parse(line);
219
220
  // Promotion gate: a real reward score (written back by the scoring daemon) decides when present;
220
221
  // until then fall back to the capture-time `graded` boolean. Replaces the bare `if (row.graded)`.
221
- if (isPromotable(row, threshold)) {
222
+ // A looped row never trains, whatever it scored — rows from before the tag are judged from their steps.
223
+ if (isPromotable({ ...row, looped: rowLooped(row) }, threshold)) {
222
224
  allRows.push(row);
223
225
  }
224
226
  }
@@ -2,11 +2,15 @@
2
2
  * score is the "good enough to train on" floor (dpo_pipeline.py treats >0 as the high side). Override with
3
3
  * KODE_FLYWHEEL_SCORE_THRESHOLD. */
4
4
  export const DEFAULT_SCORE_THRESHOLD = 0;
5
- /** The promotion gate for a flywheel row. A REAL reward score, once the scoring daemon has written it onto
6
- * the row, is the authority: promote iff `score >= threshold`. Until a score exists the gate falls back to
7
- * the capture-time `graded` boolean (the safe default) so nothing in the loop stalls waiting for the daemon.
8
- * Pure — no imports — so it is shared by the processor, the consolidation extractor, and tests alike. */
5
+ /** The promotion gate for a flywheel row. A looped row (selfimprove tags it; the processor judges older rows from
6
+ * their steps) is never promotable, whatever its score: the reward model reads the prompt and the final answer only,
7
+ * so it scored 11/02's re-read loop continuation +2.63. Otherwise a REAL reward score, once the scoring daemon has
8
+ * written it onto the row, is the authority: promote iff `score >= threshold`. Until a score exists the gate falls
9
+ * back to the capture-time `graded` boolean (the safe default) so nothing in the loop stalls waiting for the daemon.
10
+ * Pure — no imports — so it is shared by the processor and tests alike. */
9
11
  export function isPromotable(row, threshold = DEFAULT_SCORE_THRESHOLD) {
12
+ if (row.looped === true)
13
+ return false;
10
14
  if (typeof row.score === "number" && Number.isFinite(row.score))
11
15
  return row.score >= threshold;
12
16
  return row.graded === true;
@@ -5,6 +5,7 @@
5
5
  // Pre/PostToolUse hooks are configured, so the default path has zero overhead.
6
6
  import { spawn } from "node:child_process";
7
7
  import { ownChild } from "../util/owned-children.js";
8
+ import { callReport } from "../engine/batch-scheduler.js";
8
9
  function matcherHits(matcher, toolName) {
9
10
  if (matcher === undefined || matcher === "" || matcher === "*")
10
11
  return true;
@@ -160,11 +161,13 @@ function hasToolHooks(config) {
160
161
  export function withHooks(inner, config, opts) {
161
162
  if (!hasToolHooks(config))
162
163
  return inner;
163
- const gated = async (name, args) => {
164
+ const gated = async (name, args, report) => {
164
165
  const pre = await runHooks("PreToolUse", { tool_name: name, tool_input: args }, config, opts);
165
- if (pre.blocked)
166
+ if (pre.blocked) {
167
+ report?.refused("blocked");
166
168
  return DENIED_BY_HOOK(name, pre.reason);
167
- const result = await inner.execute(name, args);
169
+ }
170
+ const result = await inner.execute(name, args, report);
168
171
  const post = await runHooks("PostToolUse", { tool_name: name, tool_input: args, tool_response: result }, config, opts);
169
172
  if (post.blocked && post.reason)
170
173
  return `${result}\n\n[PostToolUse hook] ${post.reason}`;
@@ -174,21 +177,22 @@ export function withHooks(inner, config, opts) {
174
177
  };
175
178
  return {
176
179
  sched: inner.sched,
177
- execute: (name, args) => gated(name, args),
178
- executeParallel: async (calls, onSettle, signal) => {
180
+ execute: (name, args, report) => gated(name, args, report),
181
+ executeParallel: async (calls, onSettle, signal, onStart) => {
179
182
  // Hooks active ⇒ run sequentially so every call is gated (the inner scheduler's conflict-ordering is a
180
183
  // superset of sequential, so correctness holds; the perf cost applies only when hooks are configured).
181
184
  const results = [];
182
185
  for (let i = 0; i < calls.length; i++) {
183
186
  if (signal?.aborted) {
184
187
  results.push(`error: cancelled`);
185
- onSettle?.(i, results[i]);
188
+ onSettle?.(i, results[i], "cancelled");
186
189
  continue;
187
190
  }
188
191
  const c = calls[i];
189
- const r = await gated(c.name, c.args);
192
+ const report = callReport(onStart && (() => onStart(i))); // started by the layer below once the hook lets it go
193
+ const r = await gated(c.name, c.args, report);
190
194
  results.push(r);
191
- onSettle?.(i, r);
195
+ onSettle?.(i, r, report.why);
192
196
  }
193
197
  return results;
194
198
  },
package/dist/mcp/index.js CHANGED
@@ -136,7 +136,7 @@ export function withMcp(local, hub) {
136
136
  return {
137
137
  ready: () => hub?.discover() ?? Promise.resolve(),
138
138
  mcpSchemas: () => hub?.schemas() ?? [],
139
- execute: (name, args) => (hub?.has(name) ? hub.call(name, args) : local.execute(name, args)),
139
+ execute: (name, args, report) => (hub?.has(name) ? (report?.started(), hub.call(name, args)) : local.execute(name, args, report)),
140
140
  // BTX: ONE scheduled batch across local AND hub lanes (the old split-then-Promise.all started
141
141
  // hub calls alongside any local batch — cross-lane ordering was luck). Finding B (nova review):
142
142
  // this layer now EXPOSES its own hub-aware sched so OUTER wrappers keep per-session truth
@@ -146,14 +146,19 @@ export function withMcp(local, hub) {
146
146
  classify: (n) => (hub?.has(n) ? "write" : local.sched ? local.sched.classify(n) : "write"),
147
147
  keys: (n, a) => (hub?.has(n) ? ["mcp:" + n.split(":")[0]] : local.sched ? local.sched.keys(n, a) : defaultKeys(n, a)),
148
148
  },
149
- executeParallel: (calls, onSettle, signal) => runBatch(calls, {
149
+ executeParallel: (calls, onSettle, signal, onStart) => runBatch(calls, {
150
150
  classify: (n) => (hub?.has(n) ? "write" : local.sched ? local.sched.classify(n) : "write"),
151
151
  keys: (n, a) => (hub?.has(n) ? ["mcp:" + n.split(":")[0]] : local.sched ? local.sched.keys(n, a) : defaultKeys(n, a)),
152
- runOne: (c) => {
152
+ runOne: (c, report) => {
153
153
  const sc = c;
154
- return hub?.has(sc.name) ? hub.call(sc.name, sc.args) : local.execute(sc.name, sc.args);
154
+ if (!hub?.has(sc.name))
155
+ return local.execute(sc.name, sc.args, report);
156
+ report.started();
157
+ return hub.call(sc.name, sc.args);
155
158
  },
156
159
  onSettle,
160
+ onStart,
161
+ startsBelow: true,
157
162
  signal,
158
163
  }),
159
164
  };
@@ -3,6 +3,7 @@ import { EventSink } from "../telemetry/events.js";
3
3
  import { centralRecording } from "../telemetry/ingest.js";
4
4
  import { runBatch, defaultClassify, defaultKeys, cancelledResult } from "../engine/batch-scheduler.js";
5
5
  import { registrySafeTools } from "./tier.js";
6
+ import { heldForPlanReview } from "./plan-review.js";
6
7
  export { PermissionPolicy } from "./policy.js";
7
8
  const NO_RETRY = "Do not retry this call or an equivalent; choose another approach or ask the user.";
8
9
  const DENIED = (name, why) => `Permission denied: "${name}" was denied ` +
@@ -33,16 +34,17 @@ export function withPermissions(inner, policy, opts = {}) {
33
34
  // `batch` carries the round identity a PendingToolCall was stamped with (engine/agent.ts's
34
35
  // runToolCalls) onto every ToolEvent this call emits — absent for the single-call execute() path,
35
36
  // which has no round context.
36
- async function gate(name, args, exec, batch, signal) {
37
+ async function gate(name, args, exec, batch, signal, report) {
37
38
  const digest = digestArgs(name, args);
38
39
  const argHash = recording() ? argHashOf(args, digest) : undefined; // hashed BEFORE the tool runs: the args as issued
39
40
  const denyKey = `${name}\0${argHashOf(args, digest)}`;
40
41
  const prior = denied.get(denyKey);
41
42
  if (prior) {
42
43
  tool({ name, args: digest, decision: "deny", outcome: "denied", approved: false, ...batch }, argHash);
44
+ report?.refused("blocked");
43
45
  return REPEAT_DENIED(prior);
44
46
  }
45
- const refuse = (msg) => { denied.set(denyKey, msg); return msg; };
47
+ const refuse = (msg) => { denied.set(denyKey, msg); report?.refused("blocked"); return msg; };
46
48
  const decision = policy.decide(name, args);
47
49
  const t0 = performance.now();
48
50
  if (decision === "deny") {
@@ -60,22 +62,39 @@ export function withPermissions(inner, policy, opts = {}) {
60
62
  // A human-signature line (money/prod/destructive) surfaces as its own control event so a dashboard/
61
63
  // mobile flags WHY a human was pulled in — and a background sub-agent (no approver) is denied below.
62
64
  const line = policy.signatureLineFor(name, args);
63
- if (line)
64
- sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name}` } });
65
- approved = opts.approve ? await opts.approve(name, args) : false; // no approver ⇒ fail-safe deny
66
- if (!approved) {
65
+ const plan = line ? policy.planAnswer(line) : null;
66
+ if (line && plan === "hold") {
67
+ // Autonomous: the plan the owner approved does not list this class. Held, never prompted, and not remembered as
68
+ // a denial — the same call runs once a plan that lists it is approved.
69
+ sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name} (held for plan review)` } });
67
70
  tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch }, argHash);
68
- return refuse(DENIED(name, opts.approve ? "user" : "no-approver"));
71
+ return heldForPlanReview(name, line, policy.approvedPlanClasses());
72
+ }
73
+ if (plan === "run") {
74
+ approved = true; // the owner approved this class with the plan
75
+ // still a signature-line call: the dashboard's critical feed shows it ran, and on whose say-so
76
+ sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name} (run under approved plan)` } });
77
+ }
78
+ else {
79
+ if (line)
80
+ sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name}` } });
81
+ approved = opts.approve ? await opts.approve(name, args) : false; // no approver ⇒ fail-safe deny
82
+ if (!approved) {
83
+ tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch }, argHash);
84
+ return refuse(DENIED(name, opts.approve ? "user" : "no-approver"));
85
+ }
69
86
  }
70
87
  }
71
88
  // An esc during the (human) approval wait: the approval may land AFTER the interrupt, and an approved edit
72
89
  // must not then execute. Recorded as an error (the wire outcome enum is frozen; nothing was refused by policy).
73
90
  if (signal?.aborted) {
74
91
  tool({ name, args: digest, decision, outcome: "error", approved, durationMs: performance.now() - t0, ...batch }, argHash);
92
+ report?.refused("cancelled");
75
93
  return cancelledResult(name);
76
94
  }
77
95
  let result;
78
96
  try {
97
+ report?.started();
79
98
  result = await exec();
80
99
  }
81
100
  catch (e) {
@@ -91,27 +110,29 @@ export function withPermissions(inner, policy, opts = {}) {
91
110
  // The inner toolset's batch-classification truth, forwarded: withDeferred (and any outer wrapper) reads `.sched`
92
111
  // to decide which calls may overlap. Dropping it silently serialized every call of a wrapped session.
93
112
  sched: inner.sched,
94
- execute: (name, args) => gate(name, args, () => inner.execute(name, args)),
113
+ execute: (name, args, report) => gate(name, args, () => inner.execute(name, args, report), undefined, report?.signal, report),
95
114
  // BTX: batch ordering is SCHEDULED, not Promise.raced. Each slot's run is the FULL gate chain
96
115
  // (decision + approval + inner.execute), so per-call modal latency pipelines exactly as before —
97
116
  // but conflicting resources serialize in input order through the shared DAG scheduler. The old
98
117
  // Promise.all-over-execute() dropped the 0.1.225 walk at this layer: a gated batch of
99
118
  // [write f, read f] raced, the read deterministically observing pre-write state on slow writes.
100
- executeParallel: (calls, onSettle, signal) => {
119
+ executeParallel: (calls, onSettle, signal, onStart) => {
101
120
  const safe = new Set(registrySafeTools());
102
121
  return runBatch(calls, {
103
122
  // prefer the INNER executor's classification truth (per-session toolset); fall back to the
104
123
  // global registry's safe list only when inner exposes no sched (third-party executors).
105
124
  classify: inner.sched ? inner.sched.classify : defaultClassify("", (n) => safe.has(n)),
106
125
  keys: inner.sched ? (n, a) => inner.sched.keys(n, a) : defaultKeys,
107
- runOne: (c) => {
126
+ runOne: (c, report) => {
108
127
  const sc = c;
109
128
  const batch = sc.batchId !== undefined
110
129
  ? { batchId: sc.batchId, batchSize: sc.batchSize ?? calls.length, batchIndex: sc.batchIndex ?? calls.findIndex((x) => x.id === sc.id) }
111
130
  : undefined;
112
- return gate(sc.name, sc.args, () => inner.execute(sc.name, sc.args), batch, signal);
131
+ return gate(sc.name, sc.args, () => inner.execute(sc.name, sc.args, report), batch, signal, report);
113
132
  },
114
133
  onSettle,
134
+ onStart,
135
+ startsBelow: true,
115
136
  signal,
116
137
  });
117
138
  },
@@ -0,0 +1,42 @@
1
+ export const MODE_CYCLE = ["auto", "manual", "plan"];
2
+ /** The mode a session starts in: gated when the settings say so, else Autonomous. */
3
+ export function initialMode(configured) {
4
+ return configured === "gated" ? "gated" : "auto";
5
+ }
6
+ /** shift+tab. Gated is not in the cycle: shift+tab leaves it for Plan, where it led before, and never returns to it. */
7
+ export function nextMode(cur) {
8
+ if (cur === "gated")
9
+ return "plan";
10
+ return MODE_CYCLE[(MODE_CYCLE.indexOf(cur) + 1) % MODE_CYCLE.length];
11
+ }
12
+ /** `/mode <name>`. "gated" names per-mutation approval; through 0.1.351 it was an alias of manual. */
13
+ export function parseMode(arg) {
14
+ const a = arg.trim().toLowerCase();
15
+ if (a === "plan")
16
+ return "plan";
17
+ if (a === "manual")
18
+ return "manual";
19
+ if (a === "gated")
20
+ return "gated";
21
+ if (a === "auto" || a === "autonomous" || a === "bypass")
22
+ return "auto";
23
+ return null;
24
+ }
25
+ /** `/plan`: on from any mode, and off back to the mode that was in force when plan mode began. Never a less-gated mode
26
+ * than that: a remote follower may send /plan (safe-commands.ts) but not /mode, and "/plan twice" used to land a
27
+ * Gated host in Autonomous, which runs every mutation and computer control unprompted. */
28
+ export function planToggleTarget(current, beforePlan) {
29
+ if (current !== "plan")
30
+ return "plan";
31
+ return beforePlan === "plan" ? "gated" : beforePlan;
32
+ }
33
+ /** The permission config a non-plan mode runs with, and whether plan review is on. `base` is settings.permissions
34
+ * (tier, the owner's rules, allow patterns); `computerAsk` forces each computer-control action to ask (empty when
35
+ * computer control is off). An "audit" seat keeps recording in every mode. */
36
+ export function modePolicy(mode, base, computerAsk) {
37
+ const unprompted = base.mode === "audit" ? "audit" : "bypass";
38
+ if (mode === "auto")
39
+ return { permissions: { ...base, mode: unprompted, rules: { ...base.rules } }, planReview: true };
40
+ const rules = { ...base.rules, ...computerAsk };
41
+ return { permissions: { ...base, mode: mode === "gated" ? "gated" : unprompted, rules }, planReview: false };
42
+ }
@@ -0,0 +1,100 @@
1
+ // Autonomous mode's plan review (owner, 11/03): "autonomous mode has little to no user request interactions (user
2
+ // allows command) and more of planning and asking user to review plan for next steps with task list / scratchpad".
3
+ // Nothing prompts per command. For multi-step work the model writes the plan with task_add and asks once (ask_user
4
+ // with planReview: true → Approve / Adjust / Cancel). A money / prod / destructive call (the signature lines in
5
+ // signature.ts) runs "only if in the plan": approving records the classes the plan listed, and they stand until the
6
+ // plan changes. Any other signature-line call is HELD — denied with an engine note to add the step to the plan.
7
+ // Pure and node-free: the Session owns one PlanApproval and hands it to the permission policy, and the policy asks it
8
+ // on every signature-line call.
9
+ import { ENGINE_NOTE_PREFIX } from "../engine/continuation.js";
10
+ export const RISK_CLASSES = ["money", "prod", "destructive"];
11
+ // What each class covers, in the words the model reads in a held call's note (signature.ts has the patterns).
12
+ const RISK_WHAT = {
13
+ money: "payments, billing",
14
+ prod: "deploys, pushes to main, publishing, service restarts",
15
+ destructive: "recursive or forced deletes, dropping data",
16
+ };
17
+ /** The owner's standing plan approval. `planRevision` is the task list's revision (tools/registry.ts
18
+ * taskPlanRevision): it moves when a step is added or the list is cleared, never on a status update. */
19
+ export class PlanApproval {
20
+ planRevision;
21
+ openSteps;
22
+ classes = new Set();
23
+ revision = null; // the plan revision the owner approved; null = no approved plan
24
+ constructor(planRevision, openSteps = () => 1) {
25
+ this.planRevision = planRevision;
26
+ this.openSteps = openSteps;
27
+ }
28
+ /** The plan's revision now: read it when the review is asked, and pass it to approve(). */
29
+ currentRevision() {
30
+ return this.planRevision();
31
+ }
32
+ /** The owner approved the plan they were shown, including steps of these classes. False, and nothing approved, when
33
+ * a step was added while the review was open (`askedAt`): the owner never saw it. */
34
+ approve(classes, askedAt) {
35
+ if (askedAt !== undefined && askedAt !== this.planRevision()) {
36
+ this.clear();
37
+ return false;
38
+ }
39
+ this.revision = this.planRevision();
40
+ this.classes = new Set(classes);
41
+ return true;
42
+ }
43
+ /** Nothing is approved: the plan was cancelled or is being adjusted, or the conversation started over. */
44
+ clear() {
45
+ this.revision = null;
46
+ this.classes = new Set();
47
+ }
48
+ /** True while the approved plan stands. A step added or the list cleared since then ends it for good, and so does
49
+ * finishing it: with no pending or in_progress step left, a later push or rm -rf is not part of any plan. */
50
+ active() {
51
+ if (this.revision !== null && (this.revision !== this.planRevision() || this.openSteps() === 0))
52
+ this.clear();
53
+ return this.revision !== null;
54
+ }
55
+ approves(line) {
56
+ return this.active() && this.classes.has(line);
57
+ }
58
+ approvedClasses() {
59
+ return this.active() ? RISK_CLASSES.filter((c) => this.classes.has(c)) : [];
60
+ }
61
+ }
62
+ /** ask_user's `risks` argument → the classes it names, in a fixed order; anything else is ignored. A model that sends
63
+ * "prod, destructive" as one string is read the same: the Approve option shows the classes before the owner picks it. */
64
+ export function riskClasses(raw) {
65
+ const list = Array.isArray(raw) ? raw : typeof raw === "string" ? raw.split(/[\s,]+/) : [];
66
+ const named = new Set(list.map((r) => String(r).trim().toLowerCase()));
67
+ return RISK_CLASSES.filter((c) => named.has(c));
68
+ }
69
+ const joinClasses = (cs) => cs.length <= 1 ? cs.join("") : `${cs.slice(0, -1).join(", ")} and ${cs[cs.length - 1]}`;
70
+ /** The plan review's options. The harness sets them, so an approval is recognised by the exact first option. */
71
+ export function planReviewOptions(classes) {
72
+ return [classes.length ? `Approve — including its ${joinClasses(classes)} steps` : "Approve", "Adjust", "Cancel"];
73
+ }
74
+ /** The owner's answer to a plan review → whether it approves the plan, and the tool result the model reads. */
75
+ export function planReviewReply(answer, options, classes) {
76
+ const a = answer.trim();
77
+ const again = "ask for review again (ask_user, planReview: true)";
78
+ if (a === options[0]) {
79
+ return {
80
+ approved: true,
81
+ reply: `The owner APPROVED the plan${classes.length ? ` and its ${joinClasses(classes)} steps` : ""}. Carry it out now ` +
82
+ `without asking again. A money / prod / destructive step of any other class is still held. At the next milestone, ` +
83
+ `report progress in a few lines and ask for review of the next steps (ask_user, planReview: true).`,
84
+ };
85
+ }
86
+ if (a === "Adjust")
87
+ return { approved: false, reply: `The owner wants to adjust the plan. Ask in one short line what to change, update the task list, then ${again}. Do not carry the plan out before they approve it.` };
88
+ if (a === "Cancel")
89
+ return { approved: false, reply: "The owner CANCELLED the plan. Do not carry it out and change nothing; say in one line what you would need to go ahead." };
90
+ return { approved: false, reply: `The owner replied: ${a}\nThat is not an approval. Do what they said (talk it through, or change the plan), then ${again}. Do not carry the plan out before they approve it.` };
91
+ }
92
+ /** The tool result for a held call. It starts as a denial, because the engine and the activity ledger read
93
+ * "Permission denied" as "did not run". */
94
+ export function heldForPlanReview(name, line, approved) {
95
+ const why = approved.length ? `the approved plan covers only ${joinClasses(approved)} steps` : "no approved plan covers it";
96
+ return `Permission denied: "${name}" was HELD, not run: it is a ${line} step (${RISK_WHAT[line]}) and ${why}. ` +
97
+ `${ENGINE_NOTE_PREFIX}In Autonomous mode a money / prod / destructive step runs only when the plan the owner approved ` +
98
+ `lists its class. Add this step to the task list (task_add), go on with the steps that need no such class, and list ` +
99
+ `"${line}" in risks when you ask for the next plan review (ask_user, planReview: true). Do not retry it before the owner approves.`;
100
+ }
@@ -2,7 +2,7 @@
2
2
  // must be approved, or is refused. The CLASS stays inert when constructed without a mode ("bypass":
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
- // Claude Code-style; shift+tab/Autonomous or settings flip it back. "audit" allows-but-records.
5
+ // Claude Code-style; shift+tab or settings leave it (permissions/modes.ts). "audit" allows-but-records.
6
6
  import { registrySafeTools, tierAllows } 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
@@ -49,6 +49,7 @@ export class PermissionPolicy {
49
49
  tier;
50
50
  allow;
51
51
  unattended;
52
+ planReview;
52
53
  constructor(cfg = {}) {
53
54
  this.mode = cfg.mode ?? "bypass";
54
55
  this.rules = cfg.rules ?? {};
@@ -56,12 +57,14 @@ export class PermissionPolicy {
56
57
  this.tier = cfg.tier ?? "admin";
57
58
  this.allow = cfg.allow ?? [];
58
59
  this.unattended = cfg.unattended === true;
60
+ this.planReview = cfg.planReview;
59
61
  }
60
62
  /** True when the policy can never block, prompt, or log — lets the wrapper skip itself entirely (no
61
63
  * overhead). Requires the full-access owner tier: a narrowed tier is always enforced, even in bypass. An
62
- * unattended policy is never inert: with no owner to answer, the signature lines are its only floor. */
64
+ * unattended policy is never inert: with no owner to answer, the signature lines are its only floor. Nor is
65
+ * one under plan review: the signature lines are what it holds. */
63
66
  get inert() {
64
- return this.mode === "bypass" && this.tier === "admin" && !this.unattended && Object.keys(this.rules).length === 0;
67
+ return this.mode === "bypass" && this.tier === "admin" && !this.unattended && !this.planReview && Object.keys(this.rules).length === 0;
65
68
  }
66
69
  /** Whether tool actions should be recorded. On in audit/gated, or whenever a tier is enforced (a
67
70
  * multi-tenant seat is always audited — "who did what" is the point of a seat). */
@@ -84,9 +87,17 @@ export class PermissionPolicy {
84
87
  signatureLineFor(name, args) {
85
88
  return this.inert ? null : signatureLine(name, args);
86
89
  }
90
+ /** Autonomous mode's answer to a signature line, given in place of a prompt: "run" when the plan the owner
91
+ * approved lists the class, "hold" when it does not, null without plan review (a human is asked per call). */
92
+ planAnswer(line) {
93
+ return this.planReview ? (this.planReview.approves(line) ? "run" : "hold") : null;
94
+ }
95
+ approvedPlanClasses() {
96
+ return this.planReview?.approvedClasses() ?? [];
97
+ }
87
98
  /** The decision for one tool call. Precedence: tier ceiling (a denied tool can't be granted by any
88
- * rule) → human-signature line (money/prod/destructive always ask, beating a rule/mode) → per-tool
89
- * rule → allowlist pattern match → mode. */
99
+ * rule) → human-signature line (money/prod/destructive always ask, beating a rule/mode; under plan
100
+ * review the approved plan answers — see planAnswer) → per-tool rule → allowlist pattern match → mode. */
90
101
  decide(name, args) {
91
102
  if (!this.allowsTool(name))
92
103
  return "deny"; // tier ceiling — absolute, above rules and mode
@@ -36,20 +36,25 @@ const DESTRUCTIVE_CMD = [
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
38
  ];
39
- function blob(args) {
39
+ function blob(name, args) {
40
40
  const cmd = typeof args.command === "string" ? args.command : "";
41
41
  // git_command passes the subcommand array (["push","--force",...]) with no leading "git" — prepend it so
42
42
  // the git patterns match, mirroring how the audit digest renders git calls.
43
43
  const gitArgs = Array.isArray(args.args) ? `git ${args.args.join(" ")}` : "";
44
44
  const query = typeof args.query === "string" ? args.query : typeof args.sql === "string" ? args.sql : "";
45
- return `${cmd} ${gitArgs} ${query}`.trim();
45
+ // computer_applescript carries arbitrary AppleScript (`do shell script "rm -rf …"`) and computer_type types into
46
+ // whatever has focus, a terminal included: both reach a shell without passing through bash. `text` is read for
47
+ // computer_type only — voice and messaging tools take a `text` too, and it is prose there.
48
+ const script = typeof args.script === "string" ? args.script : "";
49
+ const typed = name === "computer_type" && typeof args.text === "string" ? args.text : "";
50
+ return `${cmd} ${gitArgs} ${query} ${script} ${typed}`.trim();
46
51
  }
47
52
  /** Which signature line a call crosses, or null. Checked on every gated call: null lets the normal
48
53
  * policy decide; a non-null value forces approval (and, absent an approver, a deny). */
49
54
  export function signatureLine(name, args) {
50
55
  if (MONEY_NAME.test(name))
51
56
  return "money";
52
- const b = blob(args);
57
+ const b = blob(name, args);
53
58
  if (b) {
54
59
  if (DESTRUCTIVE_CMD.some((re) => re.test(b)))
55
60
  return "destructive";
@@ -3,7 +3,7 @@
3
3
  // (broader). A follower may ONLY drive names in this list — everything else is refused in onCommand.
4
4
  //
5
5
  // Deliberately EXCLUDES (in addition to exit/login/remote):
6
- // mode — `/mode auto` flips host policy to bypass (ungated tool/MCP execution)
6
+ // mode — `/mode auto|manual` drops the host's per-mutation gate (Autonomous also runs computer control unprompted)
7
7
  // mcp — `/mcp on` enables the full fleet MCP surface for the host session
8
8
  // bg — spawns background agents with host privileges
9
9
  // Those remain local-owner-only. A follower already has `prompt` (runs under current host mode);