@xzzpig/pi-subagents 0.1.0 → 0.3.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 (108) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/README.md +4 -0
  3. package/agents/reviewer.md +3 -4
  4. package/docs/agents.md +343 -0
  5. package/docs/configuration.md +395 -0
  6. package/docs/extension-api.md +308 -0
  7. package/docs/missions.md +121 -0
  8. package/docs/models.md +192 -0
  9. package/docs/observability.md +198 -0
  10. package/docs/tool-reference.md +343 -0
  11. package/docs/watchdog.md +176 -0
  12. package/docs/workflows.md +163 -0
  13. package/package.json +13 -11
  14. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  15. package/skills/pi-subagents/references/execution-controls.md +7 -7
  16. package/skills/pi-subagents/references/management-authoring-rpc.md +1 -1
  17. package/skills/pi-subagents/references/prompting-and-roles.md +1 -1
  18. package/src/agents/agents.ts +53 -23
  19. package/src/agents/frontmatter.ts +7 -3
  20. package/src/agents/skills.ts +2 -9
  21. package/src/api/preflight.ts +1 -1
  22. package/src/api/project-panes.ts +30 -0
  23. package/src/extension/config.ts +54 -1
  24. package/src/extension/doctor.ts +40 -0
  25. package/src/extension/fanout-child.ts +5 -4
  26. package/src/extension/index.ts +114 -38
  27. package/src/extension/public-execution.ts +35 -4
  28. package/src/extension/rpc.ts +10 -15
  29. package/src/extension/schemas.ts +33 -11
  30. package/src/extension/subagent-guide.ts +39 -0
  31. package/src/extension/tool-description.ts +38 -18
  32. package/src/inspectors/herdr/actions.ts +11 -2
  33. package/src/inspectors/herdr/inspector-runner.ts +16 -3
  34. package/src/inspectors/herdr/project-panes.ts +459 -63
  35. package/src/intercom/intercom-bridge.ts +7 -2
  36. package/src/intercom/native-supervisor-channel.ts +102 -4
  37. package/src/missions/actions.ts +25 -2
  38. package/src/missions/lifecycle.ts +25 -9
  39. package/src/missions/store.ts +89 -7
  40. package/src/missions/types.ts +33 -0
  41. package/src/missions/workflow-state.ts +25 -15
  42. package/src/runs/background/active-async-capacity.ts +431 -0
  43. package/src/runs/background/active-run-index.ts +46 -0
  44. package/src/runs/background/async-execution.ts +158 -71
  45. package/src/runs/background/async-job-tracker.ts +297 -133
  46. package/src/runs/background/async-resume.ts +37 -5
  47. package/src/runs/background/async-status.ts +39 -5
  48. package/src/runs/background/chain-append.ts +33 -15
  49. package/src/runs/background/completion-replay.ts +267 -0
  50. package/src/runs/background/control-channel.ts +95 -54
  51. package/src/runs/background/fleet-view.ts +18 -5
  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-watcher.ts +113 -10
  55. package/src/runs/background/resume-guidance.ts +53 -0
  56. package/src/runs/background/retained-children.ts +14 -6
  57. package/src/runs/background/run-status.ts +119 -5
  58. package/src/runs/background/scheduled-runs.ts +25 -1
  59. package/src/runs/background/stale-run-reconciler.ts +12 -24
  60. package/src/runs/background/subagent-runner.ts +127 -41
  61. package/src/runs/background/subagent-wait.ts +5 -2
  62. package/src/runs/background/wait-completions.ts +39 -5
  63. package/src/runs/background/wait-subscriptions.ts +21 -5
  64. package/src/runs/foreground/async-dismiss-action.ts +85 -0
  65. package/src/runs/foreground/async-steering-action.ts +7 -8
  66. package/src/runs/foreground/chain-execution.ts +40 -2
  67. package/src/runs/foreground/execution.ts +97 -19
  68. package/src/runs/foreground/foreground-control.ts +12 -0
  69. package/src/runs/foreground/foreground-history.ts +137 -0
  70. package/src/runs/foreground/prompt-audit.ts +172 -0
  71. package/src/runs/foreground/subagent-executor.ts +1274 -243
  72. package/src/runs/foreground/workflow-foreground-steering.ts +187 -0
  73. package/src/runs/shared/acceptance.ts +13 -4
  74. package/src/runs/shared/completion-guard.ts +17 -1
  75. package/src/runs/shared/dynamic-fanout.ts +1 -1
  76. package/src/runs/shared/llm-intent-arbiter.ts +302 -0
  77. package/src/runs/shared/model-fallback.ts +8 -4
  78. package/src/runs/shared/model-scope.ts +12 -2
  79. package/src/runs/shared/parallel-utils.ts +3 -0
  80. package/src/runs/shared/pi-args.ts +44 -1
  81. package/src/runs/shared/run-fanout-budget.ts +280 -0
  82. package/src/runs/shared/single-output.ts +4 -2
  83. package/src/runs/shared/subagent-prompt-runtime.ts +94 -9
  84. package/src/runs/shared/task-intent.ts +19 -3
  85. package/src/runs/shared/worktree.ts +20 -7
  86. package/src/shared/agent-stream-options.ts +5 -0
  87. package/src/shared/artifacts.ts +17 -21
  88. package/src/shared/display-text.ts +150 -0
  89. package/src/shared/file-coalescer.ts +9 -0
  90. package/src/shared/fork-context.ts +13 -0
  91. package/src/shared/formatters.ts +4 -6
  92. package/src/shared/node-executable.ts +21 -0
  93. package/src/shared/prompt-resources.ts +51 -0
  94. package/src/shared/settings.ts +15 -2
  95. package/src/shared/types.ts +158 -4
  96. package/src/shared/utf8.ts +11 -0
  97. package/src/shared/utils.ts +46 -34
  98. package/src/slash/prompt-workflows.ts +2 -15
  99. package/src/slash/slash-commands.ts +22 -2
  100. package/src/tui/fleet-status.ts +29 -17
  101. package/src/tui/fleet-transcript.ts +1 -48
  102. package/src/tui/fleet.ts +362 -37
  103. package/src/tui/render.ts +235 -71
  104. package/src/watchdog/change-signature.ts +4 -3
  105. package/src/watchdog/permission-arbiter.ts +2 -1
  106. package/src/watchdog/review.ts +4 -3
  107. package/src/workflows/chat-progress.ts +8 -2
  108. package/src/workflows/scripted-workflow.ts +273 -20
