@oyasmi/pipiclaw 0.8.11 → 0.9.0-beta.2

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