@xzzpig/pi-subagents 0.2.0 → 0.4.0

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 (103) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/README.md +2 -0
  3. package/agents/oracle.md +7 -5
  4. package/agents/researcher.md +1 -1
  5. package/agents/reviewer.md +2 -2
  6. package/agents/scout.md +1 -1
  7. package/agents/worker.md +1 -1
  8. package/docs/agents.md +3 -0
  9. package/docs/configuration.md +121 -10
  10. package/docs/extension-api.md +36 -0
  11. package/docs/missions.md +5 -3
  12. package/docs/observability.md +43 -3
  13. package/docs/tool-reference.md +20 -3
  14. package/docs/workflows.md +2 -2
  15. package/package.json +4 -4
  16. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  17. package/skills/pi-subagents/references/execution-controls.md +5 -4
  18. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  19. package/skills/pi-subagents/references/prompting-and-roles.md +31 -15
  20. package/src/agents/agent-serializer.ts +2 -0
  21. package/src/agents/agents.ts +46 -15
  22. package/src/api/external-runs.ts +174 -84
  23. package/src/api/preflight.ts +13 -7
  24. package/src/extension/config.ts +59 -0
  25. package/src/extension/doctor.ts +40 -0
  26. package/src/extension/index.ts +83 -9
  27. package/src/extension/public-execution.ts +37 -4
  28. package/src/extension/rpc.ts +8 -10
  29. package/src/extension/schemas.ts +12 -10
  30. package/src/extension/tool-description.ts +13 -9
  31. package/src/inspectors/herdr/actions.ts +13 -8
  32. package/src/inspectors/herdr/inspector-runner.ts +16 -3
  33. package/src/inspectors/herdr/project-panes.ts +2 -6
  34. package/src/inspectors/herdr/shell-command.ts +16 -0
  35. package/src/intercom/intercom-bridge.ts +9 -5
  36. package/src/intercom/native-supervisor-channel.ts +19 -42
  37. package/src/missions/goal-driver.ts +3 -1
  38. package/src/missions/lifecycle.ts +4 -7
  39. package/src/missions/store.ts +12 -7
  40. package/src/missions/workflow-state.ts +6 -2
  41. package/src/runs/background/active-async-capacity.ts +431 -0
  42. package/src/runs/background/active-run-index.ts +77 -3
  43. package/src/runs/background/async-execution.ts +190 -72
  44. package/src/runs/background/async-job-tracker.ts +5 -0
  45. package/src/runs/background/async-resume.ts +21 -7
  46. package/src/runs/background/async-status-snapshot.ts +277 -0
  47. package/src/runs/background/async-status.ts +17 -6
  48. package/src/runs/background/chain-append.ts +33 -15
  49. package/src/runs/background/chain-root-attachment.ts +2 -2
  50. package/src/runs/background/completion-replay.ts +11 -1
  51. package/src/runs/background/fleet-view.ts +21 -6
  52. package/src/runs/background/owned-process-tree.ts +104 -0
  53. package/src/runs/background/process-terminal.ts +17 -3
  54. package/src/runs/background/result-files.ts +437 -0
  55. package/src/runs/background/result-watcher.ts +188 -41
  56. package/src/runs/background/resume-guidance.ts +27 -7
  57. package/src/runs/background/retained-children.ts +75 -18
  58. package/src/runs/background/run-id-resolver.ts +30 -24
  59. package/src/runs/background/run-status.ts +106 -5
  60. package/src/runs/background/scheduled-runs.ts +54 -28
  61. package/src/runs/background/stale-run-reconciler.ts +30 -16
  62. package/src/runs/background/subagent-runner.ts +352 -62
  63. package/src/runs/background/subagent-wait.ts +2 -0
  64. package/src/runs/background/wait-completions.ts +5 -2
  65. package/src/runs/foreground/async-dismiss-action.ts +2 -1
  66. package/src/runs/foreground/chain-execution.ts +53 -2
  67. package/src/runs/foreground/execution.ts +309 -34
  68. package/src/runs/foreground/foreground-control.ts +12 -0
  69. package/src/runs/foreground/prompt-audit.ts +172 -0
  70. package/src/runs/foreground/subagent-executor.ts +936 -224
  71. package/src/runs/shared/acceptance.ts +13 -4
  72. package/src/runs/shared/completion-guard.ts +107 -1
  73. package/src/runs/shared/external-cli-runner.ts +4 -0
  74. package/src/runs/shared/llm-intent-arbiter.ts +302 -0
  75. package/src/runs/shared/model-fallback.ts +16 -2
  76. package/src/runs/shared/nested-events.ts +66 -62
  77. package/src/runs/shared/orca-progress-tabs.ts +375 -0
  78. package/src/runs/shared/parallel-utils.ts +4 -0
  79. package/src/runs/shared/pi-args.ts +44 -1
  80. package/src/runs/shared/run-fanout-budget.ts +280 -0
  81. package/src/runs/shared/single-output.ts +4 -2
  82. package/src/runs/shared/subagent-control.ts +15 -0
  83. package/src/runs/shared/subagent-prompt-runtime.ts +1 -9
  84. package/src/runs/shared/subagent-startup-retry.ts +12 -0
  85. package/src/runs/shared/task-intent.ts +19 -3
  86. package/src/runs/shared/tool-timeout.ts +93 -0
  87. package/src/runs/shared/worktree.ts +17 -5
  88. package/src/shared/agent-stream-options.ts +5 -0
  89. package/src/shared/artifacts.ts +2 -6
  90. package/src/shared/display-text.ts +50 -0
  91. package/src/shared/node-executable.ts +21 -0
  92. package/src/shared/types.ts +143 -5
  93. package/src/shared/utils.ts +3 -1
  94. package/src/slash/slash-commands.ts +34 -25
  95. package/src/slash/slash-live-state.ts +3 -0
  96. package/src/tui/fleet-status.ts +164 -47
  97. package/src/tui/fleet-transcript.ts +1 -48
  98. package/src/tui/fleet.ts +352 -27
  99. package/src/tui/render.ts +122 -44
  100. package/src/watchdog/permission-arbiter.ts +2 -1
  101. package/src/watchdog/review.ts +4 -3
  102. package/src/workflows/chat-progress.ts +10 -2
  103. package/src/workflows/scripted-workflow.ts +292 -79
@@ -30,6 +30,8 @@ import { SubagentFleetStatus, resolveFleetViewPlacement } from "../tui/fleet-sta
30
30
  import { createSubagentParamsSchema } from "./schemas.ts";
