@0perator/operator 0.2.0 → 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 (75) hide show
  1. package/README.md +4 -3
  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 +2 -2
  6. package/dist/autonomy/delegate.js +41 -14
  7. package/dist/autonomy/headless.js +7 -4
  8. package/dist/autonomy/index.js +2 -4
  9. package/dist/autonomy/session-factory.js +11 -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 +311 -44
  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/synthesis.js +25 -0
  18. package/dist/bus/inbox.js +150 -6
  19. package/dist/cli.js +191 -96
  20. package/dist/config/features.js +3 -3
  21. package/dist/config/persona.js +29 -3
  22. package/dist/config/settings.js +261 -20
  23. package/dist/config/staff-prompt.js +12 -0
  24. package/dist/engine/agent.js +51 -40
  25. package/dist/engine/aurora.js +36 -4
  26. package/dist/engine/batch-scheduler.js +4 -13
  27. package/dist/engine/compaction.js +1 -1
  28. package/dist/engine/continuation.js +30 -32
  29. package/dist/engine/decision-points.js +2 -3
  30. package/dist/engine/fanout.js +16 -0
  31. package/dist/engine/loop-guard.js +26 -83
  32. package/dist/engine/messages.js +2 -2
  33. package/dist/engine/moa.js +16 -1
  34. package/dist/engine/native-vision-node.js +72 -0
  35. package/dist/engine/native-vision.js +103 -0
  36. package/dist/engine/verify-gate.js +37 -7
  37. package/dist/gateway-cli.js +14 -3
  38. package/dist/memory/live-progress.js +4 -5
  39. package/dist/moa/codeact-lane.js +98 -0
  40. package/dist/moa/codeact-sandbox.js +409 -0
  41. package/dist/moa/codeact.js +140 -0
  42. package/dist/permissions/artifact-visibility.js +10 -0
  43. package/dist/permissions/tier.js +4 -2
  44. package/dist/products/craft.js +2 -2
  45. package/dist/remote/grants.js +119 -0
  46. package/dist/remote/host.js +33 -5
  47. package/dist/router/models.js +24 -14
  48. package/dist/selfimprove/index.js +8 -6
  49. package/dist/services/preflight.js +35 -91
  50. package/dist/session.js +127 -41
  51. package/dist/skills/install-guard.js +68 -0
  52. package/dist/skills/install.js +67 -0
  53. package/dist/toolchain/manifest.json +13 -13
  54. package/dist/tools/background-result.js +1 -1
  55. package/dist/tools/classes.js +103 -0
  56. package/dist/tools/contract.js +1 -1
  57. package/dist/tools/craft.js +13 -2
  58. package/dist/tools/executor.js +25 -15
  59. package/dist/tools/generation-gateway.js +94 -0
  60. package/dist/tools/registry.js +83 -152
  61. package/dist/ui/App.js +15 -4
  62. package/dist/ui/BgPanel.js +15 -10
  63. package/dist/ui/Header.js +1 -6
  64. package/dist/ui/StatusRule.js +18 -7
  65. package/dist/ui/ToolStep.js +3 -3
  66. package/dist/ui/Transcript.js +36 -14
  67. package/dist/ui/batchLine.js +4 -4
  68. package/dist/ui/editdiff.js +2 -4
  69. package/dist/ui/format.js +4 -20
  70. package/dist/ui/liveTools.js +3 -3
  71. package/dist/ui/opsMode.js +20 -0
  72. package/dist/ui/types.js +0 -2
  73. package/dist/update-check.js +17 -6
  74. package/package.json +1 -1
  75. package/dist/tools/mutating.js +0 -15
package/README.md CHANGED
@@ -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 = ""; }
@@ -1,3 +1,4 @@
1
+ import { SHELL_ANY } from "../tools/classes.js";
1
2
  const env = () => globalThis.process?.env ?? {};
2
3
  let live = {};
