@oyasmi/pipiclaw 0.9.0-beta.5 → 0.9.0-beta.7

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 (76) hide show
  1. package/README.md +146 -177
  2. package/dist/agent/channel-runner.d.ts +8 -0
  3. package/dist/agent/channel-runner.js +154 -132
  4. package/dist/agent/commands.d.ts +6 -0
  5. package/dist/agent/job-manager.js +6 -10
  6. package/dist/agent/progress-formatter.js +3 -3
  7. package/dist/index.d.ts +2 -1
  8. package/dist/index.js +2 -1
  9. package/dist/main.js +2 -1
  10. package/dist/memory/extraction.js +0 -1
  11. package/dist/memory/maintenance-gates.d.ts +1 -1
  12. package/dist/memory/maintenance-jobs.js +2 -3
  13. package/dist/memory/metadata.d.ts +0 -15
  14. package/dist/memory/metadata.js +0 -7
  15. package/dist/memory/probation.d.ts +1 -5
  16. package/dist/memory/probation.js +2 -6
  17. package/dist/models/auth-cli.d.ts +1 -1
  18. package/dist/models/auth-cli.js +3 -2
  19. package/dist/paths.d.ts +0 -6
  20. package/dist/paths.js +0 -6
  21. package/dist/playbooks/agent-delegation.md +9 -8
  22. package/dist/playbooks/background-jobs.md +1 -1
  23. package/dist/playbooks/catalog.d.ts +2 -2
  24. package/dist/playbooks/catalog.js +20 -9
  25. package/dist/playbooks/event-scheduling.md +1 -1
  26. package/dist/playbooks/memory-and-learning.md +1 -1
  27. package/dist/playbooks/outbound-media.md +5 -5
  28. package/dist/playbooks/runtime-orientation.md +1 -1
  29. package/dist/playbooks/task-driving.md +1 -1
  30. package/dist/playbooks/task-planning.md +1 -1
  31. package/dist/runtime/app-home.d.ts +32 -0
  32. package/dist/runtime/app-home.js +319 -0
  33. package/dist/runtime/bootstrap.d.ts +3 -69
  34. package/dist/runtime/bootstrap.js +113 -511
  35. package/dist/runtime/delivery.js +1 -1
  36. package/dist/runtime/dingtalk.d.ts +7 -6
  37. package/dist/runtime/dingtalk.js +5 -13
  38. package/dist/runtime/task-wake.d.ts +54 -0
  39. package/dist/runtime/task-wake.js +99 -0
  40. package/dist/shared/host-process.d.ts +5 -5
  41. package/dist/shared/host-process.js +19 -0
  42. package/dist/shared/wake-claim.d.ts +23 -0
  43. package/dist/shared/wake-claim.js +26 -0
  44. package/dist/subagents/discovery.d.ts +9 -1
  45. package/dist/subagents/discovery.js +37 -9
  46. package/dist/subagents/external/claude-code.js +4 -5
  47. package/dist/subagents/external/codex-cli.js +1 -7
  48. package/dist/subagents/external/exec.js +7 -2
  49. package/dist/subagents/external/harness.d.ts +0 -3
  50. package/dist/subagents/external/harness.js +18 -3
  51. package/dist/subagents/external/run.d.ts +5 -0
  52. package/dist/subagents/external/run.js +70 -31
  53. package/dist/subagents/runs.d.ts +40 -9
  54. package/dist/subagents/runs.js +194 -31
  55. package/dist/subagents/tool.d.ts +3 -1
  56. package/dist/subagents/tool.js +33 -14
  57. package/dist/tools/memory-manage.js +0 -1
  58. package/dist/tools/subagent-manage.js +18 -1
  59. package/dist/tui/app.d.ts +1 -1
  60. package/dist/tui/app.js +3 -2
  61. package/dist/tui/cli.d.ts +1 -1
  62. package/dist/tui/cli.js +1 -1
  63. package/dist/tui/terminal-media-sender.d.ts +1 -1
  64. package/examples/sub-agents/README.md +25 -16
  65. package/examples/sub-agents/builder-hard.md +9 -8
  66. package/examples/sub-agents/builder.md +12 -11
  67. package/examples/sub-agents/documenter.md +11 -14
  68. package/examples/sub-agents/explorer.md +16 -13
  69. package/examples/sub-agents/git-committer.md +18 -16
  70. package/examples/sub-agents/log-sifter.md +19 -16
  71. package/examples/sub-agents/planner.md +17 -17
  72. package/examples/sub-agents/reviewer.md +13 -23
  73. package/examples/sub-agents/scout.md +5 -6
  74. package/examples/sub-agents/verifier.md +8 -14
  75. package/examples/sub-agents/worker.md +7 -8
  76. package/package.json +1 -1
@@ -2,21 +2,23 @@ import { mkdir, readdir, readFile, unlink } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import * as log from "../log.js";
4
4
  import { writeFileAtomically } from "../shared/atomic-file.js";
5
- import { isProcessAlive } from "../shared/host-process.js";
5
+ import { isProcessAlive, killProcessGroup, readProcessStartTime } from "../shared/host-process.js";
6
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
6
7
  import { createSerialQueue } from "../shared/serial-queue.js";
7
8
  import { errorMessage } from "../shared/text-utils.js";
8
9
  import { isRecord } from "../shared/type-guards.js";
10
+ import { beginWakeClaim, finishWakeClaim } from "../shared/wake-claim.js";
9
11
  import { classifyExternalOutcome } from "./external/harness.js";