31
31
  import { createSubagentExecutor, type SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
32
32
  import { createAsyncJobTracker } from "../runs/background/async-job-tracker.ts";
33
+ import { getActiveAsyncCapacitySnapshot, resolveMaxActiveAsyncRunsPerSession } from "../runs/background/active-async-capacity.ts";
34
+ import { cleanupResultIndexes } from "../runs/background/result-files.ts";
33
35
  import { createResultWatcher } from "../runs/background/result-watcher.ts";
34
36
  import { createScheduledRunManager } from "../runs/background/scheduled-runs.ts";
35
37
  import { registerSlashCommands } from "../slash/slash-commands.ts";
@@ -58,6 +60,7 @@ import { resolveMissionStoreLocation } from "../missions/store.ts";
58
60
  import { listRetainedChildren } from "../runs/background/retained-children.ts";
59
61
  import {
60
62
  type Details,
63
+ type MainWindowRendererConfig,
61
64
  type SubagentState,
62
65
  DIRS,
63
66
  DEFAULT_ARTIFACT_CONFIG,
@@ -65,6 +68,7 @@ import {
65
68
  SLASH_TEXT_RESULT_TYPE,
66
69
  SUBAGENT_ASYNC_COMPLETE_EVENT,
67
70
  SUBAGENT_ASYNC_STARTED_EVENT,
71
+ SUBAGENT_PROCESS_TERMINAL_EVENT,
68
72
  SUBAGENT_CONTROL_EVENT,
69
73
  SUBAGENT_STEERING_NOTICE_EVENT,
70
74
  WIDGET_KEY,
@@ -79,6 +83,13 @@ import {
79
83
 
80
84
  export { loadConfig, resolveAsyncByDefault } from "./config.ts";
81
85
 
86
+ const SLOW_RELOAD_PHASE_MS = 250;
87
+
88
+ function logSlowPhase(label: string, startedAt: number): void {
89
+ const elapsed = Date.now() - startedAt;
90
+ if (elapsed >= SLOW_RELOAD_PHASE_MS) console.error(`Subagent reload phase '${label}' took ${elapsed}ms.`);
91
+ }
92
+
82
93
  function workflowLaneKeys(script: string): string[] {
83
94
  const keys: string[] = [];
84
95
  const seen = new Set<string>();
@@ -251,12 +262,14 @@ function rebuildSlashResultContainer(
251
262
  result: AgentToolResult<Details>,
252
263
  options: { expanded: boolean },
253
264
  theme: ExtensionContext["ui"]["theme"],
265
+ rendererConfig?: MainWindowRendererConfig,
266
+ foregroundDetachShortcut?: string,
254
267
  ): void {
255
268
  container.clear();
256
269
  container.addChild(new Spacer(1));
257
270
  const boxTheme = isSlashResultRunning(result) ? "toolPendingBg" : isSlashResultError(result) ? "toolErrorBg" : "toolSuccessBg";
258
271
  const box = new Box(1, 1, (text: string) => theme.bg(boxTheme, text));
259
- box.addChild(renderSubagentResult(result, options, theme));
272
+ box.addChild(renderSubagentResult(result, options, theme, undefined, rendererConfig, foregroundDetachShortcut));
260
273
  container.addChild(box);
261
274
  }
262
275
 
@@ -264,6 +277,8 @@ function createSlashResultComponent(
264
277
  details: SlashMessageDetails,
265
278
  options: { expanded: boolean },
266
279
  theme: ExtensionContext["ui"]["theme"],
280
+ rendererConfig?: MainWindowRendererConfig,
281
+ foregroundDetachShortcut?: string,
267
282
  ): Container {
268
283
  const container = new Container();
269
284
  let lastVersion = -1;
@@ -271,7 +286,7 @@ function createSlashResultComponent(
271
286
  const snapshot = getSlashRenderableSnapshot(details);
272
287
  if (snapshot.version !== lastVersion || isSlashResultRunning(snapshot.result)) {
273
288
  lastVersion = snapshot.version;
274
- rebuildSlashResultContainer(container, snapshot.result, options, theme);
289
+ rebuildSlashResultContainer(container, snapshot.result, options, theme, rendererConfig, foregroundDetachShortcut);
275
290
  }
276
291
  return Container.prototype.render.call(container, width);
277
292
  };
@@ -368,6 +383,14 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
368
383
  const tempArtifactsDir = getArtifactsDir(null);
369
384
  const artifactCleanupDays = config.artifactConfig?.cleanupDays ?? DEFAULT_ARTIFACT_CONFIG.cleanupDays;
370
385
  cleanupAllArtifactDirs(artifactCleanupDays);
386
+ const resultIndexCleanupTimer = setTimeout(() => {
387
+ try {
388
+ cleanupResultIndexes(DIRS.results);
389
+ } catch (error) {
390
+ console.error("Failed to clean stale subagent result indexes:", error);
391
+ }
392
+ }, 30_000);
393
+ resultIndexCleanupTimer.unref?.();
371
394
 
372
395
  const state: SubagentState = {
373
396
  baseCwd: "",
@@ -376,6 +399,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
376
399
  ...(config.authorityPolicy ? { authorityPolicy: config.authorityPolicy } : {}),
377
400
  ...(config.missions ? { missionStoreConfig: config.missions } : {}),
378
401
  parentSessionFile: null,
402
+ trustedSessionRoots: [],
379
403
  subagentInProgress: false,
380
404
  subagentSpawns: {
381
405
  sessionId: null,
@@ -384,6 +408,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
384
408
  granted: 0,
385
409
  grantHistory: [],
386
410
  },
411
+ activeAsyncCapacity: { used: 0, limit: resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession) ?? 0 },
387
412
  asyncJobs: new Map(),
388
413
  fleetJobs: new Map(),
389
414
  foregroundRuns: new Map(),
@@ -448,6 +473,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
448
473
  );
449
474
 
450
475
  const runtimeCleanup = () => {
476
+ clearTimeout(resultIndexCleanupTimer);
451
477
  stopResultWatcher();
452
478
  state.currentSessionId = null;
453
479
  completionNotifier.dispose();
@@ -478,7 +504,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
478
504
  pi.registerMessageRenderer<SlashMessageDetails>(SLASH_RESULT_TYPE, (message, options, theme) => {
479
505
  const details = resolveSlashMessageDetails(message.details);
480
506
  if (!details) return undefined;
481
- return createSlashResultComponent(details, options, theme);
507
+ return createSlashResultComponent(details, options, theme, config.mainWindowRenderer, config.foregroundDetachShortcut);
482
508
  });
483
509
 
484
510
  pi.registerMessageRenderer<undefined>(SLASH_TEXT_RESULT_TYPE, (message, _options, _theme) => {
@@ -578,22 +604,24 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
578
604
  },
579
605
 
580
606
  renderCall(args, theme) {
607
+ const gap = " ".repeat(config.mainWindowRenderer?.horizontalSpacing ?? 1);
608
+ const title = theme.fg("toolTitle", theme.bold("subagent"));
581
609
  if (args.action) {
582
610
  const target = args.agent || args.chainName || "";
583
611
  return new Text(
584
- `${theme.fg("toolTitle", theme.bold("subagent "))}${args.action}${target ? ` ${theme.fg("accent", target)}` : ""}`,
612
+ `${title}${gap}${args.action}${target ? `${gap}${theme.fg("accent", target)}` : ""}`,
585
613
  0, 0,
586
614
  );
587
615
  }
588
616
  if (args.workflowScript)
589
617
  return new Text(
590
- `${theme.fg("toolTitle", theme.bold("subagent "))}${formatWorkflowManifest(args.workflowScript, args.async, false)}`,
618
+ `${title}${gap}${formatWorkflowManifest(args.workflowScript, args.async, false)}`,
591
619
  0,
592
620
  0,
593
621
  );
594
- const asyncLabel = args.async === true ? theme.fg("warning", " [async]") : "";
622
+ const asyncLabel = args.async === true ? `${gap}${theme.fg("warning", "[async]")}` : "";
595
623
  return new Text(
596
- `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", args.agent || "?")}${asyncLabel}`,
624
+ `${title}${gap}${theme.fg("accent", args.agent || "?")}${asyncLabel}`,
597
625
  0,
598
626
  0,
599
627
  );
@@ -604,7 +632,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
604
632
  const renderedResult = { ...result, isError: context.isError };
605
633
  return summaryInlineToolDisplay
606
634
  ? renderSubagentSummary(renderedResult, options, theme)
607
- : renderSubagentResult(renderedResult, options, theme);
635
+ : renderSubagentResult(renderedResult, options, theme, undefined, config.mainWindowRenderer, config.foregroundDetachShortcut);
608
636
  },
609
637
 
610
638
  };
@@ -634,7 +662,10 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
634
662
  }
635
663
  });
636
664
 
637
- registerSlashCommands(pi, state, { fleetKeybindings: config.fleetKeybindings });
665
+ registerSlashCommands(pi, state, {
666
+ fleetKeybindings: config.fleetKeybindings,
667
+ foregroundDetachShortcut: config.foregroundDetachShortcut,
668
+ });
638
669
 
639
670
  const eventUnsubscribeStoreKey = "__piSubagentEventUnsubscribes";
640
671
  const controlNoticeSeenStoreKey = "__piSubagentVisibleControlNotices";
@@ -677,12 +708,17 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
677
708
  };
678
709
  const asyncCompleteHandler = (payload: unknown) => {
679
710
  handleComplete(payload);
711
+ refreshActiveAsyncCapacity();
680
712
  scheduledRunManager.handleAsyncCompletion(payload);
681
713
  fleetStatus?.refresh();
682
714
  };
683
715
  const eventUnsubscribes = [
684
716
  pi.events.on(SUBAGENT_ASYNC_STARTED_EVENT, asyncStartedHandler),
685
717
  pi.events.on(SUBAGENT_ASYNC_COMPLETE_EVENT, asyncCompleteHandler),
718
+ pi.events.on(SUBAGENT_PROCESS_TERMINAL_EVENT, () => {
719
+ refreshActiveAsyncCapacity();
720
+ fleetStatus?.refresh();
721
+ }),
686
722
  pi.events.on(SUBAGENT_CONTROL_EVENT, controlEventHandler),
687
723
  pi.events.on(SUBAGENT_STEERING_NOTICE_EVENT, steeringNoticeHandler),
688
724
  herdrStatusBridge.dispose,
@@ -728,12 +764,28 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
728
764
  fleetStatus?.refresh();
729
765
  };
730
766
 
767
+ const refreshActiveAsyncCapacity = () => {
768
+ if (!state.currentSessionId) {
769
+ state.activeAsyncCapacity = { used: 0, limit: resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession) ?? 0 };
770
+ return;
771
+ }
772
+ state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(
773
+ state.currentSessionId,
774
+ resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession),
775
+ { liveWorkflowRunIds: new Set(state.workflowControllers?.keys() ?? []) },
776
+ );
777
+ };
778
+
731
779
  const resetSessionState = (ctx: ExtensionContext, recovering: boolean) => {
732
780
  state.widgetsSuspended = false;
733
781
  state.baseCwd = ctx.cwd;
734
782
  goalTurnId = 0;
735
783
  state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
736
784
  state.parentSessionFile = ctx.sessionManager.getSessionFile();
785
+ state.trustedSessionRoots = [...new Set([
786
+ ...(config.defaultSessionDir ? [path.resolve(expandTilde(config.defaultSessionDir))] : []),
787
+ ...(state.parentSessionFile ? [getSubagentSessionRoot(state.parentSessionFile)] : []),
788
+ ])];
737
789
  state.subagentSpawns = {
738
790
  sessionId: state.currentSessionId,
739
791
  count: 0,
@@ -753,17 +805,38 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
753
805
  }
754
806
  }
