@xzzpig/pi-subagents 0.15.1 → 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 (135) hide show
  1. package/CHANGELOG.md +178 -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 +19 -12
  9. package/docs/configuration.md +21 -3
  10. package/docs/extension-api.md +70 -4
  11. package/docs/fork-extensions.md +23 -15
  12. package/docs/models.md +5 -3
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +4 -4
  15. package/docs/tool-reference.md +40 -19
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +57 -3
  18. package/inspector-runner.mjs +1 -1
  19. package/package.json +14 -8
  20. package/prompts/council.md +6 -3
  21. package/runner-peer-loader.mjs +4 -7
  22. package/runner-peer-preload.mjs +5 -7
  23. package/skills/pi-subagents/SKILL.md +1 -0
  24. package/skills/pi-subagents/references/constraints-and-recipes.md +5 -2
  25. package/skills/pi-subagents/references/execution-controls.md +6 -4
  26. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  27. package/skills/pi-subagents/references/multi-lane-orchestration.md +8 -0
  28. package/skills/pi-subagents/references/prompting-and-roles.md +16 -15
  29. package/src/agents/agent-eject.ts +3 -3
  30. package/src/agents/agent-management.ts +61 -52
  31. package/src/agents/agent-memory.ts +90 -3
  32. package/src/agents/agent-serializer.ts +4 -4
  33. package/src/agents/agents.ts +125 -51
  34. package/src/agents/global-npm-root.ts +58 -0
  35. package/src/agents/proactive-skills.ts +4 -1
  36. package/src/agents/runtime-agent-registry.ts +14 -11
  37. package/src/agents/skills.ts +42 -9
  38. package/src/api/delegation.ts +15 -0
  39. package/src/api/inspectors.ts +27 -0
  40. package/src/api/preflight.ts +60 -60
  41. package/src/extension/doctor.ts +9 -4
  42. package/src/extension/fanout-child.ts +8 -0
  43. package/src/extension/index.ts +101 -48
  44. package/src/extension/rpc.ts +10 -1
  45. package/src/extension/schemas.ts +12 -6
  46. package/src/extension/subagent-guide.ts +12 -4
  47. package/src/extension/tool-activation.ts +197 -0
  48. package/src/extension/tool-description.ts +1 -1
  49. package/src/inspectors/ghostty/plugin.ts +13 -1
  50. package/src/inspectors/plugins.ts +70 -3
  51. package/src/intercom/intercom-bridge.ts +2 -0
  52. package/src/intercom/native-supervisor-channel.ts +22 -15
  53. package/src/intercom/result-intercom.ts +4 -0
  54. package/src/runs/background/active-async-capacity.ts +3 -25
  55. package/src/runs/background/async-execution.ts +100 -140
  56. package/src/runs/background/async-job-tracker.ts +28 -34
  57. package/src/runs/background/async-resume.ts +16 -8
  58. package/src/runs/background/async-status.ts +2 -0
  59. package/src/runs/background/binary-bootstrap.ts +34 -6
  60. package/src/runs/background/fleet-view.ts +51 -7
  61. package/src/runs/background/notify.ts +93 -7
  62. package/src/runs/background/pid-namespace.ts +18 -0
  63. package/src/runs/background/process-terminal-candidate.ts +98 -0
  64. package/src/runs/background/process-terminal.ts +17 -96
  65. package/src/runs/background/result-watcher.ts +1 -1
  66. package/src/runs/background/retained-children.ts +3 -2
  67. package/src/runs/background/run-child-session.ts +16 -5
  68. package/src/runs/background/run-id-resolver.ts +10 -5
  69. package/src/runs/background/run-status.ts +10 -4
  70. package/src/runs/background/runner-aliases.ts +25 -15
  71. package/src/runs/background/runner-child-launch.ts +1 -2
  72. package/src/runs/background/runner-startup-failure.ts +56 -0
  73. package/src/runs/background/stale-run-reconciler.ts +19 -3
  74. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  75. package/src/runs/background/subagent-runner.ts +96 -287
  76. package/src/runs/background/wait-tool.ts +2 -0
  77. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  78. package/src/runs/foreground/execution.ts +217 -250
  79. package/src/runs/foreground/prompt-audit.ts +3 -9
  80. package/src/runs/foreground/subagent-executor.ts +377 -119
  81. package/src/runs/shared/acceptance.ts +167 -68
  82. package/src/runs/shared/capability-ceiling.ts +4 -1
  83. package/src/runs/shared/child-hooks.ts +1 -16
  84. package/src/runs/shared/child-launch.ts +22 -14
  85. package/src/runs/shared/child-runtime-config.ts +3 -0
  86. package/src/runs/shared/child-session.ts +52 -2
  87. package/src/runs/shared/child-tool-plan.ts +23 -113
  88. package/src/runs/shared/dynamic-fanout.ts +1 -1
  89. package/src/runs/shared/external-cli-runner.ts +3 -1
  90. package/src/runs/shared/external-job-bridge.ts +54 -0
  91. package/src/runs/shared/git-environment.ts +29 -0
  92. package/src/runs/shared/mcp-config-sources.ts +3 -0
  93. package/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -1
  94. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  95. package/src/runs/shared/model-resolution.ts +6 -1
  96. package/src/runs/shared/nested-events.ts +67 -55
  97. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  98. package/src/runs/shared/parallel-utils.ts +2 -1
  99. package/src/runs/shared/pi-spawn.ts +92 -6
  100. package/src/runs/shared/profile-launch-env.ts +10 -2
  101. package/src/runs/shared/single-output.ts +11 -2
  102. package/src/runs/shared/structured-output.ts +227 -7
  103. package/src/runs/shared/subagent-control.ts +2 -16
  104. package/src/runs/shared/subagent-prompt-runtime.ts +27 -5
  105. package/src/runs/shared/tool-availability.ts +2 -2
  106. package/src/runs/shared/tool-budget.ts +21 -0
  107. package/src/runs/shared/usage-reconciliation.ts +73 -0
  108. package/src/runs/shared/worktree.ts +35 -8
  109. package/src/shared/child-session-name.ts +4 -2
  110. package/src/shared/fork-context.ts +11 -4
  111. package/src/shared/launch-contract.ts +1 -1
  112. package/src/shared/pruned-fork.ts +69 -56
  113. package/src/shared/types.ts +52 -16
  114. package/src/slash/delegation-adapters.ts +25 -1
  115. package/src/slash/prompt-template-bridge.ts +16 -1
  116. package/src/slash/prompt-workflows.ts +12 -1
  117. package/src/slash/slash-commands.ts +7 -241
  118. package/src/slash/subagent-cost.ts +313 -0
  119. package/src/slash/subagents-admin.ts +28 -29
  120. package/src/tui/fleet-status.ts +24 -2
  121. package/src/tui/fleet.ts +7 -4
  122. package/src/tui/render.ts +53 -19
  123. package/src/watchdog/diff-tool.ts +24 -3
  124. package/src/watchdog/permission-arbiter.ts +13 -15
  125. package/src/watchdog/register-child.ts +10 -2
  126. package/src/watchdog/review.ts +14 -14
  127. package/src/watchdog/runtime.ts +2 -1
  128. package/src/watchdog/turn-delta.ts +11 -5
  129. package/src/workflows/scripted-workflow.ts +109 -23
  130. package/src/workflows/workflow-child-summary.ts +4 -2
  131. package/src/workflows/workflow-settlement.ts +4 -1
  132. package/src/runs/shared/completion-evidence.ts +0 -89
  133. package/src/runs/shared/completion-guard.ts +0 -255
  134. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  135. package/src/runs/shared/task-intent.ts +0 -244
