@0perator/operator 0.1.360-next.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +5 -4
  2. package/dist/auth/commands.js +7 -3
  3. package/dist/auth/identity.js +1 -0
  4. package/dist/auth/staff.js +55 -0
  5. package/dist/autonomy/delegate-mode.js +159 -0
  6. package/dist/autonomy/delegate.js +42 -15
  7. package/dist/autonomy/headless.js +7 -4
  8. package/dist/autonomy/index.js +2 -4
  9. package/dist/autonomy/session-factory.js +13 -12
  10. package/dist/autonomy/subagent-model.js +17 -7
  11. package/dist/background/capacity.js +136 -0
  12. package/dist/background/evidence.js +42 -0
  13. package/dist/background/index.js +336 -45
  14. package/dist/background/lane-phase.js +60 -0
  15. package/dist/background/lane-summary.js +151 -0
  16. package/dist/background/notices.js +12 -3
  17. package/dist/background/resume.js +125 -0
  18. package/dist/background/synthesis.js +25 -0
  19. package/dist/browser/engine.js +163 -0
  20. package/dist/browser/session.js +130 -140
  21. package/dist/bus/inbox.js +150 -6
  22. package/dist/cli.js +343 -86
  23. package/dist/config/features.js +3 -3
  24. package/dist/config/persona.js +29 -3
  25. package/dist/config/settings.js +262 -21
  26. package/dist/config/staff-prompt.js +12 -0
  27. package/dist/engine/agent.js +52 -41
  28. package/dist/engine/aurora.js +40 -8
  29. package/dist/engine/batch-scheduler.js +4 -13
  30. package/dist/engine/compaction.js +2 -2
  31. package/dist/engine/continuation.js +30 -32
  32. package/dist/engine/decision-points.js +2 -3
  33. package/dist/engine/fanout.js +16 -0
  34. package/dist/engine/loop-guard.js +26 -83
  35. package/dist/engine/messages.js +2 -2
  36. package/dist/engine/moa.js +18 -2
  37. package/dist/engine/native-vision-node.js +72 -0
  38. package/dist/engine/native-vision.js +103 -0
  39. package/dist/engine/selfheal.js +1 -1
  40. package/dist/engine/toolcalls.js +6 -6
  41. package/dist/engine/verify-gate.js +37 -7
  42. package/dist/gateway-cli.js +14 -3
  43. package/dist/index.js +3 -0
  44. package/dist/mcp/phone-server.js +30 -0
  45. package/dist/memory/live-progress.js +4 -5
  46. package/dist/moa/codeact-lane.js +98 -0
  47. package/dist/moa/codeact-sandbox.js +409 -0
  48. package/dist/moa/codeact.js +140 -0
  49. package/dist/permissions/artifact-visibility.js +10 -0
  50. package/dist/permissions/index.js +33 -17
  51. package/dist/permissions/signature.js +5 -0
  52. package/dist/permissions/tier.js +4 -2
  53. package/dist/phone-cli.js +65 -0
  54. package/dist/products/craft.js +2 -2
  55. package/dist/remote/grants.js +119 -0
  56. package/dist/remote/host.js +63 -6
  57. package/dist/router/models.js +29 -29
  58. package/dist/selfimprove/index.js +9 -7
  59. package/dist/services/preflight.js +35 -91
  60. package/dist/session.js +173 -46
  61. package/dist/skills/install-guard.js +68 -0
  62. package/dist/skills/install.js +67 -0
  63. package/dist/toolchain/manifest.json +13 -13
  64. package/dist/tools/background-result.js +1 -1
  65. package/dist/tools/classes.js +103 -0
  66. package/dist/tools/contract.js +1 -1
  67. package/dist/tools/craft.js +13 -2
  68. package/dist/tools/deferred.js +1 -0
  69. package/dist/tools/device/android.js +227 -0
  70. package/dist/tools/device/classify.js +127 -0
  71. package/dist/tools/device/deps.js +69 -0
  72. package/dist/tools/device/desktop.js +82 -0
  73. package/dist/tools/device/harness.js +262 -0
  74. package/dist/tools/device/iphone.js +206 -0
  75. package/dist/tools/device/mirroring-jxa.js +146 -0
  76. package/dist/tools/device/setup.js +90 -0
  77. package/dist/tools/device/tools.js +70 -0
  78. package/dist/tools/device/types.js +19 -0
  79. package/dist/tools/executor.js +25 -15
  80. package/dist/tools/generation-gateway.js +94 -0
  81. package/dist/tools/registry.js +95 -155
  82. package/dist/ui/App.js +18 -6
  83. package/dist/ui/ApprovalPrompt.js +10 -4
  84. package/dist/ui/BgPanel.js +17 -12
  85. package/dist/ui/Header.js +1 -6
  86. package/dist/ui/StatusRule.js +18 -7
  87. package/dist/ui/ToolStep.js +3 -3
  88. package/dist/ui/Transcript.js +36 -14
  89. package/dist/ui/UpdatePrompt.js +40 -0
  90. package/dist/ui/batchLine.js +4 -4
  91. package/dist/ui/editdiff.js +2 -4
  92. package/dist/ui/format.js +4 -20
  93. package/dist/ui/liveTools.js +3 -3
  94. package/dist/ui/modelPicker.js +1 -1
  95. package/dist/ui/opsMode.js +20 -0
  96. package/dist/ui/slashCommands.js +1 -0
  97. package/dist/ui/types.js +0 -2
  98. package/dist/update-check.js +145 -0
  99. package/dist/update.js +59 -15
  100. package/dist/util/slash.js +2 -2
  101. package/package.json +4 -2
  102. package/src/tools/device/NOTICE +37 -0
  103. package/dist/browser/cdp.js +0 -271
  104. package/dist/tools/mutating.js +0 -15