755
807
  state.lastUiContext = ctx;
808
+ let phaseStartedAt = Date.now();
809
+ refreshActiveAsyncCapacity();
810
+ logSlowPhase("active-capacity", phaseStartedAt);
811
+ phaseStartedAt = Date.now();
756
812
  cleanupSessionArtifacts(ctx);
813
+ logSlowPhase("session-artifact-cleanup", phaseStartedAt);
757
814
  state.foregroundControls.clear();
758
815
  state.lastForegroundControlId = null;
816
+ phaseStartedAt = Date.now();
759
817
  resetJobs(ctx);
818
+ logSlowPhase("reset-jobs", phaseStartedAt);
819
+ phaseStartedAt = Date.now();
760
820
  restoreForegroundRunHistory(state, { resultsDir: DIRS.results });
821
+ logSlowPhase("foreground-history", phaseStartedAt);
822
+ phaseStartedAt = Date.now();
761
823
  restoreActiveJobs(ctx);
824
+ logSlowPhase("active-job-restore", phaseStartedAt);
825
+ phaseStartedAt = Date.now();
762
826
  scheduledRunManager.bindSession(ctx);
827
+ logSlowPhase("scheduled-runs", phaseStartedAt);
828
+ phaseStartedAt = Date.now();
763
829
  restoreSlashFinalSnapshots(ctx.sessionManager.getEntries());
830
+ logSlowPhase("slash-snapshots", phaseStartedAt);
831
+ phaseStartedAt = Date.now();
764
832
  waitSubscriptionManager.restore();
833
+ logSlowPhase("wait-subscriptions", phaseStartedAt);
834
+ phaseStartedAt = Date.now();
765
835
  startResultWatcher();
836
+ logSlowPhase("result-watcher-start", phaseStartedAt);
837
+ phaseStartedAt = Date.now();
766
838
  primeExistingResults({ triggerTurn: !recovering });
839
+ logSlowPhase("result-prime", phaseStartedAt);
767
840
  fleetStatus?.setContext(ctx);
768
841
  };
769
842
 
@@ -806,6 +879,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
806
879
 