@@ -27,9 +27,10 @@ import { cleanupOldChainDirs } from "../shared/settings.ts";
27
27
  import { clearLegacyResultAnimationTimer, renderSubagentResult, renderSubagentSummary } from "../tui/render.ts";
28
28
  import { openSubagentFleet } from "../tui/fleet.ts";
29
29
  import { SubagentFleetStatus, resolveFleetViewPlacement } from "../tui/fleet-status.ts";
30
- import { SubagentParams } from "./schemas.ts";
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";
33
34
  import { createResultWatcher } from "../runs/background/result-watcher.ts";
34
35
  import { createScheduledRunManager } from "../runs/background/scheduled-runs.ts";
35
36
  import { registerSlashCommands } from "../slash/slash-commands.ts";
@@ -37,7 +38,7 @@ import { registerPromptTemplateDelegationBridge } from "../slash/prompt-template
37
38
  import { registerMainWatchdog } from "../watchdog/register-main.ts";
38
39
  import { registerSlashSubagentBridge } from "../slash/slash-bridge.ts";
39
40
  import { createNativeSupervisorChannel } from "../intercom/native-supervisor-channel.ts";
40
- import { registerHerdrStatusBridge } from "../integrations/herdr-status.ts";
41
+ import { registerHerdrStatusBridge, type HerdrStatusRun } from "../integrations/herdr-status.ts";
41
42
  import { registerSubagentRpcBridge } from "./rpc.ts";
42
43
  import { clearSlashSnapshots, getSlashRenderableSnapshot, resolveSlashMessageDetails, restoreSlashFinalSnapshots, type SlashMessageDetails } from "../slash/slash-live-state.ts";
43
44
  import { inspectSubagentStatus } from "../runs/background/run-status.ts";
@@ -53,11 +54,12 @@ import { formatDuration, shortenPath } from "../shared/formatters.ts";
53
54
  import { loadConfig, resolveAsyncByDefault, resolveScheduledStoreRoot } from "./config.ts";
54
55
  import { buildSubagentToolDescription } from "./tool-description.ts";
55
56
  import { collectGoalContinuationNotices } from "../missions/goal-driver.ts";
56
- import { syncMissionFromAsyncCompletion } from "../missions/lifecycle.ts";
57
+ import { restoreForegroundRunHistory } from "../runs/foreground/foreground-history.ts";
57
58
  import { resolveMissionStoreLocation } from "../missions/store.ts";
58
59
  import { listRetainedChildren } from "../runs/background/retained-children.ts";
