@xzzpig/pi-subagents 0.16.0 → 0.18.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 (133) hide show
  1. package/CHANGELOG.md +164 -1
  2. package/README.md +5 -3
  3. package/agents/claude-code-writer.md +1 -0
  4. package/agents/codex-exec-writer.md +1 -0
  5. package/agents/cursor-agent-writer.md +1 -0
  6. package/agents/reviewer.md +3 -2
  7. package/agents/worker.md +3 -2
  8. package/docs/agents.md +17 -10
  9. package/docs/configuration.md +21 -3
  10. package/docs/extension-api.md +70 -4
  11. package/docs/models.md +5 -3
  12. package/docs/observability.md +23 -13
  13. package/docs/standalone-background.md +4 -4
  14. package/docs/tool-reference.md +40 -19
  15. package/docs/watchdog.md +2 -0
  16. package/docs/workflows.md +57 -3
  17. package/inspector-runner.mjs +1 -1
  18. package/package.json +14 -8
  19. package/prompts/council.md +6 -3
  20. package/runner-peer-loader.mjs +4 -7
  21. package/runner-peer-preload.mjs +5 -7
  22. package/skills/pi-subagents/SKILL.md +1 -0
  23. package/skills/pi-subagents/references/constraints-and-recipes.md +5 -2
  24. package/skills/pi-subagents/references/execution-controls.md +6 -4
  25. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  26. package/skills/pi-subagents/references/multi-lane-orchestration.md +8 -0
  27. package/skills/pi-subagents/references/prompting-and-roles.md +16 -15
  28. package/src/agents/agent-eject.ts +3 -3
  29. package/src/agents/agent-management.ts +61 -52
  30. package/src/agents/agent-memory.ts +90 -3
  31. package/src/agents/agent-serializer.ts +4 -4
  32. package/src/agents/agents.ts +125 -51
  33. package/src/agents/global-npm-root.ts +58 -0
  34. package/src/agents/proactive-skills.ts +4 -1
  35. package/src/agents/runtime-agent-registry.ts +14 -11
  36. package/src/agents/skills.ts +42 -9
  37. package/src/api/delegation.ts +15 -0
  38. package/src/api/inspectors.ts +27 -0
  39. package/src/api/preflight.ts +60 -60
  40. package/src/extension/doctor.ts +9 -4
  41. package/src/extension/fanout-child.ts +8 -0
  42. package/src/extension/index.ts +101 -48
  43. package/src/extension/rpc.ts +10 -1
  44. package/src/extension/schemas.ts +12 -6
  45. package/src/extension/subagent-guide.ts +12 -4
  46. package/src/extension/tool-activation.ts +197 -0
  47. package/src/extension/tool-description.ts +1 -1
  48. package/src/inspectors/ghostty/plugin.ts +13 -1
  49. package/src/inspectors/plugins.ts +70 -3
  50. package/src/intercom/intercom-bridge.ts +2 -0
  51. package/src/intercom/native-supervisor-channel.ts +22 -15
  52. package/src/intercom/result-intercom.ts +4 -0
  53. package/src/runs/background/active-async-capacity.ts +3 -25
  54. package/src/runs/background/async-execution.ts +100 -140
  55. package/src/runs/background/async-job-tracker.ts +28 -34
  56. package/src/runs/background/async-resume.ts +16 -8
  57. package/src/runs/background/async-status.ts +2 -0
  58. package/src/runs/background/binary-bootstrap.ts +34 -6
  59. package/src/runs/background/fleet-view.ts +51 -7
  60. package/src/runs/background/notify.ts +93 -7
  61. package/src/runs/background/pid-namespace.ts +18 -0
  62. package/src/runs/background/process-terminal-candidate.ts +98 -0
  63. package/src/runs/background/process-terminal.ts +17 -96
  64. package/src/runs/background/result-watcher.ts +1 -1
  65. package/src/runs/background/retained-children.ts +3 -2
  66. package/src/runs/background/run-child-session.ts +16 -5
  67. package/src/runs/background/run-id-resolver.ts +10 -5
  68. package/src/runs/background/run-status.ts +10 -4
  69. package/src/runs/background/runner-aliases.ts +25 -15
  70. package/src/runs/background/runner-child-launch.ts +1 -2
  71. package/src/runs/background/runner-startup-failure.ts +56 -0
  72. package/src/runs/background/stale-run-reconciler.ts +19 -3
  73. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  74. package/src/runs/background/subagent-runner.ts +96 -287
  75. package/src/runs/background/wait-tool.ts +2 -0
  76. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  77. package/src/runs/foreground/execution.ts +217 -250
  78. package/src/runs/foreground/prompt-audit.ts +3 -9
  79. package/src/runs/foreground/subagent-executor.ts +377 -119
  80. package/src/runs/shared/acceptance.ts +167 -68
  81. package/src/runs/shared/capability-ceiling.ts +4 -1
  82. package/src/runs/shared/child-hooks.ts +1 -16
  83. package/src/runs/shared/child-launch.ts +22 -14
  84. package/src/runs/shared/child-runtime-config.ts +3 -0
  85. package/src/runs/shared/child-session.ts +52 -2
  86. package/src/runs/shared/child-tool-plan.ts +23 -113
  87. package/src/runs/shared/dynamic-fanout.ts +1 -1
  88. package/src/runs/shared/external-cli-runner.ts +3 -1
  89. package/src/runs/shared/external-job-bridge.ts +54 -0
  90. package/src/runs/shared/git-environment.ts +29 -0
  91. package/src/runs/shared/mcp-config-sources.ts +3 -0
  92. package/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -1
  93. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  94. package/src/runs/shared/model-resolution.ts +6 -1
  95. package/src/runs/shared/nested-events.ts +67 -55
  96. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  97. package/src/runs/shared/parallel-utils.ts +2 -1
  98. package/src/runs/shared/pi-spawn.ts +92 -6
  99. package/src/runs/shared/single-output.ts +11 -2
  100. package/src/runs/shared/structured-output.ts +227 -7
  101. package/src/runs/shared/subagent-control.ts +2 -16
  102. package/src/runs/shared/subagent-prompt-runtime.ts +27 -5
  103. package/src/runs/shared/tool-availability.ts +2 -2
  104. package/src/runs/shared/tool-budget.ts +21 -0
  105. package/src/runs/shared/usage-reconciliation.ts +73 -0
  106. package/src/runs/shared/worktree.ts +35 -8
  107. package/src/shared/child-session-name.ts +4 -2
  108. package/src/shared/fork-context.ts +11 -4
  109. package/src/shared/launch-contract.ts +1 -1
  110. package/src/shared/pruned-fork.ts +69 -56
  111. package/src/shared/types.ts +52 -16
  112. package/src/slash/delegation-adapters.ts +25 -1
  113. package/src/slash/prompt-template-bridge.ts +16 -1
  114. package/src/slash/prompt-workflows.ts +12 -1
  115. package/src/slash/slash-commands.ts +7 -241
  116. package/src/slash/subagent-cost.ts +313 -0
  117. package/src/slash/subagents-admin.ts +28 -29
  118. package/src/tui/fleet-status.ts +24 -2
  119. package/src/tui/fleet.ts +7 -4
  120. package/src/tui/render.ts +53 -19
  121. package/src/watchdog/diff-tool.ts +24 -3
  122. package/src/watchdog/permission-arbiter.ts +13 -15
  123. package/src/watchdog/register-child.ts +10 -2
  124. package/src/watchdog/review.ts +14 -14
  125. package/src/watchdog/runtime.ts +2 -1
  126. package/src/watchdog/turn-delta.ts +11 -5
  127. package/src/workflows/scripted-workflow.ts +109 -23
  128. package/src/workflows/workflow-child-summary.ts +4 -2
  129. package/src/workflows/workflow-settlement.ts +4 -1
  130. package/src/runs/shared/completion-evidence.ts +0 -89
  131. package/src/runs/shared/completion-guard.ts +0 -255
  132. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  133. package/src/runs/shared/task-intent.ts +0 -244