807
880
  pi.on("session_shutdown", async () => {
808
881
  state.widgetsSuspended = false;
882
+ clearTimeout(resultIndexCleanupTimer);
809
883
  stopResultWatcher();
810
884
  state.currentSessionId = null;
811
885
  state.parentSessionFile = null;
@@ -9,8 +9,11 @@ export interface PublicSubagentExecutionParams {
9
9
  concurrency?: unknown;
10
10
  chainDir?: unknown;
11
11
  workflowScript?: unknown;
12
+ output?: unknown;
12
13
  resume?: unknown;
13
14
  clarify?: unknown;
15
+ runFanoutBudget?: unknown;
16
+ runFanoutAdmitted?: unknown;
14
17
  }
15
18
 
16
19
  export type PublicSubagentExecutionMode = "workflow" | "management";
@@ -24,6 +27,9 @@ export type PublicSubagentExecutionNormalization<T> =
24
27
  * Internal runs.run children and structured owned delegation bypass this boundary.
25
28
  */
26
29
  export function normalizePublicSubagentExecution<T extends PublicSubagentExecutionParams>(params: T): PublicSubagentExecutionNormalization<T> {
30
+ if (params.runFanoutBudget !== undefined || params.runFanoutAdmitted !== undefined) {
31
+ return { ok: false, error: "Public execution does not accept internal run fan-out fields.", mode: params.workflowScript !== undefined ? "workflow" : "management" };
32
+ }
27
33
  const action = params.action;
28
34
  if (action !== undefined && (typeof action !== "string" || !action.trim())) {
29
35
  return { ok: false, error: "action must be a non-empty management/control action, or omit action and use workflowScript.", mode: "management" };
@@ -42,7 +48,7 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
42
48
  if (normalizedAction !== undefined) {
43
49
  const legacyAction = normalizedAction.toLowerCase();
44
50
  if (legacyAction === "single") {
45
- return { ok: false, error: "Direct execution was removed. Use workflowScript: \"return runs.run('main', { agent, task })\".", mode: "workflow" };
51
+ return { ok: false, error: "action='single' is not supported. Omit action and pass { agent, task } for one child.", mode: "workflow" };
46
52
  }
47
53
  if (legacyAction === "parallel" || legacyAction === "tasks" || legacyAction === "chain") {
48
54
  return { ok: false, error: "Legacy top-level chain and parallel inputs were removed; use workflowScript.", mode: "workflow" };
@@ -59,13 +65,40 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
59
65
  if (params.workflowScript !== undefined) {
60
66
  return { ok: false, error: "workflowScript execution must omit action; only schedule.create accepts action with workflowScript.", mode: "management" };
61
67
  }
68
+ if (params.task !== undefined) {
69
+ return { ok: false, error: "Structured single-child task cannot be combined with a management/control action.", mode: "management" };
70
+ }
62
71
  return { ok: true, params: { ...params, action: normalizedAction } };
63
72
  }
64
- if (params.agent !== undefined || params.task !== undefined || params.step !== undefined) {
65
- return { ok: false, error: "Direct execution was removed. Use workflowScript: \"return runs.run('main', { agent, task })\".", mode: "workflow" };
73
+ if (params.step !== undefined) {
74
+ return { ok: false, error: "step is only available with action='append-step'; it is not an execution mode.", mode: "workflow" };
75
+ }
76
+ if (params.workflowScript !== undefined && (params.agent !== undefined || params.task !== undefined)) {
77
+ return { ok: false, error: "Structured single-child execution cannot be combined with workflowScript.", mode: "workflow" };
78
+ }
79
+ if (params.agent !== undefined || params.task !== undefined) {
80
+ if (typeof params.agent !== "string" || !params.agent.trim()) {
81
+ return { ok: false, error: "Structured single-child execution requires agent to be a non-empty string.", mode: "workflow" };
82
+ }
83
+ if (params.task !== undefined && typeof params.task !== "string") {
84
+ return { ok: false, error: "Structured single-child task must be a string when provided.", mode: "workflow" };
85
+ }
86
+ const { agent: _agent, task: _task, output, ...workflowDefaults } = params;
87
+ const child = {
88
+ agent: params.agent.trim(),
89
+ ...(params.task !== undefined ? { task: params.task } : {}),
90
+ output: output === undefined ? true : output,
91
+ };
92
+ return {
93
+ ok: true,
94
+ params: {
95
+ ...workflowDefaults,
96
+ workflowScript: `console.info("Converted structured single-child request to workflow runs.run('main', ...)."); return runs.run("main", ${JSON.stringify(child)})`,
97
+ } as T,
98
+ };
66
99
  }
67
100
  if (typeof params.workflowScript !== "string" || !params.workflowScript.trim()) {
68
- return { ok: false, error: "Execution requires a non-empty workflowScript. Direct execution was removed; use workflowScript: \"return runs.run('main', { agent, task })\".", mode: "workflow" };
101
+ return { ok: false, error: "Execution requires either { agent, task? } for one child or a non-empty workflowScript for orchestration.", mode: "workflow" };
69
102
  }
70
103
  return { ok: true, params };
71
104
  }
@@ -19,8 +19,8 @@ import {
19
19
  import { sanitizeDisplayText, truncateDisplayText } from "../shared/display-text.ts";
20
20
  import { readStatus } from "../shared/utils.ts";
21
21
  import { SubagentParams } from "./schemas.ts";
22
- import { formatWorkflowJsonPreview } from "../workflows/scripted-workflow.ts";
23
22
  import { normalizePublicSubagentExecution } from "./public-execution.ts";
23
+ import { ASYNC_STATUS_SNAPSHOT_KIND, ASYNC_STATUS_SNAPSHOT_VERSION, buildAsyncStatusSnapshotForState } from "../runs/background/async-status-snapshot.ts";
24
24
 
25
25
  export const SUBAGENT_RPC_PROTOCOL_VERSION = 1;
26
26
  export const SUBAGENT_RPC_REQUEST_EVENT = "subagents:rpc:v1:request";
@@ -91,6 +91,7 @@ export interface SubagentRpcFleetStatus {
91
91
  entries: SubagentRpcFleetEntry[];
92
92
  /** Total active children before the bounded entries window. */
93
93
  totalActive: number;
94
+ topLevelAsyncCapacity: { used: number; limit: number };
94
95
  omitted: number;
95
96
  }
96
97
 
@@ -154,7 +155,7 @@ function buildFleetStatus(
154
155
  }
155
156
  if (!state || !authoritativeSessionId || state.currentSessionId !== authoritativeSessionId) {
156
157
  keyState.keys.clear();
157
- return { version: 1, entries: [], totalActive: 0, omitted: 0 };
158
+ return { version: 1, entries: [], totalActive: 0, topLevelAsyncCapacity: { used: 0, limit: 0 }, omitted: 0 };
158
159
  }
159
160
 
160
161
  let totalActive = 0;
@@ -173,7 +174,6 @@ function buildFleetStatus(
173
174
  effort: child.thinking,
174
175
  startedAt: child.startedAt,
175
176
  tokens: { input: child.inputTokens ?? 0, output: child.outputTokens ?? 0, total: child.tokens ?? 0 },
176
- goal: child.description ?? control.description,
177
177
  });
178
178
  } else {
179
179
  addCandidate({
@@ -183,7 +183,6 @@ function buildFleetStatus(
183
183
  effort: control.thinking,
184
184
  startedAt: control.startedAt,
185
185
  tokens: { input: control.inputTokens ?? 0, output: control.outputTokens ?? 0, total: control.tokens ?? 0 },
186
- goal: control.description,
187
186
  });
188
187
  }
189
188
  }
@@ -191,13 +190,11 @@ function buildFleetStatus(
191
190
  if (job.sessionId !== authoritativeSessionId || !activeState(job.status)) continue;
192
191
  const startedAt = job.startedAt ?? job.updatedAt;
193
192
  if (job.mode === "workflow") {
194
- const latestEmit = job.workflow?.emits?.length ? formatWorkflowJsonPreview(job.workflow.emits.at(-1), 120) : undefined;
195
193
  addCandidate({
196
194
  internalKey: `async:${job.asyncId}`,
197
195
  agent: "workflow",
198
196
  startedAt,
199
197
  tokens: job.totalTokens,
200
- goal: latestEmit !== undefined ? `latest emit: ${latestEmit}` : job.description,
201
198
  });
202
199
  continue;
203
200
  }
@@ -214,7 +211,6 @@ function buildFleetStatus(
214
211
  agent: job.mode ?? "subagent",
215
212
  startedAt,
216
213
  tokens: job.totalTokens,
217
- goal: job.description,
218
214
  });
219
215
  continue;
220
216
  }
@@ -230,7 +226,6 @@ function buildFleetStatus(
230
226
  effort: step.thinking,
231
227
  startedAt: step.startedAt ?? startedAt,
232
228
  tokens: step.tokens ?? (steps.length === 1 ? job.totalTokens : undefined),
233
- goal: job.description,
234
229
  });
235
230
  }
236
231
  }