59
60
  import {
60
61
  type Details,
62
+ type MainWindowRendererConfig,
61
63
  type SubagentState,
62
64
  DIRS,
63
65
  DEFAULT_ARTIFACT_CONFIG,
@@ -65,6 +67,7 @@ import {
65
67
  SLASH_TEXT_RESULT_TYPE,
66
68
  SUBAGENT_ASYNC_COMPLETE_EVENT,
67
69
  SUBAGENT_ASYNC_STARTED_EVENT,
70
+ SUBAGENT_PROCESS_TERMINAL_EVENT,
68
71
  SUBAGENT_CONTROL_EVENT,
69
72
  SUBAGENT_STEERING_NOTICE_EVENT,
70
73
  WIDGET_KEY,
@@ -251,12 +254,13 @@ function rebuildSlashResultContainer(
251
254
  result: AgentToolResult<Details>,
252
255
  options: { expanded: boolean },
253
256
  theme: ExtensionContext["ui"]["theme"],
257
+ rendererConfig?: MainWindowRendererConfig,
254
258
  ): void {
255
259
  container.clear();
256
260
  container.addChild(new Spacer(1));
257
261
  const boxTheme = isSlashResultRunning(result) ? "toolPendingBg" : isSlashResultError(result) ? "toolErrorBg" : "toolSuccessBg";
258
262
  const box = new Box(1, 1, (text: string) => theme.bg(boxTheme, text));
259
- box.addChild(renderSubagentResult(result, options, theme));
263
+ box.addChild(renderSubagentResult(result, options, theme, undefined, rendererConfig));
260
264
  container.addChild(box);
261
265
  }
262
266
 
@@ -264,6 +268,7 @@ function createSlashResultComponent(
264
268
  details: SlashMessageDetails,
265
269
  options: { expanded: boolean },
266
270
  theme: ExtensionContext["ui"]["theme"],
271
+ rendererConfig?: MainWindowRendererConfig,
267
272
  ): Container {
268
273
  const container = new Container();
269
274
  let lastVersion = -1;
@@ -271,7 +276,7 @@ function createSlashResultComponent(
271
276
  const snapshot = getSlashRenderableSnapshot(details);
272
277
  if (snapshot.version !== lastVersion || isSlashResultRunning(snapshot.result)) {
273
278
  lastVersion = snapshot.version;
274
- rebuildSlashResultContainer(container, snapshot.result, options, theme);
279
+ rebuildSlashResultContainer(container, snapshot.result, options, theme, rendererConfig);
275
280
  }
276
281
  return Container.prototype.render.call(container, width);
277
282
  };
@@ -309,6 +314,36 @@ class SubagentControlNoticeComponent implements Component {
309
314
  }
310
315
  }
311
316
 
317
+ export function projectActiveHerdrRuns(state: SubagentState): HerdrStatusRun[] {
318
+ const active = (status: string) => status === "queued" || status === "running";
319
+ const foregroundChildrenByWorkflow = new Map<string, Array<{ agent: string; needsAttention: boolean }>>();
320
+ for (const control of state.foregroundControls.values()) {
321
+ if (!control.parentWorkflowRunId) continue;
322
+ const children = control.activeChildren?.size
323
+ ? [...control.activeChildren.values()].map((child) => ({
324
+ agent: child.agent,
325
+ needsAttention: child.currentActivityState === "needs_attention",
326
+ }))
327
+ : control.currentAgent
328
+ ? [{ agent: control.currentAgent, needsAttention: control.currentActivityState === "needs_attention" }]
329
+ : [];
330
+ if (children.length === 0) continue;
331
+ const existing = foregroundChildrenByWorkflow.get(control.parentWorkflowRunId) ?? [];
332
+ existing.push(...children);
333
+ foregroundChildrenByWorkflow.set(control.parentWorkflowRunId, existing);
334
+ }
335
+ return [...state.asyncJobs.values()]
336
+ .filter((job) => active(job.status))
337
+ .map((job) => {
338
+ const children = job.mode === "workflow" ? foregroundChildrenByWorkflow.get(job.asyncId) : undefined;
339
+ return {
340
+ id: job.asyncId,
341
+ agents: children?.length ? children.map((child) => child.agent) : job.agents,
342
+ needsAttention: job.activityState === "needs_attention" || children?.some((child) => child.needsAttention),
343
+ };
344
+ });
345
+ }
346
+
312
347
  export default function registerSubagentExtension(pi: ExtensionAPI): void {
313
348
  if (process.env[SUBAGENT_CHILD_ENV] === "1") {
314
349
  return;
@@ -336,7 +371,8 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
336
371
  const asyncWidgetEnabled = config.asyncWidget !== false;
337
372
  const summaryInlineToolDisplay = config.inlineToolDisplay === "summary";
338
373
  const tempArtifactsDir = getArtifactsDir(null);
339
- cleanupAllArtifactDirs(DEFAULT_ARTIFACT_CONFIG.cleanupDays);
374
+ const artifactCleanupDays = config.artifactConfig?.cleanupDays ?? DEFAULT_ARTIFACT_CONFIG.cleanupDays;
375
+ cleanupAllArtifactDirs(artifactCleanupDays);
340
376
 
341
377
  const state: SubagentState = {
342
378
  baseCwd: "",
@@ -345,6 +381,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
345
381
  ...(config.authorityPolicy ? { authorityPolicy: config.authorityPolicy } : {}),
346
382
  ...(config.missions ? { missionStoreConfig: config.missions } : {}),
347
383
  parentSessionFile: null,
384
+ trustedSessionRoots: [],
348
385
  subagentInProgress: false,
349
386
  subagentSpawns: {
350
387
  sessionId: null,
@@ -353,6 +390,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
353
390
  granted: 0,
354
391
  grantHistory: [],
355
392
  },
393
+ activeAsyncCapacity: { used: 0, limit: resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession) ?? 0 },
356
394
  asyncJobs: new Map(),
357
395
  fleetJobs: new Map(),
358
396
  foregroundRuns: new Map(),
@@ -362,6 +400,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
362
400
  lastUiContext: null,
363
401
  poller: null,
364
402
  completionSeen: new Map(),
403
+ widgetsSuspended: false,
365
404
  watcher: null,
366
405
  watcherRestartTimer: null,
367
406
  resultFileCoalescer: {
@@ -378,7 +417,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
378
417
  ? new SubagentFleetStatus(state, async (itemKey) => {
379
418
  const ctx = state.lastUiContext;
380
419
  if (!ctx?.hasUI) return;
381
- await openSubagentFleet(ctx, state, { initialKey: itemKey, asyncDirRoot: DIRS.async, resultsDir: DIRS.results });
420
+ await openSubagentFleet(ctx, state, { initialKey: itemKey, asyncDirRoot: DIRS.async, resultsDir: DIRS.results, fleetKeybindings: config.fleetKeybindings });
382
421
  }, { placement: fleetViewPlacement })
383
422
  : undefined;
384
423
  let executorScheduled: ((id: string, params: SubagentParamsLike, signal: AbortSignal, ctx: ExtensionContext) => Promise<AgentToolResult<Details>>) | undefined;
@@ -399,6 +438,9 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
399
438
  },
400
439
  resolveCapabilityCeiling: (sessionId) => resolveCurrentSubagentCapabilityCeiling(sessionId),
401
440
  });
441
+ const { ensurePoller, refreshWidget, handleStarted, handleComplete, resetJobs, restoreActiveJobs, dispose: disposeAsyncJobTracker } = createAsyncJobTracker(pi, state, DIRS.async, {
442
+ widgetEnabled: asyncWidgetEnabled,
443
+ });
402
444
  const { startResultWatcher, primeExistingResults, stopResultWatcher } = createResultWatcher(
403
445
  pi,
404
446
  state,
@@ -407,6 +449,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
407
449
  {
408
450
  notifier: completionNotifier,
409
451
  observeCompletion: (result) => scheduledRunManager.handleAsyncCompletion(result),
452
+ observedCompletionRunIds: () => scheduledRunManager.observedCompletionRunIds(),
410
453
  deliverIntercomResults: config.intercomBridge?.resultDelivery === true,
411
454
  },
412
455
  );
@@ -420,16 +463,10 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
420
463
  supervisorChannel.dispose();
421
464
  waitSubscriptionManager.dispose();
422
465
  fleetStatus?.dispose();
423
- if (state.poller) {
424
- clearInterval(state.poller);
425
- state.poller = null;
426
- }
466
+ disposeAsyncJobTracker();
427
467
  };
428
468
  globalStore[runtimeCleanupStoreKey] = runtimeCleanup;
429
469
 
430
- const { ensurePoller, refreshWidget, handleStarted, handleComplete, resetJobs, restoreActiveJobs } = createAsyncJobTracker(pi, state, DIRS.async, {
431
- widgetEnabled: asyncWidgetEnabled,
432
- });
433
470
  const executor = createSubagentExecutor({
434
471
  pi,
435
472
  state,
@@ -448,7 +485,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
448
485
  pi.registerMessageRenderer<SlashMessageDetails>(SLASH_RESULT_TYPE, (message, options, theme) => {
449
486
  const details = resolveSlashMessageDetails(message.details);
450
487
  if (!details) return undefined;
451
- return createSlashResultComponent(details, options, theme);
488
+ return createSlashResultComponent(details, options, theme, config.mainWindowRenderer);
452
489
  });
453
490
 
454
491
  pi.registerMessageRenderer<undefined>(SLASH_TEXT_RESULT_TYPE, (message, _options, _theme) => {
@@ -536,33 +573,36 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
536
573
  });
537
574
 
538
575
 
539
- const tool: ToolDefinition<typeof SubagentParams, Details> = {
576
+ const parameters = createSubagentParamsSchema(config);
577
+ const tool: ToolDefinition<typeof parameters, Details> = {
540
578
  name: "subagent",
541
579
  label: "Subagent",
542
580
  description: buildSubagentToolDescription(config),
543
- parameters: SubagentParams,
581
+ parameters,
544
582
 
545
583
  execute(id, params, signal, onUpdate, ctx) {
546
584
  return executeSubagentCollapsed(id, params as SubagentParamsLike, signal ?? new AbortController().signal, onUpdate, ctx);
547
585
  },
548
586
 
549
587
  renderCall(args, theme) {
588
+ const gap = " ".repeat(config.mainWindowRenderer?.horizontalSpacing ?? 1);
589
+ const title = theme.fg("toolTitle", theme.bold("subagent"));
550
590
  if (args.action) {
551
591
  const target = args.agent || args.chainName || "";
552
592
  return new Text(
553
- `${theme.fg("toolTitle", theme.bold("subagent "))}${args.action}${target ? ` ${theme.fg("accent", target)}` : ""}`,
593
+ `${title}${gap}${args.action}${target ? `${gap}${theme.fg("accent", target)}` : ""}`,
554
594
  0, 0,
555
595
  );
556
596
  }
557
597
  if (args.workflowScript)
558
598
  return new Text(
559
- `${theme.fg("toolTitle", theme.bold("subagent "))}${formatWorkflowManifest(args.workflowScript, args.async, false)}`,
599
+ `${title}${gap}${formatWorkflowManifest(args.workflowScript, args.async, false)}`,
560
600
  0,
561
601
  0,
562
602
  );
563
- const asyncLabel = args.async === true ? theme.fg("warning", " [async]") : "";
603
+ const asyncLabel = args.async === true ? `${gap}${theme.fg("warning", "[async]")}` : "";
564
604
  return new Text(
565
- `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", args.agent || "?")}${asyncLabel}`,
605
+ `${title}${gap}${theme.fg("accent", args.agent || "?")}${asyncLabel}`,
566
606
  0,
567
607
  0,
568
608
  );
@@ -573,7 +613,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
573
613
  const renderedResult = { ...result, isError: context.isError };
574
614
  return summaryInlineToolDisplay
575
615
  ? renderSubagentSummary(renderedResult, options, theme)
576
- : renderSubagentResult(renderedResult, options, theme);
616
+ : renderSubagentResult(renderedResult, options, theme, undefined, config.mainWindowRenderer);
577
617
  },
578
618
 
579
619
  };
@@ -603,7 +643,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
603
643
  }
604
644
  });
605
645
 
606
- registerSlashCommands(pi, state);
646
+ registerSlashCommands(pi, state, { fleetKeybindings: config.fleetKeybindings });
607
647
 
608
648
  const eventUnsubscribeStoreKey = "__piSubagentEventUnsubscribes";
609
649
  const controlNoticeSeenStoreKey = "__piSubagentVisibleControlNotices";
@@ -621,13 +661,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
621
661
  const existingVisibleControlNotices = globalStore[controlNoticeSeenStoreKey];
622
662
  const visibleControlNotices = existingVisibleControlNotices instanceof Set ? existingVisibleControlNotices as Set<string> : new Set<string>();
623
663
  globalStore[controlNoticeSeenStoreKey] = visibleControlNotices;
624
- const activeHerdrRuns = () => [...state.asyncJobs.values()]
625
- .filter((job) => job.status === "queued" || job.status === "running")
626
- .map((job) => ({
627
- id: job.asyncId,
628
- agents: job.agents,
629
- needsAttention: job.activityState === "needs_attention",
630
- }));
664
+ const activeHerdrRuns = () => projectActiveHerdrRuns(state);
631
665
  const herdrStatusBridge = registerHerdrStatusBridge({
632
666
  events: pi.events,
633
667
  getRuns: activeHerdrRuns,
@@ -652,17 +686,17 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
652
686
  };
653
687
  const asyncCompleteHandler = (payload: unknown) => {
654
688
  handleComplete(payload);
689
+ refreshActiveAsyncCapacity();
655
690
  scheduledRunManager.handleAsyncCompletion(payload);
656
- try {
657
- syncMissionFromAsyncCompletion(payload);
658
- } catch (error) {
659
- console.error("Failed to update mission from async completion:", error);
660
- }
661
691
  fleetStatus?.refresh();
662
692
  };
663
693
  const eventUnsubscribes = [
664
694
  pi.events.on(SUBAGENT_ASYNC_STARTED_EVENT, asyncStartedHandler),
665
695
  pi.events.on(SUBAGENT_ASYNC_COMPLETE_EVENT, asyncCompleteHandler),
696
+ pi.events.on(SUBAGENT_PROCESS_TERMINAL_EVENT, () => {
697
+ refreshActiveAsyncCapacity();
698
+ fleetStatus?.refresh();
699
+ }),
666
700
  pi.events.on(SUBAGENT_CONTROL_EVENT, controlEventHandler),
667
701
  pi.events.on(SUBAGENT_STEERING_NOTICE_EVENT, steeringNoticeHandler),
668
702
  herdrStatusBridge.dispose,
@@ -687,18 +721,49 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
687
721
  try {
688
722
  const sessionFile = ctx.sessionManager.getSessionFile();
689
723
  if (sessionFile) {
690
- cleanupOldArtifacts(getArtifactsDir(sessionFile), DEFAULT_ARTIFACT_CONFIG.cleanupDays);
724
+ cleanupOldArtifacts(getArtifactsDir(sessionFile), artifactCleanupDays);
691
725
  }
692
726
  } catch {
693
727
  // Cleanup failures should not block session lifecycle events.
694
728
  }
695
729
  };
696
730
 
731
+ const suspendWidgetsForCompaction = () => {
732
+ if (state.widgetsSuspended) return;
733
+ state.widgetsSuspended = true;
734
+ if (state.lastUiContext?.hasUI) state.lastUiContext.ui.setWidget(WIDGET_KEY, undefined);
735
+ fleetStatus?.refresh();
736
+ };
737
+ const resumeWidgetsAfterCompaction = () => {
738
+ if (!state.widgetsSuspended) return;
739
+ state.widgetsSuspended = false;
740
+ const ctx = state.lastUiContext;
741
+ if (ctx?.hasUI) refreshWidget(ctx);
742
+ fleetStatus?.refresh();
743
+ };
744
+
745
+ const refreshActiveAsyncCapacity = () => {
746
+ if (!state.currentSessionId) {
747
+ state.activeAsyncCapacity = { used: 0, limit: resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession) ?? 0 };
748
+ return;
749
+ }
750
+ state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(
751
+ state.currentSessionId,
752
+ resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession),
753
+ { liveWorkflowRunIds: new Set(state.workflowControllers?.keys() ?? []) },
754
+ );
755
+ };
756
+
697
757
  const resetSessionState = (ctx: ExtensionContext, recovering: boolean) => {
758
+ state.widgetsSuspended = false;
698
759
  state.baseCwd = ctx.cwd;
699
760
  goalTurnId = 0;
700
761
  state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
701
762
  state.parentSessionFile = ctx.sessionManager.getSessionFile();
763
+ state.trustedSessionRoots = [...new Set([
764
+ ...(config.defaultSessionDir ? [path.resolve(expandTilde(config.defaultSessionDir))] : []),
765
+ ...(state.parentSessionFile ? [getSubagentSessionRoot(state.parentSessionFile)] : []),
766
+ ])];
702
767
  state.subagentSpawns = {
703
768
  sessionId: state.currentSessionId,
704
769
  count: 0,
@@ -718,10 +783,12 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
718
783
  }
719
784
  }
