@0perator/operator 0.1.344 → 0.1.346

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.
package/dist/acp/agent.js CHANGED
@@ -15,6 +15,7 @@ import { isAbsolute } from "node:path";
15
15
  import { PROTOCOL_VERSION, RequestError } from "@zed-industries/agent-client-protocol";
16
16
  import { createAutonomySession } from "../autonomy/session-factory.js";
17
17
  import { modelRegistry } from "../router/models.js";
18
+ import { moaTeam } from "../engine/moa.js";
18
19
  import { hasByoToken } from "../auth/byo.js";
19
20
  import { operatorPath } from "../config/home.js";
20
21
  import { redactSecrets } from "../engine/redact.js";
@@ -182,8 +183,8 @@ export class OperatorAcpAgent {
182
183
  * read from the Session itself so a /model-style switch elsewhere is reflected here too. */
183
184
  modelOption(sessionId) {
184
185
  const live = this.sessions.get(sessionId);
185
- const moa = this.settings.moa;
186
- return buildModelConfigOption(modelRegistry(this.settings.models), live?.session.currentModel() ?? "", !!moa?.proposers?.length, hasByoToken, // the builder is the single source of selector truth: hidden + unconnectable BYO
186
+ const moa = moaTeam(this.settings.moa);
187
+ return buildModelConfigOption(modelRegistry(this.settings.models), live?.session.currentModel() ?? "", !!moa, hasByoToken, // the builder is the single source of selector truth: hidden + unconnectable BYO
187
188
  this.actor.tier === "admin"); // filtered there, active-but-hidden re-admitted there (never a lying currentValue)
188
189
  }
189
190
  /** SDK-0.4.5 legacy path (wire: session/set_model) — what Zed ships today. The spec-stable
@@ -237,6 +238,10 @@ export class OperatorAcpAgent {
237
238
  const handlers = acpHandlers((update) => void this.conn.sessionUpdate({ sessionId: live.sid, update: update }).catch(() => { }), { calls: live.calls, cwd: live.cwd });
238
239
  try {
239
240
  const outcome = await live.session.send(text, handlers);
241
+ // An engine stop is never streamed (it isn't model output), so the editor would end the turn in silence: send the
242
+ // plain question as the turn's message.
243
+ if (outcome.display && !live.cancelled)
244
+ await this.conn.sessionUpdate({ sessionId: live.sid, update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: outcome.display } } }).catch(() => { });
240
245
  return { stopReason: live.cancelled ? "cancelled" : acpStopReason(outcome) };
241
246
  }
242
247
  catch (e) {
@@ -12,9 +12,10 @@
12
12
  import { modelRegistry, selectModel, endpointBase } from "../router/models.js";
13
13
  import { MemoryStore } from "../memory/index.js";
14
14
  import { delegateBrief, inferType } from "../engine/grandmaster.js";
15
+ import { subagentModelFor, DEFAULT_SUBAGENT_MODEL } from "./subagent-model.js";
15
16
  const nodeImport = (m) => import(/* @vite-ignore */ m);
16
17
  /** Model a delegation lands on when the planner names none — the fast local tier. */
17
- export const DEFAULT_DELEGATE_MODEL = "scout";
18
+ export const DEFAULT_DELEGATE_MODEL = DEFAULT_SUBAGENT_MODEL; // kept for importers; the one default lives in subagent-model.ts
18
19
  /** How many sub-agent levels may stack. 1 = the planner may delegate; a sub-agent may NOT delegate again. */
19
20
  export const MAX_DELEGATE_DEPTH = 1;
20
21
  /** Env floor on the depth, read-only here: a harness (or a parent process) that exports it >= MAX disables
@@ -40,6 +41,26 @@ let _depthStore = null;
40
41
  function depthStore() {
41
42
  return (_depthStore ??= nodeImport("node:async_hooks").then((m) => new m.AsyncLocalStorage()));
42
43
  }
44
+ // The default sub-agent model for the turn in flight (a MoA turn sets its specialist). Async-context scoped, like the
45
+ // depth above, so two ACP sessions in one process never see each other's default.
46
+ let _defaultModelStore;
47
+ function defaultModelStore() {
48
+ return (_defaultModelStore ??= nodeImport("node:async_hooks").then((m) => new m.AsyncLocalStorage()));
49
+ }
50
+ /** Run `fn` with `modelId` as delegate_task's default model (the planner can still pass `model`). */
51
+ export async function withDelegateDefault(modelId, fn) {
52
+ return (await defaultModelStore()).run(modelId, fn);
53
+ }
54
+ /** The step's role (its prompt + scoped tool set): the turn router's trained head when the classifier is on (finds
55
+ * research steps 3× as often as the keyword rules on real prompts), the keyword rules otherwise. */
56
+ async function delegateRole(task, settings) {
57
+ const [{ resolveMode }, { classifierConfig }, { routeTurn, roleFor }] = await Promise.all([
58
+ import("../classifier/modes.js"), import("../classifier/config.js"), import("../classifier/route.js"),
59
+ ]);
60
+ if (resolveMode(settings) === "off")
61
+ return inferType(task);
62
+ return roleFor(task, await routeTurn(task, classifierConfig(settings).endpoint));
63
+ }
43
64
  /** Current delegation depth: the async-context depth, floored by KODE_DELEGATE_DEPTH. 0 = a planner. */
44
65
  export async function delegationDepth() {
45
66
  const scoped = (await depthStore()).getStore() ?? 0;
@@ -108,7 +129,7 @@ function sendWithTimeout(send, ms, interrupt) {
108
129
  const msg = (e) => (e instanceof Error ? e.message : String(e));
109
130
  // ── The `delegate_task` tool (registry wires run: runDelegateTask) ──────────
110
131
  /**
111
- * Run `args.task` on a sub-agent backed by `args.model` (default: settings autonomy.delegateModel, else "scout") and return its final answer, or an
132
+ * Run `args.task` on a sub-agent backed by `args.model` (default: autonomy/subagent-model.ts — the MoA specialist, the owner's setting, else gpt-oss-20b) and return its final answer, or an
112
133
  * `error: ...` string (the tool contract: never throws). Result size is bounded downstream — the executor's
113
134
  * capToolResult spills anything over 40KB to disk and hands the planner a re-readable pointer.
114
135
  */
@@ -123,7 +144,7 @@ export async function runDelegateTask(args, deps = defaultDeps) {
123
144
  const settings = await deps.loadSettings();
124
145
  // Default sub-agent model is a SETTING (autonomy.delegateModel), not a hardcode, so a new sub-agent can be
125
146
  // dropped in by changing one value — the planner still overrides per call via `args.model`.
126
- const defaultModel = (settings.autonomy?.delegateModel ?? "").trim() || DEFAULT_DELEGATE_MODEL;
147
+ const defaultModel = (await defaultModelStore()).getStore() || subagentModelFor(settings);
127
148
  const modelId = String(args.model ?? "").trim() || defaultModel;
128
149
  // Gate BYO providers (Claude/OpenAI/Gemini/Qwen/…) on the user actually having stored that provider's key,
129
150
  // the same check /model applies — so an unconnected provider fails fast with the actionable "store the key"
@@ -154,7 +175,7 @@ export async function runDelegateTask(args, deps = defaultDeps) {
154
175
  let session;
155
176
  try {
156
177
  session = await deps.createSession(deriveDelegateSettings(settings, profile, auroraOverride), {
157
- role: inferType(task), // the child runs as a role (prompt + scoped tools), not a clone of the owner's session
178
+ role: await delegateRole(task, settings), // the child runs as a role (prompt + scoped tools), not a clone of the owner's session
158
179
  extra: {
159
180
  sessionId: id,
160
181
  memory: new MemoryStore(`${dir}/Operator_Memory.jsonl`),
@@ -97,7 +97,12 @@ export async function runHeadless(settings, prompt, opts = {}) {
97
97
  const outcome = await session.send(prompt, handlers);
98
98
  reporter.event("done", { rounds: outcome.rounds, toolCalls: outcome.toolCalls, interrupted: outcome.interrupted, durationMs: Math.round(outcome.durationMs ?? 0) });
99
99
  result = { rounds: outcome.rounds, toolCalls: outcome.toolCalls, interrupted: outcome.interrupted, durationMs: Math.round(outcome.durationMs ?? 0) };
100
- answer(outcome.content);
100
+ if (outcome.display) {
101
+ streamed = "";
102
+ if (output === "text")
103
+ process.stdout.write("\n");
104
+ } // an engine stop always ends on its question, even after a cut-off stream
105
+ answer(outcome.display ?? outcome.content);
101
106
  await session.flushRouteShadow(); // MOA phase-0: headless one-shot exits before fire-and-forget would land
102
107
  return finish(outcome.interrupted ? 130 : 0);
103
108
  }
@@ -22,6 +22,7 @@ import { boardPath, addTask, readBoard } from "./board.js";
22
22
  import { routinesPath, readRoutines } from "./routines.js";
23
23
  import { readableRoutine, nextFire, runRoutine, launchdPlist, launchdLabel, crontabLine } from "./routine-run.js";
24
24
  import { ensureServices } from "../services/preflight.js";
25
+ import { modelRegistry } from "../router/models.js";
25
26
  const AUTONOMY_COMMANDS = new Set(["run", "loop", "board", "routine", "dream", "acp", "media-robot"]);
26
27
  /** Split argv (after the subcommand) into --bool flags, --key value pairs, and positionals. `--` ends
27
28
  * flag parsing so a task string starting with a dash is preserved. */
@@ -74,6 +75,14 @@ export function runFlags(args) {
74
75
  return "--model needs a model id";
75
76
  return { output, model, permissions: pm, cwd: f.val.get("cwd") };
76
77
  }
78
+ /** `--model`: a registry id (`moa`, `cortana`, `gpt-oss-20b` …) selects that model — the same as `/model` — so an
79
+ * orchestrated profile like MoA really runs as MoA; any other string is a raw model name on the primary endpoint. */
80
+ export function applyRunModel(settings, model) {
81
+ if (modelRegistry(settings.models).some((m) => m.id === model))
82
+ settings.activeModel = model;
83
+ else
84
+ settings.endpoints.aurora = { ...settings.endpoints.aurora, model };
85
+ }
77
86
  function usage(msg) {
78
87
  process.stderr.write(`operator: ${msg}\n${RUN_USAGE}\n`);
79
88
  return 2;
@@ -307,7 +316,7 @@ export async function dispatchAutonomy(argv, settings) {
307
316
  return usage("no task given");
308
317
  // Flags beat settings and KODE_* the same way the env overrides beat the file: for this run only.
309
318
  if (model)
310
- settings.endpoints.aurora = { ...settings.endpoints.aurora, model };
319
+ applyRunModel(settings, model);
311
320
  if (pm)
312
321
  settings.permissions = { ...settings.permissions, mode: pm };
313
322
  const loop = cmd === "loop" || f.bool.has("loop");
@@ -7,10 +7,12 @@ import { Session } from "../session.js";
7
7
  import { AuroraRouter } from "../router/router.js";
8
8
  import { buildMemory } from "../memory/providers.js";
9
9
  import { composeSystemPrompt, subagentSystemPrompt } from "../config/persona.js";
10
- import { SUBAGENT_ROLES } from "../engine/grandmaster.js";
10
+ import { SUBAGENT_ROLES, SUBAGENT_TOOL_DENY } from "../engine/grandmaster.js";
11
11
  import { ensureScratchDir } from "../config/scratch.js";
12
12
  import { modelCtxFor, leanHarnessFor, DEFAULT_MODEL_ID } from "../router/models.js";
13
13
  import { compactionThreshold, compactionCeilingTokens, turnWallClockMs, buildEndpointChain } from "../config/settings.js";
14
+ import { resolveMode } from "../classifier/modes.js";
15
+ import { classifierConfig } from "../classifier/config.js";
14
16
  /** Build the Aurora router from settings — the headless twin of cli.tsx's buildRouter(). Both share the one
15
17
  * multi-tier chain builder (primary → other fleet nodes → back-compat single failover → cloud), so a
16
18
  * wedged/degraded endpoint fails over through the whole fleet before the turn can error. */
@@ -51,11 +53,13 @@ export function createAutonomySession(settings, opts = {}) {
51
53
  loopGuard: settings.loopGuard, // tool-loop + repetition guard thresholds
52
54
  hooks: settings.hooks, // lifecycle hooks (settings.hooks); inert unless tool hooks are configured
53
55
  unattended: true, // no owner watching: the loop guard hard-stops by default (settings.loopGuard.hardStop overrides)
56
+ ...(opts.role ? { toolDeny: SUBAGENT_TOOL_DENY } : {}), // a sub-agent never writes the owner's task list
54
57
  maxRounds: settings.autonomy?.maxRounds, // soft per-turn round budget (default 200) — a deep unattended build runs to completion before the wrap-up nudge; was never passed here, so headless runs fell back to the engine's 10-round floor and cut long missions short
55
58
  temperature: settings.temperature,
56
59
  recall: settings.memory.recall,
57
60
  models: settings.models,
58
61
  moa: settings.moa,
62
+ classifier: { mode: resolveMode(settings), endpoint: classifierConfig(settings).endpoint },
59
63
  fastStart: settings.fastStart,
60
64
  features: settings.features, // feature flags — registers flag-gated tools (e.g. cloudAgents) only when on
61
65
  activeModel: settings.activeModel,
@@ -0,0 +1,20 @@
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 gpt-oss-20b, the shipped default (owner, 10/31: "make this
3
+ // application wide so me and others can test"; arena: 35/36 tasks, median 47 s). Every install's registry has it, reached
4
+ // through the local router or api.0perator.co. Node-free (pure).
5
+ import { moaTeam } from "../engine/moa.js";
6
+ export const DEFAULT_SUBAGENT_MODEL = "gpt-oss-20b";
7
+ export function subagentModelFor(settings, activeModel) {
8
+ activeModel ??= settings.activeModel;
9
+ if (activeModel === "moa") {
10
+ const team = moaTeam(settings.moa);
11
+ if (team)
12
+ return team.specialist;
13
+ }
14
+ return settings.autonomy?.subagentModel?.trim() || settings.autonomy?.delegateModel?.trim() || DEFAULT_SUBAGENT_MODEL;
15
+ }
16
+ /** The model that serves the PARENT's turn: the planner under /model moa, else the selection itself. A sub-agent on
17
+ * the same model shares its slot (the parent then yields to it); on any other model it runs beside the parent. */
18
+ export function servingModelFor(settings, activeModel) {
19
+ return activeModel === "moa" ? (moaTeam(settings.moa)?.planner.id ?? activeModel) : activeModel;
20
+ }
@@ -0,0 +1,7 @@
1
+ /** Resolve the longest known name before parsing the command, including numbered twins. */
2
+ export function parseAgentCommand(input, agents) {
3
+ const arg = input.trim();
4
+ const candidates = agents.flatMap((a) => [a.id, a.name].filter((v) => !!v)).sort((a, b) => b.length - a.length);
5
+ const matched = candidates.find((name) => arg.toLowerCase() === name.toLowerCase() || arg.toLowerCase().startsWith(name.toLowerCase() + " "));
6
+ return matched ? [matched, ...arg.slice(matched.length).trim().split(/\s+/)] : arg.split(/\s+/);
7
+ }
@@ -1,7 +1,25 @@
1
- import { buildBrief, inferType, routeLane, extractFinalAnswer, repairPrompt, verifyFinalAnswer, partialReport, } from "../engine/grandmaster.js";
1
+ import { buildBrief, routeLane, extractFinalAnswer, repairPrompt, verifyFinalAnswer, partialReport, SUBAGENT_ROLES, roleForBrief, roleCanWrite, } from "../engine/grandmaster.js";
2
+ import { isEngineFinal } from "../engine/continuation.js";
2
3
  import { createWorktree, finalizeWorktree } from "./worktree.js";
3
4
  const RECENT_STEPS = 5; // tool steps kept per agent for the live view (older ones scroll off)
4
5
  const THOUGHT_MAX = 160; // chars of the latest reasoning snippet retained (tail)
6
+ // The work ledger + stuck checks (10/31: a sub-agent ran 54 rounds / 33 min, wrote nothing, and nobody could tell).
7
+ const WRITE_TOOLS = new Set(["file_write", "file_edit", "apply_patch", "multi_edit", "write_file", "edit_file", "notebook_edit"]);
8
+ const READ_TOOLS = new Set(["file_read", "read_files", "list_directory", "find_files", "glob", "grep", "grep_search", "search",
9
+ "code_search", "codebase_search", "web_search", "web_fetch", "browser", "browser_read", "deep_research", "knowledge_search"]);
10
+ const CMD_TOOLS = new Set(["bash", "shell_exec", "shell_background"]);
11
+ const WRITTEN_MAX = 8;
12
+ const STUCK_REPEATS = 3; // the same call(s) this many batches in a row
13
+ const STUCK_ROUNDS_NO_WRITE = 15; // a writing task with this many rounds and no file written
14
+ const STUCK_TALK_MS = 8 * 60_000; // tokens flowing but no tool call for this long (the announce loop; one big file write on a slow model can take 5)
15
+ const WRITING_TASK = /\b(write|create|draft|edit|update|build|implement|fix|add|document|save)\b/i;
16
+ /** Default names when the planner gives none — short, distinct, easy to type in `/agents <name>`, and none of them a
17
+ * fleet box or service (Nova, Atlas, Forge… already mean machines here). */
18
+ export const AGENT_NAMES = ["Iris", "Orion", "Vega", "Lyra", "Juno", "Rhea", "Wren", "Milo", "Tess", "Kai"];
19
+ const pathArg = (args) => {
20
+ const v = args?.path ?? args?.file_path ?? args?.file;
21
+ return typeof v === "string" && v.trim() ? v.trim() : undefined;
22
+ };
5
23
  const THOUGHT_EMIT_MS = 700; // min gap between reasoning-driven re-renders — bounds render load during long thinks
6
24
  const IDLE_TTL_MS = 45_000; // a finished agent lingers this long (result already in the transcript) then decommissions
7
25
  const MAX_FOLLOWUP_MSGS = 6; // cap on parent->child mid-run messages processed per agent (bidirectional coms; no runaway)
@@ -56,6 +74,7 @@ export class BackgroundAgents {
56
74
  onDone;
57
75
  modelName;
58
76
  onTaskActivity;
77
+ onStuck;
59
78
  // session is created lazily in run() (a code-editing agent's session must be rooted at its worktree, which
60
79
  // requires an async `git worktree add`); wt is its isolated worktree, or null when not isolated.
61
80
  agents = new Map();
@@ -87,12 +106,16 @@ export class BackgroundAgents {
87
106
  * module-level store), but the pane only refreshed on the foreground's OWN task_* calls, so a child could
88
107
  * finish real, tracked work and the plan pane would sit frozen. Optional/back-compat: omit to keep the
89
108
  * pre-existing behavior. */
90
- constructor(makeSession, onChange, onDone, modelName = "aurora-code-1", onTaskActivity) {
109
+ constructor(makeSession, onChange, onDone, modelName = "aurora-code-1", onTaskActivity,
110
+ /** Fired ONCE per agent when the deterministic checks first find it stuck (BgAgent.stuck says why) — the shell
111
+ * wakes the orchestrator with the evidence so it steers, stops, or takes the step over. */
112
+ onStuck) {
91
113
  this.makeSession = makeSession;
92
114
  this.onChange = onChange;
93
115
  this.onDone = onDone;
94
116
  this.modelName = modelName;
95
117
  this.onTaskActivity = onTaskActivity;
118
+ this.onStuck = onStuck;
96
119
  }
97
120
  list() {
98
121
  return [...this.agents.values()].map((a) => ({ ...a.info }));
@@ -124,24 +147,49 @@ export class BackgroundAgents {
124
147
  * "no background job bg1", concluded the sub-agent had been "evicted", and re-spawned a duplicate onto
125
148
  * the one shared endpoint. Same-looking ids in two different registries was the whole bug; disjoint
126
149
  * namespaces make that specific confusion structurally impossible, not just better-worded. */
127
- spawn(task, role) {
150
+ spawn(task, role, name) {
128
151
  if (this.inFlight() >= this.maxConcurrent + this.maxQueued)
129
152
  return "";
130
153
  const id = `agent-${++this.seq}`;
131
- const type = role ?? inferType(task);
154
+ const type = role ?? roleForBrief(task);
132
155
  const brief = buildBrief({ objective: task, type }, process.cwd());
133
156
  const lane = routeLane(brief, { type });
134
157
  const label = summarizeTask(task);
135
158
  // Starts QUEUED; pump() promotes it to working when a concurrency slot is free (startedAt is stamped
136
159
  // then, so the panel timer measures real run time, not queue wait). The Session is created lazily in
137
160
  // run() so a code-editing agent can be rooted at its own worktree (an async setup).
138
- const info = { id, label, status: "queued", task, round: 0, tokens: 0, model: this.modelName, lane };
161
+ const model = typeof this.modelName === "function" ? this.modelName() : this.modelName;
162
+ const info = {
163
+ id, label, status: "queued", task, round: 0, tokens: 0, model, lane,
164
+ name: this.uniqueName(name?.trim().replace(/\s+/g, " ").slice(0, 24) || AGENT_NAMES[(this.seq - 1) % AGENT_NAMES.length]),
165
+ title: SUBAGENT_ROLES[type]?.title ?? "assistant", role: type,
166
+ };
139
167
  this.agents.set(id, { info, brief, type });
140
168
  this.queue.push(id);
141
169
  this.onChange();
142
170
  this.pump();
143
171
  return id;
144
172
  }
173
+ /** A live agent already answering to `name` gets a numbered twin ("Iris 2"), so a name always resolves to one agent. */
174
+ uniqueName(name) {
175
+ const taken = new Set([...this.agents.values()].map((a) => a.info.name?.toLowerCase()));
176
+ if (!taken.has(name.toLowerCase()))
177
+ return name;
178
+ for (let n = 2;; n++)
179
+ if (!taken.has(`${name} ${n}`.toLowerCase()))
180
+ return `${name} ${n}`;
181
+ }
182
+ /** The id for an agent id ("agent-2") or name ("Iris", any case); undefined when neither matches a known agent. */
183
+ resolve(idOrName) {
184
+ const key = idOrName.trim();
185
+ if (this.agents.has(key))
186
+ return key;
187
+ const lower = key.toLowerCase();
188
+ for (const a of [...this.agents.values()].reverse())
189
+ if (a.info.name?.toLowerCase() === lower)
190
+ return a.info.id;
191
+ return undefined;
192
+ }
145
193
  /** Start queued agents up to the concurrency cap. Called on spawn and whenever a running slot frees. */
146
194
  pump() {
147
195
  while (this.activeCount() < this.maxConcurrent && this.queue.length > 0) {
@@ -226,7 +274,7 @@ export class BackgroundAgents {
226
274
  const cwd = wt?.dir;
227
275
  let session;
228
276
  try {
229
- session = this.makeSession(cwd, type);
277
+ session = this.makeSession(cwd, type, info.model);
230
278
  }
231
279
  catch (e) {
232
280
  // makeSession is a caller-supplied factory (a real `new Session(...)`, not just an object literal) —
@@ -247,6 +295,12 @@ export class BackgroundAgents {
247
295
  entry.session = session;
248
296
  entry.wt = wt;
249
297
  }
298
+ // The model it really runs on (a failed setModel leaves it on the default chain) — the panel and the parent's
299
+ // shared-slot check read this, not the model it was meant to get.
300
+ if (typeof session.currentModel === "function") {
301
+ info.model = session.currentModel();
302
+ this.onChange();
303
+ }
250
304
  if (!entry || entry.info.status === "stopped") { // stopped while the worktree was being set up
251
305
  if (wt)
252
306
  void finalizeWorktree(wt, info.label);
@@ -254,12 +308,35 @@ export class BackgroundAgents {
254
308
  }
255
309
  let total = 0;
256
310
  let lastThoughtEmit = 0;
311
+ let lastSig = "";
312
+ let repeat = 0;
313
+ let lastBatchAt = Date.now();
314
+ const writesExpected = roleCanWrite(type) && (type === "code-edit" || WRITING_TASK.test(info.task ?? ""));
315
+ const markStuck = (why) => {
316
+ if (info.stuck)
317
+ return;
318
+ info.stuck = why;
319
+ this.onChange();
320
+ if (entry.stuckNotified)
321
+ return; // the orchestrator is woken once per agent; the panel keeps showing it
322
+ entry.stuckNotified = true;
323
+ this.onStuck?.({ ...info });
324
+ };
257
325
  const hooks = {
326
+ // message_agent while this agent works: folded in at its next round boundary, not after the whole turn.
327
+ steer: () => (entry.messages?.length ? entry.messages.shift() : undefined),
258
328
  // Authoritative live token count: the real llama.cpp per-round total for the in-flight send, added
259
329
  // to what prior sends already counted. Replaces the old ≈1-per-content-delta tally, which missed
260
330
  // every token generated as a tool-call argument or reasoning (most of a skill-writer's output — so
261
331
  // a sub-agent that wrote thousands of tokens read as "53 tok").
262
- onTokens: (t) => { info.tokens = total + t; this.touchProgress(id); this.onChange(); },
332
+ onTokens: (t) => {
333
+ info.tokens = total + t;
334
+ this.touchProgress(id);
335
+ this.onChange();
336
+ // Tokens keep the stall timer alive, so a model that talks without acting never "stalls" — catch it here.
337
+ if (Date.now() - lastBatchAt > STUCK_TALK_MS)
338
+ markStuck(`talking without acting for ${Math.round((Date.now() - lastBatchAt) / 60_000)} min`);
339
+ },
263
340
  // Reasoning stream → the "thinking" line. Coalesce (keep the tail) and throttle re-renders:
264
341
  // a long think can emit hundreds of chunks, but the panel only needs to refresh ~1/sec.
265
342
  onReasoning: (chunk) => {
@@ -293,6 +370,37 @@ export class BackgroundAgents {
293
370
  const lastOut = events.length ? String(events[events.length - 1].result ?? "").trim() : "";
294
371
  info.lastOutput = lastOut ? outputTail(lastOut) : undefined;
295
372
  info.thought = undefined;
373
+ lastBatchAt = Date.now();
374
+ // Work ledger: what it changed, read and ran — the owner's answer to "what has it actually done?".
375
+ let wrote = false;
376
+ for (const e of events) {
377
+ const out = String(e.result ?? "").trim();
378
+ if (WRITE_TOOLS.has(e.name) && !/^(error|✗)/i.test(out)) {
379
+ const p = pathArg(e.args);
380
+ if (p) {
381
+ info.written = [...(info.written ?? []).filter((x) => x !== p), p].slice(-WRITTEN_MAX);
382
+ wrote = true;
383
+ }
384
+ }
385
+ else if (READ_TOOLS.has(e.name))
386
+ info.reads = (info.reads ?? 0) + 1;
387
+ else if (CMD_TOOLS.has(e.name))
388
+ info.commands = (info.commands ?? 0) + 1;
389
+ }
390
+ if (wrote)
391
+ info.stuck = undefined; // real output: whatever looked stuck has moved on
392
+ // Stuck checks, deterministic: the same call(s) batch after batch, the loop guard's own notice, or a writing
393
+ // task that has written nothing for many rounds.
394
+ const sig = events.map((e) => `${e.name}:${JSON.stringify(e.args ?? {})}`).join("|");
395
+ repeat = sig === lastSig ? repeat + 1 : 1;
396
+ lastSig = sig;
397
+ const guard = events.map((e) => String(e.result ?? "")).find((r) => /loop guard/i.test(r));
398
+ if (repeat >= STUCK_REPEATS)
399
+ markStuck(`repeating ${events[0]?.name ?? "the same call"}${shortArg(events[0]?.args) ? ` (${shortArg(events[0]?.args)})` : ""} ×${repeat}`);
400
+ else if (guard)
401
+ markStuck(`loop guard: ${guard.split("\n").find((l) => /loop guard/i.test(l))?.replace(/^.*?loop guard:?\s*/i, "").slice(0, 80) ?? "repeating"}`);
402
+ else if (writesExpected && !info.written?.length && (info.round ?? 0) >= STUCK_ROUNDS_NO_WRITE)
403
+ markStuck(`${info.round} rounds, no file written`);
296
404
  this.touchProgress(id); // a completed round is unambiguous progress — reset the stall clock
297
405
  this.onChange();
298
406
  // This child can mutate the same session-wide task list the foreground plan pane reads (a single
@@ -306,10 +414,16 @@ export class BackgroundAgents {
306
414
  let r = await session.send(brief, hooks);
307
415
  total += r.tokens ?? 0;
308
416
  let fa = extractFinalAnswer(r.content, type);
417
+ // The engine ended the child's turn (loop guard, no progress, round cap): a repair round would hand the same loop
418
+ // a fresh budget (10/31: round 54 against a cap of 50). Finish with what it has; the stop note says why.
419
+ let engineStopped = isEngineFinal(r.content);
420
+ if (engineStopped)
421
+ info.malformed = true;
309
422
  // Mechanism 2: one repair round on a schema failure — feed the error back, re-run just the final step.
310
- if (!fa.ok && !r.interrupted) {
423
+ if (!fa.ok && !r.interrupted && !engineStopped) {
311
424
  const r2 = await session.send(repairPrompt(fa.errors ?? [], type), hooks);
312
425
  total += r2.tokens ?? 0;
426
+ engineStopped = isEngineFinal(r2.content);
313
427
  const fa2 = extractFinalAnswer(r2.content, type);
314
428
  if (fa2.ok) {
315
429
  fa = fa2;
@@ -325,20 +439,23 @@ export class BackgroundAgents {
325
439
  // Drain any queued messages as follow-up turns in the child's own conversation before finishing, so
326
440
  // the parent can steer it / answer its question mid-run. Bounded so a chatty parent can't loop it.
327
441
  let followups = 0;
328
- while (entry.messages && entry.messages.length > 0 && followups < MAX_FOLLOWUP_MSGS && !r.interrupted) {
442
+ while (entry.messages && entry.messages.length > 0 && followups < MAX_FOLLOWUP_MSGS && !r.interrupted && !engineStopped) {
329
443
  const msg = entry.messages.shift();
330
444
  followups++;
331
445
  info.thought = undefined;
332
446
  this.onChange();
333
447
  r = await session.send(msg, hooks);
334
448
  total += r.tokens ?? 0;
449
+ engineStopped = isEngineFinal(r.content);
335
450
  const faF = extractFinalAnswer(r.content, type);
336
451
  if (faF.ok)
337
452
  fa = faF;
338
453
  }
339
454
  // Mechanism 3: verify-before-done (never on the model's say-so). Verify runs IN the worktree, so a
340
455
  // code-editing child's declared verify_command tests the files it actually changed (in isolation).
341
- if (fa.ok && fa.value) {
456
+ if (engineStopped)
457
+ info.malformed = true;
458
+ if (!engineStopped && fa.ok && fa.value) {
342
459
  const v = await verifyFinalAnswer(fa.value, type, cwd ?? process.cwd(), { diffSha });
343
460
  info.verified = v.verified;
344
461
  info.verifyDetail = v.detail;
@@ -365,9 +482,11 @@ export class BackgroundAgents {
365
482
  // The parent sees the structured summary when we have one, tagged with verify/lane state so it can
366
483
  // decide whether to trust the child (mechanism 5 is the UI surfacing the same fields), plus where the
367
484
  // isolated worktree's changes landed (a review branch).
368
- const summary = (fa.value && typeof fa.value.summary === "string" && fa.value.summary.trim())
369
- ? fa.value.summary.trim()
370
- : (r.content.trim() || "(no output)");
485
+ const summary = engineStopped
486
+ ? `${partialReport(session.snapshot(), `${id} was stopped by the engine after ${info.round ?? 0} rounds`)}\n${r.content.split("\n")[0]}`
487
+ : (fa.value && typeof fa.value.summary === "string" && fa.value.summary.trim())
488
+ ? fa.value.summary.trim()
489
+ : (r.content.trim() || "(no output)");
371
490
  const tag = info.malformed ? " ⚠ malformed final_answer (unstructured)"
372
491
  : info.verified === false ? ` ⚠ unverified: ${info.verifyDetail}`
373
492
  : info.verified ? " ✓ verified"
@@ -428,7 +547,7 @@ export class BackgroundAgents {
428
547
  * follow-up turn in the child's conversation (see the drain loop in run). Returns false if the agent is
429
548
  * unknown or already finished — the parent then knows the message didn't land. */
430
549
  sendToAgent(id, text) {
431
- const a = this.agents.get(id);
550
+ const a = this.agents.get(this.resolve(id) ?? id);
432
551
  if (!a || (a.info.status !== "working" && a.info.status !== "queued"))
433
552
  return false;
434
553
  (a.messages ??= []).push(text);
@@ -436,6 +555,7 @@ export class BackgroundAgents {
436
555
  }
437
556
  /** Stop a running agent (interrupts its turn). Returns false if the id is unknown. */
438
557
  stop(id) {
558
+ id = this.resolve(id) ?? id;
439
559
  const a = this.agents.get(id);
440
560
  if (!a)
441
561
  return false;
@@ -457,6 +577,7 @@ export class BackgroundAgents {
457
577
  * interrupt() actually aborts the in-flight send) still sees r.interrupted and skips its own onDone, so
458
578
  * there is never a double post. Returns false if there was nothing running/queued to stop. */
459
579
  requestStop(id) {
580
+ id = this.resolve(id) ?? id;
460
581
  const a = this.agents.get(id);
461
582
  if (!a || (a.info.status !== "working" && a.info.status !== "queued"))
462
583
  return false;
@@ -9,14 +9,36 @@ const REPORT_CHARS = 8000; // the spawn brief asks for a ~1-2k token report; a r
9
9
  const reports = [];
10
10
  const listeners = new Set();
11
11
  const clip = (s, n) => s.length <= n ? s : s.slice(0, n) + `\n… [report clipped at ${n} chars — re-run the sub-agent with a tighter deliverable if the rest matters]`;
12
- /** The notice the model reads: who finished, then the report verbatim, framed as the self-report it is. */
12
+ const who = (a) => `${a.name ? `${a.name} (${a.title ?? "sub-agent"}, ${a.id})` : `sub-agent ${a.id}`} — ${a.label}`;
13
+ /** The notice the model reads when a sub-agent finishes: who, what it changed, its report — and what to do with it.
14
+ * Review before relaying: the report is a SELF-REPORT, and the owner should hear what was checked, not what was claimed. */
13
15
  export function formatAgentReport(agent, result) {
16
+ const files = agent.written?.length ? ` Files it wrote or edited: ${agent.written.join(", ")}.` : " No file writes were recorded by the tool ledger. Shell commands and untracked tools may have changed files; inspect their results.";
14
17
  return [
15
- `[system notice] sub-agent ${agent.id} (${agent.label}) finished. Its report follows — a SELF-REPORT: verify any ` +
16
- `side effect it claims (writes, pushes, uploads) before telling the owner it happened.`,
18
+ `[system notice] ${who(agent)} finished.${files} Its report follows — a SELF-REPORT. Review it before you tell the owner: ` +
19
+ `open what it produced, check it against the brief's Done line, fix or re-brief what is missing, update the plan, then tell ` +
20
+ `the owner in a few lines what was done, what you checked, and what is next.`,
17
21
  clip(result.trim() || "(no output)", REPORT_CHARS),
18
22
  ].join("\n");
19
23
  }
24
+ /** The one-time notice when the manager's checks find a sub-agent stuck — wakes the orchestrator with the evidence. */
25
+ export function formatStuckNotice(agent) {
26
+ const ledger = [agent.round != null ? `${agent.round} rounds` : "", agent.written?.length ? `wrote ${agent.written.join(", ")}` : "no file writes recorded",
27
+ agent.reads ? `${agent.reads} reads` : "", agent.commands ? `${agent.commands} commands` : ""].filter(Boolean).join(", ");
28
+ return `[system notice] ${who(agent)} looks STUCK: ${agent.stuck} (${ledger}). Decide now and tell the owner in one line: ` +
29
+ `steer it (message_agent with the missing piece), or stop it (stop_agent) and do the step yourself, or stop it and re-brief ` +
30
+ `a fresh sub-agent with a tighter brief. Waiting on it is not an option — it will not finish on its own.`;
31
+ }
32
+ /** Queue a stuck notice for the next turn and wake the shell (same channel as a finished report). */
33
+ export function queueAgentNotice(text) {
34
+ reports.push(text);
35
+ for (const fn of listeners) {
36
+ try {
37
+ fn();
38
+ }
39
+ catch { /* a bad listener must not lose a notice */ }
40
+ }
41
+ }
20
42
  /** Queue a finished agent's report for the next turn and tell the shell (which wakes an idle session). */
21
43
  export function queueAgentReport(agent, result) {
22
44
  reports.push(formatAgentReport(agent, result));
@@ -0,0 +1,46 @@
1
+ // The turn router client — operator-runtime/classifier (launchd co.0perator.classifier, 127.0.0.1:8400). One small
2
+ // encoder with two heads trained on real Operator prompts: will this request be answered without tools (a MoA turn
3
+ // then goes straight to the fast specialist instead of the planner), and which sub-agent role fits a step (its scoped
4
+ // tool set). Chosen 2026-10-31 on 382 real prompts over zero-shot GLiClass (AUC 0.765 vs 0.57–0.65).
5
+ // Advisory and never blocking: down, slow or malformed → null, and the caller does what it did before.
6
+ // Node-free (plain fetch) — safe for every bundle.
7
+ import { inferType } from "../engine/grandmaster.js";
8
+ const ROUTE_TIMEOUT_MS = 400; // the service answers in ~25–35 ms on CPU; anything slower is a sick service, not a slow one
9
+ const ROLES = ["research", "code-edit", "generic"];
10
+ const MIN_ROLE_P = 0.5;
11
+ export async function routeTurn(text, endpoint, timeoutMs = ROUTE_TIMEOUT_MS) {
12
+ const ctrl = new AbortController();
13
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
14
+ try {
15
+ const res = await fetch(`${endpoint.replace(/\/$/, "")}/route`, {
16
+ method: "POST",
17
+ headers: { "content-type": "application/json" },
18
+ body: JSON.stringify({ text: text.slice(0, 4000) }),
19
+ signal: ctrl.signal,
20
+ });
21
+ if (!res.ok)
22
+ return null;
23
+ const j = (await res.json());
24
+ if ((j.route !== "direct" && j.route !== "work") || typeof j.p_direct !== "number")
25
+ return null;
26
+ const role = ROLES.includes(j.role) ? j.role : undefined;
27
+ return { route: j.route, pDirect: j.p_direct, role, roleP: j.role_p, latencyMs: j.latency_ms };
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ finally {
33
+ clearTimeout(timer);
34
+ }
35
+ }
36
+ /** The sub-agent role for a delegated step. The keyword rules still own plan and review (the trained head has no
37
+ * examples of either); otherwise a confident classifier role wins — on real prompts it finds research steps 3× as
38
+ * often (12/31 vs 4/31) — and anything else falls back to the keyword rules. */
39
+ export function roleFor(task, route) {
40
+ const kw = inferType(task);
41
+ if (kw === "plan" || kw === "review")
42
+ return kw;
43
+ if (route?.role && (route.roleP ?? 0) >= MIN_ROLE_P)
44
+ return route.role;
45
+ return kw;
46
+ }