@@ -271,7 +266,7 @@ function buildFleetStatus(
271
266
  if (!activeKeys.has(internalKey)) keyState.keys.delete(internalKey);
272
267
  }
273
268
  const omitted = Math.max(0, totalActive - entries.length);
274
- return { version: 1, entries, totalActive, omitted };
269
+ return { version: 1, entries, totalActive, topLevelAsyncCapacity: state.activeAsyncCapacity ?? { used: 0, limit: 0 }, omitted };
275
270
  }
276
271
 
277
272
  interface RegisterSubagentRpcBridgeOptions {
@@ -381,6 +376,7 @@ function pingData(ctx: ExtensionContext | null) {
381
376
  capabilities: {
382
377
  status: true,
383
378
  fleetStatus: { version: 1 },
379
+ asyncStatusSnapshot: { kind: ASYNC_STATUS_SNAPSHOT_KIND, version: ASYNC_STATUS_SNAPSHOT_VERSION },
384
380
  asyncSpawn: true,
385
381
  steer: true,
386
382
  nonRecoveringSteer: true,
@@ -550,13 +546,15 @@ async function handleRequest(
550
546
  request.method,
551
547
  { action: "status", ...normalizeTargetParams(request.params, "status") },
552
548
  );
549
+ const sessionId = resolveCurrentSessionId(ctx.sessionManager);
553
550
  return {
554
551
  ...status,
555
552
  fleet: buildFleetStatus(
556
553
  options.state,
557
554
  fleetKeys,
558
- resolveCurrentSessionId(ctx.sessionManager),
555
+ sessionId,
559
556
  ),
557
+ asyncSnapshot: buildAsyncStatusSnapshotForState(options.state, sessionId),
560
558
  };
561
559
  }
562
560
  if (request.method === "steer") {
@@ -93,7 +93,7 @@ const AcceptanceOverride = Type.Unsafe({
93
93
  });
94
94
 
95
95
  const AgentContractOverride = Type.Object({
96
- version: Type.Integer({ enum: [1], description: "Enable compatibility behavior for this run/child." }),
96
+ version: Type.Integer({ minimum: 1, maximum: 1, description: "Enable compatibility behavior for this run/child." }),
97
97
  }, { additionalProperties: false, description: "Compatibility behavior. Omit for the default behavior." });
98
98
 
99
99
  const ChainGateOverride = Type.String({
@@ -255,21 +255,22 @@ const ControlOverrides = Type.Object({
255
255
  });
256
256
 
257
257
  const SubagentParamProperties = {
258
- agent: Type.Optional(Type.String({ description: "Agent target for management actions such as get, update, delete, and models." })),
258
+ agent: Type.Optional(Type.String({ description: "Agent for one-child execution, or target for agent management actions." })),
259
+ task: Type.Optional(Type.String({ description: "Optional one-child task. Requires agent; cannot combine with action or workflowScript." })),
259
260
  resume: Type.Optional(Type.String({ description: "Retained child run id for a workflowScript runs.run/runs.all item. Mutually exclusive with agent; task supplies the follow-up." })),
260
261
  // Management action (when present, tool operates in management mode)
261
262
  action: Type.Optional(Type.String({ minLength: 1,
262
- description: "Optional management/control action. Omit this field for workflowScript execution; use it only for management/control actions."
263
+ description: "Optional management/control action. Omit this field for structured single-child or workflowScript execution; use it only for management/control actions."
263
264
  })),
264
265
  name: Type.Optional(Type.String({ description: "Human-readable name for action='schedule.create'." })),
265
266
  id: Type.Optional(Type.String({
266
- description: "Run id or prefix for status, interrupt, stop, dismiss, resume, steer, append-step, approve-checkpoint, reject-checkpoint, mission.attach-run, or the decision id for mission.resolve-decision."
267
+ description: "Run id/prefix for status/debug.run, interrupt, steer, append-step, approve-checkpoint, reject-checkpoint, or mission."
267
268
  })),
268
269
  runId: Type.Optional(Type.String({
269
- description: "Target run ID for interrupt, stop, dismiss, resume, steer, append-step, approve-checkpoint, reject-checkpoint, or mission.attach-run. Prefer id for new calls."
270
+ description: "Target run ID for debug.run, interrupt, steer, append-step, or mission.attach-run. Prefer id."
270
271
  })),
271
272
  dir: Type.Optional(Type.String({
272
- description: "Async run directory for action='status', action='stop', action='resume', or action='steer'."
273
+ description: "Async run directory for status/debug.run, stop, resume, or steer."
273
274
  })),
274
275
  handoffPath: Type.Optional(Type.String({ description: "worktree.discard manifest." })),
275
276
  index: Type.Optional(Type.Integer({ minimum: 0, description: "Zero-based child index for actions that target a specific child or transcript." })),
@@ -324,8 +325,9 @@ const SubagentParamProperties = {
324
325
  description: "'fresh' or 'fork' to branch from parent session. Explicit context overrides every child in the invocation. If omitted, each requested agent uses its own defaultContext; agents without defaultContext: 'fork' run fresh.",
325
326
  })),
326
327
  async: Type.Optional(Type.Boolean({ description: "Run in background (default: false, or per config)" })),
327
- timeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "Run timeout. Foreground runs and async children default to 30m; async composites have no default parent deadline. Alias maxRuntimeMs." })),
328
- maxRuntimeMs: Type.Optional(Type.Integer({ minimum: 1, description: "Alias timeoutMs. Foreground runs and async children default to 30m; async composites have no default parent deadline." })),
328
+ timeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "Timeout. Foreground and single async runs use config timeoutMs, else 30m; async composites have no default parent deadline. Alias maxRuntimeMs." })),
329
+ maxRuntimeMs: Type.Optional(Type.Integer({ minimum: 1, description: "Alias timeoutMs. Foreground and single async runs use config timeoutMs, else 30m; async composites have no default parent deadline." })),
330
+ toolTimeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "Optional hard per-tool-call timeout in milliseconds; known-fast built-in tools have a five-minute default." })),
329
331
  turnBudget: Type.Optional(TurnBudgetOverride),
