@0perator/operator 0.2.4 → 0.2.6

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 (49) hide show
  1. package/dist/autonomy/delegate-mode.js +4 -1
  2. package/dist/autonomy/delegate.js +3 -13
  3. package/dist/background/index.js +7 -10
  4. package/dist/background/notices.js +1 -1
  5. package/dist/cli.js +31 -14
  6. package/dist/config/persona.js +20 -3
  7. package/dist/engine/agent.js +62 -7
  8. package/dist/engine/aurora.js +30 -30
  9. package/dist/engine/batch-hints.js +45 -0
  10. package/dist/engine/batch-scheduler.js +23 -7
  11. package/dist/engine/decision-points.js +12 -2
  12. package/dist/engine/delegate-turn.js +24 -0
  13. package/dist/engine/grandmaster.js +28 -11
  14. package/dist/mcp/index.js +2 -2
  15. package/dist/permissions/modes.js +7 -3
  16. package/dist/session.js +65 -12
  17. package/dist/tools/classes.js +4 -0
  18. package/dist/tools/deferred.js +11 -6
  19. package/dist/tools/readonly-shell.js +92 -0
  20. package/dist/tools/registry.js +3 -3
  21. package/dist/tools/shell-session.js +56 -1
  22. package/dist/ui/ActivitySpinner.js +2 -2
  23. package/dist/ui/App.js +9 -9
  24. package/dist/ui/ApprovalPrompt.js +5 -4
  25. package/dist/ui/ArtifactPicker.js +4 -3
  26. package/dist/ui/AuthScreen.js +2 -1
  27. package/dist/ui/BgPanel.js +11 -8
  28. package/dist/ui/Composer.js +4 -3
  29. package/dist/ui/Header.js +2 -2
  30. package/dist/ui/Markdown.js +50 -77
  31. package/dist/ui/PlanPane.js +5 -5
  32. package/dist/ui/QuestionPrompt.js +2 -1
  33. package/dist/ui/SecretPrompt.js +2 -1
  34. package/dist/ui/SessionPicker.js +4 -3
  35. package/dist/ui/SkillFinder.js +3 -2
  36. package/dist/ui/StatsCard.js +2 -2
  37. package/dist/ui/StatusRule.js +2 -2
  38. package/dist/ui/SummaryCard.js +2 -2
  39. package/dist/ui/Table.js +25 -24
  40. package/dist/ui/ThinkingSpinner.js +2 -1
  41. package/dist/ui/ToolBatch.js +3 -3
  42. package/dist/ui/ToolStep.js +4 -4
  43. package/dist/ui/Transcript.js +12 -12
  44. package/dist/ui/UpdatePrompt.js +2 -1
  45. package/dist/ui/inline.js +109 -0
  46. package/dist/ui/reportLine.js +2 -0
  47. package/dist/ui/slashCommands.js +2 -2
  48. package/dist/ui/theme.js +4 -0
  49. package/package.json +1 -1
@@ -0,0 +1,45 @@
1
+ // Two short engine notes that suggest wider rounds: reads sent one at a time, and a plan whose parts do not depend on
2
+ // each other. Each at most once per turn; they ride the conversation's tail, never the system prompt or the tools.
3
+ import { BATCHABLE_READ, DELEGATION, SHELL_FOREGROUND } from "../tools/classes.js";
4
+ import { isReadOnlyCommand } from "../tools/readonly-shell.js";
5
+ export const SINGLE_READ_ROUNDS = 4;
6
+ export const BATCH_HINT = `The last ${SINGLE_READ_ROUNDS} rounds each made one read-only call. When calls do not depend on each other, send them together in one message.`;
7
+ export const FANOUT_HINT = "The plan has independent parts. spawn_agent can run them in parallel, one `tasks` entry each, if that is faster than doing them yourself.";
8
+ const argsOf = (c) => { try {
9
+ return JSON.parse(c.function.arguments || "{}") ?? {};
10
+ }
11
+ catch {
12
+ return {};
13
+ } };
14
+ const readOnly = (c) => BATCHABLE_READ.has(c.function.name) || (SHELL_FOREGROUND.has(c.function.name) && isReadOnlyCommand(argsOf(c).command));
15
+ const PATH = /(?:[\w.~-]*\/[\w./~-]+|\b[\w-]+\.[a-z]{1,5}\b)/i;
16
+ const DEPENDS = /\b(then|after|once|based on|using|verify|test|check|review|combine|merge|summar\w+|report|commit)\b/i;
17
+ /** Three or more new steps, each on its own file or folder, none worded as following another. */
18
+ function independentPlan(c) {
19
+ if (c.function.name !== "task_add")
20
+ return false;
21
+ const tasks = argsOf(c).tasks;
22
+ if (!Array.isArray(tasks))
23
+ return false;
24
+ const targets = tasks.map((t) => (typeof t === "string" && !DEPENDS.test(t) ? PATH.exec(t)?.[0] : undefined)).filter(Boolean);
25
+ return targets.length >= 3 && targets.length === tasks.length && new Set(targets).size === targets.length;
26
+ }
27
+ export function batchHints(canSpawn) {
28
+ let singles = 0;
29
+ let batched = false;
30
+ let fannedOut = false;
31
+ return (calls) => {
32
+ if (calls.some((c) => DELEGATION.has(c.function.name)))
33
+ fannedOut = true;
34
+ singles = calls.length === 1 && readOnly(calls[0]) ? singles + 1 : 0;
35
+ if (canSpawn && !fannedOut && calls.some(independentPlan)) {
36
+ fannedOut = true;
37
+ return FANOUT_HINT;
38
+ }
39
+ if (!batched && singles >= SINGLE_READ_ROUNDS) {
40
+ batched = true;
41
+ return BATCH_HINT;
42
+ }
43
+ return undefined;
44
+ };
45
+ }
@@ -15,6 +15,7 @@
15
15
  // resource (web_search, memory_search…) never holds a writer back.
16
16
  // • Barrier tools (git_command/checkpoint/computer_*/browser*/delegate_*/…) can touch ANYTHING and
17
17
  // share a device — they run alone, in input order.
