@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
@@ -3,7 +3,7 @@ import { join } from "path";
3
3
  import { formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../agent/commands.js";
4
4
  import { channelEffectCount, noteTaskEffects, taskEffectCount } from "../agent/effect-ledger.js";
5
5
  import { getOrCreateRunner } from "../agent/index.js";
6
- import { configureJobRuntime, restoreChannelJobs } from "../agent/job-manager.js";
6
+ import { configureJobRuntime, getChannelJobManager, restoreChannelJobs, } from "../agent/job-manager.js";
7
7
  import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
8
8
  import { resetRunner } from "../agent/runner-factory.js";
9
9
  import { renderStatus } from "../agent/status-render.js";
@@ -18,8 +18,9 @@ import { PipiclawSettingsManager } from "../settings.js";
18
18
  import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
19
19
  import { fileStamp } from "../shared/file-stamp.js";
20
20
  import { errorMessage } from "../shared/text-utils.js";
21
+ import { configureSubAgentRuntime, getSubAgentRunManager, restoreAllSubAgentRuns, } from "../subagents/runs.js";
21
22
  import { readActiveTasks } from "../tasks/ledger.js";
22
- import { activateWaitingTask, claimTaskAttempt, finishTaskAttempt } from "../tasks/store.js";
23
+ import { activateWaitingTaskAndClaimAttempt, finishTaskAttempt, finishWakeTaskActivation, rollbackWakeTaskActivation, } from "../tasks/store.js";
23
24
  import { getToolsConfigPath, loadToolsConfig, loadToolsConfigWithDiagnostics } from "../tools/config.js";
24
25
  import { getUsageLedger } from "../usage/ledger.js";
25
26
  import { parseUsageMode, renderUsageReport } from "../usage/render.js";
@@ -32,6 +33,7 @@ import { handleEventsCommand as runEventsCommand } from "./event-commands.js";
32
33
  import { createEventsWatcher } from "./events.js";
33
34
  import { installLlmProxy } from "./proxy.js";
34
35
  import { ChannelStore } from "./store.js";
36
+ import { handleSubagentsCommand as runSubagentsCommand } from "./subagent-commands.js";
35
37
  import { pauseTask, handleTasksCommand as runTasksCommand } from "./task-commands.js";
36
38
  import { createTaskDriverEvent, createTaskVerificationEvent, TaskDriver } from "./task-driver.js";
37
39
  import { migrateLegacyTaskScheduleEvents, migrateLegacyTaskState } from "./task-migration.js";
@@ -399,6 +401,70 @@ function flushInactiveChannelMemory(channelRunners) {
399
401
  function isNoRunningTaskQueueError(err) {
400
402
  return err instanceof Error && err.message === "No task is currently running.";
401
403
  }
404
+ /**
405
+ * Whether a `[JOB:<jobId>] ... belongs to task <taskId>.` wake actually names a job that: exists
406
+ * on this channel, has actually finished (a still-`running` job cannot have produced this wake —
407
+ * accepting it anyway would let a message merely mentioning a live job's id activate a task
408
+ * early), and really is the one whose own contract names `taskId` (spec 040, T9). The text itself
409
+ * is never sufficient — it can be typed by any user, or echoed back by an external agent's own
410
+ * untrusted stdout.
411
+ */
412
+ export function isVerifiedJobWake(jobs, jobId, taskId) {
413
+ const job = jobs.find((candidate) => candidate.id === jobId);
414
+ return job !== undefined && job.status !== "running" && job.taskId === taskId;
415
+ }
416
+ /**
417
+ * Same check as `isVerifiedJobWake`, for a `[SUBAGENT:<runId>] ... belongs to task <taskId>.`
418
+ * delegation wake. `settledAt` (rather than `status !== "running"`) is the terminal marker here
419
+ * because it is the one field `SubAgentRunManager.settle()` sets unconditionally and first, before
420
+ * usage/archive/wake side effects — the same idempotency guard the manager itself relies on.
421
+ */
422
+ export function isVerifiedDelegationWake(record, taskId) {
423
+ return record !== undefined && record.settledAt !== undefined && record.taskId === taskId;
424
+ }
425
+ /** Plain wake text is untrusted. Only an event carrying the producer-created structured envelope
426
+ * and its exact durable dispatch id may enter task activation; normal DingTalk inbound events do
427
+ * not populate `internalWake`, so copying a real wake's text is insufficient. */
428
+ export function isTrustedInternalWake(event, kind, resourceId, taskId) {
429
+ const wake = event.internalWake;
430
+ return (wake?.kind === kind &&
431
+ wake.resourceId === resourceId &&
432
+ wake.taskId === taskId &&
433
+ typeof event.dispatchId === "string" &&
434
+ wake.dispatchId === event.dispatchId);
435
+ }
436
+ /** Claim and activate a producer-created delegation wake without consuming it yet. Keeping the
437
+ * final marker separate lets transports such as TUI mark it consumed only after they have accepted
438
+ * the corresponding turn; a rejected submit remains replayable in the same or next process. */
439
+ export async function claimVerifiedDelegationWake(event, workspaceDir, hooks) {
440
+ const wake = event.internalWake;
441
+ if (wake?.kind !== "subagent")
442
+ return undefined;
443
+ const runManager = getSubAgentRunManager(event.channelId);
444
+ const record = runManager.get(wake.resourceId);
445
+ if (!isTrustedInternalWake(event, "subagent", wake.resourceId, wake.taskId) ||
446
+ !isVerifiedDelegationWake(record, wake.taskId) ||
447
+ !(await runManager.beginWakeConsumption(wake.resourceId, wake.taskId, event.dispatchId))) {
448
+ return undefined;
449
+ }
450
+ const channelDir = getChannelDir(workspaceDir, event.channelId);
451
+ const handoff = {
452
+ kind: "subagent",
453
+ resourceId: wake.resourceId,
454
+ dispatchId: event.dispatchId,
455
+ };
456
+ const activated = await activateWaitingTaskAndClaimAttempt(channelDir, wake.taskId, "external-signal", new Date(), hooks, handoff);
457
+ return {
458
+ taskId: wake.taskId,
459
+ generation: activated?.generation,
460
+ activated: activated !== undefined,
461
+ finish: async () => {
462
+ await runManager.finishWakeConsumption(wake.resourceId, event.dispatchId);
463
+ await finishWakeTaskActivation(channelDir, wake.taskId, handoff);
464
+ },
465
+ rollback: () => rollbackWakeTaskActivation(channelDir, wake.taskId, handoff),
466
+ };
467
+ }
402
468
  export function createRuntimeContext(options) {
403
469
  const startServices = options.startServices ?? true;
404
470
  const registerSignalHandlers = options.registerSignalHandlers ?? true;
@@ -544,6 +610,16 @@ export function createRuntimeContext(options) {
544
610
  async handleContextCommand(event, bot, args) {
545
611
  await bot.sendPlain(event.channelId, getRunner(event.channelId).renderContextReport(args));
546
612
  },
613
+ // A human control path independent of the model (spec 040, D6): `/stop` no longer kills a
614
+ // dispatched delegation, so cancel must work whether or not a runner is currently active.
615
+ async handleSubagentsCommand(event, bot, args) {
616
+ const response = await runSubagentsCommand({
617
+ args,
618
+ channelId: event.channelId,
619
+ discovery: channelRunners.get(event.channelId)?.getSubAgentDiscoverySnapshot(),
620
+ });
621
+ await bot.sendPlain(event.channelId, response);
622
+ },
547
623
  async handleBusyMessage(event, bot, mode, queueText) {
548
624
  if (shuttingDown) {
549
625
  return { kind: "handled" };
@@ -607,6 +683,7 @@ export function createRuntimeContext(options) {
607
683
  }
608
684
  const runner = getRunner(event.channelId);
609
685
  await durableDispatch?.markStarted(event.dispatchId);
686
+ let structuredWakeFinalized = event.internalWake === undefined;
610
687
  const task = (async () => {
611
688
  try {
612
689
  await archiveIncomingMessage(event.channelId, {
@@ -642,6 +719,10 @@ export function createRuntimeContext(options) {
642
719
  await handler.handleUsageCommand(event, bot, builtInCommand.args);
643
720
  return;
644
721
  }
722
+ if (builtInCommand.name === "subagents") {
723
+ await handler.handleSubagentsCommand(event, bot, builtInCommand.args);
724
+ return;
725
+ }
645
726
  if (isRunnerBuiltInCommand(builtInCommand)) {
646
727
  await runner.handleBuiltinCommand(ctx, builtInCommand);
647
728
  }
@@ -666,28 +747,88 @@ export function createRuntimeContext(options) {
666
747
  // task-driver turn is measured as a delta (turns on a channel are serialized)
667
748
  // and credited to the task it was dispatched for.
668
749
  const effectsBefore = channelEffectCount(event.channelId);
669
- const jobTaskId = /^\[JOB:[^\]]+\][\s\S]*?belongs to task ([A-Za-z0-9._-]+)\./.exec(event.text)?.[1];
750
+ // Both wake formats below carry an unauthenticated claim in plain text: anything
751
+ // that can put a message on this channel can *write* "[JOB:x] ... belongs to task
752
+ // y." or "[SUBAGENT:x] ... belongs to task y." — including another user, or an
753
+ // external agent's own untrusted stdout (spec 040, D8's threat model explicitly
754
+ // treats external output as untrusted). Activating a waiting task on text pattern
755
+ // alone lets that forged claim advance an unrelated task's attempt generation. The
756
+ // pattern match only extracts a *candidate* id pair now; both paths verify the
757
+ // named run/job actually exists, is done, and really is the one that names this
758
+ // taskId before ever calling `activateWaitingTask` (T9).
759
+ const jobTextMatch = /^\[JOB:([^\]]+)\][\s\S]*?belongs to task ([A-Za-z0-9._-]+)\./.exec(event.text);
760
+ const jobMatch = event.internalWake?.kind === "job"
761
+ ? [event.text, event.internalWake.resourceId, event.internalWake.taskId]
762
+ : jobTextMatch;
670
763
  let recoveredJobTaskId;
671
- if (jobTaskId) {
672
- const channelDir = getChannelDir(options.paths.workspaceDir, event.channelId);
673
- const activated = await activateWaitingTask(channelDir, jobTaskId, "job");
674
- if (activated)
675
- recoveredJobTaskId = jobTaskId;
676
- if (activated?.fields.control) {
677
- const claim = await claimTaskAttempt(channelDir, jobTaskId, new Date());
678
- if (claim)
679
- event.taskAttemptGeneration = claim.generation;
764
+ if (jobMatch) {
765
+ const [, jobId, jobTaskId] = jobMatch;
766
+ const jobManager = getChannelJobManager(event.channelId, executor);
767
+ const jobs = await jobManager.list();
768
+ const verified = isTrustedInternalWake(event, "job", jobId, jobTaskId) &&
769
+ isVerifiedJobWake(jobs, jobId, jobTaskId) &&
770
+ (await jobManager.beginWakeConsumption(jobId, jobTaskId, event.dispatchId));
771
+ if (verified) {
772
+ const channelDir = getChannelDir(options.paths.workspaceDir, event.channelId);
773
+ const activated = await activateWaitingTaskAndClaimAttempt(channelDir, jobTaskId, "job", new Date(), options.wakeTransitionHooks?.job);
774
+ if (activated) {
775
+ recoveredJobTaskId = jobTaskId;
776
+ event.taskAttemptGeneration = activated.generation;
777
+ }
778
+ await jobManager.finishWakeConsumption(jobId, event.dispatchId);
779
+ structuredWakeFinalized = true;
780
+ if (event.internalWake?.kind === "job" && !activated)
781
+ return;
782
+ }
783
+ else {
784
+ log.logWarning(`[${event.channelId}] Ignored an unverifiable [JOB:${jobId}] wake claiming task ${jobTaskId}`);
785
+ if (event.internalWake?.kind === "job") {
786
+ structuredWakeFinalized = true;
787
+ return;
788
+ }
789
+ }
790
+ }
791
+ // Spec 040, D7: a delegation run's completion wake carries the same "belongs to
792
+ // task" contract as a background job's, and reactivates a task parked with
793
+ // waitingFor="external-signal" the same way — verified the same way (T9).
794
+ const delegationTextMatch = /^\[SUBAGENT:([^\]]+)\][\s\S]*?belongs to task ([A-Za-z0-9._-]+)\./.exec(event.text);
795
+ const delegationMatch = event.internalWake?.kind === "subagent"
796
+ ? [event.text, event.internalWake.resourceId, event.internalWake.taskId]
797
+ : delegationTextMatch;
798
+ let recoveredDelegationTaskId;
799
+ if (delegationMatch) {
800
+ const [, runId, delegationTaskId] = delegationMatch;
801
+ const claimed = await claimVerifiedDelegationWake(event, options.paths.workspaceDir, options.wakeTransitionHooks?.subagent);
802
+ if (claimed) {
803
+ if (claimed.activated)
804
+ recoveredDelegationTaskId = claimed.taskId;
805
+ if (claimed.generation !== undefined)
806
+ event.taskAttemptGeneration = claimed.generation;
807
+ await claimed.finish();
808
+ structuredWakeFinalized = true;
809
+ if (event.internalWake?.kind === "subagent" && !claimed.activated)
810
+ return;
811
+ }
812
+ else {
813
+ log.logWarning(`[${event.channelId}] Ignored an unverifiable [SUBAGENT:${runId}] wake claiming task ${delegationTaskId}`);
814
+ if (event.internalWake?.kind === "subagent") {
815
+ structuredWakeFinalized = true;
816
+ return;
817
+ }
680
818
  }
681
819
  }
682
820
  const result = await runner.run(ctx, store);
683
821
  const taskDriverMatch = /^\[TASK_DRIVER:([A-Za-z0-9._-]+)\]/.exec(event.text);
684
- const taskAttemptId = taskDriverMatch?.[1] ?? recoveredJobTaskId;
822
+ const taskAttemptId = taskDriverMatch?.[1] ?? recoveredJobTaskId ?? recoveredDelegationTaskId;
685
823
  if (taskDriverMatch?.[1]) {
686
824
  noteTaskEffects(event.channelId, taskDriverMatch[1], channelEffectCount(event.channelId) - effectsBefore);
687
825
  }
688
826
  if (recoveredJobTaskId) {
689
827
  noteTaskEffects(event.channelId, recoveredJobTaskId, channelEffectCount(event.channelId) - effectsBefore);
690
828
  }
829
+ if (recoveredDelegationTaskId) {
830
+ noteTaskEffects(event.channelId, recoveredDelegationTaskId, channelEffectCount(event.channelId) - effectsBefore);
831
+ }
691
832
  if (taskAttemptId && result.usage && result.durationMs !== undefined) {
692
833
  await finishTaskAttempt(getChannelDir(options.paths.workspaceDir, event.channelId), taskAttemptId, {
693
834
  tokens: result.usage.total,
@@ -711,7 +852,10 @@ export function createRuntimeContext(options) {
711
852
  });
712
853
  }
713
854
  finally {
714
- await durableDispatch?.markCompleted(event.dispatchId);
855
+ if (structuredWakeFinalized)
856
+ await durableDispatch?.markCompleted(event.dispatchId);
857
+ else
858
+ await durableDispatch?.markRetryable(event.dispatchId);
715
859
  runner.endTurn();
716
860
  // A finished turn may have written task files (progress/complete/set); rescan
717
861
  // now so a continuing task chain advances immediately instead of after a full sleep.
@@ -742,6 +886,15 @@ export function createRuntimeContext(options) {
742
886
  dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
743
887
  });
744
888
  void restoreChannelJobs(executor);
889
+ // Delegation runs get the same treatment (spec 040, D1/D7): persistence root, wake delivery,
890
+ // and the usage/archive authority, wired before any turn can start a run.
891
+ configureSubAgentRuntime({
892
+ stateDir: join(options.paths.appHomeDir, "state", "subagent-runs"),
893
+ dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
894
+ ledger: getUsageLedger(),
895
+ store,
896
+ });
897
+ void restoreAllSubAgentRuns();
745
898
  const eventsWatcher = options.createEventsWatcher
746
899
  ? options.createEventsWatcher(options.paths.workspaceDir, bot, executor, options.paths.eventHistoryPath)
747
900
  : createEventsWatcher(options.paths.workspaceDir, bot, executor, loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config.commandGuard, options.paths.eventHistoryPath, (event) => durableDispatch?.dispatch(event) ?? false);
@@ -37,6 +37,14 @@ export interface DingTalkEvent {
37
37
  channelName?: string;
38
38
  /** Runtime-owned durable-dispatch record, absent for normal inbound messages. */
39
39
  dispatchId?: string;
40
+ /** Structured wake provenance created only by in-process producers. DingTalk inbound parsing
41
+ * never copies arbitrary payload fields into this event, so user text cannot manufacture it. */
42
+ internalWake?: {
43
+ kind: "job" | "subagent";
44
+ resourceId: string;
45
+ taskId: string;
46
+ dispatchId: string;
47
+ };
40
48
  /**
41
49
  * The `attemptGeneration` this event's claim recorded, for `[TASK_DRIVER:id]` events only.
42
50
  * Carried through durable dispatch so `finishTaskAttempt` can tell a stale, superseded claim's
@@ -78,6 +86,7 @@ export interface DingTalkHandler {
78
86
  handleStatusCommand(event: DingTalkEvent, bot: DingTalkBot): Promise<void>;
79
87
  handleUsageCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
80
88
  handleContextCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
89
+ handleSubagentsCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
81
90
  handleBusyMessage(event: DingTalkEvent, bot: DingTalkBot, mode: BusyMessageMode, queueText: string): Promise<BusyMessageResult>;
82
91
  }
83
92
  export declare class DingTalkBot implements MediaSender {
@@ -1108,6 +1108,9 @@ export class DingTalkBot {
1108
1108
  case "context":
1109
1109
  await this.handler.handleContextCommand(event, this, builtInCommand.args);
1110
1110
  return;
1111
+ case "subagents":
1112
+ await this.handler.handleSubagentsCommand(event, this, builtInCommand.args);
1113
+ return;
1111
1114
  }
1112
1115
  }
1113
1116
  // Session commands (/model, /new, …) and unknown slash commands cannot
@@ -34,6 +34,10 @@ export declare class DurableDispatchService {
34
34
  cancelChannel(channelId: string): Promise<number>;
35
35
  markStarted(id: string | undefined): Promise<void>;
36
36
  markCompleted(id: string | undefined): Promise<void>;
37
+ /** Release a failed handler's in-process claim without deleting its durable record. Structured
38
+ * wake activation uses this for transient task/job/run persistence failures so the next drain
39
+ * can retry the same dispatch id instead of losing the only completion signal. */
40
+ markRetryable(id: string | undefined): Promise<void>;
37
41
  drainOnce(now?: number): Promise<void>;
38
42
  private read;
39
43
  private write;
@@ -160,6 +160,22 @@ export class DurableDispatchService {
160
160
  await unlink(recordPath(this.options.stateDir, id)).catch(() => undefined);
161
161
  });
162
162
  }
163
+ /** Release a failed handler's in-process claim without deleting its durable record. Structured
164
+ * wake activation uses this for transient task/job/run persistence failures so the next drain
165
+ * can retry the same dispatch id instead of losing the only completion signal. */
166
+ async markRetryable(id) {
167
+ if (!id)
168
+ return;
169
+ this.running.delete(id);
170
+ await this.queue.run(id, async () => {
171
+ const record = await this.read(id);
172
+ if (!record)
173
+ return;
174
+ record.status = "pending";
175
+ record.leaseExpiresAt = undefined;
176
+ await this.write(record);
177
+ });
178
+ }
163
179
  async drainOnce(now = Date.now()) {
164
180
  let filenames;
165
181
  try {
@@ -27,6 +27,13 @@ export interface LoggedSubAgentRun {
27
27
  failureReason?: string;
28
28
  output: string;
29
29
  outputTruncated: boolean;
30
+ /** Spec 040, D7: the run this entry archives, and its lifecycle context. Only set on terminal archiving. */
31
+ runId?: string;
32
+ runtime?: "internal" | "external";
33
+ harness?: "claude-code" | "codex-cli" | "exec";
34
+ status?: "completed" | "failed" | "cancelled" | "lost";
35
+ taskId?: string;
36
+ artifactDir?: string;
30
37
  usage: {
31
38
  input: number;
32
39
  output: number;
@@ -0,0 +1,15 @@
1
+ import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
2
+ /**
3
+ * `/subagents` — the human control path that does not depend on the model (spec 040, D6).
4
+ * `/stop` no longer kills a dispatched delegation (D2), so cancel needs a route that works even
5
+ * when the model is unavailable or the turn is stuck. Mirrors `event-commands.ts`'s shape: pure
6
+ * functions returning markdown, no bot/event coupling.
7
+ */
8
+ export interface HandleSubagentsCommandOptions {
9
+ args: string;
10
+ channelId: string;
11
+ /** Best-effort role-directory snapshot for the `list` health tail; omitted when no runner is
12
+ * currently active for this channel (mirrors how `/status` degrades without a live runner). */
13
+ discovery?: SubAgentDiscoveryResult;
14
+ }
15
+ export declare function handleSubagentsCommand(options: HandleSubagentsCommandOptions): Promise<string>;
@@ -0,0 +1,122 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { errorMessage } from "../shared/text-utils.js";
4
+ import { getSubAgentRunManager } from "../subagents/runs.js";
5
+ function usage() {
6
+ return `# Subagents
7
+
8
+ Usage:
9
+
10
+ - \`/subagents list\`
11
+ - \`/subagents show <runId>\`
12
+ - \`/subagents cancel <runId>\``;
13
+ }
14
+ function parseSubagentsCommand(args) {
15
+ const parts = args.trim().split(/\s+/).filter(Boolean);
16
+ const action = parts[0];
17
+ if (!action || action === "list") {
18
+ if (parts.length > 1)
19
+ throw new Error("Usage: /subagents list");
20
+ return { action: "list" };
21
+ }
22
+ if (action === "show") {
23
+ if (!parts[1] || parts.length > 2)
24
+ throw new Error("Usage: /subagents show <runId>");
25
+ return { action: "show", runId: parts[1] };
26
+ }
27
+ if (action === "cancel") {
28
+ if (!parts[1] || parts.length > 2)
29
+ throw new Error("Usage: /subagents cancel <runId>");
30
+ return { action: "cancel", runId: parts[1] };
31
+ }
32
+ throw new Error(`Unknown /subagents action: ${action}`);
33
+ }
34
+ function formatDuration(ms) {
35
+ const seconds = Math.round(ms / 1000);
36
+ if (seconds < 60)
37
+ return `${seconds}s`;
38
+ return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
39
+ }
40
+ function elapsedMs(record) {
41
+ return (record.finishedAt ?? Date.now()) - record.startedAt;
42
+ }
43
+ function formatRunLine(record) {
44
+ const harness = record.harness ? `${record.runtime}/${record.harness}` : record.runtime;
45
+ const task = record.taskId ? `, task ${record.taskId}` : "";
46
+ return `- [${record.runId}] ${record.agent} (${harness}) — ${record.status} (${formatDuration(elapsedMs(record))}${task})`;
47
+ }
48
+ function formatHealthTail(discovery) {
49
+ const unavailable = discovery.agents.filter((agent) => agent.unavailable);
50
+ const lines = [];
51
+ if (unavailable.length > 0 || discovery.warnings.length > 0) {
52
+ lines.push("", "## Role directory health");
53
+ }
54
+ for (const agent of unavailable) {
55
+ lines.push(`- \`${agent.name}\`: unavailable (${agent.unavailable})`);
56
+ }
57
+ for (const warning of discovery.warnings) {
58
+ lines.push(`- discovery warning: ${warning}`);
59
+ }
60
+ return lines.join("\n");
61
+ }
62
+ async function listRuns(channelId, discovery) {
63
+ const records = getSubAgentRunManager(channelId).list();
64
+ const body = records.length === 0
65
+ ? "No delegation runs."
66
+ : records
67
+ .sort((a, b) => b.startedAt - a.startedAt)
68
+ .map(formatRunLine)
69
+ .join("\n");
70
+ const tail = discovery ? formatHealthTail(discovery) : "";
71
+ return `# Subagent runs\n\n${body}${tail}`;
72
+ }
73
+ const STDERR_TAIL_CHARS = 2_000;
74
+ async function formatRunDetail(record) {
75
+ const parts = [`# Run ${record.runId}`, "", "```json", JSON.stringify(record, null, 2), "```"];
76
+ // D6: "show" is the human/model escape hatch for a stuck or failed external run, so its
77
+ // stderr belongs here even though it never rides the completion wake (that only carries
78
+ // the harness's own parsed output).
79
+ if (record.runtime === "external") {
80
+ const stderrTail = await readFile(join(record.artifactDir, "stderr.log"), "utf-8")
81
+ .then((text) => text.slice(-STDERR_TAIL_CHARS))
82
+ .catch(() => undefined);
83
+ if (stderrTail?.trim()) {
84
+ parts.push("", "## stderr (tail)", "```", stderrTail, "```");
85
+ }
86
+ }
87
+ return parts.join("\n");
88
+ }
89
+ async function showRun(channelId, runId) {
90
+ const record = getSubAgentRunManager(channelId).get(runId);
91
+ if (!record)
92
+ return `Run not found: ${runId}`;
93
+ return formatRunDetail(record);
94
+ }
95
+ async function cancelRun(channelId, runId) {
96
+ const status = await getSubAgentRunManager(channelId).cancel(runId);
97
+ if (status === "not_found")
98
+ return `Run not found: ${runId}`;
99
+ return `Cancel requested for run \`${runId}\`: ${status}`;
100
+ }
101
+ export async function handleSubagentsCommand(options) {
102
+ let command;
103
+ try {
104
+ command = parseSubagentsCommand(options.args);
105
+ }
106
+ catch (error) {
107
+ return `${errorMessage(error)}\n\n${usage()}`;
108
+ }
109
+ try {
110
+ switch (command.action) {
111
+ case "list":
112
+ return await listRuns(options.channelId, options.discovery);
113
+ case "show":
114
+ return await showRun(options.channelId, command.runId);
115
+ case "cancel":
116
+ return await cancelRun(options.channelId, command.runId);
117
+ }
118
+ }
119
+ catch (error) {
120
+ return `Could not ${command.action} subagent run(s): ${errorMessage(error)}`;
121
+ }
122
+ }
@@ -7,6 +7,7 @@ import { parseTaskEventName, taskEventPrefix } from "../shared/task-events.js";
7
7
  import { nextTaskWake, validateTaskSchedule } from "../shared/task-schedule.js";
8
8
  import { errorMessage } from "../shared/text-utils.js";
9
9
  import { isRecord } from "../shared/type-guards.js";
10
+ import { channelDelegationTaskIds } from "../subagents/runs.js";
10
11
  import { applyTaskControlPatch, createDefaultTaskControl, retiredTaskControlKeys, TASK_PRIORITIES, taskBudgetViolation, } from "../tasks/control.js";
11
12
  import { countTaskDodItems, extractTaskTitle, isTaskParked, missingStandardTaskSections, normalizeTaskId, readActiveTasks, recurringTaskMissedOccurrence, } from "../tasks/ledger.js";
12
13
  import { withTaskMutation } from "../tasks/mutation-lock.js";
@@ -474,6 +475,7 @@ async function doctor(options) {
474
475
  const archivedIds = await readArchivedTaskIds(options.channelDir);
475
476
  const events = await readTaskEvents(options.workspaceDir, options.channelId);
476
477
  const runningJobTaskIds = channelJobTaskIds(options.channelId);
478
+ const runningDelegationTaskIds = channelDelegationTaskIds(options.channelId);
477
479
  const issues = [];
478
480
  for (const entry of entries) {
479
481
  const status = entry.frontmatter.status ?? "active";
@@ -582,7 +584,9 @@ async function doctor(options) {
582
584
  // no running job carrying this id, whether it ever resumes is entirely up to the user.
583
585
  // That is legitimate when it is waiting on an answer — and indistinguishable, on disk,
584
586
  // from a task everyone has forgotten. Report the fact and name every way out.
585
- const hasDurableWaitingSource = control?.waitingFor === "verification" || (control?.waitingFor === "job" && runningJobTaskIds.has(entry.id));
587
+ const hasDurableWaitingSource = control?.waitingFor === "verification" ||
588
+ (control?.waitingFor === "job" && runningJobTaskIds.has(entry.id)) ||
589
+ (control?.waitingFor === "external-signal" && runningDelegationTaskIds.has(entry.id));
586
590
  if (isTaskParked(entry.frontmatter) && !hasDurableWaitingSource) {
587
591
  issues.push(issue(`tasks/${entry.id}.md is parked (waiting, no wake) and no running background job will wake it.`, `It resumes only when you reply to it, run /tasks run ${entry.id}, or give it a wake with /tasks set ${entry.id} wake <local time or +2h>; cancel it if what it waits for is gone.`));
588
592
  }
@@ -20,8 +20,17 @@ function getAppender(path) {
20
20
  }
21
21
  /** Persist a blocked operation without synchronously stalling the Node event loop. */
22
22
  export async function logSecurityEvent(workspaceDir, config, event) {
23
- if (!config.audit.logBlocked)
23
+ // external-agent records a permitted action, not a blocked one (spec 040, D8.1): it must not
24
+ // disappear just because the operator only wants blocked-action logging.
25
+ if (!config.audit.logBlocked && event.type !== "external-agent")
24
26
  return;
27
+ if (event.type === "external-agent") {
28
+ // External agents bypass command-guard. Their complete dispatch record is therefore a
29
+ // security gate, not best-effort observability: do not return until it is on disk, and let
30
+ // capacity/permission/I/O failures reject the dispatch before a child can be spawned.
31
+ await getAppender(getLogPath(workspaceDir, config)).appendStrict({ date: formatLocalTime(), ...event });
32
+ return;
33
+ }
25
34
  let timer;
26
35
  try {
27
36
  await Promise.race([
@@ -77,4 +77,20 @@ export interface BlockedNetworkLogEvent extends SecurityLogEventBase {
77
77
  category?: string;
78
78
  reason?: string;
79
79
  }
80
- export type SecurityLogEvent = BlockedPathLogEvent | BlockedCommandLogEvent | BlockedNetworkLogEvent;
80
+ /**
81
+ * A *permitted* external delegation dispatch (spec 040, D8.1). Unlike the three events above,
82
+ * this records an action that was executed, not one that was blocked — external runs never pass
83
+ * through command-guard, so the argv actually spawned has to be captured somewhere. `audit.logBlocked`
84
+ * must not suppress it: see `logSecurityEvent`.
85
+ */
86
+ export interface ExternalAgentLogEvent extends SecurityLogEventBase {
87
+ type: "external-agent";
88
+ runId: string;
89
+ agent: string;
90
+ harness: string;
91
+ argv: string[];
92
+ workingDirectory: string;
93
+ mutates: "read" | "write";
94
+ model?: string;
95
+ }
96
+ export type SecurityLogEvent = BlockedPathLogEvent | BlockedCommandLogEvent | BlockedNetworkLogEvent | ExternalAgentLogEvent;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Stateless host-process operations shared by background jobs and external delegation runs
3
+ * (spec 040, D1): a liveness probe and a process-group kill. Nothing here is job- or run-specific
4
+ * — both callers bring their own persisted pid and decide what "gone" means for their own state
5
+ * machine. `job-manager.ts` still probes through its shell `Executor` (its jobs are shell
6
+ * children); this is for callers that spawn argv-direct, detached children of their own (D3/D4).
7
+ */
8
+ /** True if `pid` names a live process this user can at least see, without sending a real signal. */
9
+ export declare function isProcessAlive(pid: number): boolean;
10
+ /**
11
+ * SIGTERM the process group, then unconditionally SIGKILL it after a short grace period.
12
+ * `detached: true` at spawn time makes the child its own process-group leader, so `-pid` reaches
13
+ * it and everything it spawned.
14
+ *
15
+ * The SIGKILL is not gated on a liveness probe of the leader pid: a leader that exits before a
16
+ * lingering descendant (e.g. a shell that forked and returned) would make `isProcessAlive(pid)`
17
+ * report false while the descendant is still alive and still holding the workspace, so probing
18
+ * only the leader and skipping the SIGKILL on that basis is exactly the wrong direction to err in.
19
+ * A dead group simply makes the SIGKILL a harmless ESRCH, caught below.
20
+ */
21
+ export declare function killProcessGroup(pid: number, graceMs?: number): Promise<void>;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Stateless host-process operations shared by background jobs and external delegation runs
3
+ * (spec 040, D1): a liveness probe and a process-group kill. Nothing here is job- or run-specific
4
+ * — both callers bring their own persisted pid and decide what "gone" means for their own state
5
+ * machine. `job-manager.ts` still probes through its shell `Executor` (its jobs are shell
6
+ * children); this is for callers that spawn argv-direct, detached children of their own (D3/D4).
7
+ */
8
+ /** True if `pid` names a live process this user can at least see, without sending a real signal. */
9
+ export function isProcessAlive(pid) {
10
+ try {
11
+ process.kill(pid, 0);
12
+ return true;
13
+ }
14
+ catch (error) {
15
+ // EPERM: the process exists but belongs to someone else — still alive from our view.
16
+ return error.code === "EPERM";
17
+ }
18
+ }
19
+ /**
20
+ * SIGTERM the process group, then unconditionally SIGKILL it after a short grace period.
21
+ * `detached: true` at spawn time makes the child its own process-group leader, so `-pid` reaches
22
+ * it and everything it spawned.
23
+ *
24
+ * The SIGKILL is not gated on a liveness probe of the leader pid: a leader that exits before a
25
+ * lingering descendant (e.g. a shell that forked and returned) would make `isProcessAlive(pid)`
26
+ * report false while the descendant is still alive and still holding the workspace, so probing
27
+ * only the leader and skipping the SIGKILL on that basis is exactly the wrong direction to err in.
28
+ * A dead group simply makes the SIGKILL a harmless ESRCH, caught below.
29
+ */
30
+ export async function killProcessGroup(pid, graceMs = 300) {
31
+ try {
32
+ process.kill(-pid, "SIGTERM");
33
+ }
34
+ catch {
35
+ return; // Already gone.
36
+ }
37
+ await new Promise((resolve) => setTimeout(resolve, graceMs));
38
+ try {
39
+ process.kill(-pid, "SIGKILL");
40
+ }
41
+ catch {
42
+ // Already gone.
43
+ }
44
+ }
@@ -26,6 +26,8 @@ export interface JsonlAppenderOptions {
26
26
  export interface JsonlAppender {
27
27
  /** Queue and await one record. Never throws; a full or closed writer drops it. */
28
28
  append(record: unknown, priority?: JsonlPriority): Promise<void>;
29
+ /** Queue and durably append one record, rejecting on serialization, capacity, closure, or I/O failure. */
30
+ appendStrict(record: unknown, priority?: JsonlPriority): Promise<void>;
29
31
  /** Queue one record without waiting for disk. Returns false when it cannot be accepted. */
30
32
  tryAppend(record: unknown, priority?: JsonlPriority): boolean;
31
33
  /** Wait until every currently accepted record has finished. */