package/README.md CHANGED
@@ -22,7 +22,7 @@ src/
22
22
  │ │ # exponential backoff w/ jitter (honors Retry-After)
23
23
  │ ├── compaction.ts # endpoint-aware auto-compaction + fact-preserving summaryPrompt
24
24
  │ ├── messages.ts # Msg/Conversation, buildMessages, tool-pair repair, shape validation
25
- │ └── toolcalls.ts # recover text-emitted (Qwen XML / JSON) tool calls
25
+ │ └── toolcalls.ts # recover text-emitted (XML function-call / JSON) tool calls
26
26
  ├── router/router.ts # AuroraRouter — size-based routing, failover, Saddle fallback, pin/resetTurn
27
27
  ├── tools/ # the tool set (63): shell/file/grep/git/memory/checkpoint/web_fetch/knowledge
28
28
  │ │ # + wave 1-2 (missions, kanban boards, routines, validation, pkg, code search,
@@ -78,12 +78,13 @@ One task, no terminal UI, for SSH, CI, cron and other agents (the shape of `code
78
78
  ```
79
79
  operator run "fix the failing test" # progress on stderr, the answer on stdout
80
80
  echo "summarise CHANGELOG.md" | operator run - # task from stdin (also when stdin is a pipe and no task is given)
81
- operator run --output json "…" # one result object: {type, ok, exitCode, result, rounds, toolCalls, durationMs}
81
+ operator run --output json "…" # one result object: {type, ok, exitCode, result, rounds, toolCalls, durationMs, stopKind?}
82
82
  operator run --output stream-json "…" # one JSON event per line (= --json)
83
83
  ```
84
84
  Flags: `--model ID`, `--permissions gated|audit|bypass` (headless has no one to approve, so `gated` denies),
85
85
  `--cwd DIR`, `--max-turns N`, `--max-seconds S`, `--loop`, `--log FILE`, `--keep-awake`.
86
- Exit codes: 0 done, 1 the task failed, 2 bad command line, 130 interrupted.
86
+ Exit codes: 0 done, 1 the task failed or the engine stopped the turn (`stopKind` in the json: `repetition`, `rounds`,
87
+ `unanswered`, …), 2 bad command line, 130 interrupted.
87
88
  Sign-in without a keychain (SSH, CI): export the token as `OPERATOR_TOKEN`.
88
89
 
89
90
  ### Environment
@@ -94,7 +95,7 @@ Variables use the `OPERATOR_` prefix: `OPERATOR_MODEL`, `OPERATOR_PERMISSIONS`,
94
95
  runtime's home (`~/.operator`). Fleet defaults belong in settings.json `env` / `envFiles`.
95
96
 
96
97
  ### Local model runtime
97
- `operator gateway start [-d] | stop | status | health | logs` (was `operator-gw`, which now forwards here).
98
+ `operator gateway start [-d] [--force] | stop | status | health | logs` (`start` refuses without `--force` while its model, Aurora, is retired) (was `operator-gw`, which now forwards here).
98
99
 
99
100
  ## Knowledge base
100
101
 
@@ -226,9 +226,13 @@ async function byoModel(rest) {
226
226
  return 1;
227
227
  }
228
228
  const profile = { id, label: label ?? id, kind: "single", desc: `BYO ${label ?? id} — your key`, endpoint: base, model, ctx, byo: account, transport: dialect, ...(preset?.chatPath && base === preset.endpoint ? { chatPath: preset.chatPath } : {}), ...(preset?.maxOutput && model === preset.model ? { maxOutput: preset.maxOutput } : {}) };
229
- const existing = loadSettings().models ?? [];
230
- const models = [...existing.filter((m) => m.id !== id), profile];
231
- saveSettings({ models });
229
+ try {
230
+ saveSettings((cur) => ({ models: [...(Array.isArray(cur.models) ? cur.models : []).filter((m) => m.id !== id), profile] }));
231
+ }
232
+ catch (e) {
233
+ console.error(`✗ model "${id}" not registered: ${e instanceof Error ? e.message : String(e)}`);
234
+ return 1;
235
+ }
232
236
  console.log(`✓ model "${id}" registered (${model} @ ${base}, key account "${account}")`);
233
237
  if (setByoTokenInteractive(account)) {
234
238
  console.log(`✓ ${account} key stored — /model now offers "${id}"`);
@@ -31,6 +31,7 @@ export function claimsFromVerify(account, raw = {}) {
31
31
  roles: [...strList(pick("roles")), ...strList(pick("role"))],
32
32
  groups: strList(pick("groups")),
33
33
  scopes: strList(pick("scope")),
34
+ ...(typeof pick("tier") === "string" ? { accountTier: pick("tier") } : {}),
34
35
  };
35
36
  }
36
37
  /** Claims -> a tier ceiling (or undefined = the claims say nothing about tiers). Every source that is present
@@ -0,0 +1,55 @@
1
+ /** Groups AuthGate puts in the verify response: every accepted member of its staff org, and its owners and admins. */
2
+ export const STAFF_GROUP = "axe-staff";
3
+ export const EXEC_GROUP = "axe-exec";
4
+ const RANK = { external: 0, op: 1, axe: 2 };
5
+ /** True when `type` is at least `min` (an "axe" user passes every "op" check). */
6
+ export const userTypeAtLeast = (type, min) => RANK[type] >= RANK[min];
7
+ /** "axe" for a founder account or the exec group, "op" for the staff group or role, otherwise "external". A founder
8
+ * is an owner identity AuthGate already marks today, before the groups are emitted. */
9
+ export function userTypeFromClaims(c) {
10
+ if (!c)
11
+ return "external";
12
+ if (c.accountTier === "founder" || c.groups.includes(EXEC_GROUP) || c.roles.includes("exec"))
13
+ return "axe";
14
+ if (c.groups.includes(STAFF_GROUP) || c.roles.includes("staff"))
15
+ return "op";
16
+ return "external";
17
+ }
18
+ let resolved = "external";
19
+ let inflight = null;
20
+ let forToken = "";
21
+ /** The user type resolved so far this process. "external" until a verification has said otherwise. */
22
+ export const userType = () => resolved;
23
+ /** Staff of any rank: "op" or "axe". */
24
+ export const isOp = () => userTypeAtLeast(resolved, "op");
25
+ export const isAxe = () => resolved === "axe";
26
+ /** Verify the signed-in token once per token and remember the answer in memory only. Concurrent callers share one
27
+ * lookup; a different token re-resolves; a failure leaves the answer "external". Safe to call and not await. */
28
+ export function resolveUserType(token, deps = {}) {
29
+ if (!token) {
30
+ resolved = "external";
31
+ forToken = "";
32
+ return Promise.resolve("external");
33
+ }
34
+ if (inflight && forToken === token)
35
+ return inflight;
36
+ if (!inflight && forToken === token)
37
+ return Promise.resolve(resolved);
38
+ forToken = token;
39
+ inflight = (async () => {
40
+ try {
41
+ const verify = deps.verify ?? (await import("./client.js")).verifyTokenDetailed;
42
+ const toClaims = deps.claims ?? (await import("./identity.js")).claimsFromVerify;
43
+ const r = await verify(token, deps.timeoutMs ?? 3000);
44
+ resolved = r.state === "ok" ? userTypeFromClaims(toClaims(r.account, (r.raw ?? {}))) : "external";
45
+ }
46
+ catch {
47
+ resolved = "external";
48
+ }
49
+ inflight = null;
50
+ return resolved;
51
+ })();
52
+ return inflight;
53
+ }
54
+ /** Test seam: forget everything. */
55
+ export function resetUserType() { resolved = "external"; inflight = null; forToken = ""; }
@@ -0,0 +1,159 @@
1
+ import { SHELL_ANY } from "../tools/classes.js";
2
+ const env = () => globalThis.process?.env ?? {};
3
+ let live = {};
4
+ /** The guard settings every session in this process reads per call: set at startup from settings.delegate and again
5
+ * by `/delegate`, so a toggle applies to the main loop and every running sub-agent at their next tool call. */
6
+ export function setDelegateSettings(s) {
7
+ live = { ...(s ?? {}) };
8
+ }
9
+ /** KODE_DELEGATE_GUARD=1/0 wins over the setting (a headless run can fence itself without touching settings.json). */
10
+ export function delegateGuardOn(e = env(), s = live) {
11
+ const v = e.KODE_DELEGATE_GUARD;
12
+ if (v === "1" || v === "true")
13
+ return true;
14
+ if (v === "0" || v === "false")
15
+ return false;
16
+ return !!s.guard;
17
+ }
18
+ const PUSH = /\bgit\s+(?:-C\s+\S+\s+)?push\b/i;
19
+ const DEPLOY = new RegExp("\\b(systemctl\\s+(restart|start|stop)|launchctl\\s+(kickstart|bootout|bootstrap|load|unload)" +
20
+ "|docker\\s+compose\\s+up|docker-compose\\s+up|docker\\s+stack\\s+deploy" +
21
+ "|wrangler\\s+(deploy|publish)|fly(ctl)?\\s+deploy|kamal\\s+deploy|cap\\s+\\w+\\s+deploy|vercel\\s+(--prod|deploy\\s+--prod)" +
22
+ "|npm\\s+publish|cargo\\s+publish|twine\\s+upload)\\b", "i");
23
+ const WRITE_TOOLS = { file_write: "path", file_edit: "path", file_create: "path", file_delete: "path", download_file: "dest" };
24
+ function expand(p, e) {
25
+ return p === "~" || p.startsWith("~/") ? `${e.HOME ?? ""}${p.slice(1)}` : p;
26
+ }
27
+ function absolute(p, cwd, e) {
28
+ const x = expand(p, e);
29
+ const joined = x.startsWith("/") ? x : `${cwd.replace(/\/+$/, "")}/${x}`;
30
+ const out = [];
31
+ for (const part of joined.split("/")) {
32
+ if (!part || part === ".")
33
+ continue;
34
+ if (part === "..")
35
+ out.pop();
36
+ else
37
+ out.push(part);
38
+ }
39
+ return `/${out.join("/")}`;
40
+ }
41
+ /** The nearest directory at or above `dir` holding a `.git` entry, else `dir` itself. */
42
+ export function repoRoot(dir, exists) {
43
+ for (let d = dir; d && d !== "/"; d = d.slice(0, d.lastIndexOf("/")) || "/") {
44
+ if (exists(`${d}/.git`))
45
+ return d;
46
+ }
47
+ return dir;
48
+ }
49
+ /** Where a fenced write may land. */
50
+ export function taskRoots(ctx) {
51
+ const e = ctx.env ?? env();
52
+ const s = ctx.settings ?? live;
53
+ const cwd = absolute(ctx.cwd, "/", e);
54
+ const roots = [repoRoot(cwd, ctx.exists), ...(s.repos ?? []).map((r) => absolute(r, cwd, e))];
55
+ for (const v of [e.OPERATOR_SCRATCH, e.TMPDIR, "/tmp", "/private/tmp"])
56
+ if (v)
57
+ roots.push(absolute(v, cwd, e));
58
+ return [...new Set(roots.flatMap((r) => [r, ctx.realpath(r)]))];
59
+ }
60
+ function under(path, roots) {
61
+ return roots.some((r) => path === r || path.startsWith(r.endsWith("/") ? r : `${r}/`));
62
+ }
63
+ /** Why the guard refuses this call, or null to let it run. */
64
+ export function delegateGuardReason(name, args, ctx) {
65
+ const e = ctx.env ?? env();
66
+ const s = ctx.settings ?? live;
67
+ if (!delegateGuardOn(e, s))
68
+ return null;
69
+ const pushOk = !!s.allowPush;
70
+ if (SHELL_ANY.has(name)) {
71
+ const cmd = String(args.command ?? "");
72
+ if (PUSH.test(cmd) && !pushOk)
73
+ return "git push is blocked — set delegate.allowPush (or `/delegate push on`) to let this task push";
74
+ if (DEPLOY.test(cmd))
75
+ return "production deploys and publishes are blocked (restart / deploy / publish) — queue it for the owner";
76
+ return null;
77
+ }
78
+ if (name === "git_command") {
79
+ const argv = Array.isArray(args.args) ? args.args.map(String) : String(args.args ?? "").split(/\s+/);
80
+ if (argv.find((a) => !a.startsWith("-")) === "push" && !pushOk)
81
+ return "git push is blocked — set delegate.allowPush (or `/delegate push on`) to let this task push";
82
+ return null;
83
+ }
84
+ if (name === "git_pr" && args.action === "open" && !pushOk)
85
+ return "opening a PR pushes the branch, and pushing is blocked — set delegate.allowPush (or `/delegate push on`)";
86
+ if (name === "checkpoint" && args.push && !pushOk)
87
+ return "checkpoint with push is blocked — commit without push, or set delegate.allowPush (or `/delegate push on`)";
88
+ if (name === "deploy_config" && (args.build_command || args.run_command || args.target))
89
+ return "deploy configuration is blocked — queue it for the owner";
90
+ const key = WRITE_TOOLS[name];
91
+ if (key && typeof args[key] === "string" && args[key]) {
92
+ const cwd = typeof args.cwd === "string" && args.cwd ? args.cwd : ctx.cwd;
93
+ const target = absolute(String(args[key]), absolute(cwd, "/", e), e);
94
+ const roots = taskRoots(ctx);
95
+ const real = (() => { const dir = target.slice(0, target.lastIndexOf("/")) || "/"; return `${ctx.realpath(dir)}/${target.slice(target.lastIndexOf("/") + 1)}`; })();
96
+ if (!under(target, roots) || !under(real, roots)) {
97
+ return `writes are limited to the task repos; ${target} is outside them (${roots.filter((r, i, a) => a.indexOf(r) === i).slice(0, 3).join(", ")}) — add the folder to delegate.repos to allow it`;
98
+ }
99
+ }
100
+ return null;
101
+ }
102
+ const BLOCKED = (name, reason) => `Blocked by delegate mode: "${name}" was not run. ${reason}. Do not retry it or an equivalent; continue with what is allowed, or report this step for the owner.`;
103
+ /** Fence a session's executor. A call the guard refuses is answered here (reported blocked) and never reaches the
104
+ * permission layer; everything else, and every call while the guard is off, passes through unchanged. */
105
+ export function withDelegateGuard(inner, ctx) {
106
+ const check = (name, args) => delegateGuardReason(name, args, ctx);
107
+ return {
108
+ sched: inner.sched,
109
+ execute: async (name, args, report) => {
110
+ const why = check(name, args);
111
+ if (why) {
112
+ report?.refused("blocked");
113
+ return BLOCKED(name, why);
114
+ }
115
+ return inner.execute(name, args, report);
116
+ },
117
+ executeParallel: async (calls, onSettle, signal, onStart) => {
118
+ const refused = calls.map((c) => check(c.name, c.args));
119
+ if (refused.every((r) => r === null))
120
+ return inner.executeParallel(calls, onSettle, signal, onStart);
121
+ const allowed = calls.map((c, i) => ({ c, i })).filter(({ i }) => refused[i] === null);
122
+ const results = calls.map((c, i) => (refused[i] ? BLOCKED(c.name, refused[i]) : ""));
123
+ refused.forEach((r, i) => { if (r)
124
+ onSettle?.(i, results[i], "blocked"); });
125
+ if (allowed.length) {
126
+ const out = await inner.executeParallel(allowed.map(({ c }) => c), onSettle && ((j, r, why) => onSettle(allowed[j].i, r, why)), signal, onStart && ((j) => onStart(allowed[j].i)));
127
+ out.forEach((r, j) => { results[allowed[j].i] = r; });
128
+ }
129
+ return results;
130
+ },
131
+ };
132
+ }
133
+ export const DELEGATE_USAGE = "/delegate · /delegate planner <model> [executor] · /delegate subagents <model> · /delegate guard on|off · /delegate push on|off · /delegate off";
134
+ export function parseDelegate(argText) {
135
+ const [verb, a, b, ...rest] = argText.trim().split(/\s+/).filter(Boolean);
136
+ const onOff = (x) => (x === "on" ? true : x === "off" ? false : undefined);
137
+ if (!verb || verb === "status")
138
+ return { kind: "status" };
139
+ if (verb === "off" && !a)
140
+ return { kind: "off" };
141
+ if (verb === "planner" && a && !rest.length)
142
+ return { kind: "planner", model: a, executor: b };
143
+ if ((verb === "subagents" || verb === "subagent" || verb === "agents") && a && !b)
144
+ return { kind: "subagents", model: a };
145
+ if ((verb === "guard" || verb === "push") && onOff(a) !== undefined && !b)
146
+ return { kind: verb, on: onOff(a) };
147
+ return { kind: "error", message: `usage: ${DELEGATE_USAGE}` };
148
+ }
149
+ export function delegateStatusLines(v) {
150
+ const team = v.activeModel === "moa" && v.plannerModel
151
+ ? `planner ${v.plannerModel} → executor ${v.specialist ?? "?"} (/model moa)`
152
+ : `main loop ${v.activeModel}; no delegate planner`;
153
+ return [
154
+ `delegate · ${team}`,
155
+ `sub-agents (spawn_agent, delegate_task default): ${v.subagentModel}`,
156
+ `guard ${v.guard ? "ON" : "off"}${v.guard ? ` · push ${v.allowPush ? "allowed" : "blocked"} · deploys blocked · writes: this repo${v.repos.length ? `, ${v.repos.join(", ")}` : ""}, scratch, temp` : ""}`,
157
+ DELEGATE_USAGE,
158
+ ];
159
+ }
@@ -12,8 +12,12 @@
12
12
  import { modelRegistry, selectModel, endpointBase } from "../router/models.js";
13
13
  import { MemoryStore } from "../memory/index.js";
14
14
  import { delegateBrief, inferType, roleForBrief, SUBAGENT_ROLES } from "../engine/grandmaster.js";
15
+ import { engineEnded } from "../engine/continuation.js";
15
16
  import { suggestSkillsBlock } from "./subagent-amplifier.js";
16
17
  import { subagentModelFor, DEFAULT_SUBAGENT_MODEL } from "./subagent-model.js";
18
+ import { codeActConfig, codeActEligibility, codeActReport, pickLanguage } from "../moa/codeact.js";
19
+ import { CODEACT_STEP_TOOLS, codeActBrief, codeActStepFromArgs, codeActTraceLine, makeCodeActTool } from "../moa/codeact-lane.js";
20
+ import { FILE_WRITE, LOOKUP, SHELL_ANY } from "../tools/classes.js";
17
21
  const nodeImport = (m) => import(/* @vite-ignore */ m);
18
22
  /** Model a delegation lands on when the planner names none — the fast local tier. */
19
23
  export const DEFAULT_DELEGATE_MODEL = DEFAULT_SUBAGENT_MODEL; // kept for importers; the one default lives in subagent-model.ts
@@ -116,11 +120,6 @@ async function briefFor(task, settings) {
116
120
  const block = await suggestSkillsBlock(roleTitle, task, { signal: AbortSignal.timeout(4000) });
117
121
  return block ? `${base}\n\n${block}` : base;
118
122
  }
119
- /** The turn loop hands back its OWN "no answer" notes as ordinary `content`: `[stopped …]` / `[paused …]` (the
120
- * flywheel-prefix contract, _ai-docs/conventions) and the two parenthesized empty-reply notes in engine/agent.ts.
121
- * Returned verbatim they would reach the planner AS the sub-agent's answer — seen live: Scout on a tool task
122
- * emitted whitespace twice and the planner would have been told "(the model returned an empty response…)". */
123
- const NO_ANSWER = /^\s*(\[(stopped|paused|no answer|no reply came back from the model|declined by the provider)\b|\((the model returned an empty response|hit the output limit before an answer landed))/;
124
123
  let _seq = 0;
125
124
  const TIMED_OUT = Symbol("delegate-timeout");
126
125
  const progressListeners = new Set();
@@ -136,9 +135,6 @@ function emitProgress(p) {
136
135
  catch { /* a bad listener never touches the delegation */ }
137
136
  }
138
137
  }
139
- const WRITE_TOOLS = new Set(["file_write", "file_edit", "multi_edit", "apply_patch", "notebook_edit"]);
140
- const CMD_TOOLS = new Set(["bash", "shell_exec", "shell_background"]);
141
- const READ_TOOLS = /^(file_read|read_files|list_directory|find_files|glob|grep|grep_search|search|code_search|web_search|web_fetch|browser_read|deep_research)$/;
142
138
  function shortArg(args) {
143
139
  const v = args?.path ?? args?.file ?? args?.pattern ?? args?.query ?? args?.command ?? args?.url;
144
140
  return typeof v === "string" ? v.replace(/\s+/g, " ").slice(0, 60) : undefined;
@@ -150,11 +146,11 @@ export function progressHandlers(p) {
150
146
  onToolBatch: (events) => {
151
147
  p.round += 1;
152
148
  for (const e of events) {
153
- if (WRITE_TOOLS.has(e.name))
149
+ if (FILE_WRITE.has(e.name))
154
150
  p.writes += 1;
155
- else if (CMD_TOOLS.has(e.name))
151
+ else if (SHELL_ANY.has(e.name))
156
152
  p.commands += 1;
157
- else if (READ_TOOLS.test(e.name))
153
+ else if (LOOKUP.has(e.name))
158
154
  p.reads += 1;
159
155
  }
160
156
  p.tool = undefined;
@@ -199,7 +195,7 @@ export async function runDelegateTask(args, deps = defaultDeps) {
199
195
  // dropped in by changing one value — the planner still overrides per call via `args.model`.
200
196
  const defaultModel = (await defaultModelStore()).getStore() || subagentModelFor(settings);
201
197
  const modelId = String(args.model ?? "").trim() || defaultModel;
202
- // Gate BYO providers (Claude/OpenAI/Gemini/Qwen/…) on the user actually having stored that provider's key,
198
+ // Gate BYO providers (Claude/OpenAI/Gemini/…) on the user actually having stored that provider's key,
203
199
  // the same check /model applies — so an unconnected provider fails fast with the actionable "store the key"
204
200
  // error BEFORE a sub-agent session is spun up (and before setModel would refuse it anyway, more expensively).
205
201
  // A key the owner stored explicitly, never an ambient vendor variable: the model picks this target, not the owner.
@@ -221,6 +217,9 @@ export async function runDelegateTask(args, deps = defaultDeps) {
221
217
  if (dyn)
222
218
  auroraOverride = dyn.replace(/\/v1\/?$/, "");
223
219
  }
220
+ // The CodeAct lane (moa/codeact.ts): a step that asks for it and passes the check in code gets `codeact_run` and the
221
+ // lane's brief; one that fails runs on tools as always, and the planner is told why. The author is the sub-agent model.
222
+ const lane = await codeActLane(args, task, profile.id, settings);
224
223
  const id = `delegate-${profile.id}-${Date.now().toString(36)}-${++_seq}`;
225
224
  // Isolation: the child never writes the owner's live memory / rolling summary (see autonomy/profile.ts).
226
225
  const { tmpdir } = (await nodeImport("node:os"));
@@ -235,6 +234,7 @@ export async function runDelegateTask(args, deps = defaultDeps) {
235
234
  rollingSummaryPath: `${dir}/summary.md`,
236
235
  maxRoundsHard: DELEGATE_MAX_ROUNDS,
237
236
  sleepConsolidation: { enabled: false }, // a short-lived child must not consolidate the owner's knowledge base
237
+ ...(lane.tool ? { extraTools: [lane.tool], toolAllow: CODEACT_STEP_TOOLS } : {}), // a lane step reads; codeact_run computes
238
238
  },
239
239
  });
240
240
  }
@@ -251,7 +251,7 @@ export async function runDelegateTask(args, deps = defaultDeps) {
251
251
  emitProgress(progress);
252
252
  let outcome;
253
253
  try {
254
- const brief = await briefFor(task, settings);
254
+ const brief = await briefFor(lane.task, settings);
255
255
  outcome = await sendWithTimeout(store.run(depth + 1, () => session.send(brief, progressHandlers(progress))), timeoutMs, () => session.interrupt());
256
256
  }
257
257
  finally {
@@ -263,10 +263,17 @@ export async function runDelegateTask(args, deps = defaultDeps) {
263
263
  if (outcome.interrupted)
264
264
  return `error: delegate_task: the sub-agent on ${profile.id} was interrupted before it finished`;
265
265
  const text = String(outcome.content ?? "").trim();
266
- if (!text || NO_ANSWER.test(text)) {
266
+ // The engine's own hand-back ([stopped …], [paused …], the output-limit note) is no answer: the planner must not get it as one.
267
+ if (!text || engineEnded(outcome)) {
267
268
  return `error: delegate_task: the sub-agent on ${profile.id} produced no answer (${outcome.rounds} rounds, ${outcome.toolCalls} tool calls)${text ? ` — it reported: ${text.slice(0, 300)}` : ""}. Retry with a smaller, clearer subtask or a stronger model.`;
268
269
  }
269
- return text;
270
+ if (lane.note)
271
+ return `${lane.note}\n${text}`;
272
+ if (!lane.tool)
273
+ return text;
274
+ // The program's own result goes back verbatim: the executor's closing words may paraphrase or drop the data.
275
+ const last = lane.results[lane.results.length - 1];
276
+ return `${text}${last?.ok ? `\n${codeActReport(last)}` : ""}\n${codeActTraceLine(lane.results)}`;
270
277
  }
271
278
  catch (e) {
272
279
  return `error: delegate_task: the sub-agent on ${profile.id} failed — ${msg(e)}`;
@@ -278,3 +285,23 @@ export async function runDelegateTask(args, deps = defaultDeps) {
278
285
  catch { /* already down */ }
279
286
  }
280
287
  }
288
+ /** The lane a delegated step runs on: `codeact_run` + the lane brief when it asked for the CodeAct lane and passed the
289
+ * check, a one-line note when it asked and failed, nothing when it did not ask. */
290
+ async function codeActLane(args, task, author, settings) {
291
+ const step = codeActStepFromArgs(args, author);
292
+ const results = [];
293
+ if (!step)
294
+ return { task, results };
295
+ const [{ homedir }, { existsSync }, { get_operator_home }] = await Promise.all([
296
+ nodeImport("node:os"),
297
+ nodeImport("node:fs"),
298
+ import("../config/home.js"),
299
+ ]);
300
+ const cfg = settings.moa?.codeact;
301
+ const check = codeActEligibility(step, cfg, { home: homedir(), cwd: process.cwd(), operatorHome: get_operator_home() });
302
+ if (!check.eligible)
303
+ return { task, note: `[lane: ${check.detail}]`, results };
304
+ const language = pickLanguage(codeActConfig(cfg).language, check.targets, existsSync);
305
+ const tool = makeCodeActTool({ targets: check.targets, language, settings: cfg, onResult: (r) => results.push(r) });
306
+ return { task: codeActBrief(task, check.targets, language), tool, results };
307
+ }
@@ -8,6 +8,7 @@ import { runLoop } from "./loop.js";
8
8
  import { makeReporter } from "./reporter.js";
9
9
  import { recordLiveProgress, roundProgressed, settleLiveProgress, touchedPaths } from "../memory/live-progress.js";
10
10
  import { getAgentTasks } from "../tools/registry.js";
11
+ import { engineEnded } from "../engine/continuation.js";
11
12
  const newJournal = (prompt) => ({ session: `headless-${process.pid}`, prompt, touched: [], written: false });
12
13
  function settleJournal(j, how) {
13
14
  if (j.written)
@@ -42,7 +43,8 @@ function handlersFor(reporter, json, prompt = "", onDelta, journal = newJournal(
42
43
  };
43
44
  }
44
45
  /**
45
- * Run `prompt` headless. Returns a process exit code: 0 success, 1 error, 130 interrupted. Wires SIGINT
46
+ * Run `prompt` headless. Returns a process exit code: 0 an answer, 1 an error or an engine stop (the json result names
47
+ * it in `stopKind`), 130 interrupted. Wires SIGINT
46
48
  * to interrupt the in-flight turn so Ctrl-C stops cleanly (and the caller's keep-awake teardown runs).
47
49
  */
48
50
  export async function runHeadless(settings, prompt, opts = {}) {
@@ -106,8 +108,9 @@ export async function runHeadless(settings, prompt, opts = {}) {
106
108
  return finish(res.reason === "error" ? 1 : res.reason === "interrupted" ? 130 : 0);
107
109
  }
108
110
  const outcome = await session.send(prompt, handlers);
109
- reporter.event("done", { rounds: outcome.rounds, toolCalls: outcome.toolCalls, interrupted: outcome.interrupted, durationMs: Math.round(outcome.durationMs ?? 0) });
110
- result = { rounds: outcome.rounds, toolCalls: outcome.toolCalls, interrupted: outcome.interrupted, durationMs: Math.round(outcome.durationMs ?? 0) };
111
+ const stop = outcome.stopKind ?? (outcome.stopReason === "content_filter" ? "declined" : undefined); // the engine's stop, never parsed from the text
112
+ reporter.event("done", { rounds: outcome.rounds, toolCalls: outcome.toolCalls, interrupted: outcome.interrupted, durationMs: Math.round(outcome.durationMs ?? 0), ...(stop ? { stopKind: stop } : {}) });
113
+ result = { rounds: outcome.rounds, toolCalls: outcome.toolCalls, interrupted: outcome.interrupted, durationMs: Math.round(outcome.durationMs ?? 0), ...(stop ? { stopKind: stop } : {}) };
111
114
  if (outcome.display) {
112
115
  streamed = "";
113
116
  if (output === "text")
@@ -116,7 +119,7 @@ export async function runHeadless(settings, prompt, opts = {}) {
116
119
  answer(outcome.display ?? outcome.content);
117
120
  settleJournal(journal, outcome.interrupted ? "stopped" : "completed");
118
121
  await session.flushRouteShadow(); // MOA phase-0: headless one-shot exits before fire-and-forget would land
119
- return finish(outcome.interrupted ? 130 : outcome.stopKind === "unanswered" || outcome.stopKind === "context_floor" ? 1 : 0); // nothing answered, or the model is served under the floor: a failed run
122
+ return finish(outcome.interrupted ? 130 : engineEnded(outcome) && outcome.stopKind !== "yield" ? 1 : 0); // the engine ended it (no answer, a cut or withheld one, a guard stop): a failed run; a yield handed work to sub-agents
120
123
  }
121
124
  catch (e) {
122
125
  const message = e instanceof Error ? e.message : String(e);
@@ -279,15 +279,13 @@ export async function dispatchAutonomy(argv, settings) {
279
279
  // Headless paths skip the interactive preflight (cli.tsx's ensureServices), which RESOLVES the dynamic Aurora
280
280
  // endpoint from the operator-runtime server.json. Mirror it here — the same EnsureCfg (aurora launchd cfg +
281
281
  // optional services) — so a headless `operator run/loop/board/routine` never sends to a baseless
282
- // "/v1/chat/completions" (Failed to parse URL). Aurora itself loads on demand: the session's onDemand hook starts
283
- // it for the first turn on it (session-factory.ts), so a run on another model never loads it.
284
- // Guarded to the empty-base case (the only time we must discover/start), and gateway-aware: carry the
282
+ // "/v1/chat/completions" (Failed to parse URL). It only resolves and reports: Aurora is retired, nothing starts it.
283
+ // Guarded to the empty-base case (the only time we must discover), and gateway-aware: carry the
285
284
  // gateway's published api_key (server.json) onto the endpoint config so the router authenticates to it.
286
285
  if (!settings.endpoints.aurora.base) {
287
286
  const auroraCfg = { base: settings.endpoints.aurora.base, ...settings.services?.aurora };
288
287
  await ensureServices({
289
288
  aurora: auroraCfg,
290
- auroraOnDemand: true, // resolve the endpoint only: a run on Aurora loads it at its first turn
291
289
  autopilot: settings.services?.autopilot,
292
290
  vision: settings.services?.vision,
293
291
  onProgress: (m) => process.stderr.write(`[services] ${m}\n`),
@@ -9,12 +9,12 @@ import { buildMemory } from "../memory/providers.js";
9
9
  import { composeSystemPrompt, subagentSystemPrompt } from "../config/persona.js";
10
10
  import { SUBAGENT_ROLES, SUBAGENT_TOOL_DENY } from "../engine/grandmaster.js";
11
11
  import { ensureScratchDir } from "../config/scratch.js";
12
- import { modelCtxFor, leanHarnessFor, DEFAULT_MODEL_ID } from "../router/models.js";
12
+ import { modelCtxFor, leanHarnessFor, CHAIN_MODEL_ID } from "../router/models.js";
13
13
  import { compactionThreshold, compactionCeilingTokens, compactionMinDecodeTps, turnWallClockMs, buildEndpointChain } from "../config/settings.js";
14
14
  import { resolveMode } from "../classifier/modes.js";
15
15
  import { classifierConfig } from "../classifier/config.js";
16
- import { auroraOnDemand } from "../services/preflight.js";
17
16
  import { setSpeculation, speculationEnabled } from "../engine/aurora.js";
17
+ import { setDelegateSettings } from "./delegate-mode.js";
18
18
  /** Build the Aurora router from settings — the headless twin of cli.tsx's buildRouter(). Both share the one
19
19
  * multi-tier chain builder (primary → other fleet nodes → back-compat single failover → cloud), so a
20
20
  * wedged/degraded endpoint fails over through the whole fleet before the turn can error. */
@@ -41,6 +41,7 @@ export function envSubagentRole(env = process.env) {
41
41
  export function createAutonomySession(settings, opts = {}) {
42
42
  const role = opts.role ?? envSubagentRole();
43
43
  setSpeculation(speculationEnabled(settings)); // GW-26: the owner's opt-out reaches headless, ACP and delegated runs
44
+ setDelegateSettings(settings.delegate); // delegate mode's guard fences headless, ACP and delegated runs too
44
45
  const session = new Session({
45
46
  systemPrompt: role
46
47
  ? subagentSystemPrompt({ cwd: opts.cwd ?? process.cwd(), ctxTokens: modelCtxFor(settings.activeModel, settings.models), type: role })
@@ -68,9 +69,6 @@ export function createAutonomySession(settings, opts = {}) {
68
69
  features: settings.features, // feature flags — registers flag-gated tools (e.g. cloudAgents) only when on
69
70
  activeModel: settings.activeModel,
70
71
  fallbackModel: settings.fallbackModel,
71
- // A local Aurora loads for the first turn on it (owner, 11/03), never for the run starting: a run on moa or cortana
72
- // (setModel below) never loads it.
73
- onDemand: auroraOnDemand(settings.endpoints.aurora, settings.services?.aurora, () => buildRouterFromSettings(settings), undefined, (line) => process.stderr.write(`[operator] ${line}\n`)),
74
72
  contextPin: settings.contextPin, // the owner's /context choice (KODE_CONTEXT wins in loadSettings) holds for headless, ACP and delegated runs too
75
73
  contextFloor: settings.contextFloor,
76
74
  permissions: opts.permissions ?? settings.permissions,
@@ -86,13 +84,16 @@ export function createAutonomySession(settings, opts = {}) {
86
84
  });
87
85
  // Bind the router to the SELECTED model, exactly as the interactive /model path (cli.tsx) and delegate_task
88
86
  // (delegate.ts) do. The constructor skips activeModel when a router is injected — "an injected router owns
89
- // routing" (session.ts) — and this factory always injects the default Aurora chain, so without this a
90
- // non-default activeModel (e.g. belmont) silently ran on Aurora headless/ACP. setModel points this.inner at
91
- // the profile's OWN endpoints (and its own fleet failover), so a non-Aurora model no longer self-heals onto
92
- // Aurora. The default model keeps the richer buildEndpointChain failover. An unavailable/refused id leaves
93
- // the default router — a quiet fallback matching the constructor.
94
- if (settings.activeModel && settings.activeModel !== DEFAULT_MODEL_ID)
95
- session.setModel(settings.activeModel);
87
+ // routing" (session.ts) — and this factory always injects the shell's chain, so without this a
88
+ // non-default activeModel (e.g. belmont) silently ran on the chain headless/ACP. setModel points this.inner at
89
+ // the profile's OWN endpoints (and its own fleet failover). The chain row (`main`) keeps the richer
90
+ // buildEndpointChain failover. An unavailable/refused id leaves
91
+ // the default router — a quiet fallback matching the constructor. A retired id runs on its successor, said once.
92
+ if (settings.activeModel && settings.activeModel !== CHAIN_MODEL_ID) {
93
+ const note = session.setModel(settings.activeModel).note;
94
+ if (note)
95
+ process.stderr.write(`[operator] ${note}\n`);
96
+ }
96
97
  return session;
97
98
  }
98
99
  /** Dream mode's permission posture. "readonly"/"gated" ⇒ a gated policy with no approver, so safe/read
@@ -1,18 +1,28 @@
1
- // Which model a sub-agent runs on — one answer for delegate_task and spawn_agent, resolved per spawn: the MoA
2
- // specialist under /model moa, else the owner's setting, else the `subagent` capability, the shipped default. A capability
3
- // is a name the gateway resolves (the portal's aliases), so the fleet picks the best healthy model and no client names one
4
- // (owner, 11/04; supersedes the 10/31 default of gpt-oss-20b, arena: 35/36 tasks, median 47 s). Every install's registry has
5
- // it, reached through the local router or api.0perator.co. Node-free (pure).
1
+ // Which model a sub-agent runs on — one answer for delegate_task and spawn_agent, resolved per spawn: the owner's delegate
2
+ // route once its router answers for it, else the MoA specialist under /model moa, else the owner's setting, else the
3
+ // `subagent` capability, the shipped default. A capability is a name the gateway resolves (the portal's aliases), so the
4
+ // fleet picks the best healthy model and no client names one (owner, 11/04; supersedes the 10/31 default of gpt-oss-20b,
5
+ // arena: 35/36 tasks, median 47 s). Every install's registry has it, reached through the local router or api.0perator.co.
6
+ // Node-free (pure).
6
7
  import { moaTeam } from "../engine/moa.js";
7
8
  export const DEFAULT_SUBAGENT_MODEL = "subagent";
8
- export function subagentModelFor(settings, activeModel) {
9
+ /** The route the owner set for sub-agents (autonomy.subagentModel, else delegateModel), or undefined when unset. */
10
+ export function delegateRouteFor(settings) {
11
+ return settings.autonomy?.subagentModel?.trim() || settings.autonomy?.delegateModel?.trim() || undefined;
12
+ }
13
+ /** `onDelegateRoute`: the router serving the owner's delegate route answered its capacity API, so sub-agents run there
14
+ * (sized and reserved on it) even under /model moa, where they otherwise take the specialist (owner, 11/27). */
15
+ export function subagentModelFor(settings, activeModel, onDelegateRoute = false) {
16
+ const owned = delegateRouteFor(settings);
17
+ if (onDelegateRoute && owned)
18
+ return owned;
9
19
  activeModel ??= settings.activeModel;
10
20
  if (activeModel === "moa") {
11
21
  const team = moaTeam(settings.moa);
12
22
  if (team)
13
23
  return team.specialist;
14
24
  }
15
- return settings.autonomy?.subagentModel?.trim() || settings.autonomy?.delegateModel?.trim() || DEFAULT_SUBAGENT_MODEL;
25
+ return owned || DEFAULT_SUBAGENT_MODEL;
16
26
  }
17
27
  /** The model that serves the PARENT's turn: the planner under /model moa, else the selection itself. A sub-agent on
18
28
  * the same model shares its slot (the parent then yields to it); on any other model it runs beside the parent. */