@@ -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
+ }
@@ -47,9 +47,9 @@ export type SubagentLaunchContractReasonCode =
47
47
  | "restricted_agent"
48
48
  | "thinking_ceiling"
49
49
  | "invalid_extension_bindings"
50
- | "untrusted_project"
51
- | "sandbox_unavailable"
52
- | "permission_profile_unavailable"
50
+ | "untrusted_project"
51
+ | "sandbox_unavailable"
52
+ | "permission_profile_unavailable"
53
53
  | "invalid_intercom_bridge";
54
54
 
55
55
  export type SubagentLaunchContractDiagnosticCode = SubagentLaunchContractReasonCode | "host_required" | "snapshot_warning" | "workspace_scope_authority";
@@ -94,12 +94,12 @@ export interface SubagentLaunchContractInput {
94
94
  nestedRootRunId?: string;
95
95
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
96
96
  inheritedCapabilityCeiling?: ResolvedSubagentCapabilityCeiling;
97
- /** Host-affirmed trust state for a project-scoped profile selection. */
98
- projectTrusted?: boolean;
99
- /** Exact trusted project cwd. When omitted, an affirmative trust assertion applies only to `cwd`. */
100
- trustedProjectCwd?: string;
101
- /** Builtin tool names the host runtime provides; used to intersect agent-declared tools. */
102
- hostAvailableBuiltins?: readonly string[];
97
+ /** Host-affirmed trust state for a project-scoped profile selection. */
98
+ projectTrusted?: boolean;
99
+ /** Exact trusted project cwd. When omitted, an affirmative trust assertion applies only to `cwd`. */
100
+ trustedProjectCwd?: string;
101
+ /** Builtin tool names the host runtime provides; used to intersect agent-declared tools. */
102
+ hostAvailableBuiltins?: readonly string[];
103
103
  /** Per-launch bridge config; replaces the global `intercomBridge` config exactly as the tool and delegation overrides do. */
104
104
  intercomBridge?: IntercomBridgeConfig;
105
105
  /**
@@ -189,7 +189,7 @@ export interface SubagentLaunchContract {
189
189
  model?: string;
190
190
  thinking?: string;
191
191
  thinkingCeiling?: ThinkingLevel;
192
- sandbox?: string;
192
+ sandbox?: string;
193
193
  systemPromptMode: AgentConfig["systemPromptMode"];
194
194
  inheritProjectContext: boolean;
195
195
  inheritGlobalContext: boolean;
@@ -214,15 +214,15 @@ export type SubagentLaunchContractResult =
214
214
 
215
215
  function packageVersion(): string {
216
216
  const packagePath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "package.json");
217
- try {
218
- const parsed = JSON.parse(fs.readFileSync(packagePath, "utf-8")) as { version?: unknown };
219
- if (typeof parsed.version !== "string" || !parsed.version.trim()) {
220
- throw new Error("version must be a non-empty string.");
221
- }
222
- return parsed.version;
223
- } catch (error) {
224
- throw new Error(`Invalid package version in '${packagePath}': ${error instanceof Error ? error.message : String(error)}`);
217
+ try {
218
+ const parsed = JSON.parse(fs.readFileSync(packagePath, "utf-8")) as { version?: unknown };
219
+ if (typeof parsed.version !== "string" || !parsed.version.trim()) {
220
+ throw new Error("version must be a non-empty string.");
225
221
  }
222
+ return parsed.version;
223
+ } catch (error) {
224
+ throw new Error(`Invalid package version in '${packagePath}': ${error instanceof Error ? error.message : String(error)}`);
225
+ }
226
226
  }
227
227
 
228
228
  function digestContract(contract: Omit<SubagentLaunchContract, "digest">): string {
@@ -350,38 +350,38 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
350
350
  diagnostics.push({ code: "host_required", severity: "host-required", message: "The intercomBridge instruction file names the supervisor session; supply orchestratorTarget to bind the exact child prompt." });
351
351
  }
352
352
  const agent = applyIntercomBridgeToAgent(definitionAgent, bridge);
353
- const trustedProjectCwd = input.projectTrusted === true
354
- ? path.resolve(input.trustedProjectCwd ?? effectiveCwd)
355
- : undefined;
356
- const projectScoped = agent.source === "project" || agent.override?.scope === "project";
357
- const profileTrustError = projectScopedProfileTrustError({
358
- kind: "sandbox",
359
- agentName: agent.name,
360
- profileName: agent.sandbox ?? "",
361
- projectScoped: Boolean(agent.sandbox) && projectScoped,
362
- trustedCwd: trustedProjectCwd,
363
- effectiveCwd,
364
- messageStyle: "preflight",
365
- }) ?? projectScopedProfileTrustError({
366
- kind: "permission",
367
- agentName: agent.name,
368
- profileName: agent.permissionProfile ?? "",
369
- projectScoped: Boolean(agent.permissionProfile) && projectScoped,
370
- trustedCwd: trustedProjectCwd,
371
- effectiveCwd,
372
- messageStyle: "preflight",
373
- });
374
- if (profileTrustError) {
375
- return { ok: false, code: "untrusted_project", message: profileTrustError, diagnostics: [{ code: "untrusted_project", severity: "error", message: profileTrustError }] };
376
- }
377
- if (agent.sandbox && (agent.runner?.type === "external-cli" || agent.runner?.type === "external-job")) {
378
- const message = `Agent '${agent.name}' requests sandbox profile '${agent.sandbox}', but runner.type='${agent.runner.type}' cannot load the native pi-sandbox extension.`;
379
- return { ok: false, code: "unsupported_mode", message, diagnostics: [{ code: "unsupported_mode", severity: "error", message }] };
380
- }
381
- if (agent.permissionProfile && (agent.runner?.type === "external-cli" || agent.runner?.type === "external-job")) {
382
- const message = `Agent '${agent.name}' requests permission profile '${agent.permissionProfile}', but runner.type='${agent.runner.type}' cannot load the native pi-permission-system extension.`;
383
- return { ok: false, code: "unsupported_mode", message, diagnostics: [{ code: "unsupported_mode", severity: "error", message }] };
384
- }
353
+ const trustedProjectCwd = input.projectTrusted === true
354
+ ? path.resolve(input.trustedProjectCwd ?? effectiveCwd)
355
+ : undefined;
356
+ const projectScoped = agent.source === "project" || agent.override?.scope === "project";
357
+ const profileTrustError = projectScopedProfileTrustError({
358
+ kind: "sandbox",
359
+ agentName: agent.name,
360
+ profileName: agent.sandbox ?? "",
361
+ projectScoped: Boolean(agent.sandbox) && projectScoped,
362
+ trustedCwd: trustedProjectCwd,
363
+ effectiveCwd,
364
+ messageStyle: "preflight",
365
+ }) ?? projectScopedProfileTrustError({
366
+ kind: "permission",
367
+ agentName: agent.name,
368
+ profileName: agent.permissionProfile ?? "",
369
+ projectScoped: Boolean(agent.permissionProfile) && projectScoped,
370
+ trustedCwd: trustedProjectCwd,
371
+ effectiveCwd,
372
+ messageStyle: "preflight",
373
+ });
374
+ if (profileTrustError) {
375
+ return { ok: false, code: "untrusted_project", message: profileTrustError, diagnostics: [{ code: "untrusted_project", severity: "error", message: profileTrustError }] };
376
+ }
377
+ if (agent.sandbox && (agent.runner?.type === "external-cli" || agent.runner?.type === "external-job")) {
378
+ const message = `Agent '${agent.name}' requests sandbox profile '${agent.sandbox}', but runner.type='${agent.runner.type}' cannot load the native pi-sandbox extension.`;
379
+ return { ok: false, code: "unsupported_mode", message, diagnostics: [{ code: "unsupported_mode", severity: "error", message }] };
380
+ }
381
+ if (agent.permissionProfile && (agent.runner?.type === "external-cli" || agent.runner?.type === "external-job")) {
382
+ const message = `Agent '${agent.name}' requests permission profile '${agent.permissionProfile}', but runner.type='${agent.runner.type}' cannot load the native pi-permission-system extension.`;
383
+ return { ok: false, code: "unsupported_mode", message, diagnostics: [{ code: "unsupported_mode", severity: "error", message }] };
384
+ }
385
385
  const effectiveCapabilityCeiling = intersectSubagentCapabilityCeilings(input.capabilityCeiling, input.inheritedCapabilityCeiling);
386
386
  const restrictionMessage = capabilityCeilingAgentRestrictionMessage(agent.name, effectiveCapabilityCeiling);
387
387
  if (restrictionMessage) return { ok: false, code: "restricted_agent", message: restrictionMessage, diagnostics };
@@ -463,15 +463,15 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
463
463
  capabilityCeiling: effectiveCapabilityCeiling,
464
464
  agentName: agent.name,
465
465
  permissionRules,
466
- sandbox: agent.sandbox,
467
- permissionProfile: agent.permissionProfile,
468
- hostAvailableBuiltins: input.hostAvailableBuiltins,
466
+ sandbox: agent.sandbox,
467
+ permissionProfile: agent.permissionProfile,
468
+ hostAvailableBuiltins: input.hostAvailableBuiltins,
469
469
  });
470
470
  } catch (error) {
471
471
  const message = error instanceof Error ? error.message : String(error);
472
- const code: SubagentLaunchContractReasonCode = agent.sandbox ? "sandbox_unavailable" : agent.permissionProfile ? "permission_profile_unavailable" : "denied_required_tool";
473
- diagnostics.push({ code, severity: "error", message });
474
- return { ok: false, code, message, diagnostics };
472
+ const code: SubagentLaunchContractReasonCode = agent.sandbox ? "sandbox_unavailable" : agent.permissionProfile ? "permission_profile_unavailable" : "denied_required_tool";
473
+ diagnostics.push({ code, severity: "error", message });
474
+ return { ok: false, code, message, diagnostics };
475
475
  }
476
476
  const artifactsEnabled = input.artifacts !== false;
477
477
  const artifactsDir = artifactsEnabled ? getArtifactsDir(input.parentSessionFile ?? null, effectiveCwd, input.artifactDir) : undefined;
@@ -502,8 +502,8 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
502
502
  model,
503
503
  ...(fast !== undefined ? { fast } : {}),
504
504
  ...(effectiveThinking ? { thinking: effectiveThinking } : {}),
505
- ...(agent.sandbox ? { sandbox: agent.sandbox } : {}),
506
- ...(agent.permissionProfile ? { permissionProfile: agent.permissionProfile } : {}),
505
+ ...(agent.sandbox ? { sandbox: agent.sandbox } : {}),
506
+ ...(agent.permissionProfile ? { permissionProfile: agent.permissionProfile } : {}),
507
507
  systemPrompt: buildEffectiveSystemPrompt({ agent, resolvedSkills: resolvedSkills.resolved, cwd: effectiveCwd, ...(outputPath ? { outputPath } : {}) }),
508
508
  skills: requestedSkills,
509
509
  toolPlan,
@@ -531,8 +531,8 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
531
531
  ...(model ? { model } : {}),
532
532
  ...(effectiveThinking ? { thinking: effectiveThinking } : {}),
533
533
  ...(thinkingCeiling ? { thinkingCeiling } : {}),
534
- ...(agent.sandbox ? { sandbox: agent.sandbox } : {}),
535
- ...(agent.permissionProfile ? { permissionProfile: agent.permissionProfile } : {}),
534
+ ...(agent.sandbox ? { sandbox: agent.sandbox } : {}),
535
+ ...(agent.permissionProfile ? { permissionProfile: agent.permissionProfile } : {}),
536
536
  systemPromptMode: agent.systemPromptMode,
537
537
  inheritProjectContext: agent.inheritProjectContext,
538
538
  inheritGlobalContext: agent.inheritGlobalContext,
@@ -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
@@ -16,6 +16,7 @@ import { createSubagentParamsSchema } from "./schemas.ts";
16
16
  import { finalizeToolResult } from "./tool-result.ts";
17
17
  import { loadConfig, resolveAsyncByDefault } from "./config.ts";
18
18
  import { SUBAGENT_ASYNC_STARTED_EVENT, type AsyncStartedEvent, type Details, type SubagentState } from "../shared/types.ts";
19
+ import { createChildExternalJobBridgeSweeper } from "../runs/shared/external-job-bridge.ts";
19
20
 
20
21
  function getSubagentSessionRoot(parentSessionFile: string | null): string {
21
22
  if (parentSessionFile) {
@@ -226,6 +227,11 @@ export default function registerFanoutChildSubagentExtension(pi: ExtensionAPI, c
226
227
  };
227
228
 
228
229
  pi.registerTool(tool);
230
+ const bridgeSweeper = createChildExternalJobBridgeSweeper();
231
+ const unsubscribeBridgeStarted = pi.events.on(SUBAGENT_ASYNC_STARTED_EVENT, (payload: unknown) => {
232
+ const info = payload as AsyncStartedEvent;
233
+ if (info.id && info.asyncDir && info.sessionId === state.currentSessionId) bridgeSweeper.track(info.id, info.asyncDir);
234
+ });
229
235
  let unsubscribeAsyncStarted: (() => void) | undefined;
230
236
  pi.on("session_start", (_event, ctx) => {
231
237
  supervisorChannel.registerTools();
@@ -245,6 +251,8 @@ export default function registerFanoutChildSubagentExtension(pi: ExtensionAPI, c
245
251
  });
246
252
  pi.on("session_shutdown", () => {
247
253
  unsubscribeAsyncStarted?.();
254
+ unsubscribeBridgeStarted?.();
255
+ bridgeSweeper.dispose();
248
256
  asyncChildren.clear();
249
257
  foregroundChannels.clear();
250
258
  supervisorChannel.dispose();