330
332
  toolBudget: Type.Optional(ToolBudgetOverride),
331
333
  usageBudget: Type.Optional(UsageBudgetOverride),
@@ -359,10 +361,10 @@ const { step: _legacyChainStep, ...subagentParamPropertiesWithoutStep } = Subage
359
361
  const trimmedSubagentParamProperties = {
360
362
  ...subagentParamPropertiesWithoutStep,
361
363
  id: Type.Optional(Type.String({
362
- description: "Run id or prefix for status, interrupt, stop, resume, steer, mission.attach-run, or the decision id for mission.resolve-decision."
364
+ description: "Run id/prefix for status/debug.run, interrupt, steer, or mission.attach-run."
363
365
  })),
364
366
  runId: Type.Optional(Type.String({
365
- description: "Target run ID for interrupt, stop, resume, steer, or mission.attach-run. Prefer id for new calls."
367
+ description: "Target run ID for debug.run, interrupt, steer, or mission.attach-run. Prefer id."
366
368
  })),
367
369
  };
368
370
  const SubagentParamsSchema = Type.Object(SubagentParamProperties);
@@ -8,24 +8,26 @@ const CUSTOM_TOOL_DESCRIPTION_MAX_BYTES = 50 * 1024;
8
8
 
9
9
  export const SUBAGENT_SAFETY_GUIDANCE = `SAFETY-CRITICAL SUBAGENT GUIDANCE:
10
10
  • Use { action: "list" } before execution and only run executable/non-disabled agents.
11
- • Keep execution and management separate: omit action for workflowScript execution; use action only for management/control.
12
- • Async/background runs are the default. Use async:false only when a blocking foreground result is needed. Do not sleep or poll status just to wait; use subagent_wait only when the current request must finish in this turn.
11
+ • Keep execution and management separate: omit action for structured single-child or workflowScript execution; use action only for management/control.
12
+ • Async/background runs are the default. Use async:false only when a blocking foreground result is needed. After an async launch, continue independent work only until its next dependency barrier; consume the result before work that depends on it. Do not sleep or poll status just to wait; use subagent_wait only when the current request must finish in this turn.
13
13
  • Ordinary child subagents are not orchestrators. Only explicitly configured fanout children may use the child-safe subagent tool, still bounded by depth/session limits.
14
+ • Oracle/advisor consultations should use supervisor dialogue for material unknowns when available; request one-shot only when desired.
14
15
  • Keep one writer for the same cwd/worktree. Use fresh-context read-only reviewers for independent review, then have the parent synthesize and apply fixes.
15
- • Async runs expose asyncId/asyncDir with status.json, events.jsonl, output logs, and status via { action: "status", id }. Include output paths and residual risks when reporting results.`;
16
+ • Async runs expose asyncId/asyncDir with status.json, events.jsonl, output logs, status via { action: "status", id }, and lifecycle diagnostics via { action: "debug.run", id }. Include output paths and residual risks when reporting results.`;
16
17
 
17
- export const FULL_SUBAGENT_TOOL_DESCRIPTION = `Run subagents only through { workflowScript }; omit action. Use action only for management/control actions.
18
+ export const FULL_SUBAGENT_TOOL_DESCRIPTION = `Run one child with { agent, task? }; use { workflowScript } for orchestration. Omit action for execution. Use action only for management/control actions.
18
19
 
19
20
  EXECUTION:
20
21
  • Before executing, use { action: "list" } and run only executable/non-disabled configured agents.
21
- • WORKFLOW SCRIPT: { workflowScript: "return runs.run('main', {agent:'worker', task:'...'})" }. Every execution is a workflow. Use stable-key runs.run for one child and runs.all for parallel children; ordinary JavaScript provides sequence, branching, filtering, retries, and aggregation. workflowScript is an ordinary JavaScript statement body, so use an explicit return for a useful result. For task text with Markdown fences or shell blocks, build quoted lines instead of nesting raw template literals: \`const task=["Run:","\`\`\`bash","npm test","\`\`\`"].join("\\n")\`. Scripts start asynchronously by default; pass async:false only for a small foreground run. Same-repo foreground workflows default to a live in-chat card; set chatProgress to auto, off, or live-card to control that projection. Workflow-level child controls default onto each runs.run launch, and explicit child fields override them. Use await prompts.render("package:name" | "user:name" | "project:name", vars?) for reusable plain task text, then pass the result explicitly as task. Use {action:"children.list"} to list up to 10 completed retained children from this parent session, then continue one with runs.run(key, {resume:"run-id", task:"follow-up"}); resume and agent are mutually exclusive, resume keeps the stored agent/model/tool contract, workflow resumes wait for completed output, and loops must continue from each latest returned runId. For repository mutation lanes, set worktree:true on the workflow or individual runs.run/runs.all item for managed isolation; each parallel child gets a separate worktree and handoff artifact. A workflow usageBudget is enforced once across the workflow. Available globals are runs.run, runs.all, runs.status, runs.ref/refs, prompts.render, emit, console, and standard JavaScript only. Workflows get async state.get(key) and state.set(key, JSONValue) through their automatic or explicit mission; mission:false workflows do not have a state global. Scripts cannot access filesystem, shell, arbitrary Pi tools, or host globals.
22
+ • SINGLE CHILD: { agent:"worker", task:"..." }. This structured form starts exactly one child through the workflow runtime. Workflow-level fields such as model, context, cwd, worktree, output, budgets, acceptance, and async remain defaults for that child. Do not combine agent/task with action or workflowScript.
23
+ • WORKFLOW SCRIPT: { workflowScript: "return runs.run('main', {agent:'worker', task:'...'})" }. Use stable-key runs.run for one child and runs.all for parallel children; ordinary JavaScript provides sequence, branching, filtering, retries, and aggregation. workflowScript is an ordinary JavaScript statement body, so use an explicit return for a useful result. For task text with Markdown fences or shell blocks, build quoted lines instead of nesting raw template literals: \`const task=["Run:","\`\`\`bash","npm test","\`\`\`"].join("\\n")\`. Scripts start asynchronously by default; pass async:false only for a small foreground run. Same-repo foreground workflows default to a live in-chat card; set chatProgress to auto, off, or live-card to control that projection. Workflow-level child controls default onto each runs.run launch, and explicit child fields override them. Use await prompts.render("package:name" | "user:name" | "project:name", vars?) for reusable plain task text, then pass the result explicitly as task. Use {action:"children.list"} to list recent retained workflow children with resumable/not-resumable reasons. Resume only rows reported resumable. For a simple follow-up or implementation challenge, use {action:"resume", id:"run-id", message:"..."}. Resume keeps the stored agent/model/tool contract. If no resumable child is listed, launch a same-role fallback challenge and label it as fallback. Inside workflowScript, continue one with runs.run(key, {resume:"run-id", task:"follow-up"}); workflow resumes wait for completed output, and loops must continue from each latest returned runId. For repository mutation lanes, set worktree:true on the workflow or individual runs.run/runs.all item for managed isolation; each parallel child gets a separate worktree and handoff artifact. A workflow usageBudget is enforced once across the workflow. Available globals are runs.run, runs.all, runs.status, runs.ref/refs, prompts.render, emit, console, and standard JavaScript only. Workflows get async state.get(key) and state.set(key, JSONValue) through their automatic or explicit mission; mission:false workflows do not have a state global. Scripts cannot access filesystem, shell, arbitrary Pi tools, or host globals.
22
24
  • Sequential example: { workflowScript: "const a = await runs.run('analyze', {agent:'agent-a', task:'Analyze the request'}); return (await runs.run('plan', {agent:'agent-b', task:'Plan from: '+a.output})).output" }
23
25
  • Parallel example: { workflowScript: "const [a,b] = await runs.all([{key:'correctness',agent:'agent-a',task:'Review correctness'},{key:'tests',agent:'agent-b',task:'Review tests'}]); return {correctness:a.output,tests:b.output}" }
24
26
  • Optional context is "fresh" or "fork". timeoutMs/maxRuntimeMs apply to foreground and async workflows; foreground workflows default to 30 minutes and async workflows have no default timeout. Omit acceptance for reviewer/read-only calls; evidence levels end at verified, and acceptance.review.required requests independent writer review.
25
27
  • Durable mission attachment is automatic by default. Use missionId to attach an existing mission, mission:{...} to override auto-create, or mission:false for ephemeral work. A mission object needs exactly one non-empty title or summary; objective and labels are optional. goal may only be true and requires budget:{tokens}.
26
28
 
27
29
  MANAGEMENT / CONTROL (use action; omit execution fields):
28
- • list, get, models, guide, children.list, create, update, delete, eject, disable, enable, reset, doctor, grant-spawn-budget, worktree.discard, refine/refine.show/refine.rollback, mission.create/list/show/update/resolve-decision/attach-run/close, inspector.open/status/close, project.open/status/close, and watchdog actions remain available. Use {action:"guide", topic:"overview"} for packaged current-version help; topics are overview, workflows, agents, missions, observability, tool-reference, configuration, models, watchdog, and extension-api.
30
+ • list, get, models, guide, children.list, create, update, delete, eject, disable, enable, reset, status, debug.run, doctor, grant-spawn-budget, worktree.discard, refine/refine.show/refine.rollback, mission.create/list/show/update/resolve-decision/attach-run/close, inspector.open/status/close, project.open/status/close, and watchdog actions remain available. Use {action:"guide", topic:"overview"} for packaged current-version help; topics are overview, workflows, agents, missions, observability, tool-reference, configuration, models, watchdog, and extension-api.
29
31
  • status, interrupt, stop, resume, and steer manage live or persisted runs. Use status view:"fleet" for an overview or view:"transcript" with id and optional index to tail output.
30
32
  • { action: "append-step", id: "...", step: {agent:"agent-c", task:"Use {previous}"} } appends one step to an already-running durable legacy chain. step is control-only, not an execution mode.
31
33
  • approve-checkpoint and reject-checkpoint decide a paused durable legacy chain checkpoint.
@@ -33,11 +35,12 @@ MANAGEMENT / CONTROL (use action; omit execution fields):
33
35
 
34
36
  ${SUBAGENT_SAFETY_GUIDANCE}`;