10
12
  import { getExternalHarness } from "./external/registry.js";
11
- import { releaseWorkspaceLease } from "./workspace-lease.js";
13
+ import { acquireWorkspaceLease, formatWorkspaceLeaseConflict, releaseWorkspaceLease } from "./workspace-lease.js";
12
14
  /**
13
15
  * Longest a dispatching tool call waits for its run to settle before returning a "still running"
14
16
  * placeholder instead of the result (D2). A code constant, not a settings key, per CLAUDE.md's
15
17
  * rule for numeric thresholds.
16
18
  */
17
19
  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: per-channel cap on concurrently running delegation runs. */
21
+ export const MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL = 6;
20
22
  /** D10.2: host-wide cap across every channel. Bounds unbounded process/worker growth only —
21
23
  * not the full cross-subsystem (task/job/sidecar) admission scheme the design doc leaves open. */
22
24
  export const MAX_RUNNING_SUBAGENT_RUNS_PER_HOST = 20;
@@ -190,15 +192,15 @@ export class SubAgentRunManager {
190
192
  // runaway model, not a global cross-subsystem admission scheme — see the design doc's
191
193
  // non-goals). Checked before anything is persisted, so a rejected run costs nothing.
192
194
  if (this.runningCount() >= MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL) {
193
- throw new Error(`Too many delegation runs already running on this channel (>= ${MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL}). ` +
195
+ throw new RecoverableToolError(`Too many delegation runs already running on this channel (>= ${MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL}). ` +
194
196
  "Wait for one to finish, or cancel one with subagent_manage first.");
195
197
  }
196
198
  if (totalRunningSubAgentRuns() >= MAX_RUNNING_SUBAGENT_RUNS_PER_HOST) {
197
- throw new Error(`Too many delegation runs already running host-wide (>= ${MAX_RUNNING_SUBAGENT_RUNS_PER_HOST}). ` +
199
+ throw new RecoverableToolError(`Too many delegation runs already running host-wide (>= ${MAX_RUNNING_SUBAGENT_RUNS_PER_HOST}). ` +
198
200
  "Wait for one to finish before dispatching another.");
199
201
  }
200
202
  if (this.runs.has(input.runId)) {
201
- throw new Error(`Run id "${input.runId}" is already registered on this channel.`);
203
+ throw new RecoverableToolError(`Run id "${input.runId}" is already registered on this channel.`);
202
204
  }
203
205
  const record = {
204
206
  ...input,
@@ -249,8 +251,9 @@ export class SubAgentRunManager {
249
251
  if (!record)
250
252
  return;
251
253
  record.pid = info.pid;
252
- record.fingerprint = info.fingerprint;
254
+ record.pidStartedAt = info.pidStartedAt;
253
255
  record.argv = info.argv;
256
+ record.deadlineAt = info.deadlineAt;
254
257
  // claude-code pre-assigns its session id before running (D4); persisting it here, not just
255
258
  // at settle(), means a run that crashes before any output is still resumable.
256
259
  if (info.sessionId)
@@ -262,16 +265,13 @@ export class SubAgentRunManager {
262
265
  async beginWakeConsumption(runId, taskId, dispatchId) {
263
266
  return this.queue.run(runId, async () => {
264
267
  const record = this.runs.get(runId);
265
- const expected = `subagent:${record?.channelId}:${runId}:done`;
266
- if (!record?.settledAt ||
267
- record.taskId !== taskId ||
268
- dispatchId !== expected ||
269
- record.wakeConsumedAt ||
270
- (record.wakeClaimDispatchId && record.wakeClaimDispatchId !== dispatchId)) {
268
+ if (!record)
271
269
  return false;
272
- }
270
+ const expected = `subagent:${record.channelId}:${runId}:done`;
271
+ const eligible = record.settledAt !== undefined && record.taskId === taskId && dispatchId === expected;
273
272
  const previousClaim = record.wakeClaimDispatchId;
274
- record.wakeClaimDispatchId = dispatchId;
273
+ if (!beginWakeClaim(record, eligible, dispatchId))
274
+ return false;
275
275
  try {
276
276
  await this.persist(record, true);
277
277
  }
@@ -285,9 +285,8 @@ export class SubAgentRunManager {
285
285
  async finishWakeConsumption(runId, dispatchId) {
286
286
  await this.queue.run(runId, async () => {
287
287
  const record = this.runs.get(runId);
288
- if (!record || record.wakeClaimDispatchId !== dispatchId || record.wakeConsumedAt)
288
+ if (!record || !finishWakeClaim(record, dispatchId))
289
289
  return;
290
- record.wakeConsumedAt = Date.now();
291
290
  try {
292
291
  await this.persist(record, true);
293
292
  }
@@ -301,6 +300,20 @@ export class SubAgentRunManager {
301
300
  registerCancelHandle(runId, cancel) {
302
301
  this.cancelHandles.set(runId, cancel);
303
302
  }
303
+ /** Record why a still-running external run is about to be killed, before the signal is sent
304
+ * (P1-1) — see the `terminationReason` field doc. A no-op once the run is no longer running.
305
+ * Called by both the live in-process watcher (`external/run.ts`) and `sweep()` below. */
306
+ async markTerminationReason(runId, reason) {
307
+ await this.queue.run(runId, async () => {
308
+ const record = this.runs.get(runId);
309
+ if (!record || record.status !== "running")
310
+ return;
311
+ record.terminationReason = reason;
312
+ await this.persist(record).catch((error) => {
313
+ log.logWarning(`Failed to persist termination reason for run ${runId}`, errorMessage(error));
314
+ });
315
+ });
316
+ }
304
317
  clearCancelHandle(runId) {
305
318
  this.cancelHandles.delete(runId);
306
319
  }
@@ -315,6 +328,10 @@ export class SubAgentRunManager {
315
328
  const record = this.runs.get(runId);
316
329
  if (!record || record.settledAt)
317
330
  return; // Idempotent: already settled, never replay.
331
+ // The terminal fields are persisted, required, before any side effect runs (P0-2): a
332
+ // failed persist here rolls the record back to `running` so a restart replays settlement
333
+ // from scratch instead of applying side effects the disk never recorded.
334
+ const snapshot = { ...record };
318
335
  record.status = input.status;
319
336
  record.failureReason = input.failureReason;
320
337
  record.usage = input.usage;
@@ -329,11 +346,19 @@ export class SubAgentRunManager {
329
346
  record.sessionId = input.sessionId;
330
347
  record.finishedAt = Date.now();
331
348
  record.settledAt = record.finishedAt;
349
+ try {
350
+ await this.persist(record, true);
351
+ }
352
+ catch (error) {
353
+ Object.assign(record, snapshot);
354
+ throw error;
355
+ }
332
356
  const outputSaved = await this.writeOutputFile(record, input.outputText);
333
357
  releaseWorkspaceLease(record.leaseKey);
334
- await this.persist(record);
358
+ record.leaseKey = undefined; // Terminal records never display as "lease held" (P1-4).
335
359
  this.cancelHandles.delete(runId);
336
360
  this.externalLaunches.delete(runId);
361
+ await this.persist(record);
337
362
  if (!record.usageRecorded) {
338
363
  record.usageRecorded = true;
339
364
  this.options.ledger?.record({
@@ -353,7 +378,10 @@ export class SubAgentRunManager {
353
378
  usageKnown: input.usageKnown,
354
379
  costKnown: input.costKnown,
355
380
  });
356
- await this.options.store?.logSubAgentRun(record.channelId, {
381
+ // Archive is an observability write, not a settlement fact — a full queue must not
382
+ // swallow the completion wake below (P0-2).
383
+ await this.options.store
384
+ ?.logSubAgentRun(record.channelId, {
357
385
  date: new Date().toISOString(),
358
386
  toolCallId: record.runId,
359
387
  label: record.label,
@@ -375,6 +403,9 @@ export class SubAgentRunManager {
375
403
  status: record.status,
376
404
  taskId: record.taskId,
377
405
  artifactDir: record.artifactDir,
406
+ })
407
+ .catch((error) => {
408
+ log.logWarning(`Failed to archive sub-agent run ${record.runId}`, errorMessage(error));
378
409
  });
379
410
  await this.persist(record);
380
411
  }
@@ -454,6 +485,17 @@ export class SubAgentRunManager {
454
485
  const cancelHandle = this.cancelHandles.get(runId);
455
486
  this.cancelHandles.delete(runId);
456
487
  if (cancelHandle) {
488
+ // External: mark the reason before the handle kills the process, so whichever code
489
+ // path settles this run (the live watcher below, or the sweeper if that watcher's
490
+ // process disappears mid-kill) reports "cancelled" instead of guessing from
491
+ // whatever the process happened to print before it died (P1-1). This also covers
492
+ // the pre-spawn placeholder handle `claimExternalLaunch` installs: a cancel that
493
+ // lands in that narrow window durably marks the intent even though the placeholder
494
+ // itself does nothing else.
495
+ if (record.runtime === "external") {
496
+ record.terminationReason = "cancelled";
497
+ await this.persist(record).catch(() => undefined);
498
+ }
457
499
  cancelHandle();
458
500
  }
459
501
  else if (record.runtime === "external" && this.externalLaunches.has(runId)) {
@@ -461,18 +503,27 @@ export class SubAgentRunManager {
461
503
  // and refuse to spawn instead of starting an uncancellable child.
462
504
  this.externalLaunches.get(runId).cancelRequested = true;
463
505
  }
506
+ else if (record.runtime === "external" && record.pid) {
507
+ // Adopted from a previous daemon (spec 040, D10.3): no live in-process watcher, but
508
+ // the run is genuinely still running and the sweeper is observing it. Kill it now
509
+ // rather than relabeling a live process "lost" without touching it.
510
+ record.terminationReason = "cancelled";
511
+ await this.persist(record).catch(() => undefined);
512
+ await killProcessGroup(record.pid).catch(() => undefined);
513
+ }
464
514
  else {
465
- // No in-process handle (external runtime, not yet wired, or a run this process did
466
- // not launch): mark it lost rather than pretend a cancel we could not perform happened.
515
+ // Truly unreachable (e.g. an internal run this process did not launch): mark it lost
516
+ // rather than pretend a cancel we could not perform happened.
467
517
  record.status = "lost";
468
518
  record.finishedAt = Date.now();
469
519
  record.settledAt = record.finishedAt;
470
520
  record.wakeEnqueued = true;
471
521
  releaseWorkspaceLease(record.leaseKey);
522
+ record.leaseKey = undefined;
472
523
  await this.persist(record);
473
524
  return record.status;
474
525
  }
475
- return "running"; // The registered cancel handle drives the run to its own settle() call.
526
+ return "running"; // The handle, or the sweeper once the process exits, drives the settle() call.
476
527
  });
477
528
  }
478
529
  /**
@@ -526,27 +577,64 @@ export class SubAgentRunManager {
526
577
  });
527
578
  }
528
579
  if (record.runtime === "external" && record.status === "running") {
580
+ // A write run adopted mid-flight must keep excluding other writers the same way it
581
+ // did before the restart (D10.1); the lease itself is a process-local Map, so a
582
+ // fresh process starts with none held until this rebuilds it (P0-1).
583
+ if (record.leaseKey) {
584
+ const rebuilt = acquireWorkspaceLease({
585
+ runId: record.runId,
586
+ channelId: record.channelId,
587
+ workingDirectory: record.workingDirectory,
588
+ });
589
+ if (!rebuilt.ok) {
590
+ log.logWarning(`Could not rebuild workspace lease for adopted run ${record.runId}`, formatWorkspaceLeaseConflict(rebuilt.heldBy));
591
+ }
592
+ }
529
593
  await this.reconcileExternalRun(record).catch((error) => {
530
594
  log.logWarning(`Failed to reconcile external run ${record?.runId}`, errorMessage(error));
531
595
  });
532
596
  }
533
597
  if (isTerminal(record.status) && record.settledAt) {
598
+ // A settled-but-unwoken record means the wake was lost between settlement and
599
+ // dispatch (e.g. the archive-queue failure this restart may itself be recovering
600
+ // from, P0-2) — durable dispatch is idempotent on dispatchId, so re-announcing is
601
+ // harmless even if the original wake actually made it out.
602
+ if (!record.wakeEnqueued) {
603
+ const outputText = await readFile(join(record.artifactDir, "output.md"), "utf-8").catch(() => "");
604
+ await this.announce(record, outputText, Boolean(outputText.trim())).catch((error) => {
605
+ log.logWarning(`Failed to re-announce sub-agent run ${record?.runId}`, errorMessage(error));
606
+ });
607
+ }
534
608
  await this.collectGarbageIfExpired(record);
535
609
  }
536
610
  }
537
611
  return restored;
538
612
  }
613
+ /** Whether `record.pid` is still the same process that was launched, when that can be checked
614
+ * at all (D10.3). A missing `pidStartedAt` (an older record, or a `ps` that failed once at
615
+ * launch) means there is nothing to compare against — trust `isProcessAlive` alone rather
616
+ * than manufacture a false negative. */
617
+ async isSameProcess(record) {
618
+ if (!record.pid)
619
+ return false;
620
+ if (!record.pidStartedAt)
621
+ return true;
622
+ const current = await readProcessStartTime(record.pid);
623
+ return current === record.pidStartedAt;
624
+ }
539
625
  /**
540
- * Restart reconciliation for an external run still marked `running` (D10.3). Unlike internal
626
+ * Restart reconciliation for an external run still marked `running` (D10.3), and the terminal
627
+ * judgement `sweep()` uses once an adopted run's process is confirmed gone. Unlike internal
541
628
  * runs, a `detached` external process outlives the daemon, so the first move is a liveness
542
629
  * probe, not an automatic `lost`:
543
630
  *
544
631
  * - no `pid` at all: the intent was persisted but spawn was never confirmed — cannot prove it
545
632
  * ever started, so it is judged `lost` the same as an internal run (D1).
546
- * - `pid` alive: genuinely still running. Left alone; it will settle itself when it exits.
547
- * - `pid` gone: the process finished or died while the daemon was down. `events.jsonl` is the
548
- * only remaining evidence, so it drives the terminal judgement via the same D4 status table
549
- * the live post-exit path uses.
633
+ * - `pid` alive under the same identity: genuinely still running. Left alone.
634
+ * - `pid` gone (or reused by an unrelated process): the process finished, died, or was killed
635
+ * while the daemon was down. A `terminationReason` set before the kill (P1-1) takes priority
636
+ * over guessing from output; absent that, `events.jsonl` drives the same D4 status table the
637
+ * live post-exit path uses.
550
638
  */
551
639
  async reconcileExternalRun(record) {
552
640
  if (!record.pid) {
@@ -563,9 +651,39 @@ export class SubAgentRunManager {
563
651
  }, { announce: true });
564
652
  return;
565
653
  }
566
- if (isProcessAlive(record.pid)) {
654
+ if (isProcessAlive(record.pid) && (await this.isSameProcess(record))) {
567
655
  return; // Still genuinely running; nothing to reconcile yet.
568
656
  }
657
+ const durationMs = Date.now() - record.startedAt;
658
+ if (record.terminationReason === "cancelled") {
659
+ await this.settle(record.runId, {
660
+ status: "cancelled",
661
+ failureReason: "Cancelled by request.",
662
+ usage: record.usage,
663
+ usageKnown: record.usageKnown,
664
+ costKnown: record.costKnown,
665
+ turns: record.turns ?? 0,
666
+ toolCalls: record.toolCalls ?? 0,
667
+ durationMs,
668
+ outputText: "",
669
+ }, { announce: false });
670
+ return;
671
+ }
672
+ if (record.terminationReason === "timeout") {
673
+ const budgetSec = record.deadlineAt ? Math.round((record.deadlineAt - record.startedAt) / 1000) : undefined;
674
+ await this.settle(record.runId, {
675
+ status: "failed",
676
+ failureReason: `Wall time budget exceeded${budgetSec ? ` (${budgetSec}s)` : ""}`,
677
+ usage: record.usage,
678
+ usageKnown: record.usageKnown,
679
+ costKnown: record.costKnown,
680
+ turns: record.turns ?? 0,
681
+ toolCalls: record.toolCalls ?? 0,
682
+ durationMs,
683
+ outputText: "",
684
+ }, { announce: true });
685
+ return;
686
+ }
569
687
  const harness = record.harness ? getExternalHarness(record.harness) : undefined;
570
688
  const eventsText = await readFile(join(record.artifactDir, "events.jsonl"), "utf-8").catch(() => "");
571
689
  const stderrTail = (await readFile(join(record.artifactDir, "stderr.log"), "utf-8").catch(() => "")).slice(-2_000);
@@ -575,7 +693,6 @@ export class SubAgentRunManager {
575
693
  protocolStatus: "unparsable",
576
694
  usageKnown: false,
577
695
  costKnown: false,
578
- outputTruncated: false,
579
696
  stderrTail,
580
697
  };
581
698
  const classification = harness
@@ -589,11 +706,31 @@ export class SubAgentRunManager {
589
706
  costKnown: outcome.costKnown,
590
707
  turns: record.turns ?? 0,
591
708
  toolCalls: record.toolCalls ?? 0,
592
- durationMs: Date.now() - record.startedAt,
709
+ durationMs,
593
710
  outputText: outcome.finalText,
594
711
  sessionId: outcome.sessionId,
595
712
  }, { announce: true });
596
713
  }
714
+ /**
715
+ * Periodic host-wide check for external runs (spec 040, D10.3): kills anything past its
716
+ * deadline, and reconciles anything a `close` event will never fire for — a run adopted from a
717
+ * previous daemon via `restore()`, or (rarely) one whose local watcher already unwound without
718
+ * settling it. `reconcileExternalRun` no-ops on a genuinely still-running, still-watched run,
719
+ * so sweeping one this process itself launched is harmless, not just adopted ones.
720
+ */
721
+ async sweep(now = Date.now()) {
722
+ for (const record of Array.from(this.runs.values())) {
723
+ if (record.status !== "running" || record.runtime !== "external" || !record.pid)
724
+ continue;
725
+ if (record.deadlineAt && now >= record.deadlineAt && record.terminationReason !== "timeout") {
726
+ await this.markTerminationReason(record.runId, "timeout");
727
+ await killProcessGroup(record.pid).catch(() => undefined);
728
+ }
729
+ await this.reconcileExternalRun(record).catch((error) => {
730
+ log.logWarning(`Failed to sweep external run ${record.runId}`, errorMessage(error));
731
+ });
732
+ }
733
+ }
597
734
  /** Drop a settled record once its retention window has passed, mirroring job-manager's GC. */
598
735
  async collectGarbageIfExpired(record, now = Date.now()) {
599
736
  const RETENTION_MS = 24 * 60 * 60_000;
@@ -622,9 +759,35 @@ function totalRunningSubAgentRuns() {
622
759
  return total;
623
760
  }
624
761
  let runtimeConfig = {};
762
+ /** How often the host-wide sweep checks external runs for an overdue deadline or a process that
763
+ * exited while nobody was watching it (D10.3). A code constant per CLAUDE.md's rule for numeric
764
+ * thresholds — deliberately coarse (budgets are in the 300-1800s range) since it exists to
765
+ * guarantee eventual enforcement across a restart, not to replace the live in-process watcher's
766
+ * prompt one. */
767
+ const SWEEP_INTERVAL_MS = 30_000;
768
+ let sweepTimer;
769
+ async function sweepAllChannels() {
770
+ for (const manager of managers.values()) {
771
+ await manager.sweep().catch((error) => log.logWarning("Sub-agent sweep failed", errorMessage(error)));
772
+ }
773
+ }
774
+ function startSubAgentSweeper() {
775
+ if (sweepTimer)
776
+ clearInterval(sweepTimer);
777
+ sweepTimer = setInterval(() => void sweepAllChannels(), SWEEP_INTERVAL_MS);
778
+ sweepTimer.unref?.();
779
+ }
780
+ /** Test seam: stop the background sweeper so it doesn't outlive a test's own fake timers or run. */
781
+ export function stopSubAgentSweeper() {
782
+ if (sweepTimer) {
783
+ clearInterval(sweepTimer);
784
+ sweepTimer = undefined;
785
+ }
786
+ }
625
787
  /** Give runs their persistence root, wake delivery, ledger, and archive. Called once from bootstrap. */
626
788
  export function configureSubAgentRuntime(config) {
627
789
  runtimeConfig = config;
790
+ startSubAgentSweeper();
628
791
  }
629
792
  export function getSubAgentRunManager(channelId) {
630
793
  let manager = managers.get(channelId);
@@ -24,7 +24,7 @@ declare const subagentSchema: Type.TObject<{
24
24
  purpose: Type.TOptional<Type.TUnion<[Type.TLiteral<"work">, Type.TLiteral<"verify">]>>;
25
25
  taskId: Type.TOptional<Type.TString>;
26
26
  returns: Type.TOptional<Type.TUnion<[Type.TLiteral<"text">, Type.TLiteral<"artifact">]>>;
27
- thinkingLevel: Type.TOptional<Type.TUnion<[Type.TLiteral<"off">, Type.TLiteral<"minimal">, Type.TLiteral<"low">, Type.TLiteral<"medium">, Type.TLiteral<"high">, Type.TLiteral<"xhigh">]>>;
27
+ thinkingLevel: Type.TOptional<Type.TUnion<[Type.TLiteral<"off">, Type.TLiteral<"minimal">, Type.TLiteral<"low">, Type.TLiteral<"medium">, Type.TLiteral<"high">, Type.TLiteral<"xhigh">, Type.TLiteral<"max">]>>;
28
28
  }>;
29
29
  export interface SubAgentToolDetails {
30
30
  kind: "subagent";
@@ -120,5 +120,7 @@ interface SubAgentRunContext {
120
120
  * (rooted at the sub-agent workspace) and their own per-invocation bash timeout.
121
121
  */
122
122
  declare function buildSubagentTools(executor: Executor, bashTimeoutSec: number, options: SubAgentToolOptions, runContext: SubAgentRunContext): AgentTool<any>[];
123
+ /** Shared by both runtimes' task envelopes and `subagent_manage`'s verify follow-up (spec 040, D9). */
124
+ export declare function buildVerificationProtocol(taskPath: string): string;
123
125
  export declare function createSubAgentTool(options: SubAgentToolOptions): AgentTool<typeof subagentSchema, SubAgentToolDetails>;
124
126
  export {};
@@ -13,6 +13,7 @@ import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
13
13
  import { formatLocalTime } from "../shared/local-time.js";
14
14
  import { splitH1Sections } from "../shared/markdown-sections.js";
15
15
  import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
16
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
16
17
  import { clipText, errorMessage, extractAssistantText, extractLabelFromArgs } from "../shared/text-utils.js";
17
18
  import { workspaceSubjectHash } from "../tasks/artifact-subject.js";
18
19
  import { readStoredTask } from "../tasks/store.js";
@@ -58,6 +59,7 @@ const subagentSchema = Type.Object({
58
59
  Type.Literal("medium"),
59
60
  Type.Literal("high"),
60
61
  Type.Literal("xhigh"),
62
+ Type.Literal("max"),
61
63
  ], {
62
64
  description: 'Optional reasoning effort for the sub-agent. Defaults to "medium" for purpose=verify, "off" otherwise.',
63
65
  })),
@@ -132,7 +134,7 @@ function resolveRunWorkingDirectory(requested, options) {
132
134
  return base;
133
135
  const target = resolve(base, trimmed);
134
136
  if (!existsSync(target) || !statSync(target).isDirectory()) {
135
- throw new Error(`workingDirectory "${requested}" is not an existing directory.`);
137
+ throw new RecoverableToolError(`workingDirectory "${requested}" is not an existing directory.`);
136
138
  }
137
139
  return target;
138
140
  }
@@ -140,11 +142,11 @@ async function prepareRunContext(runId, params, options) {
140
142
  const purpose = params.purpose ?? "work";
141
143
  const taskId = params.taskId?.trim() || undefined;
142
144
  if (purpose === "verify" && !taskId)
143
- throw new Error("purpose=verify requires taskId.");
145
+ throw new RecoverableToolError("purpose=verify requires taskId.");
144
146
  if (taskId && !TASK_ID_PATTERN.test(taskId))
145
- throw new Error(`Invalid taskId: ${taskId}`);
147
+ throw new RecoverableToolError(`Invalid taskId: ${taskId}`);
146
148
  if (taskId && !(await readStoredTask(options.channelDir, taskId))) {
147
- throw new Error(`Task ${taskId} does not exist. Create it with task_manage before delegating task-owned work.`);
149
+ throw new RecoverableToolError(`Task ${taskId} does not exist. Create it with task_manage before delegating task-owned work.`);
148
150
  }
149
151
  const artifactDir = await prepareArtifactDir(options.channelDir, runId);
150
152
  const workingDirectory = resolveRunWorkingDirectory(params.workingDirectory, options);
@@ -278,6 +280,16 @@ function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
278
280
  bashDefaultTimeoutSeconds: bashTimeoutSec,
279
281
  }, { forSubagent: true }).filter((tool) => runContext.purpose !== "verify" || (tool.name !== "write" && tool.name !== "edit"));
280
282
  }
283
+ /** Shared by both runtimes' task envelopes and `subagent_manage`'s verify follow-up (spec 040, D9). */
284
+ export function buildVerificationProtocol(taskPath) {
285
+ return [
286
+ "Verification protocol:",
287
+ `- Independently inspect ${taskPath} and verify every DoD/Verification item against concrete evidence.`,
288
+ "- You are the checker, not the maker. Do not edit files or fix failures; report them.",
289
+ "- Run deterministic checks when available and distinguish observed evidence from assumptions.",
290
+ "- End the response with exactly one final line: VERDICT: PASS or VERDICT: FAIL.",
291
+ ].join("\n");
292
+ }
281
293
  function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext, returns) {
282
294
  const taskText = task.trim();
283
295
  const lines = [
@@ -298,7 +310,7 @@ function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runConte
298
310
  lines.push("", `Task:`, taskText);
299
311
  if (runContext.purpose === "verify") {
300
312
  const taskPath = join(runtimeContext.workspaceDir, runtimeContext.channelId, "tasks", `${runContext.taskId}.md`);
301
- lines.push("", "Verification protocol:", `- Independently inspect ${taskPath} and verify every DoD/Verification item against concrete evidence.`, "- You are the checker, not the maker. Do not edit files or fix failures; report them.", "- Run deterministic checks when available and distinguish observed evidence from assumptions.", "- End the response with exactly one final line: VERDICT: PASS or VERDICT: FAIL.");
313
+ lines.push("", buildVerificationProtocol(taskPath));
302
314
  }
303
315
  else if (returns === "artifact") {
304
316
  lines.push("", "Output protocol:", `- Write your primary output as a file under the artifact directory above.`, "- End the response with exactly one final line: ARTIFACT: <filename>");
@@ -440,11 +452,11 @@ export function createSubAgentTool(options) {
440
452
  const currentModel = options.getCurrentModel();
441
453
  const taskLengthError = validateSubAgentTask(params.task);
442
454
  if (taskLengthError) {
443
- throw new Error(taskLengthError);
455
+ throw new RecoverableToolError(taskLengthError);
444
456
  }
445
457
  const invocation = resolveSubAgentConfig(availableModels, currentModel, discovery.agents, params, options.getSubAgentModelReference?.() ?? undefined);
446
458
  if (!invocation.config) {
447
- throw new Error(`${invocation.error}\n\nAvailable configured sub-agents:\n${formatSubAgentList(discovery.agents)}`);
459
+ throw new RecoverableToolError(`${invocation.error}\n\nAvailable configured sub-agents:\n${formatSubAgentList(discovery.agents)}`);
448
460
  }
449
461
  const config = invocation.config;
450
462
  const returns = params.returns ?? "text";
@@ -459,14 +471,14 @@ export function createSubAgentTool(options) {
459
471
  // A role that admits it writes cannot also be the checker, and `exec` has no protocol
460
472
  // terminal to prove it even ran to completion — both are hard "no"s, not advisories.
461
473
  if (config.mutates === "write") {
462
- throw new Error(`Sub-agent "${config.name}" declares mutates: write and cannot be used for purpose=verify.`);
474
+ throw new RecoverableToolError(`Sub-agent "${config.name}" declares mutates: write and cannot be used for purpose=verify.`);
463
475
  }
464
476
  if (config.runtime === "external" && config.harness === "exec") {
465
- throw new Error(`Sub-agent "${config.name}" uses the exec harness, which has no protocol terminal and cannot be used for purpose=verify.`);
477
+ throw new RecoverableToolError(`Sub-agent "${config.name}" uses the exec harness, which has no protocol terminal and cannot be used for purpose=verify.`);
466
478
  }
467
479
  const holder = findWorkspaceLeaseHolder(runContext.workingDirectory);
468
480
  if (holder) {
469
- throw new Error(`Cannot verify "${runContext.workingDirectory}": ${formatWorkspaceLeaseConflict(holder)}`);
481
+ throw new RecoverableToolError(`Cannot verify "${runContext.workingDirectory}": ${formatWorkspaceLeaseConflict(holder)}`);
470
482
  }
471
483
  }
472
484
  // Admission: a write-mutating run takes an exclusive workspace lease before it is even
@@ -480,7 +492,7 @@ export function createSubAgentTool(options) {
480
492
  workingDirectory: runContext.workingDirectory,
481
493
  });
482
494
  if (!lease.ok) {
483
- throw new Error(formatWorkspaceLeaseConflict(lease.heldBy));
495
+ throw new RecoverableToolError(formatWorkspaceLeaseConflict(lease.heldBy));
484
496
  }
485
497
  leaseKey = lease.leaseKey;
486
498
  }
@@ -490,6 +502,11 @@ export function createSubAgentTool(options) {
490
502
  throw new Error(`Sub-agent "${config.name}" has runtime: external but no harness configured.`);
491
503
  }
492
504
  try {
505
+ // D9/T5: external roles get the same task envelope internal workers do — runtime
506
+ // paths, injected context blocks, and (for purpose=verify) the verification
507
+ // protocol — rather than the raw task text (spec 040 gap closed post-review).
508
+ const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel);
509
+ const envelopedTask = buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, returns);
493
510
  await launchExternalRun({
494
511
  runId: runContext.runId,
495
512
  channelId: options.runtimeContext.channelId,
@@ -505,7 +522,7 @@ export function createSubAgentTool(options) {
505
522
  thinkingLevel: config.thinkingLevel,
506
523
  maxWallTimeSec: config.maxWallTimeSec,
507
524
  systemPrompt: config.systemPrompt,
508
- task: params.task,
525
+ task: envelopedTask,
509
526
  workingDirectory: runContext.workingDirectory,
510
527
  artifactDir: runContext.artifactDir,
511
528
  purpose: runContext.purpose,
@@ -834,7 +851,9 @@ export function createSubAgentTool(options) {
834
851
  },
835
852
  settleInput: {
836
853
  ...baseSettleInput,
837
- status: "failed",
854
+ // An explicit cancel is not a failure (P1-1) — the model asked this run to
855
+ // stop, and it did.
856
+ status: externallyCancelled ? "cancelled" : "failed",
838
857
  failureReason: effectiveFailureReason,
839
858
  outputText: finalText,
840
859
  },
@@ -857,7 +876,7 @@ export function createSubAgentTool(options) {
857
876
  /** Best-effort settle input for the one fatal path that rejects instead of resolving. */
858
877
  function fatalSettleInput(error) {
859
878
  return {
860
- status: "failed",
879
+ status: externallyCancelled ? "cancelled" : "failed",
861
880
  failureReason: failureReason || error.message,
862
881
  usage,
863
882
  usageKnown: true,
@@ -96,7 +96,6 @@ export function createMemoryManageTool(options) {
96
96
  metadata: {
97
97
  kind: normalizeMemoryKind(kind),
98
98
  sourceType: "user",
99
- trust: "explicit",
100
99
  probationUntil: null,
101
100
  },
102
101
  },
@@ -1,9 +1,11 @@
1
+ import { join } from "node:path";
1
2
  import { Type } from "typebox";
2
3
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
3
4
  import { RecoverableToolError } from "../shared/recoverable-error.js";
4
5
  import { launchExternalRun } from "../subagents/external/run.js";
5
6
  import { elapsedMs, formatCost, formatDuration, harnessLabel } from "../subagents/format.js";
6
7
  import { getSubAgentRunManager } from "../subagents/runs.js";
8
+ import { buildVerificationProtocol } from "../subagents/tool.js";
7
9
  import { acquireWorkspaceLease, formatWorkspaceLeaseConflict, releaseWorkspaceLease, } from "../subagents/workspace-lease.js";
8
10
  const subagentManageSchema = Type.Object({
9
11
  label: Type.String({ description: "Brief description of what you're checking (shown to user)" }),
@@ -94,6 +96,16 @@ export function createSubAgentManageTool(options) {
94
96
  if (role.unavailable) {
95
97
  throw new RecoverableToolError(`Role "${record.agent}" is currently unavailable: ${role.unavailable}`);
96
98
  }
99
+ // P1-2: a role hot-edited between the original run and this follow-up must not silently
100
+ // resume under a stale harness (the wrong CLI would parse a command it never wrote), or
101
+ // masquerade a shell role as resumable (there is no flag to carry `resumeSessionId` into
102
+ // `/bin/sh -lc`, so the run would silently start a fresh, unrelated session anyway).
103
+ if (role.harness !== harness) {
104
+ throw new RecoverableToolError(`Role "${record.agent}" now uses harness "${role.harness}", but run "${resolvedRunId}" was started on "${harness}". Delegate a new run instead of resuming across a harness change.`);
105
+ }
106
+ if (role.shell) {
107
+ throw new RecoverableToolError(`Role "${record.agent}" runs its command through a shell, which has no way to carry a resume session id. Delegate a new run instead, carrying forward whatever context it needs.`);
108
+ }
97
109
  // A short, human-typeable id (spec 041) — the follow-up gets a fresh identity, not the
98
110
  // dispatching tool call's own id.
99
111
  const newRunId = manager().mintRunId();
@@ -109,6 +121,11 @@ export function createSubAgentManageTool(options) {
109
121
  }
110
122
  leaseKey = lease.leaseKey;
111
123
  }
124
+ // The initial dispatch envelopes verify runs with the protocol (tool.ts); a follow-up
125
+ // on a verify run must carry the same protocol, not just the bare instruction (D9).
126
+ const envelopedTask = record.purpose === "verify" && record.taskId
127
+ ? `${task.trim()}\n\n${buildVerificationProtocol(join(options.workspaceDir ?? "", options.channelId, "tasks", `${record.taskId}.md`))}`
128
+ : task;
112
129
  try {
113
130
  await launchExternalRun({
114
131
  runId: newRunId,
@@ -125,7 +142,7 @@ export function createSubAgentManageTool(options) {
125
142
  thinkingLevel: role.thinkingLevel,
126
143
  maxWallTimeSec: role.maxWallTimeSec,
127
144
  systemPrompt: role.systemPrompt,
128
- task,
145
+ task: envelopedTask,
129
146
  workingDirectory: record.workingDirectory,
130
147
  artifactDir: record.artifactDir.replace(/[^/\\]+$/, newRunId),
131
148
  purpose: record.purpose,
package/dist/tui/app.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type BootstrapIO, type BootstrapPaths } from "../runtime/bootstrap.js";
1
+ import { type BootstrapIO, type BootstrapPaths } from "../runtime/app-home.js";
2
2
  export interface TuiAppOptions {
3
3
  channel?: string;
4
4
  /** One-shot, non-interactive run: process a single prompt then exit. */
package/dist/tui/app.js CHANGED
@@ -12,7 +12,8 @@ import { getOrCreateRunner } from "../agent/index.js";
12
12
  import { resetRunner } from "../agent/runner-factory.js";
13
13
  import * as log from "../log.js";
14
14
  import { ensureChannelMemoryFilesSync } from "../memory/files.js";
15
- import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, prepareAppServices, printBootstrapSummary, readCliVersion, } from "../runtime/bootstrap.js";
15
+ import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, printBootstrapSummary, readCliVersion, } from "../runtime/app-home.js";
16
+ import { prepareAppServices } from "../runtime/bootstrap.js";
16
17
  import { ensureChannelDir } from "../runtime/channel-paths.js";
17
18
  import { finalDeliveryOf, progressStyleOf } from "../runtime/dingtalk.js";
18
19
  import { handleEventsCommand } from "../runtime/event-commands.js";
@@ -70,7 +71,7 @@ export async function runTuiApp(options) {
70
71
  // Transport-neutral init. Unlike the DingTalk path, the TUI ignores
71
72
  // channelTemplateCreated (it needs no channel.json) and shares app services
72
73
  // (settings, diagnostics) with bootstrap via prepareAppServices.
73
- printBootstrapSummary(bootstrapAppHome(paths, io), io, paths);
74
+ printBootstrapSummary(bootstrapAppHome(paths), io, paths);
74
75
  const { settingsManager } = prepareAppServices(paths);
75
76
  log.configureLogging(settingsManager.getLoggingSettings());
76
77
  log.logStartup(paths.workspaceDir);