@oyasmi/pipiclaw 0.8.11 → 0.9.0-beta.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 (72) hide show
  1. package/dist/agent/channel-runner.d.ts +3 -0
  2. package/dist/agent/channel-runner.js +9 -0
  3. package/dist/agent/commands.d.ts +1 -1
  4. package/dist/agent/commands.js +9 -0
  5. package/dist/agent/job-manager.d.ts +5 -3
  6. package/dist/agent/job-manager.js +8 -5
  7. package/dist/agent/prompt/sections.js +46 -7
  8. package/dist/agent/prompt/types.d.ts +9 -0
  9. package/dist/agent/session-events.js +7 -42
  10. package/dist/agent/types.d.ts +4 -0
  11. package/dist/playbooks/agent-delegation.md +46 -21
  12. package/dist/playbooks/runtime-orientation.md +2 -2
  13. package/dist/runtime/bootstrap.js +45 -1
  14. package/dist/runtime/dingtalk.d.ts +1 -0
  15. package/dist/runtime/dingtalk.js +3 -0
  16. package/dist/runtime/store.d.ts +7 -0
  17. package/dist/runtime/subagent-commands.d.ts +15 -0
  18. package/dist/runtime/subagent-commands.js +122 -0
  19. package/dist/runtime/task-commands.js +5 -1
  20. package/dist/security/logger.js +3 -1
  21. package/dist/security/types.d.ts +17 -1
  22. package/dist/shared/host-process.d.ts +15 -0
  23. package/dist/shared/host-process.js +40 -0
  24. package/dist/shared/shell-words.d.ts +9 -0
  25. package/dist/shared/shell-words.js +52 -0
  26. package/dist/subagents/discovery.d.ts +42 -1
  27. package/dist/subagents/discovery.js +302 -69
  28. package/dist/subagents/external/claude-code.d.ts +2 -0
  29. package/dist/subagents/external/claude-code.js +152 -0
  30. package/dist/subagents/external/codex-cli.d.ts +2 -0
  31. package/dist/subagents/external/codex-cli.js +133 -0
  32. package/dist/subagents/external/exec.d.ts +2 -0
  33. package/dist/subagents/external/exec.js +38 -0
  34. package/dist/subagents/external/harness.d.ts +102 -0
  35. package/dist/subagents/external/harness.js +76 -0
  36. package/dist/subagents/external/registry.d.ts +2 -0
  37. package/dist/subagents/external/registry.js +11 -0
  38. package/dist/subagents/external/run.d.ts +39 -0
  39. package/dist/subagents/external/run.js +220 -0
  40. package/dist/subagents/runs.d.ts +216 -0
  41. package/dist/subagents/runs.js +522 -0
  42. package/dist/subagents/tool.d.ts +8 -0
  43. package/dist/subagents/tool.js +350 -124
  44. package/dist/subagents/workspace-lease.d.ts +36 -0
  45. package/dist/subagents/workspace-lease.js +48 -0
  46. package/dist/tasks/artifact-subject.js +50 -2
  47. package/dist/tasks/verification.d.ts +8 -0
  48. package/dist/tasks/verification.js +10 -2
  49. package/dist/tools/index.d.ts +1 -1
  50. package/dist/tools/index.js +10 -1
  51. package/dist/tools/registry.js +1 -0
  52. package/dist/tools/subagent-manage.d.ts +18 -0
  53. package/dist/tools/subagent-manage.js +141 -0
  54. package/dist/tools/tool-details.d.ts +1 -1
  55. package/dist/tui/app.js +2 -0
  56. package/dist/tui/commands.d.ts +1 -0
  57. package/dist/tui/commands.js +2 -0
  58. package/dist/tui/turn-controller.d.ts +1 -0
  59. package/dist/tui/turn-controller.js +1 -0
  60. package/dist/usage/ledger.d.ts +6 -0
  61. package/examples/sub-agents/README.md +59 -12
  62. package/examples/sub-agents/builder-hard.md +45 -0
  63. package/examples/sub-agents/builder.md +41 -0
  64. package/examples/sub-agents/documenter.md +53 -0
  65. package/examples/sub-agents/log-sifter.md +43 -0
  66. package/examples/sub-agents/planner.md +42 -0
  67. package/examples/sub-agents/reviewer.md +33 -39
  68. package/examples/sub-agents/scout.md +31 -0
  69. package/examples/sub-agents/verifier.md +29 -36
  70. package/examples/sub-agents/worker.md +36 -0
  71. package/package.json +1 -1
  72. package/examples/sub-agents/researcher.md +0 -41
