@xzzpig/pi-subagents 0.20.0 → 0.22.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 (144) hide show
  1. package/CHANGELOG.md +164 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +72 -7
  9. package/docs/configuration.md +58 -7
  10. package/docs/extension-api.md +36 -11
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/fork-supervisor-routing.md +77 -0
  13. package/docs/missions.md +34 -17
  14. package/docs/models.md +1 -1
  15. package/docs/observability.md +10 -5
  16. package/docs/tool-reference.md +117 -84
  17. package/docs/watchdog.md +8 -6
  18. package/docs/workflows.md +16 -7
  19. package/index.ts +5 -0
  20. package/package.json +6 -3
  21. package/prompts/council.md +1 -1
  22. package/skills/pi-subagents/SKILL.md +1 -1
  23. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  24. package/skills/pi-subagents/references/execution-controls.md +16 -16
  25. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  26. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  27. package/src/agents/advertised-agent-prompt.ts +9 -1
  28. package/src/agents/agent-management.ts +4 -0
  29. package/src/agents/agent-memory.ts +3 -3
  30. package/src/agents/agent-scope.ts +4 -0
  31. package/src/agents/agent-serializer.ts +8 -1
  32. package/src/agents/agents.ts +191 -145
  33. package/src/api/preflight.ts +8 -4
  34. package/src/api/supervisor-routing.ts +196 -0
  35. package/src/extension/config.ts +21 -2
  36. package/src/extension/context-injection.ts +6 -1
  37. package/src/extension/control-notices.ts +1 -9
  38. package/src/extension/declaration-pinning.ts +164 -0
  39. package/src/extension/doctor.ts +7 -10
  40. package/src/extension/fanout-child.ts +7 -8
  41. package/src/extension/index.ts +143 -134
  42. package/src/extension/reply-workflow-script.ts +20 -11
  43. package/src/extension/rpc.ts +11 -6
  44. package/src/extension/schemas.ts +34 -30
  45. package/src/extension/subagent-guide.ts +86 -6
  46. package/src/extension/subagent-options.ts +47 -0
  47. package/src/extension/tool-activation.ts +3 -2
  48. package/src/extension/tool-description.ts +51 -68
  49. package/src/inspectors/actions.ts +37 -11
  50. package/src/inspectors/plugins.ts +3 -2
  51. package/src/inspectors/tmux/actions.ts +204 -0
  52. package/src/inspectors/tmux/client.ts +85 -0
  53. package/src/inspectors/tmux/plugin.ts +21 -0
  54. package/src/integrations/herdr-status.ts +18 -49
  55. package/src/integrations/program-status.ts +215 -0
  56. package/src/intercom/fork-supervisor-routing.ts +533 -0
  57. package/src/intercom/native-supervisor-channel.ts +152 -13
  58. package/src/intercom/result-intercom.ts +3 -2
  59. package/src/intercom/supervisor-ui.ts +2 -174
  60. package/src/missions/store.ts +25 -5
  61. package/src/profiles/profiles.ts +24 -21
  62. package/src/runs/background/active-async-capacity.ts +58 -8
  63. package/src/runs/background/async-execution.ts +143 -38
  64. package/src/runs/background/async-job-tracker.ts +11 -4
  65. package/src/runs/background/async-resume.ts +5 -2
  66. package/src/runs/background/await-async-run.ts +14 -9
  67. package/src/runs/background/binary-bootstrap.ts +2 -1
  68. package/src/runs/background/calendar-schedule.ts +90 -0
  69. package/src/runs/background/chain-root-attachment.ts +9 -5
  70. package/src/runs/background/fleet-view.ts +5 -5
  71. package/src/runs/background/notify.ts +185 -12
  72. package/src/runs/background/result-files.ts +116 -5
  73. package/src/runs/background/result-watcher.ts +99 -66
  74. package/src/runs/background/resume-guidance.ts +2 -2
  75. package/src/runs/background/run-child-session.ts +16 -2
  76. package/src/runs/background/run-id-resolver.ts +8 -5
  77. package/src/runs/background/run-status.ts +21 -16
  78. package/src/runs/background/runner-child-launch.ts +1 -0
  79. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  80. package/src/runs/background/scheduled-runs.ts +256 -61
  81. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  82. package/src/runs/background/subagent-runner.ts +32 -12
  83. package/src/runs/background/subagent-wait.ts +38 -19
  84. package/src/runs/background/terminal-run-index.ts +46 -1
  85. package/src/runs/background/wait-completions.ts +1 -0
  86. package/src/runs/background/wait-tool.ts +33 -23
  87. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  88. package/src/runs/foreground/async-stop-action.ts +48 -22
  89. package/src/runs/foreground/execution.ts +94 -52
  90. package/src/runs/foreground/foreground-history.ts +1 -0
  91. package/src/runs/foreground/subagent-executor.ts +232 -77
  92. package/src/runs/shared/child-commands.ts +2 -1
  93. package/src/runs/shared/child-hooks.ts +4 -3
  94. package/src/runs/shared/child-launch.ts +3 -0
  95. package/src/runs/shared/child-session.ts +41 -24
  96. package/src/runs/shared/child-tool-plan.ts +13 -26
  97. package/src/runs/shared/dynamic-fanout.ts +1 -1
  98. package/src/runs/shared/fork-command-result.ts +10 -0
  99. package/src/runs/shared/herdr-placed-run.ts +5 -4
  100. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  101. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  102. package/src/runs/shared/model-resolution.ts +30 -1
  103. package/src/runs/shared/nested-events.ts +5 -0
  104. package/src/runs/shared/parallel-handoff.ts +56 -8
  105. package/src/runs/shared/parallel-utils.ts +2 -0
  106. package/src/runs/shared/partial-output.ts +48 -0
  107. package/src/runs/shared/runner-launcher.ts +25 -0
  108. package/src/runs/shared/single-output.ts +53 -0
  109. package/src/runs/shared/structured-output.ts +14 -7
  110. package/src/runs/shared/subagent-control.ts +3 -3
  111. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  112. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  113. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  114. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  115. package/src/runs/shared/worktree-lock.ts +29 -0
  116. package/src/runs/shared/worktree.ts +12 -1
  117. package/src/shared/atomic-json.ts +4 -2
  118. package/src/shared/edit-distance.ts +33 -0
  119. package/src/shared/file-lease.ts +74 -0
  120. package/src/shared/formatters.ts +1 -5
  121. package/src/shared/model-info.ts +22 -0
  122. package/src/shared/package-version.ts +17 -0
  123. package/src/shared/parent-wake.ts +79 -0
  124. package/src/shared/pruned-fork.ts +7 -1
  125. package/src/shared/runtime-module-path.ts +19 -0
  126. package/src/shared/settings-file-lease.ts +36 -0
  127. package/src/shared/types.ts +36 -2
  128. package/src/shared/utils.ts +8 -6
  129. package/src/slash/prompt-template-bridge.ts +21 -20
  130. package/src/slash/slash-commands.ts +3 -3
  131. package/src/slash/subagents-admin.ts +2 -1
  132. package/src/tui/fleet-native-transcript.ts +2 -0
  133. package/src/tui/fleet-transcript.ts +12 -3
  134. package/src/tui/fleet.ts +11 -8
  135. package/src/tui/render.ts +27 -19
  136. package/src/tui/subagent-messages.ts +305 -0
  137. package/src/watchdog/diff-tool.ts +2 -2
  138. package/src/watchdog/register-main.ts +2 -22
  139. package/src/watchdog/render.ts +2 -24
  140. package/src/watchdog/runtime.ts +6 -4
  141. package/src/watchdog/settings.ts +18 -13
  142. package/src/watchdog/tool-actions.ts +2 -2
  143. package/src/workflows/scripted-workflow.ts +20 -6
  144. package/src/workflows/workflow-resources.ts +11 -0
