@xzzpig/pi-subagents 0.16.0 → 0.19.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 (166) hide show
  1. package/CHANGELOG.md +233 -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 +34 -21
  9. package/docs/configuration.md +82 -7
  10. package/docs/extension-api.md +75 -8
  11. package/docs/missions.md +13 -13
  12. package/docs/models.md +7 -5
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +5 -5
  15. package/docs/tool-reference.md +98 -100
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +214 -162
  18. package/inspector-runner.mjs +1 -1
  19. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  20. package/package.json +15 -9
  21. package/prompts/council.md +6 -3
  22. package/prompts/review-loop.md +1 -1
  23. package/runner-peer-loader.mjs +4 -7
  24. package/runner-peer-preload.mjs +5 -7
  25. package/skills/council-mode/SKILL.md +1 -1
  26. package/skills/pi-subagents/SKILL.md +13 -5
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +8 -5
  28. package/skills/pi-subagents/references/execution-controls.md +72 -69
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +4 -4
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +9 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +52 -54
  32. package/src/agents/advertised-agent-prompt.ts +21 -41
  33. package/src/agents/agent-eject.ts +3 -3
  34. package/src/agents/agent-management.ts +63 -54
  35. package/src/agents/agent-memory.ts +90 -3
  36. package/src/agents/agent-serializer.ts +4 -4
  37. package/src/agents/agents.ts +132 -51
  38. package/src/agents/global-npm-root.ts +58 -0
  39. package/src/agents/proactive-skills.ts +4 -1
  40. package/src/agents/runtime-agent-registry.ts +14 -11
  41. package/src/agents/skills.ts +42 -9
  42. package/src/api/delegation.ts +15 -0
  43. package/src/api/inspectors.ts +27 -0
  44. package/src/api/preflight.ts +7 -2
  45. package/src/extension/config.ts +12 -4
  46. package/src/extension/control-notices.ts +3 -0
  47. package/src/extension/doctor.ts +10 -4
  48. package/src/extension/fanout-child.ts +20 -3
  49. package/src/extension/herdr-pi-bridge.ts +2 -0
  50. package/src/extension/index.ts +168 -206
  51. package/src/extension/public-execution.ts +69 -35
  52. package/src/extension/reply-workflow-script.ts +58 -0
  53. package/src/extension/rpc.ts +39 -11
  54. package/src/extension/schemas.ts +47 -138
  55. package/src/extension/subagent-guide.ts +12 -4
  56. package/src/extension/tool-activation.ts +146 -0
  57. package/src/extension/tool-description.ts +62 -27
  58. package/src/extension/upgrade-notice.ts +40 -0
  59. package/src/inspectors/ghostty/plugin.ts +13 -1
  60. package/src/inspectors/plugins.ts +70 -3
  61. package/src/integrations/herdr-status.ts +19 -3
  62. package/src/intercom/intercom-bridge.ts +2 -0
  63. package/src/intercom/native-supervisor-channel.ts +26 -16
  64. package/src/intercom/result-intercom.ts +4 -0
  65. package/src/runs/background/active-async-capacity.ts +3 -25
  66. package/src/runs/background/async-execution.ts +60 -95
  67. package/src/runs/background/async-job-tracker.ts +91 -56
  68. package/src/runs/background/async-resume.ts +16 -8
  69. package/src/runs/background/async-retention.ts +46 -16
  70. package/src/runs/background/async-status.ts +2 -0
  71. package/src/runs/background/await-async-run.ts +76 -0
  72. package/src/runs/background/binary-bootstrap.ts +34 -6
  73. package/src/runs/background/chain-root-attachment.ts +4 -4
  74. package/src/runs/background/control-channel.ts +18 -2
  75. package/src/runs/background/fleet-view.ts +51 -7
  76. package/src/runs/background/notify.ts +98 -7
  77. package/src/runs/background/pid-namespace.ts +18 -0
  78. package/src/runs/background/process-terminal-candidate.ts +98 -0
  79. package/src/runs/background/process-terminal.ts +17 -96
  80. package/src/runs/background/result-watcher.ts +1 -1
  81. package/src/runs/background/retained-children.ts +3 -2
  82. package/src/runs/background/run-child-session.ts +20 -6
  83. package/src/runs/background/run-id-resolver.ts +10 -5
  84. package/src/runs/background/run-status.ts +16 -4
  85. package/src/runs/background/runner-aliases.ts +54 -16
  86. package/src/runs/background/runner-child-launch.ts +4 -2
  87. package/src/runs/background/runner-startup-failure.ts +56 -0
  88. package/src/runs/background/scheduled-runs.ts +5 -5
  89. package/src/runs/background/stale-run-reconciler.ts +19 -3
  90. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  91. package/src/runs/background/subagent-runner.ts +111 -288
  92. package/src/runs/background/wait-tool.ts +2 -0
  93. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  94. package/src/runs/foreground/async-stop-action.ts +17 -3
  95. package/src/runs/foreground/execution.ts +111 -139
  96. package/src/runs/foreground/prompt-audit.ts +3 -9
  97. package/src/runs/foreground/subagent-executor.ts +715 -258
  98. package/src/runs/shared/acceptance.ts +167 -68
  99. package/src/runs/shared/async-status-projection.ts +5 -0
  100. package/src/runs/shared/capability-ceiling.ts +4 -1
  101. package/src/runs/shared/child-hooks.ts +1 -16
  102. package/src/runs/shared/child-launch.ts +37 -16
  103. package/src/runs/shared/child-runtime-config.ts +3 -0
  104. package/src/runs/shared/child-session.ts +144 -8
  105. package/src/runs/shared/child-tool-plan.ts +38 -116
  106. package/src/runs/shared/dynamic-fanout.ts +1 -1
  107. package/src/runs/shared/external-cli-runner.ts +3 -1
  108. package/src/runs/shared/external-job-bridge.ts +54 -0
  109. package/src/runs/shared/git-environment.ts +29 -0
  110. package/src/runs/shared/mcp-config-sources.ts +5 -1
  111. package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -12
  112. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  113. package/src/runs/shared/model-resolution.ts +35 -10
  114. package/src/runs/shared/model-scope.ts +28 -9
  115. package/src/runs/shared/nested-events.ts +12 -0
  116. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  117. package/src/runs/shared/parallel-utils.ts +4 -1
  118. package/src/runs/shared/pi-spawn.ts +1 -3
  119. package/src/runs/shared/single-output.ts +11 -2
  120. package/src/runs/shared/structured-output.ts +227 -7
  121. package/src/runs/shared/subagent-control.ts +2 -16
  122. package/src/runs/shared/subagent-prompt-runtime.ts +29 -5
  123. package/src/runs/shared/tool-availability.ts +2 -2
  124. package/src/runs/shared/tool-budget.ts +21 -0
  125. package/src/runs/shared/usage-reconciliation.ts +73 -0
  126. package/src/runs/shared/worktree.ts +36 -9
  127. package/src/shared/child-session-name.ts +4 -2
  128. package/src/shared/disabled-features.ts +123 -0
  129. package/src/shared/extension-context.ts +13 -0
  130. package/src/shared/fork-context.ts +11 -4
  131. package/src/shared/launch-contract.ts +1 -1
  132. package/src/shared/model-info.ts +9 -0
  133. package/src/shared/pruned-fork.ts +69 -56
  134. package/src/shared/settings.ts +1 -1
  135. package/src/shared/types.ts +73 -16
  136. package/src/slash/delegation-adapters.ts +25 -1
  137. package/src/slash/prompt-template-bridge.ts +18 -3
  138. package/src/slash/prompt-workflows.ts +12 -1
  139. package/src/slash/slash-commands.ts +17 -246
  140. package/src/slash/subagent-cost.ts +313 -0
  141. package/src/slash/subagents-admin.ts +4 -5
  142. package/src/tui/fleet-status.ts +38 -8
  143. package/src/tui/fleet.ts +21 -6
  144. package/src/tui/render.ts +166 -71
  145. package/src/tui/running-tone.ts +28 -0
  146. package/src/watchdog/diff-tool.ts +47 -12
  147. package/src/watchdog/permission-arbiter.ts +13 -15
  148. package/src/watchdog/register-child.ts +13 -5
  149. package/src/watchdog/register-main.ts +3 -3
  150. package/src/watchdog/review.ts +16 -16
  151. package/src/watchdog/runtime.ts +2 -1
  152. package/src/watchdog/turn-delta.ts +12 -6
  153. package/src/workflows/chat-progress.ts +2 -2
  154. package/src/workflows/scripted-workflow.ts +225 -59
  155. package/src/workflows/structured-workflow-scripts.ts +177 -0
  156. package/src/workflows/workflow-checklist.ts +6 -0
  157. package/src/workflows/workflow-child-summary.ts +4 -2
  158. package/src/workflows/workflow-receipt.ts +8 -2
  159. package/src/workflows/workflow-resources.ts +37 -12
  160. package/src/workflows/workflow-reuse.ts +120 -0
  161. package/src/workflows/workflow-revival.ts +123 -0
  162. package/src/workflows/workflow-settlement.ts +4 -1
  163. package/src/runs/shared/completion-evidence.ts +0 -89
  164. package/src/runs/shared/completion-guard.ts +0 -255
  165. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  166. package/src/runs/shared/task-intent.ts +0 -244