720
785
  state.lastUiContext = ctx;
786
+ refreshActiveAsyncCapacity();
721
787
  cleanupSessionArtifacts(ctx);
722
788
  state.foregroundControls.clear();
723
789
  state.lastForegroundControlId = null;
724
790
  resetJobs(ctx);
791
+ restoreForegroundRunHistory(state, { resultsDir: DIRS.results });
725
792
  restoreActiveJobs(ctx);
726
793
  scheduledRunManager.bindSession(ctx);
727
794
  restoreSlashFinalSnapshots(ctx.sessionManager.getEntries());
@@ -732,9 +799,18 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
732
799
  };
733
800
 
734
801
  pi.on("agent_start", () => {
802
+ resumeWidgetsAfterCompaction();
735
803
  herdrStatusBridge.agentStarted();
736
804
  });
737
805
 
806
+ pi.on("agent_settled", () => {
807
+ resumeWidgetsAfterCompaction();
808
+ });
809
+
810
+ pi.on("session_before_compact", (event) => {
811
+ if (event.reason !== "manual") suspendWidgetsForCompaction();
812
+ });
813
+
738
814
  pi.on("session_compact", () => {
739
815
  const hasActiveAsyncWork = [...state.asyncJobs.values()].some((job) => job.status === "queued" || job.status === "running");
740
816
  if (!hasActiveAsyncWork || state.lastUiContext?.hasUI !== true) return;
@@ -760,6 +836,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
760
836
  });