@@ -17,8 +17,8 @@ import * as fs from "node:fs";
17
17
  import * as os from "node:os";
18
18
  import * as path from "node:path";
19
19
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
20
- import { keyText, type ExtensionAPI, type ExtensionContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
21
- import { Box, Container, Spacer, Text, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component } from "@earendil-works/pi-tui";
20
+ import type { ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
21
+ import { Box, Container, Spacer, Text, type Component } from "@earendil-works/pi-tui";
22
22
  import { clearAgentDiscoveryCache, discoverAgentSnapshot, discoverAgents, discoverAgentsAll, type AgentConfig, type AgentScope } from "../agents/agents.ts";
23
23
  import { resolveGlobalNpmRoot } from "../agents/global-npm-root.ts";
24
24
  import { buildAdvertisedAgentCatalog, buildAdvertisedAgentPrompt } from "../agents/advertised-agent-prompt.ts";
@@ -26,6 +26,13 @@ import { mergeAgentsForScope } from "../agents/agent-selection.ts";
26
26
  import { clearRuntimeAgentsForPi, listRuntimeAgentConfigs, mergeRuntimeAgents } from "../agents/runtime-agent-registry.ts";
27
27
  import { discoverAgentsWithRuntime } from "../agents/runtime-discovery.ts";
28
28
  import { registerRuntimeAgentEventListener } from "../agents/runtime-agent-events.ts";
29
+ import {
30
+ createSupervisorDispatcher,
31
+ createSupervisorLaunchHooks,
32
+ disposeSupervisorRouting,
33
+ disposeSupervisorRoutingForOwner,
34
+ registerSupervisorResponderEventListener,
35
+ } from "../intercom/fork-supervisor-routing.ts";
29
36
  import { ensureAccessibleDir } from "../shared/accessible-dir.ts";
30
37
  import { cleanupAllArtifactDirs, cleanupOldArtifacts, getArtifactsDir } from "../shared/artifacts.ts";
31
38
  import { resolveCurrentSessionId } from "../shared/session-identity.ts";
@@ -42,7 +49,7 @@ import { resolveDisabledFeatureSurface } from "../shared/disabled-features.ts";
42
49
  import type { SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
43
50
  import { createAsyncJobTracker } from "../runs/background/async-job-tracker.ts";
44
51
  import { getActiveAsyncCapacitySnapshot, resolveAbandonedSlotReleaseAfterMs, resolveMaxActiveAsyncRunsPerSession } from "../runs/background/active-async-capacity.ts";
45
- import { cleanupResultIndexes, missionObserverResultCandidateFiles } from "../runs/background/result-files.ts";
52
+ import { cleanupResultIndexes, missionObserverResultCandidateFiles, resultFilePath } from "../runs/background/result-files.ts";
46
53
  import { ASYNC_RETENTION_DELAY_MS, cleanupAsyncRetention } from "../runs/background/async-retention.ts";
47
54
  import { createResultWatcher } from "../runs/background/result-watcher.ts";
48
55
  import { createResultDeliveryOwnership } from "../runs/background/result-delivery-ownership.ts";
@@ -52,14 +59,9 @@ import { registerPromptTemplateDelegationBridge } from "../slash/prompt-template
52
59
  import { registerMainWatchdog } from "../watchdog/register-main.ts";
53
60
  import { registerSlashSubagentBridge } from "../slash/slash-bridge.ts";
54
61
  import { createNativeSupervisorChannel } from "../intercom/native-supervisor-channel.ts";
55
- import {
56
- renderSupervisorReply,
57
- renderSupervisorRequest,
58
- SUPERVISOR_REPLY_ENTRY_TYPE,
59
- SUPERVISOR_REQUEST_MESSAGE_TYPE,
60
- type SupervisorRequestMessageDetails,
61
- } from "../intercom/supervisor-ui.ts";
62
+ import { renderSubagentEntry, renderSubagentMessage, SUBAGENT_ENTRY_TYPES, SUBAGENT_MESSAGE_TYPES } from "../tui/subagent-messages.ts";
62
63
  import { registerHerdrStatusBridge, type HerdrStatusRun } from "../integrations/herdr-status.ts";
64
+ import { registerProgramStatusReporter } from "../integrations/program-status.ts";
63
65
  import { hasLiveSubagentWork, registerPiWebSessionLiveness } from "../integrations/pi-web-session-liveness.ts";
64
66
  import { createRetainedNestedRouteTracker } from "../runs/background/retained-nested-route-tracker.ts";
65
67
  import { listHerdrProjectPaneRoots, restoreHerdrProjectPaneSnapshots } from "../inspectors/herdr/project-panes.ts";
@@ -68,21 +70,22 @@ import { clearSlashSnapshots, getSlashRenderableSnapshot, resolveSlashMessageDet
68
70
  import { resolveWaitToolConfig } from "../runs/background/subagent-wait.ts";
69
71
  import { registerWaitTool } from "../runs/background/wait-tool.ts";
70
72
  import { registerSubagentToolActivation } from "./tool-activation.ts";
73
+ import { recordedPromptSection, registerPinnedTool } from "./declaration-pinning.ts";
71
74
  import { createWaitSubscriptionManager } from "../runs/background/wait-subscriptions.ts";
72
75
  import { drainOutstandingWork } from "../runs/background/auto-drain.ts";
73
- import registerSubagentNotify, { parseSubagentNotifyContent, type SubagentNotifyDetails } from "../runs/background/notify.ts";
74
- import { formatSteeringNotice, handleSubagentSteeringNotice, SUBAGENT_STEERING_MESSAGE_TYPE, type SubagentSteeringMessageDetails } from "./steering-notices.ts";
76
+ import registerSubagentNotify from "../runs/background/notify.ts";
77
+ import { createParentWake } from "../shared/parent-wake.ts";
78
+ import { handleSubagentSteeringNotice, type SubagentSteeringMessageDetails } from "./steering-notices.ts";
75
79
  import { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from "../runs/shared/child-runtime-config.ts";
76
80
  import { disposeChildSessions } from "../runs/shared/child-session.ts";
77
81
  import { resolveCurrentSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.ts";
78
- import { formatDuration, shortenPath } from "../shared/formatters.ts";
79
82
  import { loadConfig, resolveAsyncByDefault, resolveScheduledStoreRoot } from "./config.ts";
80
83
  import { applyInjectionBlock, renderInjectionBlock, resolveInjectableAgents } from "./context-injection.ts";
81
84
  import { buildSubagentToolDescription, buildSubagentToolPromptMetadata } from "./tool-description.ts";
82
85
  import { formatWorkflowPreflightSummary, normalizeWorkflowPreflight } from "../workflows/workflow-preflight.ts";
83
86
  import { runtimeReplacedAbortReason } from "../workflows/workflow-reuse.ts";
84
87
  import { finalizeToolResult } from "./tool-result.ts";
85
- import { removedModelWorkflowFieldError } from "./public-execution.ts";
88
+ import { flattenSubagentToolOptions } from "./subagent-options.ts";
86
89
  import { collectGoalContinuationNotices } from "../missions/goal-driver.ts";
87
90
  import { restoreForegroundRunHistory } from "../runs/foreground/foreground-history.ts";
88
91
  import { resolveMissionStoreLocation } from "../missions/store.ts";
@@ -90,6 +93,7 @@ import { listRetainedChildren } from "../runs/background/retained-children.ts";
90
93
  import {
91
94
  type Details,
92
95
  type MainWindowRendererConfig,
96
+ type AsyncJobState,
93
97
  type SubagentState,
94
98
  DIRS,
95
99
  DEFAULT_ARTIFACT_CONFIG,
@@ -104,9 +108,7 @@ import {
104
108
  resolveMaxSubagentSpawnsPerSession,
105
109
  } from "../shared/types.ts";
106
110
  import {
107
- formatSubagentControlNotice,
108
111
  handleSubagentControlNotice,
109
- SUBAGENT_CONTROL_MESSAGE_TYPE,
110
112
  type SubagentControlMessageDetails,
111
113
  } from "./control-notices.ts";
112
114
  import { showUpgradeNotice } from "./upgrade-notice.ts";
@@ -123,7 +125,7 @@ type SubagentExecutor = ReturnType<SubagentExecutorModule["createSubagentExecuto
123
125
  type SubagentExecutorDeps = Parameters<SubagentExecutorModule["createSubagentExecutor"]>[0];
124
126
 
125
127
  interface SubagentRuntimeEntry {
126
- cleanup(): void;
128
+ cleanup(shutdownReason?: string): void;
127
129
  sessionManager: object | null;
128
130
  visibleControlNotices: Set<string>;
129
131
  }
@@ -236,37 +238,6 @@ function createSlashResultComponent(
236
238
  return container;
237
239
  }
238
240
 
239
- class SubagentControlNoticeComponent implements Component {
240
- private readonly details: SubagentControlMessageDetails;
241
- private readonly theme: ExtensionContext["ui"]["theme"];
242
-
243
- constructor(details: SubagentControlMessageDetails, theme: ExtensionContext["ui"]["theme"]) {
244
- this.details = details;
245
- this.theme = theme;
246
- }
247
-
248
- invalidate(): void {}
249
-
250
- render(width: number): string[] {
251
- const eventLabel = this.details.event.type.replaceAll("_", " ");
252
- if (width < 3) return [truncateToWidth(`Subagent ${eventLabel}`, width)];
253
- const bodyWidth = Math.max(1, width - 2);
254
- const borderChar = "─";
255
- const header = ` ⚠ Subagent ${eventLabel}: ${this.details.event.agent} `;
256
- const headerText = truncateToWidth(header, bodyWidth, "");
257
- const headerPadding = Math.max(0, bodyWidth - visibleWidth(headerText));
258
- const lines = [this.theme.fg("accent", `╭${headerText}${borderChar.repeat(headerPadding)}╮`)];
259
-
260
- for (const line of wrapTextWithAnsi(formatSubagentControlNotice(this.details), bodyWidth)) {
261
- const text = truncateToWidth(line, bodyWidth, "");
262
- const padding = Math.max(0, bodyWidth - visibleWidth(text));
263
- lines.push(this.theme.fg("accent", `│${text}${" ".repeat(padding)}│`));
264
- }
265
- lines.push(this.theme.fg("accent", `╰${borderChar.repeat(bodyWidth)}╯`));
266
- return lines;
267
- }
268
- }
269
-
270
241
  export function projectActiveHerdrRuns(state: SubagentState): HerdrStatusRun[] {
271
242
  const active = (status: string) => status === "queued" || status === "running";
272
243
  const foregroundChildrenByWorkflow = new Map<string, Array<{ agent: string; needsAttention: boolean }>>();
@@ -332,6 +303,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
332
303
  const fleetViewPlacement = resolveFleetViewPlacement(config.fleetViewPlacement);
333
304
  const asyncWidgetEnabled = config.asyncWidget !== false;
334
305
  const asyncWidgetCollapsed = config.asyncWidgetCollapsed === true;
306
+ const asyncWidgetLayout = config.asyncWidgetLayout ?? "adaptive";
335
307
  const summaryInlineToolDisplay = config.inlineToolDisplay === "summary";
336
308
  const tempArtifactsDir = getArtifactsDir(null);
337
309
  const artifactCleanupDays = config.artifactConfig?.cleanupDays ?? DEFAULT_ARTIFACT_CONFIG.cleanupDays;
@@ -382,14 +354,30 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
382
354
  }, run);
383
355
  };
384
356
 
357
+ // Every notice that wakes the parent goes through parentWake; the watchdog wakes only inside a run.
358
+ const parentWake = createParentWake(pi);
359
+ const wakingPi = { events: pi.events, sendMessage: parentWake.sendMessage, on: pi.on };
385
360
  const supervisorChannel = createNativeSupervisorChannel(pi, state, {
386
361
  // Owner states are created only by scheduled execution, which loads the executor first.
387
362
  getCurrentOwnerStates: () => executor?.getCurrentSupervisorOwnerStates() ?? [],
363
+ parentWake,
364
+ // Exclusive takeover for registered responder routes; unregistered routes
365
+ // keep the native wake/detach path untouched.
366
+ supervisorDispatcher: createSupervisorDispatcher(pi, () => state.supervisorOwnerSessionId ?? null),
388
367
  });
389
- const waitSubscriptionManager = createWaitSubscriptionManager(pi, state);
368
+ const waitSubscriptionManager = createWaitSubscriptionManager(wakingPi, state);
390
369
  const mainWatchdog = registerMainWatchdog(pi);
391
370
  const resultDeliveryOwnership = createResultDeliveryOwnership(state);
392
- const completionNotifier = registerSubagentNotify(pi, state, { batchConfig: config.completionBatch, ownership: resultDeliveryOwnership });
371
+ const completionNotifier = registerSubagentNotify(wakingPi, state, { batchConfig: config.completionBatch, ownership: resultDeliveryOwnership });
372
+ // Ended async runs whose result has not reached the notifier yet.
373
+ const owedResultRunIds = new Set<string>();
374
+ // Tracked runs whose result was already delivered, so a later terminal
375
+ // transition (the tracker can see the end after the result) holds nothing.
376
+ const deliveredRunIds = new Set<string>();
377
+ const holdOwedResult = (job: AsyncJobState) => {
378
+ if (!job.parentWorkflowRunId && !deliveredRunIds.has(job.asyncId) && job.sessionId
379
+ && resultDeliveryOwnership.owns(job.sessionId, job.completionOwnerId)) owedResultRunIds.add(job.asyncId);
380
+ };
393
381
  let retainedNestedRouteTracker: ReturnType<typeof createRetainedNestedRouteTracker> | undefined;
394
382
  const fleetStatus = fleetViewEnabled
395
383
  ? new SubagentFleetStatus(state, async (itemKey) => {
@@ -421,7 +409,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
421
409
  });
422
410
  let refreshResultDelivery = () => {};
423
411
  let advertisedAgents: AgentConfig[] = [];
424
- let advertisedContext: Pick<ExtensionContext, "cwd" | "model"> | undefined;
412
+ let advertisedContext: Pick<ExtensionContext, "cwd" | "model"> & { projectTrusted?: boolean } | undefined;
425
413
  let advertisementGeneration = 0;
426
414
  let globalRoot: string | null = null;
427
415
  let advertisementReady: Promise<void | { error: unknown }> = Promise.resolve();
@@ -439,7 +427,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
439
427
  advertisedAgents = [];
440
428
  if (!advertisedContext) return;
441
429
  clearAgentDiscoveryCache();
442
- advertisedAgents = discoverAgents(advertisedContext.cwd, "both", advertisedContext.model?.provider, { globalNpmRoot: globalRoot }).agents
430
+ advertisedAgents = discoverAgents(advertisedContext.cwd, "both", advertisedContext.model?.provider, { globalNpmRoot: globalRoot, projectTrusted: advertisedContext.projectTrusted }).agents
443
431
  .filter((agent) => agent.advertise === true);
444
432
  };
445
433
  const beginAdvertisement = (ctx: ExtensionContext) => {
@@ -447,7 +435,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
447
435
  notifySessionChange();
448
436
  sessionChanged = new Promise<void>((resolve) => { notifySessionChange = resolve; });
449
437
  advertisedAgents = [];
450
- advertisedContext = { cwd: ctx.cwd, model: ctx.model };
438
+ advertisedContext = { cwd: ctx.cwd, model: ctx.model, projectTrusted: typeof ctx.isProjectTrusted === "function" ? ctx.isProjectTrusted() : undefined };
451
439
  globalRoot = null;
452
440
  advertisementReady = resolveGlobalNpmRoot().then((root) => {
453
441
  if (generation !== advertisementGeneration) return;
@@ -461,14 +449,15 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
461
449
  });
462
450
  };
463
451
  const hasResultDeliveryDemand = () => {
452
+ if (owedResultRunIds.size > 0) return true;
464
453
  if ([...state.asyncJobs.values()].some((job) => job.status === "queued" || job.status === "running")) return true;
465
454
  if (state.foregroundControls.size > 0) return true;
466
455
  if (scheduledRunManager.observedCompletionRunIds().size > 0) return true;
467
456
  return missionObserverResultCandidateFiles(DIRS.results).length > 0;
468
457
  };
469
- const discoverAgentsForRuntime = (cwd: string, scope: AgentScope, preferredModelProvider?: string) => {
470
- if (listRuntimeAgentConfigs(pi).length === 0) return discoverAgents(cwd, scope, preferredModelProvider, { globalNpmRoot: globalRoot });
471
- const snapshot = discoverAgentSnapshot(cwd, scope, preferredModelProvider, { includeChains: false, globalNpmRoot: globalRoot });
458
+ const discoverAgentsForRuntime = (cwd: string, scope: AgentScope, preferredModelProvider?: string, options: { projectTrusted?: boolean } = {}) => {
459
+ if (listRuntimeAgentConfigs(pi).length === 0) return discoverAgents(cwd, scope, preferredModelProvider, { globalNpmRoot: globalRoot, projectTrusted: options.projectTrusted });
460
+ const snapshot = discoverAgentSnapshot(cwd, scope, preferredModelProvider, { includeChains: false, globalNpmRoot: globalRoot, projectTrusted: options.projectTrusted });
472
461
  const discovered = snapshot.effective;
473
462
  const all = snapshot.all;
474
463
  const configuredAgents: AgentConfig[] = [
@@ -477,18 +466,31 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
477
466
  ...all.user,
478
467
  ...all.project,
479
468
  ];
480
- const merged = mergeRuntimeAgents(pi, discovered, configuredAgents, { cwd, scope, preferredModelProvider });
469
+ // Runtime agents take model settings from the scope discovery actually used.
470
+ const merged = mergeRuntimeAgents(pi, discovered, configuredAgents, { cwd, scope: discovered.scope, preferredModelProvider, projectTrusted: options.projectTrusted });
481
471
  if (discovered.maxThinking === undefined) return merged;
482
472
  return {
483
473
  ...merged,
484
474
  agents: merged.agents.map((agent) => agent.maxThinking === discovered.maxThinking ? agent : { ...agent, maxThinking: discovered.maxThinking }),
485
475
  };
486
476
  };
477
+ const programStatus = registerProgramStatusReporter({
478
+ enabled: config.programStatus !== false,
479
+ // Fleet history keeps recent finished runs after the widget drops them.
480
+ getJobs: () => new Map([...(state.fleetJobs ?? []), ...state.asyncJobs]).values(),
481
+ getPendingRequests: () => supervisorChannel.pending.values(),
482
+ });
487
483
  const { ensurePoller, refreshWidget, handleStarted, handleComplete, resetJobs, restoreActiveJobs, dispose: disposeAsyncJobTracker } = createAsyncJobTracker(pi, state, DIRS.async, {
488
484
  widgetEnabled: asyncWidgetEnabled,
489
485
  widgetCollapsed: asyncWidgetCollapsed,
490
- onJobTerminal: () => refreshResultDelivery(),
486
+ widgetLayout: asyncWidgetLayout,
487
+ onJobTerminal: (job) => {
488
+ holdOwedResult(job);
489
+ refreshResultDelivery();
490
+ },
491
+ onJobCleanup: (asyncId) => deliveredRunIds.delete(asyncId),
491
492
  supervisorRequestState: supervisorChannel.getSupervisorRequestState,
493
+ onJobsChanged: programStatus.sync,
492
494
  });
493
495
  const resultWatcher = createResultWatcher(
494
496
  pi,
@@ -498,6 +500,10 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
498
500
  {
499
501
  notifier: completionNotifier,
500
502
  ownership: resultDeliveryOwnership,
503
+ onResultDelivered: (runId) => {
504
+ owedResultRunIds.delete(runId);
505
+ if (state.asyncJobs.has(runId)) deliveredRunIds.add(runId);
506
+ },
501
507
  observeCompletion: (result) => scheduledRunManager.handleAsyncCompletion(result),
502
508
  observedCompletionRunIds: () => scheduledRunManager.observedCompletionRunIds(),
503
509
  hasDeliveryDemand: hasResultDeliveryDemand,
@@ -544,6 +550,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
544
550
 
545
551
  const executorDeps: SubagentExecutorDeps = {
546
552
  pi,
553
+ parentWake,
547
554
  state,
548
555
  config,
549
556
  asyncByDefault,
@@ -595,15 +602,15 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
595
602
  modulePreloadTimer.unref?.();
596
603
  };
597
604
 
598
- pi.registerMessageRenderer<SupervisorRequestMessageDetails>(SUPERVISOR_REQUEST_MESSAGE_TYPE, renderSupervisorRequest);
605
+ for (const customType of SUBAGENT_MESSAGE_TYPES) pi.registerMessageRenderer(customType, renderSubagentMessage);
599
606
  // SAFETY: `registerEntryRenderer` is not part of the typed ExtensionAPI in the
600
607
  // pinned dependency version; this cast pins the runtime shape of the entry
601
608
  // renderer registration surface, guarded below by a typeof check.
602
609
  const registerEntryRenderer = (pi as unknown as {
603
- registerEntryRenderer?: (customType: string, renderer: (entry: { data?: unknown }, options: { expanded: boolean }, theme: ExtensionContext["ui"]["theme"]) => Component | undefined) => void;
610
+ registerEntryRenderer?: (customType: string, renderer: (entry: { customType: string; data?: unknown }, options: { expanded: boolean }, theme: ExtensionContext["ui"]["theme"]) => Component | undefined) => void;
604
611
  }).registerEntryRenderer;
605
612
  if (typeof registerEntryRenderer === "function") {
606
- registerEntryRenderer.call(pi, SUPERVISOR_REPLY_ENTRY_TYPE, renderSupervisorReply);
613
+ for (const customType of SUBAGENT_ENTRY_TYPES) registerEntryRenderer.call(pi, customType, renderSubagentEntry);
607
614
  }
608
615
 
609
616
  pi.registerMessageRenderer<SlashMessageDetails>(SLASH_RESULT_TYPE, (message, options, theme) => {
@@ -629,59 +636,6 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
629
636
  return new Text(content, 0, 0);
630
637
  });
631
638
 
632
- pi.registerMessageRenderer<SubagentNotifyDetails>("subagent-notify", (message, options, theme) => {
633
- const content = typeof message.content === "string" ? message.content : "";
634
- const details = (message.details as SubagentNotifyDetails | undefined) ?? parseSubagentNotifyContent(content);
635
- if (!details) return new Text(content, 0, 0);
636
- const icon = details.status === "completed"
637
- ? theme.fg("success", "✓")
638
- : details.status === "paused"
639
- ? theme.fg("warning", "■")
640
- : theme.fg("error", "✗");
641
- const parts: string[] = [];
642
- if (details.taskInfo) parts.push(details.taskInfo);
643
- if (details.durationMs !== undefined) parts.push(formatDuration(details.durationMs));
644
- let text = `${icon} ${theme.bold(details.agent)} ${theme.fg("dim", details.status)}`;
645
- if (parts.length > 0) text += ` ${theme.fg("dim", "·")} ${parts.map((part) => theme.fg("dim", part)).join(` ${theme.fg("dim", "·")} `)}`;
646
- const trimmedPreview = details.resultPreview.trim();
647
- const previewLines = options.expanded
648
- ? trimmedPreview.split("\n").filter((line) => line.trim())
649
- : [trimmedPreview.split("\n", 1)[0] ?? ""].filter((line) => line.trim());
650
- for (const line of previewLines.length > 0 ? previewLines : ["(no output)"]) {
651
- text += `\n ${theme.fg("dim", `⎿ ${line}`)}`;
652
- }
653
- if (!options.expanded && trimmedPreview.includes("\n")) {
654
- const expandKey = keyText("app.tools.expand");
655
- text += `\n ${theme.fg("dim", `${expandKey} full notification`)}`;
656
- }
657
- if (details.workflowRunId) {
658
- text += `\n ${theme.fg("muted", `workflow: ${details.workflowRunId}`)}`;
659
- }
660
- if (details.childRuns?.length) {
661
- text += `\n ${theme.fg("muted", `children: ${details.childRuns.map((child) => `${child.workflowKey ?? child.agent ?? "child"}=${child.runId}`).join(", ")}`)}`;
662
- }
663
- if (details.reconciledFromDetachedChild) {
664
- text += `\n ${theme.fg("muted", `reconciled child: ${details.reconciledFromDetachedChild}`)}`;
665
- }
666
- if (details.sessionLabel && details.sessionValue) {
667
- text += `\n ${theme.fg("muted", `${details.sessionLabel}: ${shortenPath(details.sessionValue)}`)}`;
668
- }
669
- return new Text(text, 0, 0);
670
- });
671
-
672
- pi.registerMessageRenderer<SubagentSteeringMessageDetails>(SUBAGENT_STEERING_MESSAGE_TYPE, (message, _options, theme) => {
673
- const details = message.details as SubagentSteeringMessageDetails | undefined;
674
- if (!details) return undefined;
675
- return new Text(theme.fg(details.state === "recovered" ? "warning" : "error", formatSteeringNotice(details)), 0, 0);
676
- });
677
-
678
- pi.registerMessageRenderer<SubagentControlMessageDetails>(SUBAGENT_CONTROL_MESSAGE_TYPE, (message, _options, theme) => {
679
- const details = message.details as SubagentControlMessageDetails | undefined;
680
- if (!details?.event) return undefined;
681
- const content = typeof message.content === "string" ? message.content : undefined;
682
- return new SubagentControlNoticeComponent({ ...details, noticeText: formatSubagentControlNotice(details, content) }, theme);
683
- });
684
-
685
639
  const executeSubagentReady = async (id: string, params: SubagentParamsLike, signal: AbortSignal, onUpdate: ((result: AgentToolResult<Details>) => void) | undefined, ctx: ExtensionContext) => {
686
640
  await waitForAdvertisement();
687
641
  return (await getExecutor()).executePublic(id, params, signal, onUpdate, ctx);
@@ -703,10 +657,22 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
703
657
  getContext: () => state.lastUiContext,
704
658
  execute: (requestId, params, signal, ctx, onUpdate) =>
705
659
  executeSubagentCollapsed(requestId, params, signal, onUpdate, ctx),
706
- executeStructured: async (requestId, params, signal, ctx, onUpdate) => {
660
+ executeStructured: async (requestId, params, signal, ctx, onUpdate, request) => {
707
661
  if (ctx.hasUI) ctx.ui.setToolsExpanded(false);
708
662
  await waitForAdvertisement();
709
- return (await getExecutor()).executeDelegated(requestId, params, signal, onUpdate, ctx);
663
+ // The responder is bound to the REAL child route (runId + canonical
664
+ // agent + index) inside the executor, before the first prompt. Passing
665
+ // it here keeps callbacks out of model parameters, artifacts and child
666
+ // env; an unregistered attempt gets no hooks and keeps default behaviour.
667
+ const supervisorLaunchHooks = request
668
+ ? createSupervisorLaunchHooks(pi, {
669
+ requestId: request.requestId,
670
+ ownerRunId: request.ownerRunId,
671
+ nodeId: request.nodeId,
672
+ agent: request.agent,
673
+ }, () => state.supervisorOwnerSessionId ?? null)
674
+ : undefined;
675
+ return (await getExecutor()).executeDelegated(requestId, params, signal, onUpdate, ctx, supervisorLaunchHooks);
710
676
  },
711
677
  });
712
678
 
@@ -730,9 +696,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
730
696
  parameters,
731
697
 
732
698
  async execute(id, params, signal, onUpdate, ctx) {
733
- const removedField = removedModelWorkflowFieldError(params);
734
- if (removedField) throw new Error(removedField);
735
- return finalizeToolResult(await executeSubagentCollapsed(id, params as SubagentParamsLike, signal ?? new AbortController().signal, onUpdate, ctx));
699
+ return finalizeToolResult(await executeSubagentCollapsed(id, flattenSubagentToolOptions(params, disabledFeatures), signal ?? new AbortController().signal, onUpdate, ctx));
736
700
  },
737
701
 
738
702
  renderCall(args, theme) {
@@ -745,9 +709,10 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
745
709
  0, 0,
746
710
  );
747
711
  }
712
+ const preflight = args.options?.preflight ?? (args as { preflight?: unknown }).preflight;
748
713
  if (args.workflow !== undefined)
749
714
  return new Text(
750
- `${title}${gap}${theme.fg("accent", args.workflow === true || args.workflow === "true" ? "workflow (reply block)" : `workflow ${String(args.workflow)}`)}${args.async === true ? `${gap}${theme.fg("warning", "[async]")}` : ""}${args.preflight !== undefined ? `${gap}${theme.fg("dim", formatWorkflowPreflightCall(args.preflight))}` : ""}`,
715
+ `${title}${gap}${theme.fg("accent", args.workflow === true || args.workflow === "true" ? "workflow (reply block)" : `workflow ${String(args.workflow)}`)}${args.async === true ? `${gap}${theme.fg("warning", "[async]")}` : ""}${preflight !== undefined ? `${gap}${theme.fg("dim", formatWorkflowPreflightCall(preflight))}` : ""}`,
751
716
  0,
752
717
  0,
753
718
  );
@@ -769,15 +734,22 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
769
734
 
770
735
  };
771
736
 
772
- pi.registerTool(tool);
737
+ registerPinnedTool(pi, tool);
773
738
 
774
- pi.on("before_agent_start", (event) => {
739
+ pi.on("before_agent_start", (event, ctx) => {
775
740
  if (process.env[SUBAGENT_CHILD_ENV] === "1") return undefined;
741
+ const projectTrusted = typeof ctx.isProjectTrusted !== "function" || ctx.isProjectTrusted() !== false;
742
+ const trustChanged = contextInjectionProjectTrusted !== projectTrusted;
743
+ if (trustChanged) {
744
+ refreshContextInjectionSnapshot(ctx);
745
+ beginAdvertisement(ctx);
746
+ }
776
747
  const next = applyInjectionBlock({
777
748
  systemPrompt: event.systemPrompt,
778
749
  block: state.contextInjectionBlock ?? "",
750
+ replaceExisting: !projectTrusted || trustChanged,
779
751
  });
780
- return next ? { systemPrompt: next } : undefined;
752
+ return next !== undefined ? { systemPrompt: next } : undefined;
781
753
  });
782
754
 
783
755
  pi.on("before_agent_start", async (event, ctx) => {
@@ -787,7 +759,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
787
759
  // Structured sections let Pi append a transcript delta instead of replacing the
788
760
  // cached system prompt. Set the section on every turn it applies: Pi rebuilds the
789
761
  // options each turn, and an unset turn records a removal.
790
- const catalog = buildAdvertisedAgentCatalog(advertisedAgents, resolveCurrentSubagentCapabilityCeiling(sessionId));
762
+ const catalog = buildAdvertisedAgentCatalog(advertisedAgents, resolveCurrentSubagentCapabilityCeiling(sessionId), recordedPromptSection(pi, "advertised_subagents"));
791
763
  if (catalog) event.systemPromptOptions.sections.advertised_subagents = catalog;
792
764
  });
793
765
 
@@ -795,7 +767,10 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
795
767
 
796
768
  pi.on("agent_end", async (_event, ctx) => {
797
769
  try {
798
- if (!ctx.hasUI) await drainOutstandingWork({ state, events: pi.events, hasPendingSupervisorRequest: supervisorChannel.hasPendingRequests });
770
+ // A headless host may dispose the session as soon as this turn settles, so hand
771
+ // finished results to Pi now; Pi runs the queued completion turn after agent_end.
772
+ // A failed drain rejects without this step so its deadline stays exact.
773
+ if (!ctx.hasUI) await drainOutstandingWork({ state, events: pi.events, hasPendingSupervisorRequest: supervisorChannel.hasPendingRequests }).then(resultWatcher.deliverPendingResults);
799
774
  } finally {
800
775
  // Deliver notices after a failed drain without suppressing its rejection.
801
776
  const ownerSessionId = state.currentSessionId;
@@ -806,7 +781,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
806
781
  const retainedChildren = listRetainedChildren(DIRS.async, ownerSessionId);
807
782
  for (const notice of collectGoalContinuationNotices({ location, ownerSessionId, retainedChildren, turnId: goalTurnId })) {
808
783
  handleSubagentControlNotice({
809
- pi,
784
+ pi: parentWake,
810
785
  state,
811
786
  visibleControlNotices: new Set(),
812
787
  details: { source: "goal", event: notice.event, noticeText: notice.message },
@@ -837,14 +812,14 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
837
812
  });
838
813
  const controlEventHandler = (payload: unknown) => {
839
814
  handleSubagentControlNotice({
840
- pi,
815
+ pi: parentWake,
841
816
  state,
842
817
  visibleControlNotices,
843
818
  details: payload as SubagentControlMessageDetails,
844
819
  });
845
820
  };
846
821
  const steeringNoticeHandler = (payload: unknown) => {
847
- handleSubagentSteeringNotice({ pi, state, details: payload as SubagentSteeringMessageDetails });
822
+ handleSubagentSteeringNotice({ pi: parentWake, state, details: payload as SubagentSteeringMessageDetails });
848
823
  };
849
824
  const asyncStartedHandler = (payload: unknown) => {
850
825
  handleStarted(payload);
@@ -854,6 +829,11 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
854
829
  };
855
830
  const asyncCompleteHandler = (payload: unknown) => {
856
831
  handleComplete(payload);
832
+ // Detached-workflow reconciliation publishes the result, then ends the job
833
+ // with this event; the next status refresh sees it already terminal.
834
+ const job = state.asyncJobs.get((payload as { id?: string } | null)?.id ?? "");
835
+ if (job && job.status !== "queued" && job.status !== "running"
836
+ && fs.existsSync(resultFilePath(DIRS.results, job.asyncId))) holdOwedResult(job);
857
837
  refreshResultDelivery();
858
838
  refreshActiveAsyncCapacity();
859
839
  scheduledRunManager.handleAsyncCompletion(payload);
@@ -861,6 +841,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
861
841
  };
862
842
  const eventUnsubscribes = [
863
843
  registerRuntimeAgentEventListener(pi),
844
+ registerSupervisorResponderEventListener(pi, () => state.supervisorOwnerSessionId ?? null),
864
845
  registerInspectorEventListener(pi),
865
846
  pi.events.on(SUBAGENT_ASYNC_STARTED_EVENT, asyncStartedHandler),
866
847
  pi.events.on(SUBAGENT_ASYNC_COMPLETE_EVENT, asyncCompleteHandler),
@@ -933,7 +914,12 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
933
914
  resultDeliveryOwnership.claimPredecessor(previousSessionFile, previousRuntimeSessionId);
934
915
  state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
935
916
  state.supervisorOwnerSessionId = ctx.sessionManager.getSessionId() || null;
917
+ // A responder binding belongs to one exact runtime session; a reset or
918
+ // tree switch must release every registration that is no longer live.
919
+ disposeSupervisorRoutingForOwner(pi, state.supervisorOwnerSessionId);
936
920
  transitionResultDelivery();
921
+ owedResultRunIds.clear();
922
+ deliveredRunIds.clear();
937
923
  state.parentSessionFile = ctx.sessionManager.getSessionFile();
938
924
  state.trustedSessionFileRoot = state.parentSessionFile ? path.join(getAgentDir(), "sessions") : undefined;
939
925
  state.trustedSessionRoots = [...new Set([
@@ -996,6 +982,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
996
982
  // Snapshot the injectable-agent advertisement once per session so the
997
983
  // appended `<available_subagents>` block stays byte-identical across turns
998
984
  // and provider prompt caching is never invalidated mid-session.
985
+ let contextInjectionProjectTrusted: boolean | undefined;
999
986
  const refreshContextInjectionSnapshot = (ctx: ExtensionContext) => {
1000
987
  if (process.env[SUBAGENT_CHILD_ENV] === "1") return;
1001
988
  try {
@@ -1005,7 +992,8 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1005
992
  state.contextInjectionUnknownNames = [];
1006
993
  return;
1007
994
  }
1008
- const discovery = discoverAgentsAll(cwd);
995
+ contextInjectionProjectTrusted = typeof ctx.isProjectTrusted !== "function" || ctx.isProjectTrusted() !== false;
996
+ const discovery = discoverAgentsAll(cwd, undefined, { projectTrusted: contextInjectionProjectTrusted });
1009
997
  const mergedAgents = mergeAgentsForScope("both", discovery.user, discovery.project, discovery.builtin, discovery.package);
1010
998
  const resolved = resolveInjectableAgents({
1011
999
  agents: mergedAgents,
@@ -1026,11 +1014,21 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1026
1014
  const runtimeEntry: SubagentRuntimeEntry = {
1027
1015
  sessionManager: null,
1028
1016
  visibleControlNotices,
1029
- cleanup() {
1017
+ cleanup(shutdownReason) {
1030
1018
  if (runtimeCleaned) return;
1031
1019
  runtimeCleaned = true;
1020
+ programStatus.dispose(shutdownReason);
1032
1021
  releaseHostSessionLiveness();
1033
1022
  releaseHostSessionLiveness = () => {};
1023
+ // Detached foreground children run in this runtime's memory, and the next runtime
1024
+ // cannot see or control them, so stop each one and record it as stopped.
1025
+ for (const control of state.foregroundControls.values()) {
1026
+ try {
1027
+ control.stopForRuntimeReplacement?.();
1028
+ } catch (error) {
1029
+ console.error(`Failed to stop detached foreground run ${control.runId}:`, error);
1030
+ }
1031
+ }
1034
1032
  // Workflow continuations retain their launch context; abort them before
1035
1033
  // teardown so a reload cannot launch through a stale context.
1036
1034
  for (const controller of state.workflowControllers?.values() ?? []) {
@@ -1076,6 +1074,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1076
1074
  state.widgetsSuspended = false;
1077
1075
  state.currentSessionId = null;
1078
1076
  state.supervisorOwnerSessionId = null;
1077
+ disposeSupervisorRouting(pi);
1079
1078
  state.statusProjectionSessionId = null;
1080
1079
  state.parentSessionFile = null;
1081
1080
  if (runtimeEntry.sessionManager && runtimeRegistry.bySessionManager.get(runtimeEntry.sessionManager) === runtimeEntry) {
@@ -1122,12 +1121,17 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1122
1121
  };
1123
1122
 
1124
1123
  pi.on("agent_start", () => {
1124
+ parentWake.agentStarted();
1125
1125
  resumeWidgetsAfterCompaction();
1126
1126
  herdrStatusBridge.agentStarted();
1127
+ programStatus.agentStarted();
1127
1128
  });
1128
1129
 
1130
+ pi.on("message_start", (event) => completionNotifier.messageStarted(event.message));
1131
+
1129
1132
  pi.on("agent_settled", () => {
1130
1133
  resumeWidgetsAfterCompaction();
1134
+ programStatus.agentSettled();
1131
1135
  });
1132
1136
 
1133
1137
  pi.on("session_before_compact", (event) => {
@@ -1138,7 +1142,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1138
1142
  if (event.reason !== "manual") return;
1139
1143
  const hasActiveAsyncWork = [...state.asyncJobs.values()].some((job) => job.status === "queued" || job.status === "running");
1140
1144
  if (!hasActiveAsyncWork || !withLastUiContext(() => true)) return;
1141
- pi.sendMessage(
1145
+ parentWake.sendMessage(
1142
1146
  {
1143
1147
  customType: "subagent-compaction-resume",
1144
1148
  content: "Compaction is complete. Resume the parent task now; background subagent results will arrive separately when ready.",
@@ -1149,6 +1153,8 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1149
1153
  });
1150
1154
 
1151
1155
  pi.on("session_start", (event, ctx) => {
1156
+ parentWake.bindSession(ctx);
1157
+ completionNotifier.bindSession(ctx.sessionManager);
1152
1158
  installRuntime(ctx);
1153
1159
  startSessionMaintenance();
1154
1160
  scheduleModulePreload();
@@ -1162,7 +1168,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1162
1168
  ? registerPiWebSessionLiveness({
1163
1169
  sessionId,
1164
1170
  ...(sessionFile ? { sessionFile } : {}),
1165
- isActive: () => hasLiveSubagentWork(state) || completionNotifier.hasPendingDelivery(),
1171
+ isActive: () => owedResultRunIds.size > 0 || hasLiveSubagentWork(state) || completionNotifier.hasPendingDelivery() || parentWake.isPending(),
1166
1172
  })
1167
1173
  : { registered: false, release: () => {} };
1168
1174
  releaseHostSessionLiveness = liveness.release;
@@ -1174,13 +1180,16 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1174
1180
  hasUI: ctx.hasUI === true,
1175
1181
  runs: activeHerdrRuns(),
1176
1182
  });
1183
+ programStatus.sessionStarted({ hasUI: ctx.hasUI === true, mode: ctx.mode });
1177
1184
  rpcBridge.emitReady(ctx);
1178
1185
  supervisorChannel.start();
1179
1186
  supervisorChannel.activateTransport();
1180
1187
  });
1181
1188
 
1182
- pi.on("session_shutdown", async () => {
1183
- runtimeEntry.cleanup();
1189
+ pi.on("session_shutdown", async (event) => {
1190
+ completionNotifier.sessionShutdown(event?.reason);
1191
+ parentWake.sessionShutdown(event?.reason);
1192
+ runtimeEntry.cleanup(event?.reason);
1184
1193
  try {
1185
1194
  await disposeChildSessions();
1186
1195
  } catch (error) {