35
37
 
36
- export const COMPACT_SUBAGENT_TOOL_DESCRIPTION = `Run subagents only through { workflowScript }; omit action. Use action only for management/control actions.
38
+ export const COMPACT_SUBAGENT_TOOL_DESCRIPTION = `Run one child with { agent, task? }; use { workflowScript } for orchestration. Omit action for execution. Use action only for management/control actions.
37
39
 
38
40
  EXECUTE:
39
41
  • Call { action:"list" } first and use only executable/non-disabled agents.
40
- • SCRIPT {workflowScript:"return runs.run('main', {agent:'worker', task:'...'})"}. Use stable-key runs.run for one child and runs.all for parallel work. Use await prompts.render("package:name" | "user:name" | "project:name", vars?) for reusable task text and pass it explicitly to runs.run. Use {action:"children.list"} for the last 10 retained children in this parent session, then runs.run(key,{resume:"run-id",task:"follow-up"}) to continue one with its stored contract; workflow resumes wait for completion and loops continue from the latest returned runId. Workflows get async state.get/state.set through their automatic or explicit mission; mission:false does not. Scripts are ordinary JavaScript statement bodies; use explicit return for a useful result. For task text with Markdown fences or shell blocks, build quoted lines instead of nesting raw template literals: \`const task=["Run:","\`\`\`bash","npm test","\`\`\`"].join("\\n")\`. Use JavaScript for sequence, branching, retries, and aggregation. For repository mutation lanes, use worktree:true on the workflow or runs.run/runs.all item for managed isolation. Scripts start async by default; async:false is the foreground escape hatch and auto-enables a same-repo live chat card unless chatProgress is off.
42
+ • SINGLE {agent:"worker",task:"..."} starts exactly one child through the workflow runtime. Workflow-level fields remain child defaults. Do not combine agent/task with action or workflowScript.
43
+ • SCRIPT {workflowScript:"return runs.run('main', {agent:'worker', task:'...'})"}. Use stable-key runs.run for one child and runs.all for parallel work. Use await prompts.render("package:name" | "user:name" | "project:name", vars?) for reusable task text and pass it explicitly to runs.run. Use {action:"children.list"} for recent retained workflow children and resume only rows reported resumable. Use {action:"resume",id:"run-id",message:"..."} for a simple follow-up or challenge; resume keeps the stored agent/model/tool contract. If none is resumable, launch a same-role fallback challenge and label it as fallback. Inside workflowScript use runs.run(key,{resume:"run-id",task:"follow-up"}) when the script must wait for completion and continue from the latest returned runId. Workflows get async state.get/state.set through their automatic or explicit mission; mission:false does not. Scripts are ordinary JavaScript statement bodies; use explicit return for a useful result. For task text with Markdown fences or shell blocks, build quoted lines instead of nesting raw template literals: \`const task=["Run:","\`\`\`bash","npm test","\`\`\`"].join("\\n")\`. Use JavaScript for sequence, branching, retries, and aggregation. For repository mutation lanes, use worktree:true on the workflow or runs.run/runs.all item for managed isolation. Scripts start async by default; async:false is the foreground escape hatch and auto-enables a same-repo live chat card unless chatProgress is off.
41
44
  • Example: {workflowScript:"const [a,b]=await runs.all([{key:'a',agent:'agent-a',task:'Implement A',worktree:true},{key:'b',agent:'agent-b',task:'Implement B',worktree:true}]); return [a.output,b.output]"}
42
45
  • context can be fresh or fork. timeoutMs/maxRuntimeMs apply to foreground and async workflows; foreground workflows default to 30 minutes and async workflows have no default timeout. Omit acceptance for reviewer/read-only calls.
43
46
 
@@ -47,8 +50,9 @@ MANAGE / CONTROL:
47
50
  • A mission object needs exactly one non-empty title or summary; objective and labels are optional. goal may only be true and requires budget:{tokens}.
48
51
 
49
52
  ASYNC / SAFETY:
50
- • Omitted async detaches background work. Do not sleep or poll merely to wait; use subagent_wait only when this turn must receive results.
53
+ • Omitted async detaches background work. Continue independent work only until its next dependency barrier; consume the result before work that depends on it. Do not sleep or poll merely to wait; use subagent_wait only when this turn must receive results.
51
54
  • Ordinary children are not orchestrators. Keep one writer per cwd/worktree and use fresh read-only reviewers for independent checks.
55
+ • Oracle/advisor consultations use available supervisor dialogue for material unknowns; request one-shot when desired.
52
56
  • Status and artifacts live under asyncId/asyncDir with status.json, events.jsonl, output logs, and {action:"status",id:"..."}.`;