@@ -19,10 +19,11 @@ import * as path from "node:path";
19
19
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
20
20
  import { keyText, type ExtensionAPI, type ExtensionContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
21
21
  import { Box, Container, Spacer, Text, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component } from "@earendil-works/pi-tui";
22
- import { clearAgentDiscoveryCache, discoverAgents, discoverAgentsAll, type AgentConfig, type AgentScope } from "../agents/agents.ts";
22
+ import { clearAgentDiscoveryCache, discoverAgentSnapshot, discoverAgents, discoverAgentsAll, type AgentConfig, type AgentScope } from "../agents/agents.ts";
23
+ import { resolveGlobalNpmRoot } from "../agents/global-npm-root.ts";
23
24
  import { appendAdvertisedAgentPrompt, buildAdvertisedAgentPrompt } from "../agents/advertised-agent-prompt.ts";
24
25
  import { mergeAgentsForScope } from "../agents/agent-selection.ts";
25
- import { clearRuntimeAgentsForPi } from "../agents/runtime-agent-registry.ts";
26
+ import { clearRuntimeAgentsForPi, listRuntimeAgentConfigs, mergeRuntimeAgents } from "../agents/runtime-agent-registry.ts";
26
27
  import { discoverAgentsWithRuntime } from "../agents/runtime-discovery.ts";
27
28
  import { registerRuntimeAgentEventListener } from "../agents/runtime-agent-events.ts";
28
29
  import { ensureAccessibleDir } from "../shared/accessible-dir.ts";
@@ -33,11 +34,10 @@ import { isStaleExtensionContextError, withCachedUiContext } from "../shared/ext
33
34
  import { currentCompletionOwnerId } from "../shared/completion-owner.ts";
34
35
  import { cleanupOldChainDirs } from "../shared/settings.ts";
35
36
  import { clearLegacyResultAnimationTimer, renderSubagentResult, renderSubagentSummary, setInlineWorkflowCoverage } from "../tui/render.ts";
36
- import { openSubagentFleet } from "../tui/fleet.ts";
37
- import { createBuiltinInspectorPlugins } from "../inspectors/plugins.ts";
37
+ import { getInspectorPlugins, registerInspectorEventListener } from "../inspectors/plugins.ts";
38
38
  import { SubagentFleetStatus, resolveFleetViewPlacement } from "../tui/fleet-status.ts";
39
39
  import { createSubagentParamsSchema } from "./schemas.ts";
40
- import { createSubagentExecutor, type SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
40
+ import type { SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
41
41
  import { createAsyncJobTracker } from "../runs/background/async-job-tracker.ts";
42
42
  import { getActiveAsyncCapacitySnapshot, resolveAbandonedSlotReleaseAfterMs, resolveMaxActiveAsyncRunsPerSession } from "../runs/background/active-async-capacity.ts";
43
43
  import { cleanupResultIndexes, missionObserverResultCandidateFiles } from "../runs/background/result-files.ts";
@@ -65,6 +65,7 @@ import { registerSubagentRpcBridge } from "./rpc.ts";
65
65
  import { clearSlashSnapshots, getSlashRenderableSnapshot, resolveSlashMessageDetails, restoreSlashFinalSnapshots, type SlashMessageDetails } from "../slash/slash-live-state.ts";
66
66
  import { resolveWaitToolConfig } from "../runs/background/subagent-wait.ts";
67
67
  import { registerWaitTool } from "../runs/background/wait-tool.ts";
68
+ import { registerSubagentToolActivation } from "./tool-activation.ts";
68
69
  import { createWaitSubscriptionManager } from "../runs/background/wait-subscriptions.ts";
69
70
  import { drainOutstandingWork } from "../runs/background/auto-drain.ts";
70
71
  import registerSubagentNotify, { parseSubagentNotifyContent, type SubagentNotifyDetails } from "../runs/background/notify.ts";
@@ -110,6 +111,10 @@ export { loadConfig, resolveAsyncByDefault } from "./config.ts";
110
111
  const SLOW_RELOAD_PHASE_MS = 250;
111
112
  const RUNTIME_REGISTRY_STORE_KEY = "__piSubagentRuntimeRegistry";
112
113
 
114
+ type SubagentExecutorModule = typeof import("../runs/foreground/subagent-executor.ts");
115
+ type SubagentExecutor = ReturnType<SubagentExecutorModule["createSubagentExecutor"]>;
116
+ type SubagentExecutorDeps = Parameters<SubagentExecutorModule["createSubagentExecutor"]>[0];
117
+
113
118
  interface SubagentRuntimeEntry {
114
119
  cleanup(): void;
115
120
  sessionManager: object | null;
@@ -490,7 +495,8 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
490
495
  };
491
496
 
492
497
  const supervisorChannel = createNativeSupervisorChannel(pi, state, {
493
- getCurrentOwnerStates: () => executor.getCurrentSupervisorOwnerStates(),
498
+ // Owner states are created only by scheduled execution, which loads the executor first.
499
+ getCurrentOwnerStates: () => executor?.getCurrentSupervisorOwnerStates() ?? [],
494
500
  });
495
501
  const waitSubscriptionManager = createWaitSubscriptionManager(pi, state);
496
502
  const mainWatchdog = registerMainWatchdog(pi);
@@ -502,7 +508,8 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
502
508
  const ctx = withLastUiContext((current) => current);
503
509
  if (!ctx) return;
504
510
  try {
505
- await openSubagentFleet(ctx, state, { initialKey: itemKey, asyncDirRoot: DIRS.async, resultsDir: DIRS.results, fleetKeybindings: config.fleetKeybindings, inspectorPlugins: createBuiltinInspectorPlugins(), events: pi.events });
511
+ const { openSubagentFleet } = await import("../tui/fleet.ts");
512
+ await openSubagentFleet(ctx, state, { initialKey: itemKey, asyncDirRoot: DIRS.async, resultsDir: DIRS.results, fleetKeybindings: config.fleetKeybindings, inspectorPlugins: () => getInspectorPlugins(pi), events: pi.events });
506
513
  } catch (error) {
507
514
  if (isStaleExtensionContextError(error)) {
508
515
  if (state.lastUiContext === ctx) state.lastUiContext = null;
@@ -512,44 +519,83 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
512
519
  }
513
520
  }, { placement: fleetViewPlacement, onWorkflowCoverageChange: setInlineWorkflowCoverage })
514
521
  : undefined;
515
- let executorScheduled: ((id: string, params: SubagentParamsLike, signal: AbortSignal, ctx: ExtensionContext) => Promise<AgentToolResult<Details>>) | undefined;
516
522
  let goalTurnId = 0;
517
- let parentSessionEnvValue: string | null = null;
518
523
  let releaseHostSessionLiveness = () => {};
519
524
  const scheduledStoreRoot = config.scheduledRuns?.storeRoot === undefined ? undefined : resolveScheduledStoreRoot(config.scheduledRuns.storeRoot);
520
525
  const scheduledRunManager = createScheduledRunManager({
521
526
  config,
522
527
  storeRoot: scheduledStoreRoot,
523
- launch: (params, ctx, signal) => {
524
- if (!executorScheduled) {
525
- return Promise.resolve({
526
- content: [{ type: "text", text: "Scheduled subagent launch is unavailable (executor not ready)." }],
527
- isError: true,
528
- details: { mode: "management" as const, results: [] },
529
- });
530
- }
531
- return executorScheduled(randomUUID(), params, signal, ctx);
528
+ launch: async (params, ctx, signal) => {
529
+ await waitForAdvertisement();
530
+ return (await getExecutor()).executeScheduled(randomUUID(), params, signal, ctx);
532
531
  },
533
532
  resolveCapabilityCeiling: (sessionId) => resolveCurrentSubagentCapabilityCeiling(sessionId),
534
533
  });
535
534
  let refreshResultDelivery = () => {};
536
535
  let advertisedAgents: AgentConfig[] = [];
537
536
  let advertisedContext: Pick<ExtensionContext, "cwd" | "model"> | undefined;
537
+ let advertisementGeneration = 0;
538
+ let globalRoot: string | null = null;
539
+ let advertisementReady: Promise<void | { error: unknown }> = Promise.resolve();
540
+ let notifySessionChange = () => {};
541
+ let sessionChanged: Promise<void> = Promise.resolve();
542
+ const waitForAdvertisement = async () => {
543
+ let pending: typeof advertisementReady;
544
+ do {
545
+ pending = advertisementReady;
546
+ const result = await Promise.race([pending, sessionChanged]);
547
+ if (pending === advertisementReady && result) throw result.error;
548
+ } while (pending !== advertisementReady);
549
+ };
538
550
  const refreshAdvertisedAgents = () => {
539
551
  advertisedAgents = [];
540
552
  if (!advertisedContext) return;
541
553
  clearAgentDiscoveryCache();
542
- advertisedAgents = discoverAgents(advertisedContext.cwd, "both", advertisedContext.model?.provider).agents
554
+ advertisedAgents = discoverAgents(advertisedContext.cwd, "both", advertisedContext.model?.provider, { globalNpmRoot: globalRoot }).agents
543
555
  .filter((agent) => agent.advertise === true);
544
556
  };
557
+ const beginAdvertisement = (ctx: ExtensionContext) => {
558
+ const generation = ++advertisementGeneration;
559
+ notifySessionChange();
560
+ sessionChanged = new Promise<void>((resolve) => { notifySessionChange = resolve; });
561
+ advertisedAgents = [];
562
+ advertisedContext = { cwd: ctx.cwd, model: ctx.model };
563
+ globalRoot = null;
564
+ advertisementReady = resolveGlobalNpmRoot().then((root) => {
565
+ if (generation !== advertisementGeneration) return;
566
+ globalRoot = root;
567
+ refreshAdvertisedAgents();
568
+ }).catch((error) => {
569
+ if (generation !== advertisementGeneration) return;
570
+ // Settle without an unhandled rejection if no turn follows session_start.
571
+ console.error("Failed to refresh advertised agents:", error);
572
+ return { error };
573
+ });
574
+ };
545
575
  const hasResultDeliveryDemand = () => {
546
576
  if ([...state.asyncJobs.values()].some((job) => job.status === "queued" || job.status === "running")) return true;
547
577
  if (state.foregroundControls.size > 0) return true;
548
578
  if (scheduledRunManager.observedCompletionRunIds().size > 0) return true;
549
579
  return missionObserverResultCandidateFiles(DIRS.results).length > 0;
550
580
  };
551
- const discoverAgentsForRuntime = (cwd: string, scope: AgentScope, preferredModelProvider?: string) =>
552
- discoverAgentsWithRuntime(pi, cwd, scope, preferredModelProvider);
581
+ const discoverAgentsForRuntime = (cwd: string, scope: AgentScope, preferredModelProvider?: string) => {
582
+ if (listRuntimeAgentConfigs(pi).length === 0) return discoverAgents(cwd, scope, preferredModelProvider, { globalNpmRoot: globalRoot });
583
+ const snapshot = discoverAgentSnapshot(cwd, scope, preferredModelProvider, { includeChains: false, globalNpmRoot: globalRoot });
584
+ const discovered = snapshot.effective;
585
+ const all = snapshot.all;
586
+ const configuredAgents: AgentConfig[] = [
587
+ ...all.builtin,
588
+ ...all.package,
589
+ ...all.user,
590
+ ...all.project,
591
+ ];
592
+ const merged = mergeRuntimeAgents(pi, discovered, configuredAgents, { cwd, scope, preferredModelProvider });
593
+ if (discovered.maxThinking === undefined) return merged;
594
+ return {
595
+ ...merged,
596
+ agents: merged.agents.map((agent) => agent.maxThinking === discovered.maxThinking ? agent : { ...agent, maxThinking: discovered.maxThinking }),
597
+ };
598
+ };
553
599
  const { ensurePoller, refreshWidget, handleStarted, handleComplete, resetJobs, restoreActiveJobs, dispose: disposeAsyncJobTracker } = createAsyncJobTracker(pi, state, DIRS.async, {
554
600
  widgetEnabled: asyncWidgetEnabled,
555
601
  onJobTerminal: () => refreshResultDelivery(),
@@ -607,7 +653,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
607
653
  }
608
654
  };
609
655
 
610
- const executorDeps: Parameters<typeof createSubagentExecutor>[0] = {
656
+ const executorDeps: SubagentExecutorDeps = {
611
657
  pi,
612
658
  state,
613
659
  config,
@@ -620,6 +666,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
620
666
  getSubagentSessionRoot,
621
667
  expandTilde,
622
668
  discoverAgents: discoverAgentsForRuntime,
669
+ discoverAgentsAll: (cwd, provider) => discoverAgentsAll(cwd, provider, { globalNpmRoot: globalRoot }),
623
670
  onAgentsChanged: () => {
624
671
  try {
625
672
  refreshAdvertisedAgents();
@@ -633,8 +680,15 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
633
680
  refreshResultDelivery: () => refreshResultDelivery(),
634
681
  trackRetainedNestedRoute: undefined,
635
682
  };
636
- const executor = createSubagentExecutor(executorDeps);
637
- executorScheduled = executor.executeScheduled;
683
+ let executor: SubagentExecutor | undefined;
684
+ let executorPromise: Promise<SubagentExecutor> | undefined;
685
+ const getExecutor = (): Promise<SubagentExecutor> => {
686
+ executorPromise ??= import("../runs/foreground/subagent-executor.ts").then(({ createSubagentExecutor }) => {
687
+ executor = createSubagentExecutor(executorDeps);
688
+ return executor;
689
+ });
690
+ return executorPromise;
691
+ };
638
692
 
639
693
  pi.registerMessageRenderer<SupervisorRequestMessageDetails>(SUPERVISOR_REQUEST_MESSAGE_TYPE, renderSupervisorRequest);
640
694
  // SAFETY: `registerEntryRenderer` is not part of the typed ExtensionAPI in the
@@ -723,9 +777,13 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
723
777
  return new SubagentControlNoticeComponent({ ...details, noticeText: formatSubagentControlNotice(details, content) }, theme);
724
778
  });
725
779
 
780
+ const executeSubagentReady = async (id: string, params: SubagentParamsLike, signal: AbortSignal, onUpdate: ((result: AgentToolResult<Details>) => void) | undefined, ctx: ExtensionContext) => {
781
+ await waitForAdvertisement();
782
+ return (await getExecutor()).executePublic(id, params, signal, onUpdate, ctx);
783
+ };
726
784
  const executeSubagentCollapsed = (id: string, params: SubagentParamsLike, signal: AbortSignal, onUpdate: ((result: AgentToolResult<Details>) => void) | undefined, ctx: ExtensionContext) => {
727
785
  if (ctx.hasUI) ctx.ui.setToolsExpanded(false);
728
- return executor.executePublic(id, params, signal, onUpdate, ctx);
786
+ return executeSubagentReady(id, params, signal, onUpdate, ctx);
729
787
  };
730
788
 
731
789
  const slashBridge = registerSlashSubagentBridge({
@@ -740,16 +798,17 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
740
798
  getContext: () => state.lastUiContext,
741
799
  execute: (requestId, params, signal, ctx, onUpdate) =>
742
800
  executeSubagentCollapsed(requestId, params, signal, onUpdate, ctx),
743
- executeStructured: (requestId, params, signal, ctx, onUpdate) => {
801
+ executeStructured: async (requestId, params, signal, ctx, onUpdate) => {
744
802
  if (ctx.hasUI) ctx.ui.setToolsExpanded(false);
745
- return executor.executeDelegated(requestId, params, signal, onUpdate, ctx);
803
+ await waitForAdvertisement();
804
+ return (await getExecutor()).executeDelegated(requestId, params, signal, onUpdate, ctx);
746
805
  },
747
806
  });
748
807
 
749
808
  const rpcBridge = registerSubagentRpcBridge({
750
809
  events: pi.events,
751
810
  getContext: () => state.lastUiContext,
752
- execute: (id, params, signal, onUpdate, ctx) => executor.executePublic(id, params, signal, onUpdate, ctx),
811
+ execute: executeSubagentReady,
753
812
  state,
754
813
  });
755
814
 
@@ -817,7 +876,8 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
817
876
  return next ? { systemPrompt: next } : undefined;
818
877
  });
819
878
 
820
- pi.on("before_agent_start", (event, ctx) => {
879
+ pi.on("before_agent_start", async (event, ctx) => {
880
+ await waitForAdvertisement();
821
881
  const selectedTools = event.systemPromptOptions?.selectedTools ?? (typeof pi.getActiveTools === "function" ? pi.getActiveTools() : []);
822
882
  const sessionId = state.currentSessionId ?? resolveCurrentSessionId(ctx.sessionManager);
823
883
  const advertisedPrompt = Array.isArray(selectedTools) && selectedTools.includes("subagent")
@@ -827,7 +887,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
827
887
  if (systemPrompt !== event.systemPrompt) return { systemPrompt };
828
888
  });
829
889
 
830
- registerWaitTool(pi, state, waitToolConfig.enabled, waitSubscriptionManager, waitToolConfig.defaultTimeoutMs);
890
+ registerWaitTool(pi, state, waitToolConfig.enabled, waitSubscriptionManager, waitToolConfig.defaultTimeoutMs, undefined, supervisorChannel.hasPendingRequests);
831
891
 
832
892
  pi.on("agent_end", async (_event, ctx) => {
833
893
  if (!ctx.hasUI) await drainOutstandingWork({ state, events: pi.events, hasPendingSupervisorRequest: supervisorChannel.hasPendingRequests });
@@ -891,6 +951,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
891
951
  };
892
952
  const eventUnsubscribes = [
893
953
  registerRuntimeAgentEventListener(pi),
954
+ registerInspectorEventListener(pi),
894
955
  pi.events.on(SUBAGENT_ASYNC_STARTED_EVENT, asyncStartedHandler),
895
956
  pi.events.on(SUBAGENT_ASYNC_COMPLETE_EVENT, asyncCompleteHandler),
896
957
  pi.events.on(SUBAGENT_PROCESS_TERMINAL_EVENT, () => {
@@ -978,17 +1039,10 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
978
1039
  };
979
1040
  const projectPaneOwnerRoot = path.resolve(ctx.cwd);
980
1041
  restoreHerdrProjectPaneSnapshots(state, [...new Set([...(state.herdrProjectPanes?.keys() ?? []), ...listHerdrProjectPaneRoots(projectPaneOwnerRoot), projectPaneOwnerRoot])]);
981
- // Set PI_SUBAGENT_PARENT_SESSION for permission-system forwarding.
982
- // Only set in the root session (the interactive UI session), not in a
983
- // child host: the runner process inherits the parent's value through
984
- // its environment at spawn time and must not overwrite it with a child
985
- // session's identity.
1042
+ // Root hosts may contain independent sessions, so a process-global parent
1043
+ // identity is unsafe. Dedicated child runners retain their launch-owned value.
986
1044
  if (!process.env[SUBAGENT_CHILD_ENV]) {
987
- const sessionId = ctx.sessionManager.getSessionId();
988
- if (sessionId) {
989
- process.env[SUBAGENT_PARENT_SESSION_ENV] = sessionId;
990
- parentSessionEnvValue = sessionId;
991
- }
1045
+ delete process.env[SUBAGENT_PARENT_SESSION_ENV];
992
1046
  }
993
1047
  state.lastUiContext = ctx;
994
1048
  let phaseStartedAt = Date.now();
@@ -1065,7 +1119,6 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1065
1119
  cleanup() {
1066
1120
  if (runtimeCleaned) return;
1067
1121
  runtimeCleaned = true;
1068
- const shuttingDownParentSession = parentSessionEnvValue;
1069
1122
  releaseHostSessionLiveness();
1070
1123
  releaseHostSessionLiveness = () => {};
1071
1124
  // Workflow continuations retain their launch context; abort them before
@@ -1113,10 +1166,6 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1113
1166
  state.supervisorOwnerSessionId = null;
1114
1167
  state.statusProjectionSessionId = null;
1115
1168
  state.parentSessionFile = null;
1116
- parentSessionEnvValue = null;
1117
- if (shuttingDownParentSession && process.env[SUBAGENT_PARENT_SESSION_ENV] === shuttingDownParentSession) {
1118
- delete process.env[SUBAGENT_PARENT_SESSION_ENV];
1119
- }
1120
1169
  if (runtimeEntry.sessionManager && runtimeRegistry.bySessionManager.get(runtimeEntry.sessionManager) === runtimeEntry) {
1121
1170
  runtimeRegistry.bySessionManager.delete(runtimeEntry.sessionManager);
1122
1171
  }
@@ -1227,8 +1276,12 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1227
1276
  await herdrStatusBridge.flush();
1228
1277
  });
1229
1278
 
1230
- pi.on("session_start", (_event, ctx) => {
1231
- advertisedContext = { cwd: ctx.cwd, model: ctx.model };
1232
- refreshAdvertisedAgents();
1279
+ pi.on("session_start", (_event, ctx) => beginAdvertisement(ctx));
1280
+
1281
+ registerSubagentToolActivation(pi, {
1282
+ advertisedPrompt: async () => {
1283
+ await waitForAdvertisement();
1284
+ return buildAdvertisedAgentPrompt(advertisedAgents, resolveCurrentSubagentCapabilityCeiling(state.currentSessionId ?? undefined));
1285
+ },
1233
1286
  });
1234
1287
  }
@@ -23,6 +23,7 @@ import { sanitizeDisplayText, truncateDisplayText } from "../shared/display-text
23
23
  import { readStatus } from "../shared/utils.ts";
24
24
  import { SubagentParams } from "./schemas.ts";
25
25
  import { normalizePublicSubagentExecution } from "./public-execution.ts";
26
+ import { collectSubagentCost, SUBAGENT_COST_REPORT_VERSION } from "../slash/subagent-cost.ts";
26
27
  import { ASYNC_STATUS_SNAPSHOT_KIND, ASYNC_STATUS_SNAPSHOT_VERSION, buildAsyncStatusSnapshotForState } from "../runs/background/async-status-snapshot.ts";
27
28
  import { isStoppableAsyncStatusStep, resolveAsyncStatusChild, stopStoppableAsyncStatusChildren, type ResolvedAsyncStatusChild } from "../runs/shared/child-identity.ts";
28
29
 
@@ -31,7 +32,7 @@ export const SUBAGENT_RPC_REQUEST_EVENT = "subagents:rpc:v1:request";
31
32
  export const SUBAGENT_RPC_READY_EVENT = "subagents:rpc:v1:ready";
32
33
  export const SUBAGENT_RPC_REPLY_EVENT_PREFIX = "subagents:rpc:v1:reply:";
33
34
 
34
- export const SUBAGENT_RPC_METHODS = ["ping", "status", "manage", "spawn", "steer", "interrupt", "stop", "resume"] as const;
35
+ export const SUBAGENT_RPC_METHODS = ["ping", "status", "manage", "spawn", "steer", "interrupt", "stop", "resume", "cost"] as const;
35
36
  export type SubagentRpcMethod = typeof SUBAGENT_RPC_METHODS[number];
36
37
 
37
38
  export interface SubagentRpcRequestEnvelope {
@@ -456,6 +457,7 @@ function pingData(ctx: ExtensionContext | null) {
456
457
  launchResolvedExtensions: { version: 1, source: "launch-resolved" },
457
458
  runtimeAcknowledgedExtensions: { version: 1, source: "child-runtime", event: "subagent:acknowledge-extension" },
458
459
  processTerminalProof: { version: 1, lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION },
460
+ cost: { version: SUBAGENT_COST_REPORT_VERSION },
459
461
  },
460
462
  events: {
461
463
  ready: SUBAGENT_RPC_READY_EVENT,
@@ -765,6 +767,13 @@ async function handleRequest(
765
767
  if (request.method === "resume") {
766
768
  return executeChecked(options, ctx, request.requestId, request.method, resumeParams(request.params));
767
769
  }
770
+ if (request.method === "cost") {
771
+ // The same parent-plus-child accounting `/subagent-cost` renders, as data.
772
+ // Read-only: it walks the current session branch and existing artifacts,
773
+ // so callers should request it on their own turn boundaries, not on a timer.
774
+ if (request.params !== undefined && !isRecord(request.params)) throw new SubagentRpcError("invalid_params", "RPC cost params must be an object when provided.");
775
+ return collectSubagentCost(ctx, options.state ?? { baseCwd: ctx.cwd });
776
+ }
768
777
  throw new SubagentRpcError("unsupported_method", `Unsupported subagent RPC method: ${String(request.method)}`);
769
778
  }
770
779
 
@@ -120,7 +120,7 @@ const ToolBudgetOverride = Type.Object({
120
120
  soft: Type.Optional(Type.Integer({ minimum: 1 })),
121
121
  hard: Type.Integer({ minimum: 1 }),
122
122
  block: Type.Optional(ToolBudgetBlock),
123
- }, { additionalProperties: false, description: "soft nudges; after hard, block tools (default read/grep/find/ls, '*' for all) so child can finalize." });
123
+ }, { additionalProperties: false, description: "soft <= hard; after hard block read/grep/find/ls or '*' for all." });
124
124
 
125
125
  const UsageBudgetLimitOverride = Type.Object({
126
126
  soft: Type.Optional(Type.Number({ exclusiveMinimum: 0 })),
@@ -130,7 +130,7 @@ const UsageBudgetLimitOverride = Type.Object({
130
130
  const UsageBudgetOverride = Type.Object({
131
131
  tokens: Type.Optional(UsageBudgetLimitOverride),
132
132
  costUsd: Type.Optional(UsageBudgetLimitOverride),
133
- }, { additionalProperties: false, description: "Root-only reported usage; hard prevents later launches. Running children are not stopped." });
133
+ }, { additionalProperties: false, minProperties: 1, description: "tokens or costUsd; soft <= hard. Root-only reported usage; blocks launches. Running children are not stopped." });
134
134
 
135
135
  const WorkflowPreflightLane = Type.Object({
136
136
  key: Type.String({ minLength: 1, maxLength: 128 }),
@@ -145,7 +145,7 @@ const WorkflowPreflightOverride = Type.Object({
145
145
  version: Type.Integer({ minimum: 1, maximum: 1 }),
146
146
  coverage: Type.Optional(Type.String({ enum: ["complete", "partial"] })),
147
147
  lanes: Type.Array(WorkflowPreflightLane, { maxItems: 64 }),
148
- }, { additionalProperties: false, description: "Display-only lane hints; coverage mismatches warn, never change authority/execution." });
148
+ }, { additionalProperties: false, description: "workflowScript/workflowScriptPath only; display-only hints; coverage warns." });
149
149
 
150
150
  // Parallel task item (within a parallel step)
151
151
  export const ParallelTaskSchema = Type.Object({
@@ -279,7 +279,7 @@ const ControlOverrides = Type.Object({
279
279
  const SubagentParamProperties = {
280
280
  agent: Type.Optional(Type.String({ description: "One-child agent or management target." })),
281
281
  task: Type.Optional(Type.String({ description: "One-child task; requires agent." })),
282
- extensionBindings: Type.Optional(Type.Unsafe({ type: "object", maxProperties: 16, additionalProperties: true, description: "Child-only bounded JSON; namespaces package.name/1." })),
282
+ extensionBindings: Type.Optional(Type.Unsafe({ type: "object", maxProperties: 16, additionalProperties: true, description: "Child-only plain JSON; package.name/1; depth 16, 256 props, 16 KiB." })),
283
283
  // Management action (when present, tool operates in management mode)
284
284
  action: Type.Optional(Type.String({ minLength: 1,
285
285
  description: "Management/control only; omit for execution. validate accepts either script input. Discover actions with guide topic tool-reference."
@@ -358,7 +358,7 @@ const SubagentParamProperties = {
358
358
  description: "fresh/fork overrides every child; profile requires agent's declared defaultContext, ignoring config. Omitted: defaultSubagentContext wins over each agent defaultContext; implicit fork needs persisted parent + leaf, else fresh. forkContext may prune forks before spawn.",
359
359
  })),
360
360
  async: Type.Optional(Type.Boolean({ description: "Background; default asyncByDefault. false only to block parent." })),
361
- 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." })),
361
+ timeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "Foreground and single async runs use config timeoutMs, else 30m; async composites have no default parent deadline. Alias maxRuntimeMs; must agree." })),
362
362
  maxRuntimeMs: Type.Optional(Type.Integer({ minimum: 1, description: "Alias timeoutMs (same defaults)." })),
363
363
  checkpointBeforeDeadlineMs: Type.Optional(Type.Integer({ minimum: 1, maximum: 2_147_483_647, description: "Async single-agent runs only: the runner requests that the child checkpoint and stop this many ms before the run deadline (best-effort; the deadline kill still applies)." })),
364
364
  toolTimeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "Per-tool deadline (ms); fast builtins default 5m." })),
@@ -389,7 +389,13 @@ const SubagentParamProperties = {
389
389
  outputSchema: Type.Optional(OutputSchemaOverride),
390
390
  agentContract: Type.Optional(AgentContractOverride),
391
391
  acceptance: Type.Optional(AcceptanceOverride),
392
- gate: Type.Optional(Type.String({ minLength: 1, description: "Host gate command. Cannot be combined with acceptance; an explicit acceptance of false is treated as omitted." })),
392
+ gate: Type.Optional(Type.Unsafe({
393
+ anyOf: [
394
+ { type: "string", minLength: 1 },
395
+ { type: "object", properties: { command: { type: "string", minLength: 1 }, output: { type: "string", enum: ["json"] }, schema: { type: "object" }, timeoutMs: { type: "integer", minimum: 1 } }, required: ["command"], additionalProperties: false },
396
+ ],
397
+ description: "Host gate command run after the child finishes: a string, or { command, output: \"json\", schema?, timeoutMs? } whose passing stdout becomes structuredOutput (not with outputSchema). Cannot be combined with acceptance; an explicit acceptance of false is treated as omitted.",
398
+ })),
393
399
  };
394
400
 
395
401
  const SubagentParamsSchema = Type.Object(SubagentParamProperties);
@@ -13,12 +13,21 @@ export const SUBAGENT_GUIDE_TOPICS = [
13
13
  "models",
14
14
  "watchdog",
15
15
  "extension-api",
16
+ "council",
16
17
  ] as const;
17
18
 
18
19
  export type SubagentGuideTopic = (typeof SUBAGENT_GUIDE_TOPICS)[number];
19
20
 
20
21
  const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
21
22
 
23
+ // /council must work under `pi --no-skills`, which drops the package skills from context,
24
+ // so this topic serves the council skill together with the references it tells the model to read.
25
+ const COUNCIL_FILES = [
26
+ "skills/council-mode/SKILL.md",
27
+ "skills/council-mode/references/pass-contracts.md",
28
+ "skills/pi-subagents/references/execution-controls.md",
29
+ ];
30
+
22
31
  function isGuideTopic(value: string): value is SubagentGuideTopic {
23
32
  return (SUBAGENT_GUIDE_TOPICS as readonly string[]).includes(value);
24
33
  }
@@ -27,11 +36,10 @@ export function readSubagentGuide(topic = "overview", root = packageRoot): strin
27
36
  if (!isGuideTopic(topic)) {
28
37
  return `Unknown subagents guide topic '${topic}'. Valid topics: ${SUBAGENT_GUIDE_TOPICS.join(", ")}. No files were changed.`;
29
38
  }
30
- const filePath = topic === "overview"
31
- ? path.join(root, "README.md")
32
- : path.join(root, "docs", `${topic}.md`);
39
+ const files = topic === "overview" ? ["README.md"] : topic === "council" ? COUNCIL_FILES : [path.join("docs", `${topic}.md`)];
33
40
  try {
34
- return fs.readFileSync(filePath, "utf-8");
41
+ const contents = files.map((file) => fs.readFileSync(path.join(root, file), "utf-8"));
42
+ return files.length === 1 ? contents[0]! : contents.map((content, index) => `<!-- ${files[index]} -->\n\n${content}`).join("\n\n");
35
43
  } catch (error) {
36
44
  const message = error instanceof Error ? error.message : String(error);
37
45
  throw new Error(`Failed to read packaged subagents guide '${topic}': ${message}`, { cause: error instanceof Error ? error : undefined });
@@ -0,0 +1,197 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
4
+ import { Type } from "typebox";
5
+ import { PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../shared/utils.ts";
6
+ import { PI_CODING_AGENT_PACKAGE, resolveInstalledPiPackageRoot, resolveRunningPiPackageRoot, type PiSpawnDeps } from "../runs/shared/pi-spawn.ts";
7
+
8
+ interface ActivationDetails {
9
+ enabled?: string[];
10
+ missing?: string[];
11
+ unavailable?: string[];
12
+ }
13
+
14
+ const LOADER_NAME = "subagents_enable";
15
+ const SUBAGENT_NAME = "subagent";
16
+ const MINIMUM_DYNAMIC_TOOLS_VERSION = [0, 86, 1] as const;
17
+ const UNSUPPORTED_HOST_MESSAGE = "Dynamic tool activation requires Pi 0.86.1 or newer";
18
+ let warnedUnsupportedHost = false;
19
+
20
+ /** Returns why dynamic tool activation is unavailable, or undefined when the host supports it. */
21
+ export function unsupportedDynamicToolsReason(pi: ExtensionAPI, deps: PiSpawnDeps = {}): string | undefined {
22
+ if (typeof pi.getAllTools !== "function" || typeof pi.getActiveTools !== "function" || typeof pi.setActiveTools !== "function") return UNSUPPORTED_HOST_MESSAGE;
23
+ const probe = probeHostPiVersion(deps);
24
+ if ("reason" in probe) return probe.reason;
25
+ return supportsMinimumVersion(probe.version) ? undefined : `${UNSUPPORTED_HOST_MESSAGE} (detected ${probe.version} in ${probe.root})`;
26
+ }
27
+
28
+ type HostPiProbe = { version: string; root: string } | { reason: string };
29
+
30
+ /**
31
+ * The host SDK is not a dependency of this package, so a bare module
32
+ * resolution only works where it happens to be installed next to us (a
33
+ * repository checkout with devDependencies). Distributed installs read the
34
+ * version from the Pi that owns the session instead: argv ownership, Pi's
35
+ * package directory, the explicit subagents override, then validated compiled
36
+ * image layouts. A
37
+ * selected root must expose a valid manifest — failures are reported rather
38
+ * than silently falling through to a different Pi installation.
39
+ */
40
+ function probeHostPiVersion(deps: PiSpawnDeps): HostPiProbe {
41
+ const runningRoot = resolveRunningPiPackageRoot(deps);
42
+ // Only the running host and an explicit override identify the Pi that owns this
43
+ // session. An SDK reached through our own install tree cannot be proven to be
44
+ // that installation, so it may inform the reason but never the gate: dynamic
45
+ // activation stays off until the host is verified.
46
+ if (runningRoot && "reason" in runningRoot) return runningRoot;
47
+ if (runningRoot) return readHostPiManifest(runningRoot.root, runningRoot.source === "PI_SUBAGENTS_PI_CODING_AGENT_PACKAGE_ROOT", deps.readFileSync, deps.platform);
48
+ const installedRoot = resolveInstalledPiPackageRoot();
49
+ return { reason: installedRoot
50
+ ? `Could not verify the running Pi installation; ${installedRoot} is not confirmed to be the host that owns this session`
51
+ : "Could not locate the running Pi installation to verify dynamic tool support" };
52
+ }
53
+
54
+ function readHostPiManifest(
55
+ root: string,
56
+ fromOverride: boolean,
57
+ readFileSync: (filePath: string, encoding: "utf-8") => string = (filePath, encoding) => fs.readFileSync(filePath, encoding),
58
+ platform: NodeJS.Platform = process.platform,
59
+ ): HostPiProbe {
60
+ const manifestPath = (platform === "win32" ? path.win32 : path.posix).join(root, "package.json");
61
+ let source: string;
62
+ try {
63
+ source = readFileSync(manifestPath, "utf-8");
64
+ } catch (error) {
65
+ return { reason: `Could not read the Pi package manifest at ${manifestPath}: ${errorMessage(error)}` };
66
+ }
67
+ let parsed: unknown;
68
+ try {
69
+ parsed = JSON.parse(source);
70
+ } catch (error) {
71
+ return { reason: `Invalid Pi package manifest at ${manifestPath}: ${errorMessage(error)}` };
72
+ }
73
+ if (!isRecord(parsed) || parsed.name !== PI_CODING_AGENT_PACKAGE) {
74
+ return { reason: `${manifestPath} is not ${PI_CODING_AGENT_PACKAGE}${fromOverride ? ` (${PI_CODING_AGENT_PACKAGE_ROOT_ENV} override)` : ""}` };
75
+ }
76
+ return typeof parsed.version === "string" && parsed.version
77
+ ? { version: parsed.version, root }
78
+ : { reason: `The Pi package manifest at ${manifestPath} has no version` };
79
+ }
80
+
81
+ function errorMessage(error: unknown): string {
82
+ return error instanceof Error ? error.message : String(error);
83
+ }
84
+
85
+ function isRecord(value: unknown): value is Record<string, unknown> {
86
+ return typeof value === "object" && value !== null && !Array.isArray(value);
87
+ }
88
+
89
+ export function supportsMinimumVersion(version: string): boolean {
90
+ const parsed = version.split(".").slice(0, 3).map(Number);
91
+ if (parsed.length !== 3 || parsed.some((part) => !Number.isInteger(part) || part < 0)) return false;
92
+ for (let index = 0; index < 3; index++) {
93
+ const part = parsed[index]!;
94
+ const minimum = MINIMUM_DYNAMIC_TOOLS_VERSION[index]!;
95
+ if (part !== minimum) return part > minimum;
96
+ }
97
+ return true;
98
+ }
99
+
100
+ type ToolSelectionMessage = {
101
+ role: string;
102
+ toolsAdded?: readonly { name: string }[];
103
+ toolsRemoved?: readonly { name: string }[];
104
+ };
105
+
106
+ function hasNativeToolSelection(messages: readonly ToolSelectionMessage[]): boolean {
107
+ return messages.some((message) => message.role === "system"
108
+ && (Object.hasOwn(message, "toolsAdded") || Object.hasOwn(message, "toolsRemoved")));
109
+ }
110
+
111
+ function setSelection(pi: ExtensionAPI, includeSubagent: boolean): void {
112
+ const active = pi.getActiveTools();
113
+ const next = includeSubagent ? [...active, SUBAGENT_NAME] : active.filter((name) => name !== SUBAGENT_NAME);
114
+ if (!next.includes(LOADER_NAME)) next.push(LOADER_NAME);
115
+ pi.setActiveTools([...new Set(next)]);
116
+ }
117
+
118
+ function applyRecordedSelection(pi: ExtensionAPI, ctx: ExtensionContext): void {
119
+ const available = pi.getAllTools();
120
+ if (!Array.isArray(available) || !Array.isArray(pi.getActiveTools())) return;
121
+ if (!available.some((tool) => tool.name === LOADER_NAME)) return;
122
+ // SAFETY: The running Pi session manager exposes buildSessionContext, but its read-only extension type omits it.
123
+ const messages = (ctx.sessionManager as typeof ctx.sessionManager & { buildSessionContext(): { messages: ToolSelectionMessage[] } }).buildSessionContext().messages;
124
+ if (hasNativeToolSelection(messages)) {
125
+ // Only this tool's membership matters; a package-local pi-ai may be older than the running Pi.
126
+ let selected = false;
127
+ for (const message of messages) {
128
+ if (message.role !== "system") continue;
129
+ if (message.toolsRemoved?.some((tool) => tool.name === SUBAGENT_NAME)) selected = false;
130
+ if (message.toolsAdded?.some((tool) => tool.name === SUBAGENT_NAME)) selected = true;
131
+ }
132
+ setSelection(pi, selected);
133
+ return;
134
+ }
135
+ setSelection(pi, messages.length > 0 && pi.getActiveTools().includes(SUBAGENT_NAME));
136
+ }
137
+
138
+ export function registerSubagentToolActivation(
139
+ pi: ExtensionAPI,
140
+ options: { advertisedPrompt: () => string | undefined | Promise<string | undefined> },
141
+ ): void {
142
+ const unsupportedReason = unsupportedDynamicToolsReason(pi);
143
+ if (unsupportedReason) {
144
+ if (!warnedUnsupportedHost) {
145
+ warnedUnsupportedHost = true;
146
+ console.warn(`[pi-subagents] ${unsupportedReason}; keeping subagent eagerly available.`);
147
+ }
148
+ return;
149
+ }
150
+
151
+ // Takes no arguments, but a stray one (DeepSeek sends `{ action: "enable" }`) must not fail validation.
152
+ const parameters = Type.Object({});
153
+ const loader: ToolDefinition<typeof parameters, ActivationDetails> = {
154
+ name: LOADER_NAME,
155
+ label: "Enable Subagents",
156
+ description: "Enable pi-subagents delegation and management tools without launching work. Call when delegation is authorized by the current request or applicable user/project instructions, or when managing existing runs. Direct execution is the default; complexity alone never authorizes delegation. Full tools are available on the next model request.",
157
+ promptSnippet: "pi-subagents is installed. For authorized specialist, independent-review, or parallel work, call subagents_enable, then subagent. Authorization must come from the current request or applicable instructions; complexity alone is not authorization.",
158
+ parameters,
159
+ async execute() {
160
+ if (!pi.getAllTools().some((tool) => tool.name === SUBAGENT_NAME)) return {
161
+ isError: true,
162
+ content: [{ type: "text", text: "Cannot enable unavailable tools: subagent." }],
163
+ details: { unavailable: [SUBAGENT_NAME] },
164
+ };
165
+ try {
166
+ setSelection(pi, true);
167
+ } catch (error) {
168
+ return {
169
+ isError: true,
170
+ content: [{ type: "text", text: `Activation failed: ${error instanceof Error ? error.message : String(error)}` }],
171
+ details: { missing: [SUBAGENT_NAME] },
172
+ };
173
+ }
174
+ if (!pi.getActiveTools().includes(SUBAGENT_NAME)) return {
175
+ isError: true,
176
+ content: [{ type: "text", text: "Activation failed: subagent." }],
177
+ details: { missing: [SUBAGENT_NAME] },
178
+ };
179
+ const advertised = await options.advertisedPrompt();
180
+ return {
181
+ content: [{ type: "text", text: `Enabled: subagent. On the next model request, call subagent({action:\"list\",capabilities:true}) for current capabilities.${advertised ? `\n\n${advertised}` : ""}` }],
182
+ details: { enabled: [SUBAGENT_NAME] },
183
+ };
184
+ },
185
+ };
186
+ pi.registerTool(loader);
187
+
188
+ pi.on("session_start", (_event, ctx) => applyRecordedSelection(pi, ctx));
189
+ pi.on("session_tree", (_event, ctx) => applyRecordedSelection(pi, ctx));
190
+ pi.on("before_agent_start", (event) => {
191
+ const available = pi.getAllTools();
192
+ if (!Array.isArray(available) || !available.some((tool) => tool.name === LOADER_NAME)) return;
193
+ const selectedTools = event.systemPromptOptions.selectedTools ??= [...pi.getActiveTools()];
194
+ if (!selectedTools.includes(LOADER_NAME)) selectedTools.push(LOADER_NAME);
195
+ if (!pi.getActiveTools().includes(LOADER_NAME)) pi.setActiveTools([...pi.getActiveTools(), LOADER_NAME]);
196
+ });
197
+ }