@0perator/operator 0.1.345 → 0.1.347
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/autonomy/delegate.js +4 -3
- package/dist/autonomy/session-factory.js +2 -1
- package/dist/autonomy/subagent-model.js +20 -0
- package/dist/background/commands.js +7 -0
- package/dist/background/index.js +135 -14
- package/dist/background/notices.js +25 -3
- package/dist/cli.js +64 -32
- package/dist/config/persona.js +29 -16
- package/dist/engine/agent.js +40 -18
- package/dist/engine/anthropic-chat.js +2 -2
- package/dist/engine/aurora.js +8 -4
- package/dist/engine/continuation.js +30 -5
- package/dist/engine/grandmaster.js +18 -1
- package/dist/engine/loop-guard.js +58 -24
- package/dist/session.js +48 -26
- package/dist/tools/executor.js +2 -1
- package/dist/ui/ActivitySpinner.js +11 -16
- package/dist/ui/BgPanel.js +35 -24
- package/dist/ui/PlanPane.js +26 -2
- package/dist/ui/ToolStep.js +16 -2
- package/package.json +1 -1
|
@@ -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 =
|
|
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
|
|
@@ -128,7 +129,7 @@ function sendWithTimeout(send, ms, interrupt) {
|
|
|
128
129
|
const msg = (e) => (e instanceof Error ? e.message : String(e));
|
|
129
130
|
// ── The `delegate_task` tool (registry wires run: runDelegateTask) ──────────
|
|
130
131
|
/**
|
|
131
|
-
* Run `args.task` on a sub-agent backed by `args.model` (default:
|
|
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
|
|
132
133
|
* `error: ...` string (the tool contract: never throws). Result size is bounded downstream — the executor's
|
|
133
134
|
* capToolResult spills anything over 40KB to disk and hands the planner a re-readable pointer.
|
|
134
135
|
*/
|
|
@@ -143,7 +144,7 @@ export async function runDelegateTask(args, deps = defaultDeps) {
|
|
|
143
144
|
const settings = await deps.loadSettings();
|
|
144
145
|
// Default sub-agent model is a SETTING (autonomy.delegateModel), not a hardcode, so a new sub-agent can be
|
|
145
146
|
// dropped in by changing one value — the planner still overrides per call via `args.model`.
|
|
146
|
-
const defaultModel = (await defaultModelStore()).getStore() || (settings
|
|
147
|
+
const defaultModel = (await defaultModelStore()).getStore() || subagentModelFor(settings);
|
|
147
148
|
const modelId = String(args.model ?? "").trim() || defaultModel;
|
|
148
149
|
// Gate BYO providers (Claude/OpenAI/Gemini/Qwen/…) on the user actually having stored that provider's key,
|
|
149
150
|
// the same check /model applies — so an unconnected provider fails fast with the actionable "store the key"
|
|
@@ -7,7 +7,7 @@ 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";
|
|
@@ -53,6 +53,7 @@ export function createAutonomySession(settings, opts = {}) {
|
|
|
53
53
|
loopGuard: settings.loopGuard, // tool-loop + repetition guard thresholds
|
|
54
54
|
hooks: settings.hooks, // lifecycle hooks (settings.hooks); inert unless tool hooks are configured
|
|
55
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
|
|
56
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
|
|
57
58
|
temperature: settings.temperature,
|
|
58
59
|
recall: settings.memory.recall,
|
|
@@ -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
|
+
}
|
package/dist/background/index.js
CHANGED
|
@@ -1,7 +1,25 @@
|
|
|
1
|
-
import { buildBrief,
|
|
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 ??
|
|
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
|
|
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) => {
|
|
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 (
|
|
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 =
|
|
369
|
-
?
|
|
370
|
-
: (
|
|
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
|
-
|
|
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]
|
|
16
|
-
`
|
|
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));
|