53
57
 
54
58
 
@@ -10,7 +10,9 @@ import { writeAtomicJson } from "../../shared/atomic-json.ts";
10
10
  import { DIRS, type Details, type SubagentState } from "../../shared/types.ts";
11
11
  import { readStatus } from "../../shared/utils.ts";
12
12
  import { resolveSubagentRunId } from "../../runs/background/run-id-resolver.ts";
13
+ import { resolveNodeExecutable } from "../../shared/node-executable.ts";
13
14
  import { createHerdrClient, detectHerdr, type HerdrClient, type HerdrErrorCode, type HerdrResult } from "./client.ts";
15
+ import { formatShellCommand } from "./shell-command.ts";
14
16
 
15
17
  export const HERDR_INSPECTOR_ACTIONS = ["inspector.open", "inspector.status", "inspector.close"] as const;
16
18
  export type HerdrInspectorAction = typeof HERDR_INSPECTOR_ACTIONS[number];
@@ -45,6 +47,7 @@ interface InspectorDeps {
45
47
  client?: HerdrClient;
46
48
  missions?: MissionStoreConfig;
47
49
  authorityPolicy?: AuthorityPolicyConfig;
50
+ sessionRoots?: string[];
48
51
  cwd: string;
49
52
  signal?: AbortSignal;
50
53
  now?: () => Date;
@@ -84,16 +87,11 @@ function extractPaneId(value: unknown): string | undefined {
84
87
  return undefined;
85
88
  }
86
89
 
87
- function shellQuote(value: string): string {
88
- if (process.platform === "win32") return `"${value.replaceAll('"', '\\"')}"`;
89
- return `'${value.replaceAll("'", "'\\''")}'`;
90
- }
91
-
92
- function inspectorCommand(input: { runnerPath: string; asyncDir: string; runId: string; index?: number; missionPath?: string; allowSteer: boolean; allowStop: boolean }): string {
93
- const args = [process.execPath, input.runnerPath, "--async-dir", input.asyncDir, "--run-id", input.runId, "--allow-steer", String(input.allowSteer), "--allow-stop", String(input.allowStop)];
90
+ function inspectorCommand(input: { runnerPath: string; asyncDir: string; runId: string; index?: number; missionPath?: string; allowSteer: boolean; allowStop: boolean; sessionRoots: string[] }): string {
91
+ const args = [input.runnerPath, "--async-dir", input.asyncDir, "--run-id", input.runId, "--allow-steer", String(input.allowSteer), "--allow-stop", String(input.allowStop), "--session-roots", JSON.stringify(input.sessionRoots)];
94
92
  if (input.index !== undefined) args.push("--index", String(input.index));
95
93
  if (input.missionPath) args.push("--mission-path", input.missionPath);
96
- return `${process.platform === "win32" ? "& " : ""}${args.map(shellQuote).join(" ")}`;
94
+ return formatShellCommand(resolveNodeExecutable(), args);
97
95
  }
98
96
 
99
97
  function missionForRun(asyncDir: string, cwd: string, config: MissionStoreConfig | undefined, runId: string): { id: string; path: string } | undefined {
@@ -114,6 +112,12 @@ function pathWithin(base: string, candidate: string): boolean {
114
112
  return resolvedCandidate === resolvedBase || resolvedCandidate.startsWith(`${resolvedBase}${path.sep}`);
115
113
  }
116
114
 
115
+ function herdrSessionRoots(target: { runId: string }, deps: InspectorDeps): string[] {
116
+ const roots = deps.sessionRoots ?? deps.state?.trustedSessionRoots ?? [];
117
+ const job = deps.state?.asyncJobs.get(target.runId) ?? deps.state?.fleetJobs?.get(target.runId);
118
+ return [...new Set([...roots, ...(job?.sessionRoot ? [job.sessionRoot] : [])])];
119
+ }
120
+
117
121
  function isTrustedAsyncDir(asyncDir: string, deps: InspectorDeps): boolean {
118
122
  try {
119
123
  if (fs.lstatSync(asyncDir).isSymbolicLink() || !fs.statSync(asyncDir).isDirectory()) return false;
@@ -204,6 +208,7 @@ export async function handleHerdrInspectorAction(action: HerdrInspectorAction, p
204
208
  missionPath: mission?.path,
205
209
  allowSteer: resolveAuthorityDecision({ action: "steerRun", policy: deps.authorityPolicy }) === "auto",
206
210
  allowStop: resolveAuthorityDecision({ action: "stopRun", policy: deps.authorityPolicy }) === "auto",
211
+ sessionRoots: herdrSessionRoots(target, deps),
207
212
  });
208
213
  const started = await client.run(["pane", "run", paneId, command], { timeoutMs: 15_000, signal: deps.signal });
209
214
  if (started.ok === false) {