@@ -5,7 +5,7 @@ import { validateAcceptanceInput } from "../runs/shared/acceptance.ts";
5
5
  import { validatePermissionRules, type PermissionRules } from "../runs/shared/permissions.ts";
6
6
  import { validateToolBudgetConfig } from "../runs/shared/tool-budget.ts";
7
7
  import { BUILTIN_AGENT_NAMES } from "./builtin-names.ts";
8
- import type { AgentConfig, AgentDefaultContext, AgentDiscoveryDiagnostic } from "./agents.ts";
8
+ import { applyRuntimeAgentSettings, type AgentConfig, type AgentDefaultContext, type AgentDiscoveryDiagnostic, type RuntimeAgentSettingsContext } from "./agents.ts";
9
9
  import { validateSandboxProfileName } from "../shared/sandbox-profile.ts";
10
10
  import { validatePermissionProfileName } from "../shared/permission-profile.ts";
11
11
 
@@ -51,7 +51,6 @@ export interface RuntimeAgentDefinition {
51
51
  injectToContext?: boolean;
52
52
  interactive?: boolean;
53
53
  maxSubagentDepth?: number;
54
- completionGuard?: boolean;
55
54
  toolBudget?: ToolBudgetConfig;
56
55
  sandbox?: string;
57
56
  permissionProfile?: string;
@@ -208,7 +207,7 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
208
207
  "systemPromptMode", "inheritProjectContext", "inheritGlobalContext", "inheritSkills", "defaultContext", "defaultAsync", "defaultTimeoutMs",
209
208
  "defaultToolTimeoutMs", "defaultAcceptance", "acceptanceRole", "runner", "machine", "skills", "skillPath",
210
209
  "extensions", "subagentOnlyExtensions", "mutationTools", "output", "outputMode", "defaultReads", "defaultProgress", "injectToContext", "interactive",
211
- "maxSubagentDepth", "completionGuard", "toolBudget", "sandbox", "permissionProfile", "permissions",
210
+ "maxSubagentDepth", "toolBudget", "sandbox", "permissionProfile", "permissions",
212
211
  ]);