3
4
  /** The guard settings every session in this process reads per call: set at startup from settings.delegate and again
@@ -19,7 +20,6 @@ const DEPLOY = new RegExp("\\b(systemctl\\s+(restart|start|stop)|launchctl\\s+(k
19
20
  "|docker\\s+compose\\s+up|docker-compose\\s+up|docker\\s+stack\\s+deploy" +
20
21
  "|wrangler\\s+(deploy|publish)|fly(ctl)?\\s+deploy|kamal\\s+deploy|cap\\s+\\w+\\s+deploy|vercel\\s+(--prod|deploy\\s+--prod)" +
21
22
  "|npm\\s+publish|cargo\\s+publish|twine\\s+upload)\\b", "i");
22
- const SHELL_TOOLS = new Set(["bash", "shell_exec", "shell_background", "shell_task_start"]);
23
23
  const WRITE_TOOLS = { file_write: "path", file_edit: "path", file_create: "path", file_delete: "path", download_file: "dest" };
24
24
  function expand(p, e) {
25
25
  return p === "~" || p.startsWith("~/") ? `${e.HOME ?? ""}${p.slice(1)}` : p;
@@ -67,7 +67,7 @@ export function delegateGuardReason(name, args, ctx) {
67
67
  if (!delegateGuardOn(e, s))
68
68
  return null;
69
69
  const pushOk = !!s.allowPush;
70
- if (SHELL_TOOLS.has(name)) {
70
+ if (SHELL_ANY.has(name)) {
71
71
  const cmd = String(args.command ?? "");
72
72
  if (PUSH.test(cmd) && !pushOk)
73
73
  return "git push is blocked — set delegate.allowPush (or `/delegate push on`) to let this task push";
@@ -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;
@@ -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,11 +9,10 @@ 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";
18
17
  import { setDelegateSettings } from "./delegate-mode.js";
19
18
  /** Build the Aurora router from settings — the headless twin of cli.tsx's buildRouter(). Both share the one
@@ -70,9 +69,6 @@ export function createAutonomySession(settings, opts = {}) {
70
69
  features: settings.features, // feature flags — registers flag-gated tools (e.g. cloudAgents) only when on
71
70
  activeModel: settings.activeModel,
72
71
  fallbackModel: settings.fallbackModel,
73
- // A local Aurora loads for the first turn on it (owner, 11/03), never for the run starting: a run on moa or cortana
74
- // (setModel below) never loads it.
75
- onDemand: auroraOnDemand(settings.endpoints.aurora, settings.services?.aurora, () => buildRouterFromSettings(settings), undefined, (line) => process.stderr.write(`[operator] ${line}\n`)),
76
72
  contextPin: settings.contextPin, // the owner's /context choice (KODE_CONTEXT wins in loadSettings) holds for headless, ACP and delegated runs too
77
73
  contextFloor: settings.contextFloor,
78
74
  permissions: opts.permissions ?? settings.permissions,
@@ -88,13 +84,16 @@ export function createAutonomySession(settings, opts = {}) {
88
84
  });
89
85
  // Bind the router to the SELECTED model, exactly as the interactive /model path (cli.tsx) and delegate_task
90
86
  // (delegate.ts) do. The constructor skips activeModel when a router is injected — "an injected router owns
91
- // routing" (session.ts) — and this factory always injects the default Aurora chain, so without this a
92
- // non-default activeModel (e.g. belmont) silently ran on Aurora headless/ACP. setModel points this.inner at
93
- // the profile's OWN endpoints (and its own fleet failover), so a non-Aurora model no longer self-heals onto
94
- // Aurora. The default model keeps the richer buildEndpointChain failover. An unavailable/refused id leaves
95
- // the default router — a quiet fallback matching the constructor.
96
- if (settings.activeModel && settings.activeModel !== DEFAULT_MODEL_ID)
97
- 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
+ }
98
97
  return session;
99
98
  }
100
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. */
@@ -0,0 +1,136 @@
1
+ // Smart slots: how many sub-agent lanes run at once comes from the router's live capacity for the delegate route
2
+ // (portal/src/router/capacity.ts), not a fixed number. A lane starts only once the router has RESERVED a unit for it,
3
+ // so two spawns can never both take the last free unit, and every request the lane makes carries the reservation and
4
+ // goes to the leg it was given. A backend that comes up grows the pool on the next look; one that goes away shrinks it
5
+ // for new lanes only (a running lane keeps its reservation). An endpoint without the capacity API (a direct
6
+ // llama-server, a vendor) puts the scheduler back on the static cap it always had.
7
+ import { authHeaders } from "../engine/aurora.js";
8
+ export class CapacityUnavailable extends Error {
9
+ transient;
10
+ /** transient: the router did not answer in time or the connection dropped. It is busy, not absent, so the
11
+ * scheduler retries instead of falling back to the static cap. */
12
+ constructor(why, transient = false) {
13
+ super(why);
14
+ this.transient = transient;
15
+ this.name = "CapacityUnavailable";
16
+ }
17
+ }
18
+ /** A cap no live pool may exceed: each lane is a process-local session with its own context and tools. */
19
+ export const MAX_LANES = 8;
20
+ export const RESERVATION_TTL_MS = 120_000;
21
+ /** The hard ceiling on running lanes: KODE_ENDPOINT_SLOTS when set (an owner's explicit cap), else MAX_LANES. */
22
+ export function laneCeiling(env = process.env) {
23
+ const n = Number(env.KODE_ENDPOINT_SLOTS);
24
+ return Number.isFinite(n) && n >= 1 ? Math.min(MAX_LANES, Math.floor(n)) : MAX_LANES;
25
+ }
26
+ /** How many lanes may run: live = what is running plus what the router has free (bounded by the ceiling); static = the
27
+ * configured cap. Never below what is already running — shrinking only stops new lanes. */
28
+ export function laneBudget(mode, running, ceiling) {
29
+ if (mode.kind === "static")
30
+ return Math.max(running, Math.min(ceiling, mode.lanes));
31
+ const s = mode.snapshot;
32
+ if (!s)
33
+ return Math.max(running, 1);
34
+ const room = s.unbounded ? ceiling : running + s.free;
35
+ return Math.max(running, Math.min(ceiling, room));
36
+ }
37
+ /** "subagent 4/6 busy · flash 3/4, planner 1/2 · kimi down" for the lanes header. */
38
+ export function poolLine(s) {
39
+ const up = s.legs.filter((l) => l.healthy);
40
+ const down = s.legs.filter((l) => !l.healthy).map((l) => l.name);
41
+ const legs = up.map((l) => (l.maxInflight !== undefined ? `${l.name} ${l.maxInflight - (l.free ?? 0)}/${l.maxInflight}` : `${l.name} open`));
42
+ const head = s.total ? `${s.route} ${s.total - s.free}/${s.total} busy` : `${s.route} pool`;
43
+ return [head, legs.join(", "), down.length ? `${down.join(", ")} down` : ""].filter(Boolean).join(" · ");
44
+ }
45
+ /** The capacity API of the router at `base` for `route`. `spare` is the main turn's route: the router keeps one unit of
46
+ * the leg main lands on free. */
47
+ export function routerCapacity(o) {
48
+ const base = o.base.replace(/\/v1\/?$/, "").replace(/\/+$/, "");
49
+ const f = o.fetch ?? ((u, i) => fetch(u, i));
50
+ const headers = () => ({ "content-type": "application/json", ...authHeaders({ base, model: o.route }) });
51
+ const call = async (path, body) => {
52
+ let r;
53
+ try {
54
+ // 10 s: these are tiny requests, but on a busy box the router's reply can take a few seconds.
55
+ r = await f(`${base}${path}`, { method: body === undefined ? "GET" : "POST", headers: headers(), ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(o.timeoutMs ?? 10_000) });
56
+ }
57
+ catch (e) {
58
+ throw new CapacityUnavailable(`capacity API unreachable: ${e.message}`, true);
59
+ }
60
+ // An older router or a vendor (404/405), a refused key, or a router without this route: no live capacity here.
61
+ if ([401, 403, 404, 405].includes(r.status))
62
+ throw new CapacityUnavailable(`no capacity API for ${o.route} at ${base} (HTTP ${r.status})`);
63
+ return r;
64
+ };
65
+ const snapshotOf = (j) => {
66
+ const s = j;
67
+ return s && Array.isArray(s.legs) && typeof s.free === "number" ? s : undefined;
68
+ };
69
+ return {
70
+ base, route: o.route,
71
+ async snapshot() {
72
+ const r = await call(`/v1/capacity?route=${encodeURIComponent(o.route)}`);
73
+ const s = r.ok ? snapshotOf(await r.json().catch(() => undefined)) : undefined;
74
+ if (!s)
75
+ throw new CapacityUnavailable(`capacity API answered HTTP ${r.status}`);
76
+ return s;
77
+ },
78
+ async reserve(session) {
79
+ const spare = o.spare?.();
80
+ const r = await call("/v1/capacity/reserve", { route: o.route, session, ttlMs: RESERVATION_TTL_MS, ...(spare ? { spare } : {}) });
81
+ const j = await r.json().catch(() => ({}));
82
+ if (r.ok && j.leaseId && j.leg)
83
+ return { ok: true, leaseId: j.leaseId, leg: j.leg };
84
+ if (r.status === 409)
85
+ return { ok: false, reason: j.error?.message ?? `${o.route} is busy`, snapshot: snapshotOf(j.capacity) };
86
+ throw new CapacityUnavailable(`reserve answered HTTP ${r.status}`);
87
+ },
88
+ async renew(leaseId) {
89
+ try {
90
+ return (await call("/v1/capacity/renew", { leaseId, ttlMs: RESERVATION_TTL_MS })).ok;
91
+ }
92
+ catch {
93
+ return false;
94
+ }
95
+ },
96
+ async release(leaseId) {
97
+ try {
98
+ await call("/v1/capacity/release", { leaseId });
99
+ }
100
+ catch { /* the TTL gives it back */ }
101
+ },
102
+ };
103
+ }
104
+ /** The base a model's requests go to first and the name it is asked for there. */
105
+ export function capacityTarget(p) {
106
+ const ep = p?.endpoint ?? p?.endpoints?.[0];
107
+ if (!p || !ep)
108
+ return undefined;
109
+ return { base: ep.replace(/\/v1\/?$/, "").replace(/\/+$/, ""), route: p.endpointModels?.[0] ?? p.model ?? p.id };
110
+ }
111
+ /** The capacity source for the delegate model, or undefined when it has no endpoint to ask. `mainModel` is read on every
112
+ * reserve: when main's requests go to the same router, its route is the one whose leg keeps a unit for the main turn. */
113
+ export function delegateCapacity(registry, delegate, mainModel, fetch) {
114
+ const t = capacityTarget(registry.find((p) => p.id === delegate));
115
+ if (!t)
116
+ return undefined;
117
+ const spare = () => {
118
+ const m = capacityTarget(registry.find((p) => p.id === mainModel()));
119
+ return m && m.base === t.base ? m.route : undefined;
120
+ };
121
+ return routerCapacity({ ...t, spare, fetch });
122
+ }
123
+ /** The owner's delegate route as a capacity source, only once its router answers the capacity API for it: undefined
124
+ * for an unset route, one with no endpoint, or an endpoint that is not the router (the caller keeps what it had). */
125
+ export async function liveDelegateRoute(registry, route, mainModel, fetch) {
126
+ const source = route ? delegateCapacity(registry, route, mainModel, fetch) : undefined;
127
+ if (!source)
128
+ return undefined;
129
+ try {
130
+ await source.snapshot();
131
+ return source;
132
+ }
133
+ catch {
134
+ return undefined;
135
+ }
136
+ }
@@ -0,0 +1,42 @@
1
+ // Evidence-size guard. Sibling agents handed the same large input each pay its full prefill (11/27: a status turn
2
+ // prefilled 561K tokens because three agents re-read the same 210 KB digest). Two sources: identical large blocks in their
3
+ // briefs, and the same file read by several of them. Pure: the manager records, this groups.
4
+ import { createHash } from "node:crypto";
5
+ /** Shared input at or above this many tokens (≈ chars/4) is worth a warning. */
6
+ export const EVIDENCE_TOKENS = 50_000;
7
+ const BLOCK_MIN_CHARS = 1_000;
8
+ const hash = (s) => createHash("sha256").update(s).digest("hex").slice(0, 16);
9
+ /** One record per large paragraph of a brief: pasted context shows up as the same paragraphs in several briefs. */
10
+ export function briefRecords(agent, brief) {
11
+ return brief.split(/\n\s*\n/).filter((p) => p.length >= BLOCK_MIN_CHARS).map((p) => ({ agent, key: `brief:${hash(p)}`, label: "brief context", chars: p.length }));
12
+ }
13
+ /** A file read: keyed by path, so partial reads of one file still count as the same evidence. */
14
+ export function readRecord(agent, path, chars) {
15
+ return { agent, key: `file:${path}`, label: path.split("/").pop() || path, chars };
16
+ }
17
+ /** Inputs that two or more agents each received at ≥ `minTokens`: brief blocks shared by the same set of agents are
18
+ * summed (a digest pasted into three briefs is many paragraphs), files are taken per path at each agent's largest read. */
19
+ export function evidenceOverlap(records, minTokens = EVIDENCE_TOKENS) {
20
+ const byKey = new Map();
21
+ for (const r of records) {
22
+ const e = byKey.get(r.key) ?? { label: r.label, per: new Map() };
23
+ e.per.set(r.agent, Math.max(e.per.get(r.agent) ?? 0, r.chars));
24
+ byKey.set(r.key, e);
25
+ }
26
+ const groups = new Map();
27
+ for (const [key, e] of byKey) {
28
+ if (e.per.size < 2)
29
+ continue;
30
+ const agents = [...e.per.keys()].sort();
31
+ const chars = Math.min(...e.per.values());
32
+ const g = key.startsWith("brief:") ? `brief|${agents.join(",")}` : key;
33
+ const prev = groups.get(g);
34
+ groups.set(g, prev ? { ...prev, chars: prev.chars + chars } : { label: e.label, agents, chars });
35
+ }
36
+ return [...groups.values()].filter((o) => o.chars / 4 >= minTokens).sort((a, b) => b.chars - a.chars);
37
+ }
38
+ /** "3 agents re-reading the same 210 KB digest.md: give each a distinct slice". */
39
+ export function overlapLine(o) {
40
+ const size = o.chars >= 1_000_000 ? `${(o.chars / 1_000_000).toFixed(1)} MB` : `${Math.round(o.chars / 1000)} KB`;
41
+ return `${o.agents.length} agents re-reading the same ${size} ${o.label} (${o.agents.join(", ")}): give each a distinct slice`;
42
+ }