761
837
 
762
838
  pi.on("session_shutdown", async () => {
839
+ state.widgetsSuspended = false;
763
840
  stopResultWatcher();
764
841
  state.currentSessionId = null;
765
842
  state.parentSessionFile = null;
@@ -776,8 +853,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
776
853
  delete globalStore[eventUnsubscribeStoreKey];
777
854
  }
778
855
  scheduledRunManager.stop();
779
- if (state.poller) clearInterval(state.poller);
780
- state.poller = null;
856
+ disposeAsyncJobTracker();
781
857
  for (const timer of state.cleanupTimers.values()) {
782
858
  clearTimeout(timer);
783
859
  }
@@ -11,6 +11,8 @@ export interface PublicSubagentExecutionParams {
11
11
  workflowScript?: unknown;
12
12
  resume?: unknown;
13
13
  clarify?: unknown;
14
+ runFanoutBudget?: unknown;
15
+ runFanoutAdmitted?: unknown;
14
16
  }
15
17
 
16
18
  export type PublicSubagentExecutionMode = "workflow" | "management";
@@ -24,6 +26,9 @@ export type PublicSubagentExecutionNormalization<T> =
24
26
  * Internal runs.run children and structured owned delegation bypass this boundary.
25
27
  */
26
28
  export function normalizePublicSubagentExecution<T extends PublicSubagentExecutionParams>(params: T): PublicSubagentExecutionNormalization<T> {
29
+ if (params.runFanoutBudget !== undefined || params.runFanoutAdmitted !== undefined) {
30
+ return { ok: false, error: "Public execution does not accept internal run fan-out fields.", mode: params.workflowScript !== undefined ? "workflow" : "management" };
31
+ }
27
32
  const action = params.action;
28
33
  if (action !== undefined && (typeof action !== "string" || !action.trim())) {
29
34
  return { ok: false, error: "action must be a non-empty management/control action, or omit action and use workflowScript.", mode: "management" };
@@ -42,7 +47,7 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
42
47
  if (normalizedAction !== undefined) {
43
48
  const legacyAction = normalizedAction.toLowerCase();
44
49
  if (legacyAction === "single") {
45
- return { ok: false, error: "Direct execution was removed. Use workflowScript: \"return runs.run('main', { agent, task })\".", mode: "workflow" };
50
+ return { ok: false, error: "action='single' is not supported. Omit action and pass { agent, task } for one child.", mode: "workflow" };
46
51
  }
47
52
  if (legacyAction === "parallel" || legacyAction === "tasks" || legacyAction === "chain") {
48
53
  return { ok: false, error: "Legacy top-level chain and parallel inputs were removed; use workflowScript.", mode: "workflow" };
@@ -59,13 +64,39 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
59
64
  if (params.workflowScript !== undefined) {
60
65
  return { ok: false, error: "workflowScript execution must omit action; only schedule.create accepts action with workflowScript.", mode: "management" };
61
66
  }
67
+ if (params.task !== undefined) {
68
+ return { ok: false, error: "Structured single-child task cannot be combined with a management/control action.", mode: "management" };
69
+ }
62
70
  return { ok: true, params: { ...params, action: normalizedAction } };
63
71
  }
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" };
72
+ if (params.step !== undefined) {
73
+ return { ok: false, error: "step is only available with action='append-step'; it is not an execution mode.", mode: "workflow" };
74
+ }
75
+ if (params.workflowScript !== undefined && (params.agent !== undefined || params.task !== undefined)) {
76
+ return { ok: false, error: "Structured single-child execution cannot be combined with workflowScript.", mode: "workflow" };
77
+ }
78
+ if (params.agent !== undefined || params.task !== undefined) {
79
+ if (typeof params.agent !== "string" || !params.agent.trim()) {
80
+ return { ok: false, error: "Structured single-child execution requires agent to be a non-empty string.", mode: "workflow" };
81
+ }
82
+ if (params.task !== undefined && typeof params.task !== "string") {
83
+ return { ok: false, error: "Structured single-child task must be a string when provided.", mode: "workflow" };
84
+ }
85
+ const { agent: _agent, task: _task, ...workflowDefaults } = params;
86
+ const child = {
87
+ agent: params.agent.trim(),
88
+ ...(params.task !== undefined ? { task: params.task } : {}),
89
+ };
90
+ return {
91
+ ok: true,
92
+ params: {
93
+ ...workflowDefaults,
94
+ workflowScript: `console.info("Converted structured single-child request to workflow runs.run('main', ...)."); return runs.run("main", ${JSON.stringify(child)})`,
95
+ } as T,
96
+ };
66
97
  }
67
98
  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" };
99
+ return { ok: false, error: "Execution requires either { agent, task? } for one child or a non-empty workflowScript for orchestration.", mode: "workflow" };
69
100
  }
70
101
  return { ok: true, params };
71
102
  }
@@ -16,9 +16,9 @@ import {
16
16
  SUBAGENT_PROCESS_TERMINAL_EVENT,
17
17
  SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
18
18
  } from "../shared/types.ts";
19
+ import { sanitizeDisplayText, truncateDisplayText } from "../shared/display-text.ts";
19
20
  import { readStatus } from "../shared/utils.ts";
20
21
  import { SubagentParams } from "./schemas.ts";
21
- import { formatWorkflowJsonPreview } from "../workflows/scripted-workflow.ts";
22
22
  import { normalizePublicSubagentExecution } from "./public-execution.ts";
23
23
 
24
24
  export const SUBAGENT_RPC_PROTOCOL_VERSION = 1;
@@ -90,6 +90,7 @@ export interface SubagentRpcFleetStatus {
90
90
  entries: SubagentRpcFleetEntry[];
91
91
  /** Total active children before the bounded entries window. */
92
92
  totalActive: number;
93
+ topLevelAsyncCapacity: { used: number; limit: number };
93
94
  omitted: number;
94
95
  }
95
96
 
@@ -101,12 +102,8 @@ const MAX_METADATA_LENGTH = 128;
101
102
 
102
103
  function displayText(value: unknown, maxLength: number): string | undefined {
103
104
  if (typeof value !== "string") return undefined;
104
- // Strip complete CSI/OSC/DCS/APC/PM strings and C1 controls before collapsing
105
- // whitespace; never leave CSI parameters behind after removing ESC.
106
- const normalized = value.slice(0, 4_096)
107
- .replace(/\x1b\[[0-?]*[ -/]*[@-~]|\x9b[0-?]*[ -/]*[@-~]|\x1b][\s\S]*?(?:\x07|\x1b\\)|\x1b[PX^_][\s\S]*?\x1b\\|[\u0000-\u001f\u007f-\u009f]/g, " ")
108
- .replace(/\s+/g, " ").trim();
109
- return normalized ? normalized.slice(0, maxLength) : undefined;
105
+ const normalized = sanitizeDisplayText(value.slice(0, 4_096));
106
+ return normalized ? truncateDisplayText(normalized, maxLength) : undefined;
110
107
  }
111
108
 
112
109
  function publicTokens(value: unknown): { input: number; output: number; total: number } {
@@ -157,7 +154,7 @@ function buildFleetStatus(
157
154
  }
158
155
  if (!state || !authoritativeSessionId || state.currentSessionId !== authoritativeSessionId) {
159
156
  keyState.keys.clear();
160
- return { version: 1, entries: [], totalActive: 0, omitted: 0 };
157
+ return { version: 1, entries: [], totalActive: 0, topLevelAsyncCapacity: { used: 0, limit: 0 }, omitted: 0 };
161
158
  }
162
159
 
163
160
  let totalActive = 0;
@@ -176,7 +173,6 @@ function buildFleetStatus(
176
173
  effort: child.thinking,
177
174
  startedAt: child.startedAt,
178
175
  tokens: { input: child.inputTokens ?? 0, output: child.outputTokens ?? 0, total: child.tokens ?? 0 },
179
- goal: child.description ?? control.description,
180
176
  });
181
177
  } else {
182
178
  addCandidate({
@@ -186,7 +182,6 @@ function buildFleetStatus(
186
182
  effort: control.thinking,
187
183
  startedAt: control.startedAt,
188
184
  tokens: { input: control.inputTokens ?? 0, output: control.outputTokens ?? 0, total: control.tokens ?? 0 },
189
- goal: control.description,
190
185
  });
191
186
  }
192
187
  }
@@ -194,13 +189,11 @@ function buildFleetStatus(
194
189
  if (job.sessionId !== authoritativeSessionId || !activeState(job.status)) continue;
195
190
  const startedAt = job.startedAt ?? job.updatedAt;
196
191
  if (job.mode === "workflow") {
197
- const latestEmit = job.workflow?.emits?.length ? formatWorkflowJsonPreview(job.workflow.emits.at(-1), 120) : undefined;
198
192
  addCandidate({
199
193
  internalKey: `async:${job.asyncId}`,
200
194
  agent: "workflow",
201
195
  startedAt,
202
196
  tokens: job.totalTokens,
203
- goal: latestEmit !== undefined ? `latest emit: ${latestEmit}` : job.description,
204
197
  });
205
198
  continue;
206
199
  }
@@ -217,7 +210,6 @@ function buildFleetStatus(
217
210
  agent: job.mode ?? "subagent",
218
211
  startedAt,
219
212
  tokens: job.totalTokens,
220
- goal: job.description,
221
213
  });
222
214
  continue;
223
215
  }