213
212
  const unknown = Object.keys(definition).filter((key) => !supported.has(key));
214
213
  if (unknown.length > 0) throw new Error(`Runtime agent definition has unknown fields: ${unknown.join(", ")}.`);
@@ -249,7 +248,6 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
249
248
  const injectToContext = validateBoolean(definition.injectToContext, "Runtime agent definition injectToContext");
250
249
  const interactive = validateBoolean(definition.interactive, "Runtime agent definition interactive");
251
250
  const maxSubagentDepth = validatePositiveInteger(definition.maxSubagentDepth, "Runtime agent definition maxSubagentDepth");
252
- const completionGuard = validateBoolean(definition.completionGuard, "Runtime agent definition completionGuard");
253
251
  const toolBudget = validateToolBudget(definition.toolBudget);
254
252
  const sandbox = definition.sandbox === undefined
255
253
  ? undefined
@@ -298,7 +296,6 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
298
296
  ...(injectToContext !== undefined ? { injectToContext } : {}),
299
297
  ...(interactive !== undefined ? { interactive } : {}),
300
298
  ...(maxSubagentDepth !== undefined ? { maxSubagentDepth } : {}),
301
- ...(completionGuard !== undefined ? { completionGuard } : {}),
302
299
  ...(toolBudget !== undefined ? { toolBudget } : {}),
303
300
  ...(sandbox !== undefined ? { sandbox } : {}),
304
301
  ...(permissionProfile !== undefined ? { permissionProfile } : {}),
@@ -383,7 +380,6 @@ function toAgentConfig(name: string, definition: RuntimeAgentDefinition): AgentC
383
380
  ...(definition.injectToContext !== undefined ? { injectToContext: definition.injectToContext } : {}),
384
381
  ...(definition.interactive !== undefined ? { interactive: definition.interactive } : {}),
385
382
  ...(definition.maxSubagentDepth !== undefined ? { maxSubagentDepth: definition.maxSubagentDepth } : {}),
386
- ...(definition.completionGuard !== undefined ? { completionGuard: definition.completionGuard } : {}),
387
383
  ...(definition.toolBudget !== undefined ? { toolBudget: definition.toolBudget } : {}),
388
384
  ...(definition.sandbox !== undefined ? { sandbox: definition.sandbox } : {}),
389
385
  ...(definition.permissionProfile !== undefined ? { permissionProfile: definition.permissionProfile } : {}),
@@ -445,10 +441,17 @@ function assertNoConfiguredCollision(configuredAgents: readonly AgentConfig[], r
445
441
  }
446
442
  }
447
443
 