@@ -0,0 +1,522 @@
1
+ import { mkdir, readdir, readFile, unlink } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import * as log from "../log.js";
4
+ import { writeFileAtomically } from "../shared/atomic-file.js";
5
+ import { isProcessAlive } from "../shared/host-process.js";
6
+ import { createSerialQueue } from "../shared/serial-queue.js";
7
+ import { errorMessage } from "../shared/text-utils.js";
8
+ import { isRecord } from "../shared/type-guards.js";
9
+ import { classifyExternalOutcome } from "./external/harness.js";
10
+ import { getExternalHarness } from "./external/registry.js";
11
+ import { releaseWorkspaceLease } from "./workspace-lease.js";
12
+ /**
13
+ * Longest a dispatching tool call waits for its run to settle before returning a "still running"
14
+ * placeholder instead of the result (D2). A code constant, not a settings key, per CLAUDE.md's
15
+ * rule for numeric thresholds.
16
+ */
17
+ export const SYNC_GRACE_MS = 120_000;
18
+ /** D10.2: per-channel cap on concurrently running delegation runs, mirrors job-manager's MAX_RUNNING_JOBS. */
19
+ export const MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL = 5;
20
+ /** D10.2: host-wide cap across every channel. Bounds unbounded process/worker growth only —
21
+ * not the full cross-subsystem (task/job/sidecar) admission scheme the design doc leaves open. */
22
+ export const MAX_RUNNING_SUBAGENT_RUNS_PER_HOST = 20;
23
+ /** Bytes of the reply text carried inline in the completion wake, matching job-manager's tail budget. */
24
+ const WAKE_OUTPUT_TAIL_CHARS = 2_000;
25
+ function isTerminal(status) {
26
+ return status !== "running";
27
+ }
28
+ function parseRunRecord(raw) {
29
+ const value = JSON.parse(raw);
30
+ if (!isRecord(value) ||
31
+ typeof value.runId !== "string" ||
32
+ typeof value.channelId !== "string" ||
33
+ (value.runtime !== "internal" && value.runtime !== "external") ||
34
+ typeof value.agent !== "string" ||
35
+ typeof value.workingDirectory !== "string" ||
36
+ typeof value.artifactDir !== "string" ||
37
+ typeof value.status !== "string" ||
38
+ typeof value.startedAt !== "number") {
39
+ return undefined;
40
+ }
41
+ return value;
42
+ }
43
+ function formatDuration(ms) {
44
+ const seconds = Math.round(ms / 1000);
45
+ if (seconds < 60)
46
+ return `${seconds}s`;
47
+ return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
48
+ }
49
+ /**
50
+ * Per-channel manager for delegation runs — the single settlement/usage/wake authority for both
51
+ * internal sub-agents and (once wired) external harnesses (D7). Modeled directly on
52
+ * `ChannelJobManager`; the two are not unified because a run's terminal status depends on a
53
+ * protocol verdict, not just process exit (D4), so the state machines genuinely differ.
54
+ */
55
+ export class SubAgentRunManager {
56
+ constructor(channelId, options) {
57
+ this.channelId = channelId;
58
+ this.options = options;
59
+ this.runs = new Map();
60
+ /** In-memory cancel handles for runs alive in *this* process (internal runs; external process
61
+ * kill goes through pid, not this map, once phase 2/3 lands). Never persisted: a restart loses
62
+ * the only thing that could reach an in-process worker anyway (D10.3). */
63
+ this.cancelHandles = new Map();
64
+ this.queue = createSerialQueue();
65
+ }
66
+ recordPath(runId) {
67
+ return this.options.stateDir ? join(this.options.stateDir, this.channelId, `${runId}.json`) : undefined;
68
+ }
69
+ async persist(record) {
70
+ const path = this.recordPath(record.runId);
71
+ if (!path)
72
+ return;
73
+ try {
74
+ await writeFileAtomically(path, `${JSON.stringify(record)}\n`);
75
+ }
76
+ catch (error) {
77
+ log.logWarning(`Failed to persist sub-agent run ${record.runId}`, errorMessage(error));
78
+ }
79
+ }
80
+ /**
81
+ * The full reply text always lands in `<artifactDir>/output.md` (spec 032 D4, carried into 040
82
+ * D1's settlement step). It is written here, in the one place every runtime settles, rather than
83
+ * in each caller: the completion wake points at this file, and it is what makes an inline-returned
84
+ * result self-recoverable after a crash (D2). A failed write must not block settlement — losing
85
+ * the artifact is bad, leaving the run stuck in `running` is worse.
86
+ */
87
+ async writeOutputFile(record, outputText) {
88
+ if (!outputText.trim())
89
+ return false;
90
+ try {
91
+ await writeFileAtomically(join(record.artifactDir, "output.md"), outputText);
92
+ return true;
93
+ }
94
+ catch (error) {
95
+ log.logWarning(`Failed to write output.md for sub-agent run ${record.runId}`, errorMessage(error));
96
+ return false;
97
+ }
98
+ }
99
+ async forget(record) {
100
+ this.runs.delete(record.runId);
101
+ this.cancelHandles.delete(record.runId);
102
+ const path = this.recordPath(record.runId);
103
+ if (path)
104
+ await unlink(path).catch(() => undefined);
105
+ }
106
+ get(runId) {
107
+ return this.runs.get(runId);
108
+ }
109
+ list() {
110
+ return Array.from(this.runs.values());
111
+ }
112
+ /** Task ids a still-running delegation on this channel will eventually wake. Feeds `/tasks doctor`. */
113
+ runningTaskIds() {
114
+ const ids = new Set();
115
+ for (const record of this.runs.values()) {
116
+ if (record.status === "running" && record.taskId) {
117
+ ids.add(record.taskId);
118
+ }
119
+ }
120
+ return ids;
121
+ }
122
+ runningCount() {
123
+ return Array.from(this.runs.values()).filter((record) => record.status === "running").length;
124
+ }
125
+ /** Register the run's lifecycle before any work starts, and persist it immediately (D1). */
126
+ async register(input) {
127
+ // D10.2: a per-channel and a host-wide cap, both code constants (a local response to a
128
+ // runaway model, not a global cross-subsystem admission scheme — see the design doc's
129
+ // non-goals). Checked before anything is persisted, so a rejected run costs nothing.
130
+ if (this.runningCount() >= MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL) {
131
+ throw new Error(`Too many delegation runs already running on this channel (>= ${MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL}). ` +
132
+ "Wait for one to finish, or cancel one with subagent_manage first.");
133
+ }
134
+ if (totalRunningSubAgentRuns() >= MAX_RUNNING_SUBAGENT_RUNS_PER_HOST) {
135
+ throw new Error(`Too many delegation runs already running host-wide (>= ${MAX_RUNNING_SUBAGENT_RUNS_PER_HOST}). ` +
136
+ "Wait for one to finish before dispatching another.");
137
+ }
138
+ const record = {
139
+ ...input,
140
+ status: "running",
141
+ startedAt: Date.now(),
142
+ usage: emptyUsage(),
143
+ usageKnown: true,
144
+ costKnown: true,
145
+ };
146
+ this.runs.set(record.runId, record);
147
+ await this.persist(record);
148
+ return record;
149
+ }
150
+ /**
151
+ * Persist the pid once a spawn actually succeeds — the second half of D1's launch ordering.
152
+ * `register()` already durably recorded the intent (argv, working directory, artifact dir)
153
+ * with pid unknown; a crash between that persist and this one leaves an intent-only record
154
+ * that restore treats as `lost` rather than guessing (D1/D10.3).
155
+ */
156
+ async setLaunched(runId, info) {
157
+ const record = this.runs.get(runId);
158
+ if (!record)
159
+ return;
160
+ record.pid = info.pid;
161
+ record.fingerprint = info.fingerprint;
162
+ record.argv = info.argv;
163
+ // claude-code pre-assigns its session id before running (D4); persisting it here, not just
164
+ // at settle(), means a run that crashes before any output is still resumable.
165
+ if (info.sessionId)
166
+ record.sessionId = info.sessionId;
167
+ await this.persist(record);
168
+ }
169
+ /** Let a caller (subagent tool) register a way to abort this run's in-process worker. */
170
+ registerCancelHandle(runId, cancel) {
171
+ this.cancelHandles.set(runId, cancel);
172
+ }
173
+ clearCancelHandle(runId) {
174
+ this.cancelHandles.delete(runId);
175
+ }
176
+ /**
177
+ * Settle a run exactly once (D1/D7 order: settle → record usage/archive → enqueue wake).
178
+ * `announce: false` is the inline-return path (D2): the model already has the result in this
179
+ * same tool call, so `wakeEnqueued` is set without ever dispatching — waking the channel for a
180
+ * result it is already holding would burn a turn to say nothing.
181
+ */
182
+ async settle(runId, input, options) {
183
+ await this.queue.run(runId, async () => {
184
+ const record = this.runs.get(runId);
185
+ if (!record || record.settledAt)
186
+ return; // Idempotent: already settled, never replay.
187
+ record.status = input.status;
188
+ record.failureReason = input.failureReason;
189
+ record.usage = input.usage;
190
+ record.usageKnown = input.usageKnown;
191
+ record.costKnown = input.costKnown;
192
+ record.turns = input.turns;
193
+ record.toolCalls = input.toolCalls;
194
+ record.durationMs = input.durationMs;
195
+ record.verificationVerdict = input.verificationVerdict;
196
+ record.verificationStrength = input.verificationStrength;
197
+ if (input.sessionId)
198
+ record.sessionId = input.sessionId;
199
+ record.finishedAt = Date.now();
200
+ record.settledAt = record.finishedAt;
201
+ const outputSaved = await this.writeOutputFile(record, input.outputText);
202
+ releaseWorkspaceLease(record.leaseKey);
203
+ await this.persist(record);
204
+ this.cancelHandles.delete(runId);
205
+ if (!record.usageRecorded) {
206
+ record.usageRecorded = true;
207
+ this.options.ledger?.record({
208
+ channelId: record.channelId,
209
+ kind: "subagent",
210
+ model: record.model ?? "unknown",
211
+ label: record.label,
212
+ runId: record.runId,
213
+ usage: {
214
+ input: input.usage.input,
215
+ output: input.usage.output,
216
+ cacheRead: input.usage.cacheRead,
217
+ cacheWrite: input.usage.cacheWrite,
218
+ total: input.usage.total,
219
+ },
220
+ cost: { ...input.usage.cost },
221
+ usageKnown: input.usageKnown,
222
+ costKnown: input.costKnown,
223
+ });
224
+ await this.options.store?.logSubAgentRun(record.channelId, {
225
+ date: new Date().toISOString(),
226
+ toolCallId: record.runId,
227
+ label: record.label,
228
+ agent: record.agent,
229
+ source: record.source,
230
+ model: record.model ?? "unknown",
231
+ tools: record.tools,
232
+ turns: input.turns,
233
+ toolCalls: input.toolCalls,
234
+ durationMs: input.durationMs,
235
+ failed: input.status !== "completed",
236
+ failureReason: input.failureReason,
237
+ output: input.outputText.length > 16_000 ? input.outputText.slice(0, 16_000) : input.outputText,
238
+ outputTruncated: input.outputText.length > 16_000,
239
+ usage: { ...input.usage, cost: { ...input.usage.cost } },
240
+ runId: record.runId,
241
+ runtime: record.runtime,
242
+ harness: record.harness,
243
+ status: record.status,
244
+ taskId: record.taskId,
245
+ artifactDir: record.artifactDir,
246
+ });
247
+ await this.persist(record);
248
+ }
249
+ if (record.wakeEnqueued)
250
+ return;
251
+ if (!options.announce) {
252
+ record.wakeEnqueued = true;
253
+ await this.persist(record);
254
+ return;
255
+ }
256
+ await this.announce(record, input.outputText, outputSaved);
257
+ });
258
+ }
259
+ /**
260
+ * Dispatch the completion wake. Durable-dispatch persists its own pending record before this
261
+ * call can be interrupted (`DurableDispatchService.dispatch`), and `dispatch()` is idempotent on
262
+ * `dispatchId`, so calling it again after a crash between here and marking `wakeEnqueued` is
263
+ * harmless — this is the same fix as job-manager's `announce()` reordering (D7).
264
+ */
265
+ async announce(record, outputText, outputSaved) {
266
+ if (!this.options.dispatch)
267
+ return;
268
+ const tail = outputText.slice(-WAKE_OUTPUT_TAIL_CHARS).trim();
269
+ const harnessLabel = record.harness ? `${record.runtime}/${record.harness}` : record.runtime;
270
+ const belongsTo = record.taskId ? ` It belongs to task ${record.taskId}.` : "";
271
+ const verdictLine = record.verificationVerdict !== undefined
272
+ ? `\nVerdict: ${record.verificationVerdict === "pass" ? "PASS" : "FAIL"}${record.verificationStrength === "advisory" ? " (advisory)" : ""}`
273
+ : "";
274
+ const event = {
275
+ type: record.channelId.startsWith("group_") ? "group" : "dm",
276
+ channelId: record.channelId,
277
+ user: "SUBAGENT",
278
+ userName: "SUBAGENT",
279
+ text: `[SUBAGENT:${record.runId}] Delegation "${record.label}" -> ${record.agent} (${harnessLabel}) finished: ` +
280
+ `${record.status} (${formatDuration(record.durationMs ?? 0)}).${belongsTo}${verdictLine}\n` +
281
+ `Result:\n${tail || "(no output)"}\n` +
282
+ // A run that produced no text has no output.md; pointing at it would send the model
283
+ // after a file that does not exist. The artifact dir still holds the run's evidence
284
+ // (an external run's stderr.log in particular), so that is what it gets instead.
285
+ (outputSaved
286
+ ? `Full output: ${join(record.artifactDir, "output.md")}\n`
287
+ : `No text output was produced. Run artifacts: ${record.artifactDir}\n`) +
288
+ "Continue whatever was waiting on this delegation. If it needs no follow-up, respond with exactly [SILENT].",
289
+ ts: String(Date.now()),
290
+ conversationId: "",
291
+ conversationType: record.channelId.startsWith("group_") ? "2" : "1",
292
+ dispatchId: `subagent:${record.channelId}:${record.runId}:done`,
293
+ };
294
+ try {
295
+ await this.options.dispatch(event);
296
+ }
297
+ catch (error) {
298
+ log.logWarning(`Failed to dispatch completion wake for run ${record.runId}`, errorMessage(error));
299
+ return;
300
+ }
301
+ record.wakeEnqueued = true;
302
+ await this.persist(record);
303
+ }
304
+ /** Explicit cancel (`subagent_manage op=cancel`, spec 040 D6). Does not wake — it is the model's own decision. */
305
+ async cancel(runId) {
306
+ return this.queue.run(runId, async () => {
307
+ const record = this.runs.get(runId);
308
+ if (!record)
309
+ return "not_found";
310
+ if (record.status !== "running")
311
+ return record.status;
312
+ const cancelHandle = this.cancelHandles.get(runId);
313
+ this.cancelHandles.delete(runId);
314
+ if (cancelHandle) {
315
+ cancelHandle();
316
+ }
317
+ else {
318
+ // No in-process handle (external runtime, not yet wired, or a run this process did
319
+ // not launch): mark it lost rather than pretend a cancel we could not perform happened.
320
+ record.status = "lost";
321
+ record.finishedAt = Date.now();
322
+ record.settledAt = record.finishedAt;
323
+ record.wakeEnqueued = true;
324
+ releaseWorkspaceLease(record.leaseKey);
325
+ await this.persist(record);
326
+ return record.status;
327
+ }
328
+ return "running"; // The registered cancel handle drives the run to its own settle() call.
329
+ });
330
+ }
331
+ /**
332
+ * Rebuild in-memory state after a restart. Internal runs cannot survive a restart by
333
+ * construction (D10.3): the worker lived in the process that just disappeared, so any record
334
+ * still `running` is settled as `lost` and the channel is woken to say so. External runs are
335
+ * left alone here — the harness-specific probe (spec 040 phase 2/3) reconciles those.
336
+ */
337
+ async restore() {
338
+ const stateDir = this.options.stateDir;
339
+ if (!stateDir)
340
+ return 0;
341
+ const dir = join(stateDir, this.channelId);
342
+ let filenames;
343
+ try {
344
+ filenames = (await readdir(dir)).filter((name) => name.endsWith(".json"));
345
+ }
346
+ catch {
347
+ return 0;
348
+ }
349
+ let restored = 0;
350
+ for (const filename of filenames) {
351
+ const path = join(dir, filename);
352
+ let record;
353
+ try {
354
+ record = parseRunRecord(await readFile(path, "utf-8"));
355
+ }
356
+ catch {
357
+ record = undefined;
358
+ }
359
+ if (!record) {
360
+ log.logWarning(`Discarding unreadable sub-agent run record: ${filename}`);
361
+ await unlink(path).catch(() => undefined);
362
+ continue;
363
+ }
364
+ this.runs.set(record.runId, record);
365
+ restored++;
366
+ if (record.runtime === "internal" && record.status === "running") {
367
+ await this.settle(record.runId, {
368
+ status: "lost",
369
+ failureReason: "The daemon restarted while this delegation was running; its result is unknown.",
370
+ usage: record.usage,
371
+ usageKnown: record.usageKnown,
372
+ costKnown: record.costKnown,
373
+ turns: record.turns ?? 0,
374
+ toolCalls: record.toolCalls ?? 0,
375
+ durationMs: Date.now() - record.startedAt,
376
+ outputText: "",
377
+ }, { announce: true }).catch((error) => {
378
+ log.logWarning(`Failed to reconcile sub-agent run ${record?.runId}`, errorMessage(error));
379
+ });
380
+ }
381
+ if (record.runtime === "external" && record.status === "running") {
382
+ await this.reconcileExternalRun(record).catch((error) => {
383
+ log.logWarning(`Failed to reconcile external run ${record?.runId}`, errorMessage(error));
384
+ });
385
+ }
386
+ if (isTerminal(record.status) && record.settledAt) {
387
+ await this.collectGarbageIfExpired(record);
388
+ }
389
+ }
390
+ return restored;
391
+ }
392
+ /**
393
+ * Restart reconciliation for an external run still marked `running` (D10.3). Unlike internal
394
+ * runs, a `detached` external process outlives the daemon, so the first move is a liveness
395
+ * probe, not an automatic `lost`:
396
+ *
397
+ * - no `pid` at all: the intent was persisted but spawn was never confirmed — cannot prove it
398
+ * ever started, so it is judged `lost` the same as an internal run (D1).
399
+ * - `pid` alive: genuinely still running. Left alone; it will settle itself when it exits.
400
+ * - `pid` gone: the process finished or died while the daemon was down. `events.jsonl` is the
401
+ * only remaining evidence, so it drives the terminal judgement via the same D4 status table
402
+ * the live post-exit path uses.
403
+ */
404
+ async reconcileExternalRun(record) {
405
+ if (!record.pid) {
406
+ await this.settle(record.runId, {
407
+ status: "lost",
408
+ failureReason: "No pid was ever recorded for this run; it cannot be proven to have started.",
409
+ usage: record.usage,
410
+ usageKnown: record.usageKnown,
411
+ costKnown: record.costKnown,
412
+ turns: record.turns ?? 0,
413
+ toolCalls: record.toolCalls ?? 0,
414
+ durationMs: Date.now() - record.startedAt,
415
+ outputText: "",
416
+ }, { announce: true });
417
+ return;
418
+ }
419
+ if (isProcessAlive(record.pid)) {
420
+ return; // Still genuinely running; nothing to reconcile yet.
421
+ }
422
+ const harness = record.harness ? getExternalHarness(record.harness) : undefined;
423
+ const eventsText = await readFile(join(record.artifactDir, "events.jsonl"), "utf-8").catch(() => "");
424
+ const stderrTail = (await readFile(join(record.artifactDir, "stderr.log"), "utf-8").catch(() => "")).slice(-2_000);
425
+ const outcome = harness?.parseOutcome({ eventsText, exitCode: undefined, stderrTail }) ?? {
426
+ finalText: "",
427
+ terminalSeen: false,
428
+ protocolStatus: "unparsable",
429
+ usageKnown: false,
430
+ costKnown: false,
431
+ outputTruncated: false,
432
+ stderrTail,
433
+ };
434
+ const classification = harness
435
+ ? classifyExternalOutcome(harness.id, outcome)
436
+ : { status: "failed", failureReason: `Unknown harness "${record.harness}"; cannot judge this run.` };
437
+ await this.settle(record.runId, {
438
+ status: classification.status,
439
+ failureReason: classification.failureReason,
440
+ usage: record.usage,
441
+ usageKnown: outcome.usageKnown,
442
+ costKnown: outcome.costKnown,
443
+ turns: record.turns ?? 0,
444
+ toolCalls: record.toolCalls ?? 0,
445
+ durationMs: Date.now() - record.startedAt,
446
+ outputText: outcome.finalText,
447
+ sessionId: outcome.sessionId,
448
+ }, { announce: true });
449
+ }
450
+ /** Drop a settled record once its retention window has passed, mirroring job-manager's GC. */
451
+ async collectGarbageIfExpired(record, now = Date.now()) {
452
+ const RETENTION_MS = 24 * 60 * 60_000;
453
+ if (record.settledAt && now - record.settledAt >= RETENTION_MS) {
454
+ await this.forget(record);
455
+ }
456
+ }
457
+ }
458
+ function emptyUsage() {
459
+ return {
460
+ input: 0,
461
+ output: 0,
462
+ cacheRead: 0,
463
+ cacheWrite: 0,
464
+ total: 0,
465
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
466
+ };
467
+ }
468
+ const managers = new Map();
469
+ /** Host-wide running count for the D10.2 admission check, summed across every known channel. */
470
+ function totalRunningSubAgentRuns() {
471
+ let total = 0;
472
+ for (const manager of managers.values()) {
473
+ total += manager.runningCount();
474
+ }
475
+ return total;
476
+ }
477
+ let runtimeConfig = {};
478
+ /** Give runs their persistence root, wake delivery, ledger, and archive. Called once from bootstrap. */
479
+ export function configureSubAgentRuntime(config) {
480
+ runtimeConfig = config;
481
+ }
482
+ export function getSubAgentRunManager(channelId) {
483
+ let manager = managers.get(channelId);
484
+ if (!manager) {
485
+ manager = new SubAgentRunManager(channelId, runtimeConfig);
486
+ managers.set(channelId, manager);
487
+ }
488
+ return manager;
489
+ }
490
+ /** Read-only view for `/tasks doctor`, mirroring `channelJobTaskIds`. */
491
+ export function channelDelegationTaskIds(channelId) {
492
+ return managers.get(channelId)?.runningTaskIds() ?? new Set();
493
+ }
494
+ /**
495
+ * Re-adopt every channel's persisted runs at startup, settling any internal run still marked
496
+ * `running` as `lost` (D10.3). Channels are discovered from the state directory itself, exactly
497
+ * like `restoreChannelJobs`.
498
+ */
499
+ export async function restoreAllSubAgentRuns() {
500
+ const stateDir = runtimeConfig.stateDir;
501
+ if (!stateDir)
502
+ return 0;
503
+ let channelIds;
504
+ try {
505
+ await mkdir(stateDir, { recursive: true });
506
+ channelIds = (await readdir(stateDir, { withFileTypes: true }))
507
+ .filter((entry) => entry.isDirectory())
508
+ .map((entry) => entry.name);
509
+ }
510
+ catch (error) {
511
+ log.logWarning("Failed to scan persisted sub-agent runs", errorMessage(error));
512
+ return 0;
513
+ }
514
+ let restored = 0;
515
+ for (const channelId of channelIds) {
516
+ restored += await getSubAgentRunManager(channelId).restore();
517
+ }
518
+ if (restored > 0) {
519
+ log.logInfo(`Restored ${restored} sub-agent run record(s)`);
520
+ }
521
+ return restored;
522
+ }
@@ -47,6 +47,12 @@ export interface SubAgentToolDetails {
47
47
  artifactPath?: string;
48
48
  /** True when the reply text was truncated against MAX_SUBAGENT_RESULT_UNITS; the full text is still on disk. */
49
49
  resultTruncated: boolean;
50
+ /**
51
+ * True only for the "still running" placeholder returned once the sync grace window elapses
52
+ * (spec 040, D2). The run keeps executing; its eventual result arrives as a completion wake,
53
+ * not as another tool result.
54
+ */
55
+ dispatched?: boolean;
50
56
  }
51
57
  export interface SubAgentToolOptions {
52
58
  executor: Executor;
@@ -76,6 +82,8 @@ export interface SubAgentToolOptions {
76
82
  }) => SubAgentWorker;
77
83
  /** Test-only override for the D6 convergence-turn wall clock; defaults to CONVERGENCE_WALL_CLOCK_MS. */
78
84
  convergenceWallClockMs?: number;
85
+ /** Test-only override for the D2 sync grace window; defaults to SYNC_GRACE_MS. */
86
+ syncGraceMs?: number;
79
87
  }
80
88
  interface SubAgentWorker {
81
89
  state: {