@@ -233,7 +225,6 @@ function buildFleetStatus(
233
225
  effort: step.thinking,
234
226
  startedAt: step.startedAt ?? startedAt,
235
227
  tokens: step.tokens ?? (steps.length === 1 ? job.totalTokens : undefined),
236
- goal: job.description,
237
228
  });
238
229
  }
239
230
  }
@@ -274,7 +265,7 @@ function buildFleetStatus(
274
265
  if (!activeKeys.has(internalKey)) keyState.keys.delete(internalKey);
275
266
  }
276
267
  const omitted = Math.max(0, totalActive - entries.length);
277
- return { version: 1, entries, totalActive, omitted };
268
+ return { version: 1, entries, totalActive, topLevelAsyncCapacity: state.activeAsyncCapacity ?? { used: 0, limit: 0 }, omitted };
278
269
  }
279
270
 
280
271
  interface RegisterSubagentRpcBridgeOptions {
@@ -493,6 +484,10 @@ function stopAsyncRun(
493
484
  throw new SubagentRpcError("not_found", `Async run '${initialRunId}' was not found in the active session.`);
494
485
  }
495
486
 
487
+ if (initialStatus.mode === "workflow" && initialStatus.state === "running") {
488
+ throw new SubagentRpcError("invalid_state", `Workflow ${initialRunId} is not controlled by this extension runtime; reload recovery cannot stop it safely.`);
489
+ }
490
+
496
491
  let status;
497
492
  try {
498
493
  status = reconcileAsyncRun(location.asyncDir, { resultsDir, kill: options.kill, now: options.now }).status;