448
- export function mergeRuntimeAgents<T extends { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[] }>(pi: RuntimeAgentOwner, discovered: T, configuredAgents: readonly AgentConfig[] = discovered.agents): T {
449
- const runtimeAgents = listRuntimeAgentConfigs(pi).filter((agent) => agent.disabled !== true);
450
- if (runtimeAgents.length === 0) return discovered;
451
- assertNoIdentityCollisions(runtimeAgents, "Runtime agent registration");
452
- assertNoConfiguredCollision(configuredAgents, runtimeAgents);
444
+ /**
445
+ * Append registered runtime agents to a discovery result. With `settings`, the
446
+ * runtime agents also receive the subagent model-tier settings that apply in
447
+ * that discovery context (see `applyRuntimeAgentSettings`); without it they
448
+ * carry only their registered definition.
449
+ */
450
+ export function mergeRuntimeAgents<T extends { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[] }>(pi: RuntimeAgentOwner, discovered: T, configuredAgents: readonly AgentConfig[] = discovered.agents, settings?: RuntimeAgentSettingsContext): T {
451
+ const registered = listRuntimeAgentConfigs(pi).filter((agent) => agent.disabled !== true);
452
+ if (registered.length === 0) return discovered;
453
+ assertNoIdentityCollisions(registered, "Runtime agent registration");
454
+ assertNoConfiguredCollision(configuredAgents, registered);
455
+ const runtimeAgents = settings ? applyRuntimeAgentSettings(registered, settings) : registered;
453
456
  return { ...discovered, agents: [...discovered.agents, ...runtimeAgents] };
454
457
  }
@@ -6,6 +6,7 @@ import { execSync } from "node:child_process";
6
6
  import * as fs from "node:fs";
7
7
  import * as os from "node:os";
8
8
  import * as path from "node:path";
9
+ import { parse as parseYaml } from "yaml";
9
10
  import { parseFrontmatter } from "./frontmatter.ts";
10
11
  import { getAgentDir, getProjectConfigDir } from "../shared/utils.ts";
11
12
 
@@ -26,6 +27,7 @@ interface ResolvedSkill {
26
27
  content: string;
27
28
  description?: string;
28
29
  source: SkillSource;
30
+ disableModelInvocation?: boolean;
29
31
  }
30
32
 
31
33
  interface SkillCacheEntry {
@@ -38,6 +40,7 @@ interface CachedSkillEntry {
38
40
  filePath: string;
39
41
  source: SkillSource;
40
42
  description?: string;
43
+ disableModelInvocation?: boolean;
41
44
  order: number;
42
45
  }
43
46
 
@@ -142,7 +145,7 @@ function getGlobalNpmRoot(): string | null {
142
145
  }
143
146
 
144
147
  try {
145
- cachedGlobalNpmRoot = fs.realpathSync(execSync("npm root -g", { encoding: "utf-8", timeout: 5000, windowsHide: true }).trim());
148
+ cachedGlobalNpmRoot = fs.realpathSync(execSync("npm root -g", { encoding: "utf-8", timeout: 5000, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] }).trim());
146
149
  return cachedGlobalNpmRoot;
147
150
  } catch {
148
151
  // Global npm root is optional in constrained environments.
@@ -399,11 +402,30 @@ function parseSkillDescription(content: string): string | undefined {
399
402
  return parseFrontmatter(content).frontmatter.description;
400
403
  }
401
404
 
402
- function maybeReadSkillDescription(filePath: string): string | undefined {
405
+ function maybeReadSkillMetadata(filePath: string): Pick<CachedSkillEntry, "description" | "disableModelInvocation"> {
403
406
  try {
404
- return parseSkillDescription(fs.readFileSync(filePath, "utf-8"));
407
+ const content = fs.readFileSync(filePath, "utf-8");
408
+ return { description: parseSkillDescription(content), disableModelInvocation: maybeReadSkillDisableModelInvocation(content) };
405
409
  } catch {
406
- // Description parsing is best-effort metadata extraction.
410
+ return {};
411
+ }
412
+ }
413
+
414
+ function maybeReadSkillDisableModelInvocation(content: string): boolean | undefined {
415
+ try {
416
+ const normalized = content.replace(/\r\n/g, "\n");
417
+ if (!normalized.startsWith("---")) return undefined;
418
+ const endIndex = normalized.indexOf("\n---", 3);
419
+ if (endIndex === -1) return undefined;
420
+ const parsed: unknown = parseYaml(normalized.slice(4, endIndex));
421
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
422
+ // Match the pi host's skill loader semantics: only YAML boolean true
423
+ // disables model invocation; strings and other values stay invocable.
424
+ // Hidden skills remain user-invocable via explicit `/skill:name` commands
425
+ // but must stay out of the model-facing default skill set.
426
+ return (parsed as Record<string, unknown>)["disable-model-invocation"] === true ? true : undefined;
427
+ } catch {
428
+ // Best-effort metadata extraction.
407
429
  return undefined;
408
430
  }
409
431
  }
@@ -418,17 +440,18 @@ function collectFilesystemSkills(cwd: string, agentDir: string, skillPaths: Skil
418
440
  const resolvedFile = path.resolve(filePath);
419
441
  if (!fs.existsSync(resolvedFile)) return;
420
442
  const source = inferSkillSource(resolvedFile, cwd, agentDir, sourceHint);
421
- const description = maybeReadSkillDescription(resolvedFile);
443
+ const { description, disableModelInvocation } = maybeReadSkillMetadata(resolvedFile);
422
444
  const existingIndex = seen.get(resolvedFile);
423
445
  if (existingIndex !== undefined) {
424
446
  const existing = entries[existingIndex];
425
447
  if (existing && (SOURCE_PRIORITY[source] ?? 0) > (SOURCE_PRIORITY[existing.source] ?? 0)) {
426
- const { description: _description, ...existingWithoutDescription } = existing;
448
+ const { description: _description, disableModelInvocation: _disableModelInvocation, ...existingWithoutMetadata } = existing;
427
449
  entries[existingIndex] = {
428
- ...existingWithoutDescription,
450
+ ...existingWithoutMetadata,
429
451
  name,
430
452
  source,
431
453
  ...(description !== undefined ? { description } : {}),
454
+ ...(disableModelInvocation !== undefined ? { disableModelInvocation } : {}),
432
455
  };
433
456
  }
434
457
  return;
@@ -439,6 +462,7 @@ function collectFilesystemSkills(cwd: string, agentDir: string, skillPaths: Skil
439
462
  filePath: resolvedFile,
440
463
  source,
441
464
  ...(description !== undefined ? { description } : {}),
465
+ ...(disableModelInvocation !== undefined ? { disableModelInvocation } : {}),
442
466
  order: order++,
443
467
  });
444
468
  };
@@ -598,11 +622,13 @@ function readSkill(
598
622
  const raw = fs.readFileSync(skillPath, "utf-8");
599
623
  const content = stripSkillFrontmatter(raw);
600
624
  const description = parseSkillDescription(raw);
625
+ const disableModelInvocation = maybeReadSkillDisableModelInvocation(raw);
601
626
  const skill: ResolvedSkill = {
602
627
  name: skillName,
603
628
  path: skillPath,
604
629
  content,
605
630
  ...(description !== undefined ? { description } : {}),
631
+ ...(disableModelInvocation !== undefined ? { disableModelInvocation } : {}),
606
632
  source,
607
633
  };
608
634
 
@@ -679,7 +705,12 @@ export function resolveSkillsWithFallback(
679
705
  }
680
706
 
681
707
  export function buildSkillInjection(skills: ResolvedSkill[]): string {
682
- if (skills.length === 0) return "";
708
+ // Hidden skills (disable-model-invocation: true) must never reach a child
709
+ // prompt, even if a caller resolves them by name. This is the single
710
+ // chokepoint every prompt-injection path funnels through, so filtering
711
+ // here closes the leak regardless of which caller assembled the list.
712
+ const visibleSkills = skills.filter((skill) => !skill.disableModelInvocation);
713
+ if (visibleSkills.length === 0) return "";
683
714
 
684
715
  const lines = [
685
716
  "The following configured skills are available to this subagent.",
@@ -688,7 +719,7 @@ export function buildSkillInjection(skills: ResolvedSkill[]): string {
688
719
  "",
689
720
  "<available_skills>",
690
721
  ];
691
- for (const skill of skills) {
722
+ for (const skill of visibleSkills) {
692
723
  lines.push(" <skill>");
693
724
  lines.push(` <name>${escapeXmlText(skill.name)}</name>`);
694
725
  lines.push(` <description>${escapeXmlText(skill.description ?? "")}</description>`);
@@ -736,6 +767,7 @@ export function discoverAvailableSkills(cwd: string): Array<{
736
767
  name: string;
737
768
  source: SkillSource;
738
769
  description?: string;
770
+ disableModelInvocation?: boolean;
739
771
  }> {
740
772
  const skills = getCachedSkills(cwd);
741
773
  return skills
@@ -744,6 +776,7 @@ export function discoverAvailableSkills(cwd: string): Array<{
744
776
  name: s.name,
745
777
  source: s.source,
746
778
  ...(s.description !== undefined ? { description: s.description } : {}),
779
+ ...(s.disableModelInvocation !== undefined ? { disableModelInvocation: s.disableModelInvocation } : {}),
747
780
  }))
748
781
  .sort((a, b) => a.name.localeCompare(b.name));
749
782
  }
@@ -48,6 +48,20 @@ export interface SubagentDelegationStarted {
48
48
  nodeId: string;
49
49
  }
50
50
 
51
+ /**
52
+ * Cumulative usage for one attempt at one observation time. This snapshot is
53
+ * emitted only when every counter is known, finite, and non-negative. It does
54
+ * not combine retries or replace authoritative terminal usage; absence means
55
+ * unavailable, not zero. UPDATE `tokens` keeps its input-plus-output meaning.
56
+ */
57
+ export interface SubagentDelegationUpdateUsage {
58
+ input: number;
59
+ output: number;
60
+ cacheRead: number;
61
+ cacheWrite: number;
62
+ turns: number;
63
+ }
64
+
51
65
  export interface SubagentDelegationUpdate extends SubagentDelegationStarted {
52
66
  runId?: string;
53
67
  currentTool?: string;
@@ -59,6 +73,7 @@ export interface SubagentDelegationUpdate extends SubagentDelegationStarted {
59
73
  toolCount?: number;
60
74
  durationMs?: number;
61
75
  tokens?: number;
76
+ usage?: SubagentDelegationUpdateUsage;
62
77
  }
63
78
 
64
79
  export type SubagentDelegationStatus =
@@ -0,0 +1,27 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import type { InspectorPlugin } from "../inspectors/types.ts";
3
+
4
+ export type { InspectorContext, InspectorLaunch, InspectorParams, InspectorPlugin, InspectorTarget } from "../inspectors/types.ts";
5
+
6
+ export const INSPECTOR_REGISTER_EVENT = "pi-subagents:inspector-register:v1";
7
+
8
+ export interface InspectorRegistration {
9
+ dispose(): void;
10
+ }
11
+
12
+ export interface InspectorRegistrationRequest {
13
+ version: 1;
14
+ plugin: InspectorPlugin;
15
+ result?:
16
+ | { ok: true; registration: InspectorRegistration }
17
+ | { ok: false; error: Error };
18
+ }
19
+
20
+ /** Register with the installed owner, even when each extension has its own module root. */
21
+ export function registerInspector(pi: Pick<ExtensionAPI, "events">, plugin: InspectorPlugin): InspectorRegistration {
22
+ const request: InspectorRegistrationRequest = { version: 1, plugin };
23
+ pi.events.emit(INSPECTOR_REGISTER_EVENT, request);
24
+ if (!request.result) throw new Error("pi-subagents is not installed, not ready, or does not support inspector registration.");
25
+ if (!request.result.ok) throw request.result.error;
26
+ return request.result.registration;
27
+ }
@@ -15,7 +15,7 @@ import { assertThinkingWithinCeiling, intersectThinkingCeilings, type ThinkingLe
15
15
  import { SUBAGENT_LIFECYCLE_ARTIFACT_VERSION, type ArtifactDirPreference, type ArtifactPaths, type IntercomBridgeConfig, type IntercomBridgeMode, type JsonSchemaObject, type OutputMode } from "../shared/types.ts";
16
16
  import { capabilityCeilingAgentRestrictionMessage, intersectSubagentCapabilityCeilings, type ResolvedSubagentCapabilityCeiling, type SubagentCapabilityAudit } from "../runs/shared/capability-ceiling.ts";
17
17
  import { resolvePermissionRules } from "../runs/shared/permissions.ts";
18
- import type { ResolvedMcpDirectToolSelection } from "../runs/shared/mcp-direct-tool-allowlist.ts";
18
+ import type { McpRuntimeSnapshotHost, ResolvedMcpDirectToolSelection } from "../runs/shared/mcp-direct-tool-allowlist.ts";
19
19
  import { resolveStepBehavior } from "../shared/settings.ts";
20
20
  import { canPreferForkFromSnapshot, resolveSubagentLaunchContext } from "../shared/fork-context.ts";
21
21
  import { loadConfig } from "../extension/config.ts";
@@ -72,6 +72,8 @@ export interface SubagentLaunchContractInput {
72
72
  thinkingCeiling?: ThinkingLevel;
73
73
  inheritedThinkingCeiling?: ThinkingLevel;
74
74
  parentModel?: ParentModel;
75
+ /** Scoped-model snapshot (`provider/id` strings); drives the `scoped` allow token. Omitting it degrades `scoped` to `inherit`, so callers comparing preflight with execution must pass the session snapshot. */
76
+ scopedModelIds?: readonly string[];
75
77
  availableModels?: ReadonlyArray<AvailableModelInfo | { provider: string; id: string; fullId?: string; reasoning?: boolean }>;
76
78
  preferredProvider?: string;
77
79
  skill?: string | string[] | boolean;
@@ -100,6 +102,8 @@ export interface SubagentLaunchContractInput {
100
102
  trustedProjectCwd?: string;
101
103
  /** Builtin tool names the host runtime provides; used to intersect agent-declared tools. */
102
104
  hostAvailableBuiltins?: readonly string[];
105
+ /** The calling extension's `pi`, so `mcp:` selectors resolve against the MCP the launch uses. Without it, preflight cannot see Pi's built-in MCP and resolves through pi-mcp-adapter's configuration. */
106
+ runtimeSnapshotHost?: McpRuntimeSnapshotHost;
103
107
  /** Per-launch bridge config; replaces the global `intercomBridge` config exactly as the tool and delegation overrides do. */
104
108
  intercomBridge?: IntercomBridgeConfig;
105
109
  /**
@@ -414,7 +418,7 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
414
418
  }
415
419
  const availableModels = normalizeAvailableModels(input.availableModels);
416
420
  const preferredProvider = agent.modelProvider ?? input.preferredProvider ?? input.parentModel?.provider;
417
- const modelScopes = resolveModelScopesForAgent(discovered.modelScope, agent.name, input.parentModel);
421
+ const modelScopes = resolveModelScopesForAgent(discovered.modelScope, agent.name, input.parentModel, input.scopedModelIds);
418
422
  const modelOrigin = resolveModelOrigin({ explicitModel: input.model, agentModel: agent.model, parentModel: input.parentModel });
419
423
  const primaryModel = externalRunner
420
424
  ? undefined
@@ -466,6 +470,7 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
466
470
  sandbox: agent.sandbox,
467
471
  permissionProfile: agent.permissionProfile,
468
472
  hostAvailableBuiltins: input.hostAvailableBuiltins,
473
+ runtimeSnapshotHost: input.runtimeSnapshotHost,
469
474
  });
470
475
  } catch (error) {
471
476
  const message = error instanceof Error ? error.message : String(error);
@@ -10,6 +10,11 @@ import { validatePermissionConfig } from "../runs/shared/permissions.ts";
10
10
  import { MAX_ABANDONED_SLOT_RELEASE_AFTER_MS, MIN_ABANDONED_SLOT_RELEASE_AFTER_MS } from "../runs/background/active-async-capacity.ts";
11
11
  import { normalizeWorktreeBranchPrefix } from "../runs/shared/worktree.ts";
12
12
  import { validateModelResponseAliases } from "../shared/model-response-aliases.ts";
13
+ import { validateDisabledFeatures } from "../shared/disabled-features.ts";
14
+
15
+ // Explicit route identity, worktree, checkpoint, and tool-surface policies must not be silently
16
+ // discarded and replaced by the built-in defaults after validation fails.
17
+ const FAIL_CLOSED_CONFIG_KEYS = ["worktreeProvider", "worktreeBranchPrefix", "modelResponseAliases", "modelExclusions", "checkpointBeforeDeadlineMs", "disabledFeatures", "scheduledRuns", "toolActivation"];
13
18
 
14
19
  const ARTIFACT_DIR_PREFERENCES = new Set<ArtifactDirPreference>(["project", "session", "temp"]);
15
20
  const FLEET_KEYBINDING_ACTION_SET = new Set<string>(FLEET_KEYBINDING_ACTIONS);
@@ -55,6 +60,8 @@ export function resolveScheduledStoreRoot(value: string): string {
55
60
  function validateScheduledRunsConfig(value: unknown): void {
56
61
  if (value === undefined) return;
57
62
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("config.scheduledRuns must be a JSON object");
63
+ const enabled = (value as Record<string, unknown>).enabled;
64
+ if (enabled !== undefined && typeof enabled !== "boolean") throw new Error("config.scheduledRuns.enabled must be a boolean");
58
65
  const storeRoot = (value as Record<string, unknown>).storeRoot;
59
66
  if (storeRoot === undefined) return;
60
67
  if (typeof storeRoot !== "string" || !storeRoot.trim()) throw new Error("config.scheduledRuns.storeRoot must be a non-empty string");
@@ -165,10 +172,14 @@ function validateConfig(config: Record<string, unknown>): void {
165
172
  if (config.resultScanLogging !== undefined && config.resultScanLogging !== "all" && config.resultScanLogging !== "activity" && config.resultScanLogging !== "off") {
166
173
  throw new Error('config.resultScanLogging must be "all", "activity", or "off"');
167
174
  }
175
+ if (config.toolActivation !== undefined && config.toolActivation !== "auto" && config.toolActivation !== "dynamic" && config.toolActivation !== "eager") {
176
+ throw new Error('config.toolActivation must be "auto", "dynamic", or "eager"');
177
+ }
168
178
  validateMissionStoreConfig(config.missions);
169
179
  validateAuthorityPolicy(config.authorityPolicy);
170
180
  validatePermissionConfig(config.permissions);
171
181
  validateScheduledRunsConfig(config.scheduledRuns);
182
+ validateDisabledFeatures(config.disabledFeatures);
172
183
  validateFleetKeybindingsConfig(config.fleetKeybindings);
173
184
  validateArtifactConfig(config.artifactConfig);
174
185
  validateCapacityConfig(config.capacity);
@@ -217,12 +228,9 @@ export function loadConfig(): ExtensionConfig {
217
228
  return readConfigForUpdate(configPath);
218
229
  } catch (error) {
219
230
  if (error instanceof PrunedForkConfigError) throw error;
220
- // Explicit route identity, worktree, and checkpoint policies must not be silently
221
- // discarded and replaced by the built-in defaults after validation fails.
222
231
  try {
223
232
  const raw = JSON.parse(fs.readFileSync(configPath, "utf-8")) as unknown;
224
- if (raw && typeof raw === "object" && !Array.isArray(raw)
225
- && (Object.hasOwn(raw, "worktreeProvider") || Object.hasOwn(raw, "worktreeBranchPrefix") || Object.hasOwn(raw, "modelResponseAliases") || Object.hasOwn(raw, "modelExclusions") || Object.hasOwn(raw, "checkpointBeforeDeadlineMs"))) throw error;
233
+ if (raw && typeof raw === "object" && !Array.isArray(raw) && FAIL_CLOSED_CONFIG_KEYS.some((key) => Object.hasOwn(raw, key))) throw error;
226
234
  } catch (readError) {
227
235
  if (readError === error) throw error;
228
236
  }
@@ -10,6 +10,8 @@ export interface SubagentControlMessageDetails {
10
10
  asyncDir?: string;
11
11
  childIntercomTarget?: string;
12
12
  noticeText?: string;
13
+ /** Status-only copy of a supervisor request; the tracker sends the notice later if the request is still unanswered. */
14
+ noticeDeferred?: boolean;
13
15
  }
14
16
 
15
17
  export function controlNoticeTarget(details: SubagentControlMessageDetails): string | undefined {
@@ -48,6 +50,7 @@ export function handleSubagentControlNotice(input: {
48
50
  details: SubagentControlMessageDetails;
49
51
  }): void {
50
52
  if (!input.details?.event || input.details.event.type === "active_long_running") return;
53
+ if (input.details.noticeDeferred) return;
51
54
  if (input.details.source === "foreground") {
52
55
  // A foreground tool blocks Pi from displaying this message. The run can
53
56
  // finish before Pi flushes it, and queued messages cannot be withdrawn.
@@ -214,12 +214,17 @@ function formatPermissionSystemSection(): string[] {
214
214
  const lines: string[] = [];
215
215
  const parentSession = process.env["PI_SUBAGENT_PARENT_SESSION"] ?? "";
216
216
  const trimmed = parentSession.trim();
217
- if (trimmed) {
218
- lines.push(`- parent session: set (${trimmed})`);
217
+ const isChild = process.env["PI_SUBAGENT_CHILD"] === "1";
218
+ if (isChild && trimmed) {
219
+ lines.push(`- runner parent session: set (${trimmed}) — explicit target for this dedicated child process`);
220
+ } else if (isChild) {
221
+ lines.push("- runner parent session: not set — this child process has no forwarding target");
222
+ } else if (trimmed) {
223
+ lines.push("- root parent session: ignored legacy process-global value — root sessions do not use it for routing");
219
224
  } else {
220
- lines.push("- parent session: not set — ask forwarding from background children will not reach a parent UI");
225
+ lines.push("- root parent session: not set (healthy) — detached forwarding is attached at runner launch");
221
226
  }
222
- const isChild = process.env["PI_SUBAGENT_CHILD"] === "1";
227
+ if (!isChild) lines.push("- foreground external ask forwarding: unavailable until the permission extension supports a session-scoped target");
223
228
  lines.push(`- subagent process: ${isChild ? "yes (PI_SUBAGENT_CHILD=1)" : "no"}`);
224
229
  // Whether pi-permission-system is installed and where it stores config is
225
230
  // outside pi-subagents' control, so we only report the forwarding signal we
@@ -229,6 +234,7 @@ function formatPermissionSystemSection(): string[] {
229
234
 
230
235
  function formatWorkflowScriptSection(): string[] {
231
236
  return [
237
+ "- launch: write a ```js workflow block in the reply, then call subagent({ workflow: true }); or pass a file as workflow: \"./path.js\"",
232
238
  "- helpers: runs.run, runs.all, runs.steer, runs.status, runs.ref/refs, emit, console",
233
239
  "- recovery: if runs.all is missing, reload or update pi-subagents; await Promise.all([runs.run(...)]) is also supported",
234
240
  ];
@@ -13,9 +13,13 @@ import { createNativeSupervisorChannel, NATIVE_SUPERVISOR_TOOL_NAME, resolveSupe
13
13
  import { readStatus } from "../shared/utils.ts";
14
14
  import { resolveSubagentIntercomTarget } from "../intercom/intercom-bridge.ts";
15
15
  import { createSubagentParamsSchema } from "./schemas.ts";
16
+ import { resolveDisabledFeatureSurface } from "../shared/disabled-features.ts";
16
17
  import { finalizeToolResult } from "./tool-result.ts";
18
+ import { removedModelWorkflowFieldError } from "./public-execution.ts";
17
19
  import { loadConfig, resolveAsyncByDefault } from "./config.ts";
18
20
  import { SUBAGENT_ASYNC_STARTED_EVENT, type AsyncStartedEvent, type Details, type SubagentState } from "../shared/types.ts";
21
+ import { createChildExternalJobBridgeSweeper } from "../runs/shared/external-job-bridge.ts";
22
+ import { MODEL_ONLY_TOOL } from "../shared/extension-context.ts";
19
23
 
20
24
  function getSubagentSessionRoot(parentSessionFile: string | null): string {
21
25
  if (parentSessionFile) {
@@ -210,22 +214,33 @@ export default function registerFanoutChildSubagentExtension(pi: ExtensionAPI, c
210
214
  findPendingAsks: supervisorChannel.findPendingAsks,
211
215
  });
212
216
 
213
- const params = createSubagentParamsSchema();
217
+ const disabledFeatures = resolveDisabledFeatureSurface(config);
218
+ const listEnabled = (actions: string[]) => actions.filter((action) => !disabledFeatures.actions.has(action)).join(", ");
219
+ const blockedActions = listEnabled(["create", "update", "delete", "eject", "disable", "enable", "reset", "grant-spawn-budget", "lane.recordMerge", "lane.recordSupersession"]);
220
+ const params = createSubagentParamsSchema(disabledFeatures);
214
221
  const tool: ToolDefinition<typeof params, Details> = {
215
222
  name: "subagent",
223
+ ...MODEL_ONLY_TOOL,
216
224
  label: "Subagent",
217
225
  description: [
218
226
  "Delegate to subagents from child-safe fanout mode.",
219
- "Allowed management/control actions: list, get, status, lane.status, interrupt, resume, steer, doctor.",
220
- "Mutating management actions (create, update, delete, eject, disable, enable, reset, grant-spawn-budget, lane.recordMerge, lane.recordSupersession) are blocked in this mode.",
227
+ `Allowed management/control actions: ${listEnabled(["list", "get", "status", "lane.status", "interrupt", "resume", "steer", "doctor"])}.`,
228
+ ...(blockedActions ? [`Mutating management actions (${blockedActions}) are blocked in this mode.`] : []),
221
229
  ].join("\n"),
222
230
  parameters: params,
223
231
  async execute(id, params, signal, onUpdate, ctx) {
232
+ const removedField = removedModelWorkflowFieldError(params);
233
+ if (removedField) throw new Error(removedField);
224
234
  return finalizeToolResult(await executor.executePublic(id, params as SubagentParamsLike, signal ?? new AbortController().signal, onUpdate, ctx));
225
235
  },
226
236
  };
227
237
 
228
238
  pi.registerTool(tool);
239
+ const bridgeSweeper = createChildExternalJobBridgeSweeper();
240
+ const unsubscribeBridgeStarted = pi.events.on(SUBAGENT_ASYNC_STARTED_EVENT, (payload: unknown) => {
241
+ const info = payload as AsyncStartedEvent;
242
+ if (info.id && info.asyncDir && info.sessionId === state.currentSessionId) bridgeSweeper.track(info.id, info.asyncDir);
243
+ });
229
244
  let unsubscribeAsyncStarted: (() => void) | undefined;
230
245
  pi.on("session_start", (_event, ctx) => {
231
246
  supervisorChannel.registerTools();
@@ -245,6 +260,8 @@ export default function registerFanoutChildSubagentExtension(pi: ExtensionAPI, c
245
260
  });
246
261
  pi.on("session_shutdown", () => {
247
262
  unsubscribeAsyncStarted?.();
263
+ unsubscribeBridgeStarted?.();
264
+ bridgeSweeper.dispose();
248
265
  asyncChildren.clear();
249
266
  foregroundChannels.clear();
250
267
  supervisorChannel.dispose();
@@ -13,6 +13,7 @@ import { buildAgentMemoryInjection } from "../agents/agent-memory.ts";
13
13
  import { appendAgentRefinementOverlay } from "../agents/agent-refinements.ts";
14
14
  import { rewriteSubagentPrompt } from "../runs/shared/subagent-prompt-runtime.ts";
15
15
  import { resolveExistingReadPaths } from "../shared/settings.ts";
16
+ import { MODEL_ONLY_TOOL } from "../shared/extension-context.ts";
16
17
 
17
18
  interface PendingRequest { operation: "prompt" | "steer" | "follow-up" | "abort" | "supervisor-reply"; text?: string; supervisorId?: string }
18
19
  interface BridgeContext {
@@ -75,6 +76,7 @@ export default function registerHerdrPiBridge(pi: ExtensionAPI): void {
75
76
 
76
77
  pi.registerTool({
77
78
  name: "contact_supervisor",
79
+ ...MODEL_ONLY_TOOL,
78
80
  label: "Contact supervisor",
79
81
  description: "Contact the parent/supervisor session for a blocking decision, structured interview, or progress update.",
80
82
  parameters: Type.Object({ reason: Type.Union([Type.Literal("need_decision"), Type.Literal("interview_request"), Type.Literal("progress_update")]), message: Type.Optional(Type.String({ maxLength: 65_536 })), interview: Type.Optional(Type.Unknown()) }, { additionalProperties: false }),