18
+ // • A plainly read-only shell ("look") overlaps reads and other looks; writes, shells and barriers keep their order.
18
19
  // • Shell tools (bash/shell_exec) can also touch anything, but INDEPENDENT shells in one round run
19
20
  // concurrently (matches Cursor). A shell waits for every prior non-shell; later non-shells wait for
20
21
  // the whole shell wave. Shells do NOT wait for each other. (Ephemeral one-shot processes when a
@@ -23,6 +24,7 @@
23
24
  // failure never strands its dependents — the chain advances regardless.
24
25
  // Pure JS: no node builtins, no asyncLocalStorage — safe for the neutral engine bundle (run-jsc).
25
26
  import { SCHED_BARRIER, SHELL_FOREGROUND } from "../tools/classes.js";
27
+ import { isReadOnlyCommand } from "../tools/readonly-shell.js";
26
28
  /** The report runBatch hands each runOne — and a hand-rolled batch loop builds the same way: `started` fires `onStart`
27
29
  * once, `why` holds the refusal. */
28
30
  export function callReport(onStart, signal) {
@@ -47,9 +49,9 @@ const BARRIER_PREFIX = ["computer_", "browser", "shell", "mcp__"]; // browser_va
47
49
  // NOTE: "shell" prefix still matches shell_background / shell_*; SHELL_FOREGROUND is checked FIRST so
48
50
  // bash/shell_exec become "shell" (parallelizable) instead of falling through to barrier.
49
51
  export function defaultClassify(_unused, isSafe) {
50
- return (n) => {
52
+ return (n, args) => {
51
53
  if (SHELL_FOREGROUND.has(n))
52
- return "shell";
54
+ return isReadOnlyCommand(args?.command) ? "look" : "shell";
53
55
  if (SCHED_BARRIER.has(n))
54
56
  return "barrier";
55
57
  for (const p of BARRIER_PREFIX)
@@ -107,6 +109,8 @@ export function runBatch(calls, opts) {
107
109
  const keyedReads = []; // prior reads that named a resource (a later conflicting write waits for them)
108
110
  const inflight = new Set(); // everything not yet settled (barrier gate)
109
111
  const shellInflight = new Set(); // shells currently running — other shells skip these
112
+ const looks = new Set(); // read-only shells: later writes wait, other reads do not
113
+ const namedReads = new Set(); // reads that named a resource: a read-only shell need not wait
110
114
  let afterBarrier = Promise.resolve(); // every op must clear the last hard barrier / shell wave
111
115
  // Cancellation: `aborted` settles when the turn is interrupted so queued calls stop waiting on their
112
116
  // predecessors and are cancelled, not run late. The listener is removed when the batch ends — a long turn
@@ -130,11 +134,11 @@ export function runBatch(calls, opts) {
130
134
  };
131
135
  for (let i = 0; i < calls.length; i++) {
132
136
  const c = calls[i];
133
- const kind = opts.classify(c.name);
137
+ const kind = opts.classify(c.name, c.args);
134
138
  // Flush before scheduling a non-shell so it observes the whole prior shell wave.
135
139
  if (kind !== "shell")
136
140
  flushShellWave();
137
- let keys = (kind === "barrier" || kind === "shell") ? [] : opts.keys(c.name, c.args);
141
+ let keys = (kind === "barrier" || kind === "shell" || kind === "look") ? [] : opts.keys(c.name, c.args);
138
142
  // no-path MUTATIONS (memory_store, task_add, cron create…): serialize per tool-name lock.
139
143
  // Reads never take the lock — a path-less read pairs with nothing and is safe to overlap.
140
144
  if (kind === "write" && keys.length === 0)
@@ -153,11 +157,19 @@ export function runBatch(calls, opts) {
153
157
  if (!shellInflight.has(p))
154
158
  gate.push(p);
155
159
  }
160
+ else if (kind === "look") {
161
+ // Waits like a shell, except on work that changes nothing: named reads and other read-only shells.
162
+ gate.push(afterBarrier);
163
+ for (const p of inflight)
164
+ if (!looks.has(p) && !namedReads.has(p))
165
+ gate.push(p);
166
+ }
156
167
  else if (kind === "read") {
157
168
  gate.push(afterBarrier); // barriers/shells can change anything a read observes
158
169
  if (!keys.length) {
159
170
  for (const t2 of writeTails.values())
160
171
  gate.push(t2); // path-less read: any prior write may target it
172
+ gate.push(...looks); // it may write (scratchpad), which an earlier look must not see
161
173
  }
162
174
  for (const k of keys) {
163
175
  // A read waits only for PRIOR WRITES on overlapping resources; prior reads never block it.
@@ -167,7 +179,7 @@ export function runBatch(calls, opts) {
167
179
  }
168
180
  }
169
181
  else {
170
- gate.push(afterBarrier);
182
+ gate.push(afterBarrier, ...looks);
171
183
  for (const k of keys) {
172
184
  for (const [wk, wt] of writeTails)
173
185
  if (conflicts(k, wk))
@@ -212,10 +224,14 @@ export function runBatch(calls, opts) {
212
224
  else if (kind === "write")
213
225
  for (const k of keys)
214
226
  writeTails.set(k, run);
215
- else if (keys.length)
227
+ else if (kind === "look")
228
+ looks.add(run);
229
+ else if (keys.length) {
216
230
  keyedReads.push({ keys, run });
231
+ namedReads.add(run);
232
+ }
217
233
  inflight.add(run);
218
- run.then(() => { inflight.delete(run); shellInflight.delete(run); });
234
+ run.then(() => { inflight.delete(run); shellInflight.delete(run); looks.delete(run); namedReads.delete(run); });
219
235
  done.push(run);
220
236
  }
221
237
  return Promise.all(done).then(() => { detach(); return results; });
@@ -5,7 +5,7 @@
5
5
  // owner turn, the FIRST mutating call before any ask_user is held back once and the model is told to offer a
6
6
  // plan + options first — or, in Autonomous mode, to put the plan up for review. Pure and dependency-free so the
7
7
  // gate's trigger logic is unit-testable.
8
- import { SHELL_ANY, isMutatingTool } from "../tools/classes.js";
8
+ import { DISPATCH, SHELL_ANY, isMutatingTool } from "../tools/classes.js";
9
9
  // Shell commands that change the workspace or the machine. Read-only probes (ls, cat, grep, git status, a test
10
10
  // run) are NOT here — the gate must never hold back investigation, only the first change.
11
11
  const MUTATING_SHELL_RE = new RegExp([
@@ -84,6 +84,16 @@ export function decisionPointsEnabled(setting, env = process.env) {
84
84
  return true;
85
85
  return setting !== false;
86
86
  }
87
+ /** A spawn_agent call whose sub-agents may change files: any role but the four that cannot write, or none given. */
88
+ function isWriterSpawn(name, rawArgs) {
89
+ let args = {};
90
+ try {
91
+ args = JSON.parse(rawArgs || "{}");
92
+ }
93
+ catch { /* partial args: a writer */ }
94
+ const real = unwrapToolCall(name ?? "", args);
95
+ return DISPATCH.has(real.name) && !/^(?:research|search|review|plan)$/.test(String(real.args.role ?? ""));
96
+ }
87
97
  /** The gate's per-turn decision: hold back this round's mutating calls and nudge, or let them run. The hold is
88
98
  * ENFORCED, not one-shot — it KEEPS holding every mutating round (re-injecting the nudge) until the model
89
99
  * actually calls ask_user (`askedThisTurn`), so a model cannot just walk past a single nudge. Bounded by
@@ -93,5 +103,5 @@ export function shouldHoldForDecision(s) {
93
103
  return false;
94
104
  if (s.calls.some((c) => c.name === "ask_user"))
95
105
  return false;
96
- return s.calls.some((c) => isMutatingCall(c.name, c.args));
106
+ return s.calls.some((c) => isMutatingCall(c.name, c.args) || (!!s.writerSpawns && isWriterSpawn(c.name, c.args)));
97
107
  }
@@ -0,0 +1,24 @@
1
+ // Delegate mode's turn rules (permissions/modes.ts): which owner messages are asked to fan out, and the one note a turn
2
+ // that did not gets. Pure and dependency-free (agent.ts is also bundled for the browser). Not the delegate GUARD
3
+ // (autonomy/delegate-mode.ts, `/delegate guard`), which fences what delegated work may do.
4
+ import { isStatusAsk } from "./continuation.js";
5
+ /** Tool rounds without a spawn_agent call before the mid-turn note. */
6
+ export const DELEGATE_ROUNDS = 3;
7
+ const SOCIAL = /^(?:(?:hi|hey|hello|yo|howdy|gm|good (?:morning|afternoon|evening|night)|thanks|thank you|thx|ty|cheers|cool|nice|great|awesome|perfect|ok|okay|got it|sounds good|well done|bye|goodbye|there|operator|all|so much|man)[\s,.!:)-]*)+$/i;
8
+ const REQUEST = /^(?:please\b|(?:can|could|would|will) (?:you|we)\b(?!\s+(?:tell|explain)\b))/i;
9
+ const QUESTION = /^(?:what|why|how|where|when|who|which|is|are|am|was|were|does|do|did|can|could|would|will|should|has|have)\b/i;
10
+ /** Whether the owner's message asks for work. A greeting, thanks, a status ask or a one-line question does not. */
11
+ export function isWorkAsk(text) {
12
+ const t = text.trim();
13
+ if (!t || t.startsWith("[engine note") || SOCIAL.test(t) || isStatusAsk(t))
14
+ return false;
15
+ if (t.includes("\n") || t.length > 200 || REQUEST.test(t))
16
+ return true;
17
+ const oneSentence = !/[.!?]\s+\S/.test(t);
18
+ return !(oneSentence && t.endsWith("?") && (QUESTION.test(t) || t.split(/\s+/).length <= 12));
19
+ }
20
+ export const DELEGATE_ROUNDS_NOTE = "Delegate mode: several tool rounds and no spawn_agent call. Hand the independent parts that remain to sub-agents " +
21
+ "with spawn_agent now, or say in one line why not, and carry on.";
22
+ export const DELEGATE_FINAL_NOTE = "Delegate mode: this turn made no spawn_agent call. Your answer above stands and the owner has it. Either call " +
23
+ "spawn_agent now for independent parts still worth covering, or reply with ONE line saying why you did not " +
24
+ "delegate. Do not repeat the answer.";
@@ -11,6 +11,7 @@
11
11
  // mechanical children don't pin the single 1M slot.
12
12
  // Pure + framework-agnostic; node builtins (fs/child_process for verify) load lazily so the neutral bundle
13
13
  // is unaffected. The verify predicate (isVerifyCmd/ranButFailed) is shared with the main-loop verify gate.
14
+ import { FILE_READ, LOCAL_SEARCH, WEB_SEARCH } from "../tools/classes.js";
14
15
  import { isVerifyCmd, ranButFailed } from "./verify-gate.js";
15
16
  import { applySRFTMask } from "../flywheel/srft.js"; // PURE half — node-free, neutral-graph safe
16
17
  // runMutationCheck needs node:fs/child_process — resolved lazily via nodeImport() inside verifyMutation.
@@ -365,8 +366,9 @@ export function routeLane(brief, hint) {
365
366
  * searches it ran, and short excerpts of the last pages. Pure: the caller passes session.snapshot(). */
366
367
  function partialFindings(msgs) {
367
368
  const urls = [];
369
+ const files = [];
368
370
  const queries = [];
369
- const fetchIds = new Set();
371
+ const readIds = new Set();
370
372
  for (const m of msgs) {
371
373
  if (m.role !== "assistant" || !m.tool_calls)
372
374
  continue;
@@ -378,35 +380,50 @@ function partialFindings(msgs) {
378
380
  catch { /* unparseable args: skip */ }
379
381
  if ((c.function.name === "web_fetch" || c.function.name === "browser_read") && typeof a.url === "string") {
380
382
  urls.push(a.url);
381
- fetchIds.add(c.id);
383
+ readIds.add(c.id);
382
384
  }
383
- if ((c.function.name === "web_search" || c.function.name === "deep_research") && typeof (a.query ?? a.question) === "string")
384
- queries.push(String(a.query ?? a.question));
385
+ if (FILE_READ.has(c.function.name)) {
386
+ for (const p of Array.isArray(a.paths) ? a.paths : [a.path])
387
+ if (typeof p === "string") {
388
+ files.push(p);
389
+ readIds.add(c.id);
390
+ }
391
+ }
392
+ const q = a.query ?? a.question ?? a.pattern;
393
+ if ((WEB_SEARCH.has(c.function.name) || LOCAL_SEARCH.has(c.function.name)) && typeof q === "string")
394
+ queries.push(q);
385
395
  }
386
396
  }
387
397
  const notes = [...msgs].reverse().find((m) => m.role === "assistant" && m.content.trim() && !m.content.startsWith("[engine note"))?.content.trim() ?? "";
388
- return { urls, queries, fetchIds, notes };
398
+ return { urls, files, queries, readIds, notes };
389
399
  }
390
400
  /** What a stopped child had gathered, as counts for the owner's one-line report ("partial: 3 sources · 2 searches"). */
391
401
  export function partialCounts(msgs) {
392
- const { urls, queries, notes } = partialFindings(msgs);
402
+ const { urls, files, queries, notes } = partialFindings(msgs);
393
403
  const n = (k, one, many) => `${k} ${k === 1 ? one : many}`;
394
- const sources = new Set(urls).size, searches = new Set(queries).size;
395
- const parts = [sources ? n(sources, "source", "sources") : "", searches ? n(searches, "search", "searches") : "", notes ? "notes" : ""].filter(Boolean);
404
+ const sources = new Set(urls).size, read = new Set(files).size, searches = new Set(queries).size;
405
+ const parts = [sources ? n(sources, "source", "sources") : "", read ? n(read, "file", "files") : "", searches ? n(searches, "search", "searches") : "", notes ? "notes" : ""].filter(Boolean);
396
406
  return parts.length ? `partial: ${parts.join(" · ")}` : "partial: nothing gathered yet";
397
407
  }
408
+ /** A stopped child's conversation without the stop line the engine wrote as its last reply, which is not one of its
409
+ * notes. A reply cut at the output limit is the child's own words and stays. */
410
+ export function beforeStopNote(msgs, r) {
411
+ return r.stopKind !== "length" && msgs.at(-1)?.content === r.content ? msgs.slice(0, -1) : msgs;
412
+ }
398
413
  export function partialReport(msgs, why) {
399
- const { urls, queries, fetchIds, notes } = partialFindings(msgs);
400
- const excerpts = msgs.filter((m) => m.role === "tool" && m.tool_call_id && fetchIds.has(m.tool_call_id) && m.content.trim())
414
+ const { urls, files, queries, readIds, notes } = partialFindings(msgs);
415
+ const excerpts = msgs.filter((m) => m.role === "tool" && m.tool_call_id && readIds.has(m.tool_call_id) && m.content.trim())
401
416
  .slice(-2).map((m) => m.content.replace(/\s+/g, " ").trim().slice(0, 600));
402
417
  const uniq = (xs) => [...new Set(xs)];
403
418
  const parts = [`[${why} — PARTIAL findings below, gathered before it ended; verify before relying on them]`];
404
419
  parts.push(notes ? `Notes so far:\n${notes.slice(0, 3000)}` : "Notes so far: (none written yet)");
405
420
  if (urls.length)
406
421
  parts.push(`Sources read (${uniq(urls).length}):\n${uniq(urls).slice(0, 15).map((u) => `- ${u}`).join("\n")}`);
422
+ if (files.length)
423
+ parts.push(`Files read (${uniq(files).length}):\n${uniq(files).slice(-25).map((p) => `- ${p}`).join("\n")}`);
407
424
  if (queries.length)
408
425
  parts.push(`Searches run: ${uniq(queries).slice(0, 8).map((q) => `"${q}"`).join(" · ")}`);
409
426
  if (excerpts.length)
410
- parts.push(`Last pages read (excerpts):\n${excerpts.map((e) => `> ${e}`).join("\n")}`);
427
+ parts.push(`Last reads (excerpts):\n${excerpts.map((e) => `> ${e}`).join("\n")}`);
411
428
  return parts.join("\n\n");
412
429
  }
package/dist/mcp/index.js CHANGED
@@ -143,11 +143,11 @@ export function withMcp(local, hub) {
143
143
  // through the full composition; finding C: hub tools serialize PER SERVER (mcp:<server> key)
144
144
  // instead of a global barrier — same-server calls keep input order, independent servers overlap.
145
145
  sched: {
146
- classify: (n) => (hub?.has(n) ? "write" : local.sched ? local.sched.classify(n) : "write"),
146
+ classify: (n, a) => (hub?.has(n) ? "write" : local.sched ? local.sched.classify(n, a) : "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
149
  executeParallel: (calls, onSettle, signal, onStart) => runBatch(calls, {
150
- classify: (n) => (hub?.has(n) ? "write" : local.sched ? local.sched.classify(n) : "write"),
150
+ classify: (n, a) => (hub?.has(n) ? "write" : local.sched ? local.sched.classify(n, a) : "write"),
151
151
  keys: (n, a) => (hub?.has(n) ? ["mcp:" + n.split(":")[0]] : local.sched ? local.sched.keys(n, a) : defaultKeys(n, a)),
152
152
  runOne: (c, report) => {
153
153
  const sc = c;
@@ -1,4 +1,5 @@
1
- export const MODE_CYCLE = ["auto", "manual", "plan"];
1
+ export const MODE_CYCLE = ["auto", "delegate", "manual", "plan"];
2
+ export const MODE_NAME = { auto: "Autonomous", delegate: "Delegate", manual: "Manual", plan: "Plan", gated: "Gated" };
2
3
  /** The mode a session starts in: gated when the settings say so, else Autonomous. */
3
4
  export function initialMode(configured) {
4
5
  return configured === "gated" ? "gated" : "auto";
@@ -16,6 +17,8 @@ export function parseMode(arg) {
16
17
  return "plan";
17
18
  if (a === "manual")
18
19
  return "manual";
20
+ if (a === "delegate")
21
+ return "delegate";
19
22
  if (a === "gated")
20
23
  return "gated";
21
24
  if (a === "auto" || a === "autonomous" || a === "bypass")
@@ -35,8 +38,9 @@ export function planToggleTarget(current, beforePlan) {
35
38
  * computer control is off). An "audit" seat keeps recording in every mode. */
36
39
  export function modePolicy(mode, base, computerAsk) {
37
40
  const unprompted = base.mode === "audit" ? "audit" : "bypass";
38
- if (mode === "auto")
39
- return { permissions: { ...base, mode: unprompted, rules: { ...base.rules } }, planReview: true };
41
+ if (mode === "auto" || mode === "delegate") {
42
+ return { permissions: { ...base, mode: unprompted, rules: { ...base.rules } }, planReview: true, ...(mode === "delegate" ? { delegate: true } : {}) };
43
+ }
40
44
  const rules = { ...base.rules, ...computerAsk };
41
45
  return { permissions: { ...base, mode: mode === "gated" ? "gated" : unprompted, rules }, planReview: false };
42
46
  }
package/dist/session.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // Headless session controller — owns the conversation + engine wiring for ONE interactive session,
2
2
  // with no UI dependency, so it is testable end-to-end without a TTY. cli.tsx is a thin Ink shell
3
3
  // that maps these callbacks onto React state; a test can drive the same `send()` directly.
4
+ import { DELEGATION, CAN_WRITE } from "./tools/classes.js";
4
5
  import { runTurn, TurnAbortedError } from "./engine/agent.js";
5
6
  import { recordTruncation } from "./observability/blackbox.js";
6
7
  import { Conversation, placeSessionContext, SESSION_CONTEXT_OPEN, SESSION_CONTEXT_CLOSE, SESSION_CONTEXT_REQUEST_LINE } from "./engine/messages.js";
@@ -28,6 +29,7 @@ import { operatorPath } from "./config/home.js";
28
29
  import { moaTeam, plannerBrief } from "./engine/moa.js";
29
30
  import { WATERFALL_MODEL_ID, WATERFALL_SEATS, waterfallTeam, waterfallTier } from "./engine/waterfall.js";
30
31
  import { routeTurn } from "./classifier/route.js";
32
+ import { isWorkAsk } from "./engine/delegate-turn.js";
31
33
  import { engineNote, isStatusAsk, STATUS_FIRST_NOTE } from "./engine/continuation.js";
32
34
  import { withDelegateDefault } from "./autonomy/delegate.js";
33
35
  import { withDelegateGuard } from "./autonomy/delegate-mode.js";
@@ -53,7 +55,7 @@ import { McpHub, withMcp } from "./mcp/index.js";
53
55
  import { deferredEnabled, deferredRequestSchemas, deferredState, withDeferred, nativeCatalog, setNativeCatalogMcp, withNativeDeferred } from "./tools/deferred.js";
54
56
  import { withPermissions, PermissionPolicy } from "./permissions/index.js";
55
57
  import { PlanApproval, planReviewOptions, planReviewReply, riskClasses } from "./permissions/plan-review.js";
56
- import { AUTONOMOUS_MODE_ON, AUTONOMOUS_MODE_OFF } from "./config/persona.js";
58
+ import { AUTONOMOUS_MODE_ON, AUTONOMOUS_MODE_OFF, DELEGATE_MODE_OFF, delegateModeOn } from "./config/persona.js";
57
59
  import { withHooks } from "./hooks/index.js";
58
60
  import { servedTask } from "./engine/loop-guard.js";
59
61
  import { Telemetry } from "./observability/index.js";
@@ -492,6 +494,10 @@ export class Session {
492
494
  decisionPoints;
493
495
  planReview = false; // Autonomous mode: plan reviews instead of per-command prompts (setOperatingMode)
494
496
  planReviewTold = false; // what the conversation last told the model about Autonomous mode (modeCarry)
497
+ delegateMode = false; // Delegate mode: work turns are asked to fan out (delegateCarry)
498
+ delegateTold = false; // the conversation carries a Delegate mode note not yet withdrawn
499
+ spawnLanes;
500
+ canSpawn;
495
501
  planApproval = new PlanApproval(taskPlanRevision, openTaskCount); // the owner's standing plan approval, read by the policy
496
502
  planMode = false; // /plan: research read-only + propose a plan, no mutations until the owner approves
497
503
  thinkMode = "off"; // /think, /ultrathink — extended reasoning
@@ -657,6 +663,8 @@ export class Session {
657
663
  if (this.hub)
658
664
  this.hub.spillSink = spillToolOutput; // GW-10-COMPLETE: offload huge MCP results too
659
665
  this.planReview = cfg.planReview === true;
666
+ this.canSpawn = !!cfg.spawnAgent;
667
+ this.spawnLanes = cfg.spawnSlots;
660
668
  this.permissionCfg = this.underReview(cfg.permissions ?? { mode: "bypass" });
661
669
  this.policy = new PermissionPolicy(this.permissionCfg);
662
670
  this.approve = cfg.approve;
@@ -827,6 +835,7 @@ export class Session {
827
835
  * ends when the plan changes. */
828
836
  setOperatingMode(m) {
829
837
  this.planReview = m.planReview;
838
+ this.delegateMode = m.delegate === true;
830
839
  // keep what /allow added this session: the mode's config is built from the startup settings, which lack it
831
840
  const allow = [...new Set([...(m.permissions.allow ?? []), ...(this.permissionCfg.allow ?? [])])];
832
841
  this.permissionCfg = this.underReview(allow.length ? { ...m.permissions, allow } : m.permissions);
@@ -842,10 +851,27 @@ export class Session {
842
851
  const on = this.planReview && !this.planMode;
843
852
  return { note: on === this.planReviewTold ? "" : engineNote(on ? AUTONOMOUS_MODE_ON : AUTONOMOUS_MODE_OFF), on };
844
853
  }
845
- /** What a compaction summary must keep: the active skill, and Autonomous mode's rules while they apply. */
854
+ inDelegateMode() {
855
+ return this.delegateMode;
856
+ }
857
+ /** Delegate mode's note for this message. While on, each owner message that asks for work carries the rules, and
858
+ * `fanOut` has the engine check the turn delegated; a wake turn, a greeting or a one-line question carries nothing.
859
+ * Sessions without spawn_agent (headless, sub-agents) are never asked. */
860
+ delegateCarry(ownerText) {
861
+ const on = this.delegateMode && !this.planMode;
862
+ if (!on)
863
+ return { note: this.delegateTold ? engineNote(DELEGATE_MODE_OFF) : "", on, fanOut: false };
864
+ const work = this.canSpawn && !this.background && !this.unattended && !this.wakeTurn && isWorkAsk(ownerText);
865
+ if (!work)
866
+ return { note: "", on, fanOut: false };
867
+ const free = this.spawnLanes?.();
868
+ return { note: engineNote(delegateModeOn(free)), on, fanOut: free !== 0 };
869
+ }
870
+ /** What a compaction summary must keep: the active skill, and Autonomous and Delegate mode's rules while they apply. */
846
871
  pinned() {
847
872
  const mode = this.planReview && !this.planMode ? engineNote(AUTONOMOUS_MODE_ON) : "";
848
- return [this.activeSkillBlock, mode].filter(Boolean).join("\n\n") || undefined;
873
+ const fan = this.delegateMode && !this.planMode ? engineNote(delegateModeOn()) : "";
874
+ return [this.activeSkillBlock, mode, fan].filter(Boolean).join("\n\n") || undefined;
849
875
  }
850
876
  /** `cfg` with this session's plan approval attached while plan review is on, and detached otherwise. */
851
877
  underReview(cfg) {
@@ -1151,6 +1177,7 @@ export class Session {
1151
1177
  this.rollingSummarizer.clear(); // clear the rolling summary on new session
1152
1178
  this.planApproval.clear(); // a fresh conversation has no reviewed plan
1153
1179
  this.planReviewTold = false; // …and has not been told the mode
1180
+ this.delegateTold = false;
1154
1181
  }
1155
1182
  /** Sleep-time consolidation — trigger memory reorganization. Returns the result. */
1156
1183
  async consolidate() {
@@ -1351,6 +1378,7 @@ export class Session {
1351
1378
  this.convo.replaceAll(msgs);
1352
1379
  this.planApproval.clear(); // another conversation: its plan was never reviewed here
1353
1380
  this.planReviewTold = false; // …and it has not been told the mode
1381
+ this.delegateTold = false;
1354
1382
  return true;
1355
1383
  }
1356
1384
  /** The fact-preserving summarizer: engine prompt + content||reasoning fallback (Aurora empties content). */
@@ -1489,11 +1517,13 @@ export class Session {
1489
1517
  rollBudget() {
1490
1518
  return rollingBudget(this.effectiveContext(), SUMMARY_MAX_TOKENS, this.compactionSpeedTargetTokens);
1491
1519
  }
1492
- /** Where compaction.summaryModel may take a background pass: its first leg on a private address that is proven to
1520
+ /** Where compaction.summaryModel may take a background pass: its first leg, on a server other than the
1521
+ * conversation's own, at a private address that is proven to
1493
1522
  * stay there — a llama-server answering `/props` itself, or a router route marked `fleet_only` — with room for a
1494
1523
  * pass. A provider-key row, the Anthropic wire, a retired row and a gateway host never qualify: the pass carries
1495
1524
  * conversation text. Asked before every pass (a router's table reloads live). Undefined = the live endpoint. */
1496
1525
  async summaryLeg(b) {
1526
+ const live = { base: this.lastBase ?? this.inner.base, model: this.lastModel ?? this.inner.model };
1497
1527
  const id = this.compactionSummaryModel;
1498
1528
  if (!id)
1499
1529
  return undefined;
@@ -1509,9 +1539,12 @@ export class Session {
1509
1539
  const s = await probeServed(leg.base, { timeoutMs: 1500, model: leg.model });
1510
1540
  if ((!s.direct && !s.fleetOnly) || (s.ctx ?? p.ctx ?? 0) < need)
1511
1541
  continue;
1542
+ // One llama-server answers every model name; a router tells its servers apart only by route.
1543
+ if (new URL(leg.base).origin === new URL(live.base).origin && (s.direct || leg.model === live.model))
1544
+ continue;
1512
1545
  return { leg, ...(s.direct && s.slots && s.slots > 1 ? { slots: s.slots } : {}) };
1513
1546
  }
1514
- return this.summaryRefused("no leg proven to stay on your own machines with room for a pass");
1547
+ return this.summaryRefused("no leg on another server, proven to stay on your own machines, with room for a pass");
1515
1548
  }
1516
1549
  summaryRefused(reason) {
1517
1550
  if (!this.summaryModelTold)
@@ -1532,7 +1565,9 @@ export class Session {
1532
1565
  return { ...own, slot };
1533
1566
  }
1534
1567
  /** One rolling pass, a lean request (no system prompt, no tools) so what it reads is its own prompt whatever the
1535
- * server has cached. A note pass reads the next uncovered chunk before `upTo` and appends its note; a live one (a
1568
+ * server has cached. It shares no prefix with the conversation, so on a llama.cpp leg it would replace the cache the
1569
+ * next turn needs (a hybrid model cannot rewind, and a long session is too big to keep aside): a background pass
1570
+ * runs there only on a separate summary model, and otherwise waits for compaction. A note pass reads the next uncovered chunk before `upTo` and appends its note; a live one (a
1536
1571
  * compaction, the owner waiting) takes the whole uncovered tail at once. Once the notes are over their cap the pass
1537
1572
  * folds their older half into one summary instead. False when nothing advanced: nothing left, an empty answer, or
1538
1573
  * the conversation was replaced meanwhile. */
@@ -1575,7 +1610,8 @@ export class Session {
1575
1610
  });
1576
1611
  let r;
1577
1612
  const side = live ? undefined : await this.summaryLeg(b);
1578
- if (signal?.aborted)
1613
+ const keepsOurCache = !live && shipsLlamaCacheKnobs(base, leg?.transport);
1614
+ if (signal?.aborted || (keepsOurCache && !side))
1579
1615
  return false;
1580
1616
  if (side) {
1581
1617
  try {
@@ -1589,6 +1625,8 @@ export class Session {
1589
1625
  }
1590
1626
  if (!r)
1591
1627
  this.summaryRefused("its request failed or came back empty");
1628
+ if (!r && keepsOurCache)
1629
+ return false;
1592
1630
  }
1593
1631
  const via = r ? this.compactionSummaryModel : undefined;
1594
1632
  r ??= await ask(leg, { base, model }, this.affinity({ base, model, transport: leg?.transport })); // the live turn's slot or session: the span is cached there
@@ -1603,7 +1641,7 @@ export class Session {
1603
1641
  return true;
1604
1642
  }
1605
1643
  /** After a settled turn: while half a chunk or more is uncovered (or the notes are over their cap), summarize it in
1606
- * the background, one bounded pass at a time. send() aborts the pass in flight, so the owner's next message never
1644
+ * the background, where a pass may run at all (rollingPass), one bounded pass at a time. send() aborts the pass in flight, so the owner's next message never
1607
1645
  * waits for it; what a pass had not finished is picked up after the next turn, or read live at compaction. Never
1608
1646
  * for a sub-agent: its session ends with its turn, and nothing would abort its pass when the owner's turn wants
1609
1647
  * the model. */
@@ -2101,9 +2139,13 @@ export class Session {
2101
2139
  if (this.memoryNote)
2102
2140
  text = `${text}\n\n${this.memoryNote}`; // after the owner's words: a leading note would mark the message as the engine's
2103
2141
  this.memoryNote = "";
2142
+ const fan = this.delegateCarry(ownerText);
2143
+ if (fan.note)
2144
+ text = `${text}\n\n${fan.note}`; // after the owner's words too: it rides every work message
2104
2145
  const turn = { text, task, convoStart, t0: _t0 };
2105
2146
  this.inflight = turn;
2106
2147
  const turnModelId = routeLabel ?? this.modelId; // the MoA specialist's own id, else the /model pick
2148
+ const shape = { toolRounds: 0, multiCallRounds: 0, subAgentCalls: 0 }; // for the turn's telemetry record
2107
2149
  try {
2108
2150
  const res = await runTurn(text, this.convo, {
2109
2151
  ownerText,
@@ -2119,6 +2161,7 @@ export class Session {
2119
2161
  onTurnState: (read) => { turn.read = read; }, // an interrupted turn is recorded from it (interruptedRecord)
2120
2162
  pinnedContext: () => this.pinned(), // a summary is a rewrite anyway: the skill and Autonomous mode's rules ride it
2121
2163
  preservedState: this.background ? undefined : () => renderActiveTasks() ?? undefined, // a mid-turn compaction keeps the active task list — the FOREGROUND's; the list is one module store, so a sub-agent must not see (or close on) the owner's items
2164
+ canWrite: this.localSchemas.some((t) => CAN_WRITE.has(t.function.name)),
2122
2165
  background: this.background, // endpoint gate: a sub-agent's rounds yield the shared slot to the main turn
2123
2166
  affinity: this.affinity,
2124
2167
  liveSubAgents: this.wakeTurn ? this.liveAgents : undefined, // a wake turn with sub-agents live yields from its first idle round
@@ -2150,7 +2193,15 @@ export class Session {
2150
2193
  onToolResult: h.onToolResult,
2151
2194
  onToolCallStart: h.onToolCallStart,
2152
2195
  onToolDraft: h.onToolDraft,
2153
- onToolBatch: h.onToolBatch,
2196
+ onToolBatch: (events, durationMs) => {
2197
+ shape.toolRounds++;
2198
+ if (events.length > 1)
2199
+ shape.multiCallRounds++;
2200
+ shape.subAgentCalls += events.filter((e) => DELEGATION.has(e.name)).length;
2201
+ h.onToolBatch?.(events, durationMs);
2202
+ },
2203
+ batchHints: !this.background,
2204
+ delegate: fan.fanOut ? { freeLanes: this.spawnLanes } : undefined,
2154
2205
  onAutoContinue: h.onAutoContinue,
2155
2206
  onCacheStats: h.onCacheStats,
2156
2207
  onServed: h.onServed,
@@ -2200,12 +2251,14 @@ export class Session {
2200
2251
  // Decision points: a build turn's first change waits for the owner's choice of direction (ask_user) — in
2201
2252
  // Autonomous mode, for a plan review. Off in plan mode (the plan + exit picker IS the decision) and inert where
2202
2253
  // ask_user isn't registered (headless).
2203
- decisionPoints: { enabled: this.decisionPoints && !this.planMode, planReview: this.planReview },
2254
+ decisionPoints: { enabled: this.decisionPoints && !this.planMode, planReview: this.planReview, writerSpawns: fan.on },
2204
2255
  });
2205
2256
  // The conversation knows the mode only once the carried note is in it (a fast-start rewrite sends the raw text).
2206
2257
  if (mode.note && this.convo.all.slice(convoStart).some((m) => m.role === "user" && typeof m.content === "string" && m.content.includes(mode.note)))
2207
2258
  this.planReviewTold = mode.on;
2208
- this.telemetry.record({ type: "turn", rounds: res.rounds, toolCalls: res.toolCalls, interrupted: false, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct(), stopReason: res.stopReason });
2259
+ if (fan.note && this.convo.all.slice(convoStart).some((m) => m.role === "user" && typeof m.content === "string" && m.content.includes(fan.note)))
2260
+ this.delegateTold = fan.on;
2261
+ this.telemetry.record({ type: "turn", ...shape, model: turnModelId, rounds: res.rounds, toolCalls: res.toolCalls, interrupted: false, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct(), stopReason: res.stopReason });
2209
2262
  // MOA phase-0 ROUTE SHADOW (observability ONLY — routing is untouched): OPT-IN with KODE_MOA_SHADOW=1 (was on
2210
2263
  // by default until 0.1.334). Its classifier call goes to the SAME endpoint as the turn, and on a single-slot
2211
2264
  // llama-server (Cortana, --parallel 1) that 8-token call evicted the session's cached prompt after every turn:
@@ -2275,7 +2328,7 @@ export class Session {
2275
2328
  }
2276
2329
  catch (e) {
2277
2330
  if (e instanceof TurnAbortedError) {
2278
- this.telemetry.record({ type: "turn", rounds: 0, toolCalls: 0, interrupted: true, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct() });
2331
+ this.telemetry.record({ type: "turn", ...shape, rounds: 0, toolCalls: 0, interrupted: true, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct() });
2279
2332
  const r = this.interruptedRecord(turn); // an esc is how the owner usually ends a loop: the loop still teaches
2280
2333
  const cfg = this.selfImproveCfg();
2281
2334
  if (r)
@@ -29,6 +29,8 @@ export const WEB_SEARCH = set("web_search", "deep_research");
29
29
  export const WEB_FETCH = set("web_fetch", "browser", "browser_read", "http_request");
30
30
  /** Everything that only looks something up: the "reads" a sub-agent's activity counters add up. */
31
31
  export const LOOKUP = set(FILE_READ, "list_directory", LOCAL_SEARCH, WEB_SEARCH, WEB_FETCH);
32
+ /** Reads worth sending together: one of these alone, round after round, draws the batching note (engine/batch-hints.ts). */
33
+ export const BATCHABLE_READ = set(FILE_READ, "list_directory", LOCAL_SEARCH, WEB_SEARCH, "web_fetch", "git_status");
32
34
  /** Read-only tools: the same call returning the same result again is no new information. */
33
35
  export const IDEMPOTENT = set("file_read", "read_files", "search", "grep_search", "list_directory", "find_files", "locate", "web_search", "web_fetch", "git_status", "memory_search", "session_search", "session_read", "skill_catalog", "skill_fetch", "skill_list");
34
36
  // ── Plan, agents, polling ─────────────────────────────────────────────────────────────────────────────────
@@ -60,6 +62,8 @@ export const FAILURE_TOLERANT = set("bash", "shell_exec", "shell_background", "b
60
62
  /** Write-progress for the investigate-loop detector. Narrower than PROGRESS: a grep inside bash is the pattern that
61
63
  * detector exists for, so shells and git_command are out. */
62
64
  export const WRITE_PROGRESS = set(FILE_WRITE, "checkpoint", PLAN_WRITE, "memory_store", DELEGATION, "cronjob");
65
+ /** An agent holding none of these cannot write, so it is never stopped for not writing (agent.ts). */
66
+ export const CAN_WRITE = set(WRITE_PROGRESS, SHELL_ANY, "git_command");
63
67
  // ── Scheduling ────────────────────────────────────────────────────────────────────────────────────────────
64
68
  /** Calls that run alone in a batch: each can touch anything. delegate_task is a whole sub-agent session with the full
65
69
  * tool set, delegate_to_agent an external CLI agent with write and shell access, spawn_cloud_agent a whole agent in a
@@ -94,10 +94,13 @@ export function withDeferred(base, st) {
94
94
  // Promise.all barrier made base calls wait for every meta first. Now: search/describe classify
95
95
  // read, tool_call is an exclusive barrier (it can invoke ANYTHING downstream), pass-through
96
96
  // keeps the chain's truth. sched is exposed so any outer wrapper propagates it.
97
+ // No meta call: the chain below owns the whole round (its batch ids, its gates).
98
+ if (!calls.some((c) => DEFERRED_META_NAMES.includes(c.name)))
99
+ return base.executeParallel(calls, onSettle, signal, onStart);
97
100
  return runBatch(calls, {
98
- classify: (n) => (n === "tool_call" ? "barrier"
101
+ classify: (n, a) => (n === "tool_call" ? "barrier"
99
102
  : n === "tool_search" || n === "tool_describe" ? "read"
100
- : base.sched ? base.sched.classify(n) : "write"),
103
+ : base.sched ? base.sched.classify(n, a) : "write"),
101
104
  keys: (n, a) => (base.sched ? base.sched.keys(n, a) : defaultKeys(n, a)),
102
105
  runOne: (c, report) => (DEFERRED_META_NAMES.includes(c.name)
103
106
  ? runMeta(c.name, c.args, report) : base.execute(c.name, c.args, report)),
@@ -108,9 +111,9 @@ export function withDeferred(base, st) {
108
111
  });
109
112
  },
110
113
  sched: {
111
- classify: (n) => (n === "tool_call" ? "barrier"
114
+ classify: (n, a) => (n === "tool_call" ? "barrier"
112
115
  : n === "tool_search" || n === "tool_describe" ? "read"
113
- : base.sched ? base.sched.classify(n) : "write"),
116
+ : base.sched ? base.sched.classify(n, a) : "write"),
114
117
  keys: (n, a) => (base.sched ? base.sched.keys(n, a) : defaultKeys(n, a)),
115
118
  },
116
119
  };
@@ -281,15 +284,17 @@ export function withNativeDeferred(base, cat) {
281
284
  return base.execute(target, toolArgs, report);
282
285
  };
283
286
  const isMeta = (n) => NATIVE_META_NAMES.includes(n);
284
- const classify = (n) => (n === "tool_call" ? "barrier"
287
+ const classify = (n, a) => (n === "tool_call" ? "barrier"
285
288
  : n === "tool_search" ? "read"
286
- : base.sched ? base.sched.classify(n) : "write");
289
+ : base.sched ? base.sched.classify(n, a) : "write");
287
290
  const keys = (n, a) => (base.sched ? base.sched.keys(n, a) : defaultKeys(n, a));
288
291
  return {
289
292
  async execute(name, args, report) {
290
293
  return isMeta(name) ? runMeta(name, args, report) : base.execute(name, args, report);
291
294
  },
292
295
  async executeParallel(calls, onSettle, signal, onStart) {
296
+ if (!calls.some((c) => isMeta(c.name)))
297
+ return base.executeParallel(calls, onSettle, signal, onStart);
293
298
  return runBatch(calls, {
294
299
  classify, keys,
295
300
  runOne: (c, report) => (isMeta(c.name) ? runMeta(c.name, c.args, report) : base.execute(c.name, c.args, report)),