@xzzpig/pi-subagents 0.13.0 → 0.15.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 (202) hide show
  1. package/CHANGELOG.md +243 -0
  2. package/README.md +6 -5
  3. package/agents/evidence-auditor.md +34 -0
  4. package/agents/researcher.md +23 -13
  5. package/agents/reviewer.md +3 -2
  6. package/docs/agents.md +56 -15
  7. package/docs/configuration.md +93 -15
  8. package/docs/extension-api.md +132 -19
  9. package/docs/missions.md +10 -2
  10. package/docs/models.md +11 -22
  11. package/docs/observability.md +67 -11
  12. package/docs/standalone-background.md +59 -0
  13. package/docs/tool-reference.md +42 -23
  14. package/docs/watchdog.md +39 -10
  15. package/docs/workflows.md +58 -19
  16. package/index.ts +5 -2
  17. package/inspector-runner.mjs +2 -2
  18. package/node_modules/@xzzpig/pi-components/CHANGELOG.md +19 -0
  19. package/node_modules/@xzzpig/pi-components/README.md +28 -0
  20. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +46 -4
  21. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +65 -17
  22. package/node_modules/@xzzpig/pi-components/package.json +1 -1
  23. package/node_modules/@xzzpig/pi-components/src/transcript.ts +107 -14
  24. package/package.json +10 -5
  25. package/prompts/parallel-review.md +1 -1
  26. package/runner-peer-loader.mjs +24 -0
  27. package/runner-peer-preload.mjs +36 -0
  28. package/skills/pi-subagents/SKILL.md +34 -22
  29. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  30. package/skills/pi-subagents/references/execution-controls.md +27 -8
  31. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  32. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  33. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  34. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  35. package/src/agents/advertised-agent-prompt.ts +94 -0
  36. package/src/agents/agent-management.ts +71 -59
  37. package/src/agents/agent-serializer.ts +6 -3
  38. package/src/agents/agents.ts +198 -72
  39. package/src/agents/builtin-names.ts +1 -0
  40. package/src/agents/chain-serializer.ts +5 -0
  41. package/src/agents/runtime-agent-registry.ts +7 -6
  42. package/src/api/delegation.ts +4 -0
  43. package/src/api/preflight.ts +110 -71
  44. package/src/api/required-child-extensions.ts +6 -0
  45. package/src/api/shared-types.ts +3 -1
  46. package/src/api/workflow-resources.ts +6 -0
  47. package/src/extension/config.ts +14 -37
  48. package/src/extension/fanout-child.ts +68 -5
  49. package/src/extension/herdr-pi-bridge.ts +164 -0
  50. package/src/extension/index.ts +141 -51
  51. package/src/extension/public-execution.ts +7 -6
  52. package/src/extension/rpc.ts +8 -21
  53. package/src/extension/schemas.ts +86 -84
  54. package/src/extension/tool-description.ts +32 -79
  55. package/src/inspectors/actions.ts +148 -0
  56. package/src/inspectors/ghostty/actions.ts +74 -0
  57. package/src/inspectors/ghostty/plugin.ts +17 -0
  58. package/src/inspectors/herdr/actions.ts +99 -179
  59. package/src/inspectors/herdr/plugin.ts +20 -0
  60. package/src/inspectors/herdr/project-panes.ts +4 -1
  61. package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
  62. package/src/inspectors/plugins.ts +8 -0
  63. package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
  64. package/src/inspectors/types.ts +51 -0
  65. package/src/integrations/pi-web-session-liveness.ts +73 -0
  66. package/src/intercom/intercom-bridge.ts +50 -8
  67. package/src/intercom/native-supervisor-channel.ts +142 -115
  68. package/src/intercom/supervisor-ui.ts +3 -2
  69. package/src/missions/workflow-state.ts +37 -16
  70. package/src/policy/authority.ts +4 -0
  71. package/src/profiles/profiles.ts +12 -6
  72. package/src/runs/background/active-async-capacity.ts +22 -18
  73. package/src/runs/background/active-run-index.ts +17 -1
  74. package/src/runs/background/async-execution.ts +359 -176
  75. package/src/runs/background/async-job-tracker.ts +41 -7
  76. package/src/runs/background/async-resume.ts +19 -12
  77. package/src/runs/background/async-retention.ts +20 -0
  78. package/src/runs/background/async-status-snapshot.ts +10 -12
  79. package/src/runs/background/async-status.ts +32 -13
  80. package/src/runs/background/auto-drain.ts +59 -35
  81. package/src/runs/background/binary-bootstrap.ts +38 -0
  82. package/src/runs/background/chain-append.ts +1 -1
  83. package/src/runs/background/chain-root-attachment.ts +22 -33
  84. package/src/runs/background/control-channel.ts +78 -44
  85. package/src/runs/background/fleet-view.ts +30 -2
  86. package/src/runs/background/notify.ts +193 -19
  87. package/src/runs/background/owned-process-tree.ts +35 -8
  88. package/src/runs/background/process-terminal.ts +23 -23
  89. package/src/runs/background/result-files.ts +8 -4
  90. package/src/runs/background/result-watcher.ts +19 -2
  91. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  92. package/src/runs/background/run-child-session.ts +118 -41
  93. package/src/runs/background/run-status.ts +78 -5
  94. package/src/runs/background/runner-aliases.ts +22 -5
  95. package/src/runs/background/runner-child-launch.ts +93 -0
  96. package/src/runs/background/runner-child-sessions.ts +5 -4
  97. package/src/runs/background/runner-http-dispatcher.ts +119 -0
  98. package/src/runs/background/scheduled-runs.ts +51 -18
  99. package/src/runs/background/stale-run-reconciler.ts +38 -12
  100. package/src/runs/background/steering.ts +20 -2
  101. package/src/runs/background/subagent-runner.ts +766 -432
  102. package/src/runs/background/subagent-wait.ts +179 -28
  103. package/src/runs/background/wait-completions.ts +79 -27
  104. package/src/runs/background/wait-subscriptions.ts +9 -3
  105. package/src/runs/background/wait-tool.ts +5 -3
  106. package/src/runs/foreground/async-steering-action.ts +37 -7
  107. package/src/runs/foreground/async-stop-action.ts +93 -3
  108. package/src/runs/foreground/execution.ts +174 -194
  109. package/src/runs/foreground/foreground-history.ts +5 -2
  110. package/src/runs/foreground/prompt-audit.ts +12 -6
  111. package/src/runs/foreground/subagent-executor.ts +896 -397
  112. package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
  113. package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
  114. package/src/runs/shared/acceptance.ts +54 -14
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +172 -78
  117. package/src/runs/shared/capability-ceiling.ts +2 -0
  118. package/src/runs/shared/child-hooks.ts +167 -3
  119. package/src/runs/shared/child-launch-plan.ts +15 -3
  120. package/src/runs/shared/child-launch.ts +44 -16
  121. package/src/runs/shared/child-lifecycle.ts +6 -3
  122. package/src/runs/shared/child-runtime-config.ts +8 -1
  123. package/src/runs/shared/child-session.ts +130 -24
  124. package/src/runs/shared/child-tool-plan.ts +145 -14
  125. package/src/runs/shared/completion-evidence.ts +2 -2
  126. package/src/runs/shared/completion-guard.ts +6 -3
  127. package/src/runs/shared/dynamic-fanout.ts +2 -2
  128. package/src/runs/shared/effective-system-prompt.ts +33 -0
  129. package/src/runs/shared/external-cli-contract.ts +11 -1
  130. package/src/runs/shared/external-cli-preflight.ts +6 -2
  131. package/src/runs/shared/external-cli-runner.ts +9 -7
  132. package/src/runs/shared/herdr-connection.ts +134 -0
  133. package/src/runs/shared/herdr-external-adapters.ts +169 -0
  134. package/src/runs/shared/herdr-machine.ts +279 -0
  135. package/src/runs/shared/herdr-pi-protocol.ts +59 -0
  136. package/src/runs/shared/herdr-placed-run.ts +263 -0
  137. package/src/runs/shared/host-step-status.ts +11 -11
  138. package/src/runs/shared/llm-intent-arbiter.ts +40 -21
  139. package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
  140. package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
  141. package/src/runs/shared/model-scope.ts +1 -1
  142. package/src/runs/shared/nested-events.ts +19 -10
  143. package/src/runs/shared/orca-progress-tabs.ts +7 -1
  144. package/src/runs/shared/parallel-handoff.ts +57 -12
  145. package/src/runs/shared/parallel-utils.ts +10 -4
  146. package/src/runs/shared/pi-spawn.ts +10 -0
  147. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  148. package/src/runs/shared/run-fanout-budget.ts +8 -8
  149. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  150. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  151. package/src/runs/shared/task-intent.ts +46 -13
  152. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  153. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  154. package/src/runs/shared/worktree-setup-command.ts +213 -0
  155. package/src/runs/shared/worktree.ts +437 -214
  156. package/src/shared/child-cache-retention.ts +43 -0
  157. package/src/shared/fork-context.ts +15 -72
  158. package/src/shared/launch-contract.ts +70 -8
  159. package/src/shared/model-response-aliases.ts +13 -0
  160. package/src/shared/opencode-session-headers.ts +30 -0
  161. package/src/shared/pruned-fork.ts +1 -1
  162. package/src/shared/required-child-extensions.ts +81 -0
  163. package/src/shared/settings.ts +5 -2
  164. package/src/shared/shortcuts.ts +0 -4
  165. package/src/shared/types.ts +164 -90
  166. package/src/shared/utils.ts +10 -2
  167. package/src/shared/watch-strategy.ts +2 -0
  168. package/src/shared/workflow-child-permit.ts +18 -13
  169. package/src/slash/delegation-adapters.ts +3 -1
  170. package/src/slash/delegation-request.ts +14 -0
  171. package/src/slash/slash-commands.ts +2 -7
  172. package/src/slash/subagents-admin.ts +31 -14
  173. package/src/tui/fleet-native-transcript.ts +50 -6
  174. package/src/tui/fleet-status.ts +165 -20
  175. package/src/tui/fleet.ts +52 -21
  176. package/src/tui/render.ts +210 -50
  177. package/src/watchdog/child-status.ts +28 -28
  178. package/src/watchdog/lsp-diagnostics.ts +1 -1
  179. package/src/watchdog/model-selection.ts +21 -1
  180. package/src/watchdog/permission-arbiter.ts +5 -2
  181. package/src/watchdog/register-child.ts +10 -2
  182. package/src/watchdog/register-main.ts +39 -35
  183. package/src/watchdog/render.ts +1 -1
  184. package/src/watchdog/review.ts +122 -74
  185. package/src/watchdog/rules.ts +1 -1
  186. package/src/watchdog/runtime.ts +100 -27
  187. package/src/watchdog/scope.ts +1 -1
  188. package/src/watchdog/settings.ts +3 -0
  189. package/src/watchdog/tool-actions.ts +13 -12
  190. package/src/watchdog/turn-delta.ts +23 -0
  191. package/src/watchdog/types.ts +5 -3
  192. package/src/watchdog/warning-format.ts +1 -1
  193. package/src/workflows/chat-progress.ts +3 -3
  194. package/src/workflows/scripted-workflow.ts +349 -26
  195. package/src/workflows/workflow-checklist.ts +17 -20
  196. package/src/workflows/workflow-child-summary.ts +57 -8
  197. package/src/workflows/workflow-preflight.ts +19 -19
  198. package/src/workflows/workflow-receipt.ts +24 -6
  199. package/src/workflows/workflow-resources.ts +108 -22
  200. package/src/workflows/workflow-settlement.ts +3 -0
  201. package/src/runs/shared/model-exclusions.ts +0 -373
  202. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -2,13 +2,13 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import * as readline from "node:readline";
4
4
  import { fileURLToPath } from "node:url";
5
- import { parseMissionRecord } from "../../missions/store.ts";
6
- import type { MissionRecord } from "../../missions/types.ts";
7
- import { requestAsyncSteer, requestAsyncStop } from "../../runs/background/control-channel.ts";
8
- import { formatAsyncRunTranscript } from "../../runs/background/fleet-view.ts";
9
- import { steeringReceipt } from "../../runs/background/steering.ts";
10
- import type { AsyncStatus } from "../../shared/types.ts";
11
- import { readStatus } from "../../shared/utils.ts";
5
+ import { parseMissionRecord } from "../missions/store.ts";
6
+ import type { MissionRecord } from "../missions/types.ts";
7
+ import { requestAsyncSteer, requestAsyncStop } from "../runs/background/control-channel.ts";
8
+ import { formatAsyncRunTranscript } from "../runs/background/fleet-view.ts";
9
+ import { steeringReceipt } from "../runs/background/steering.ts";
10
+ import type { AsyncStatus } from "../shared/types.ts";
11
+ import { readStatus } from "../shared/utils.ts";
12
12
  import { decodeSessionRoots } from "./session-roots-codec.ts";
13
13
 
14
14
  export interface RunnerOptions {
@@ -31,7 +31,7 @@ export function formatInspectorDashboard(input: { status: AsyncStatus; asyncDir:
31
31
  const { status, asyncDir, mission } = input;
32
32
  const lines = [
33
33
  `pi-subagents inspector for ${status.runId}`,
34
- "This pane mirrors lifecycle artifacts; closing it does not stop the run.",
34
+ "This inspector mirrors lifecycle artifacts; closing it does not stop the run.",
35
35
  "",
36
36
  ];
37
37
  if (mission) {
@@ -43,7 +43,7 @@ export function formatInspectorDashboard(input: { status: AsyncStatus; asyncDir:
43
43
  lines.push(formatAsyncRunTranscript(status, asyncDir, { index: input.index, lines: 60, sessionRoots: input.sessionRoots }));
44
44
  const acceptsPlainGuidance = input.index !== undefined || status.mode === "single";
45
45
  const controls = [input.allowSteer === false || !acceptsPlainGuidance ? undefined : "type guidance", input.allowSteer === false ? undefined : "steer <message>", input.allowStop === false ? undefined : "stop", "status"].filter(Boolean);
46
- lines.push("", `Controls: ${controls.join(" | ")}`, "Supervisor replies remain in the parent Pi session (subagent_supervisor/intercom).");
46
+ lines.push("", `Controls: ${controls.join(" | ")}`, "Supervisor replies remain in the parent Pi session (subagent_supervisor/intercom); this inspector is read-only.");
47
47
  return lines.join("\n");
48
48
  }
49
49
 
@@ -91,7 +91,7 @@ function queueInspectorSteer(options: RunnerOptions, status: AsyncStatus, messag
91
91
  requestAsyncSteer(options.asyncDir, {
92
92
  message,
93
93
  ...(targetIndex !== undefined ? { targetIndex } : { targetIndexes: runningIndexes }),
94
- source: "herdr-inspector",
94
+ source: "inspector-runner",
95
95
  });
96
96
  return steeringReceipt(message, `Steering queued for run ${options.runId}.`);
97
97
  }
@@ -104,7 +104,7 @@ export function submitInspectorControl(options: RunnerOptions, line: string): st
104
104
  if (command === "stop") {
105
105
  if (options.allowStop === false) throw new Error("Authority policy does not allow stop from this inspector.");
106
106
  if (isTerminal(status)) throw new Error(`Run '${options.runId}' is ${status.state} and cannot be stopped.`);
107
- requestAsyncStop(options.asyncDir, { source: "herdr-inspector" });
107
+ requestAsyncStop(options.asyncDir, { source: "inspector-runner" });
108
108
  return `Stop requested for run ${options.runId}.`;
109
109
  }
110
110
  if (command.startsWith("steer ")) {
@@ -147,7 +147,7 @@ export function runInspector(argv = process.argv.slice(2)): void {
147
147
 
148
148
  if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url))) {
149
149
  try { runInspector(); } catch (cause) {
150
- process.stderr.write(`Herdr inspector failed: ${cause instanceof Error ? cause.message : String(cause)}\n`);
150
+ process.stderr.write(`Inspector failed: ${cause instanceof Error ? cause.message : String(cause)}\n`);
151
151
  process.exitCode = 1;
152
152
  }
153
153
  }
@@ -0,0 +1,8 @@
1
+ import { createHerdrInspectorPlugin } from "./herdr/plugin.ts";
2
+ import { createGhosttyInspectorPlugin } from "./ghostty/plugin.ts";
3
+ import type { InspectorPlugin } from "./types.ts";
4
+
5
+ /** Built-in inspector plugins, ordered by host preference. */
6
+ export function createBuiltinInspectorPlugins(): readonly InspectorPlugin[] {
7
+ return [createHerdrInspectorPlugin(), createGhosttyInspectorPlugin()];
8
+ }
@@ -19,24 +19,13 @@ function parseStringArray(value: unknown): string[] | undefined {
19
19
  return value;
20
20
  }
21
21
 
22
- /**
23
- * Decodes a `--session-roots` argument produced by {@link encodeSessionRoots}.
24
- * Falls back to parsing the value as raw JSON so any externally-launched
25
- * inspector runner (a cached copy, or a manual invocation) that still passes
26
- * the legacy unencoded form keeps working.
27
- */
22
+ /** Decodes a `--session-roots` argument produced by {@link encodeSessionRoots}. */
28
23
  export function decodeSessionRoots(raw: string): string[] {
29
24
  try {
30
25
  const decoded = parseStringArray(JSON.parse(Buffer.from(raw, "base64").toString("utf-8")));
31
26
  if (decoded) return decoded;
32
27
  } catch {
33
- // fall through to legacy raw-JSON parsing below
34
- }
35
- try {
36
- const parsed = parseStringArray(JSON.parse(raw));
37
- if (parsed) return parsed;
38
- } catch {
39
- // fall through to the shared error below
28
+ // Report one stable validation error below.
40
29
  }
41
- throw new Error("--session-roots must be a base64-encoded or raw JSON array of strings.");
30
+ throw new Error("--session-roots must be a base64-encoded JSON array of strings.");
42
31
  }
@@ -0,0 +1,51 @@
1
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
+ import type { Details } from "../shared/types.ts";
3
+
4
+ export const INSPECTOR_ACTIONS = ["inspector.open", "inspector.command", "inspector.status", "inspector.close"] as const;
5
+ export type InspectorAction = typeof INSPECTOR_ACTIONS[number];
6
+
7
+ export interface InspectorParams {
8
+ id?: string;
9
+ runId?: string;
10
+ dir?: string;
11
+ index?: number;
12
+ focus?: boolean;
13
+ }
14
+
15
+ export interface InspectorTarget {
16
+ runId: string;
17
+ asyncDir: string;
18
+ index?: number;
19
+ status: {
20
+ cwd?: string;
21
+ state: string;
22
+ steps?: unknown[];
23
+ };
24
+ }
25
+
26
+ export interface InspectorContext {
27
+ cwd: string;
28
+ signal?: AbortSignal;
29
+ env: NodeJS.ProcessEnv;
30
+ now?: () => Date;
31
+ target: InspectorTarget;
32
+ }
33
+
34
+ export interface InspectorLaunch {
35
+ executable: string;
36
+ argv: string[];
37
+ displayCommand: string;
38
+ mission?: { id: string; path: string };
39
+ allowSteer: boolean;
40
+ allowStop: boolean;
41
+ sessionRoots: string[];
42
+ }
43
+
44
+ export interface InspectorPlugin {
45
+ readonly name: string;
46
+ available(context: InspectorContext): Promise<boolean> | boolean;
47
+ owns(context: InspectorContext): boolean;
48
+ open(context: InspectorContext, launch: InspectorLaunch, params: InspectorParams): Promise<AgentToolResult<Details>>;
49
+ status?(context: InspectorContext): Promise<AgentToolResult<Details>>;
50
+ close?(context: InspectorContext): Promise<AgentToolResult<Details>>;
51
+ }
@@ -0,0 +1,73 @@
1
+ import { hasLiveNestedDescendants, projectNestedEvents } from "../runs/shared/nested-events.ts";
2
+ import type { NestedRouteInfo, SubagentState } from "../shared/types.ts";
3
+
4
+ export const PI_WEB_SESSION_LIVENESS_REGISTRY_KEY = "@agegr/pi-web/session-liveness/v1";
5
+ const PI_WEB_SESSION_LIVENESS_PROTOCOL_VERSION = 1;
6
+
7
+ interface PiWebSessionLivenessProvider {
8
+ name: string;
9
+ sessionId: string;
10
+ sessionFile?: string;
11
+ isActive(): boolean;
12
+ }
13
+
14
+ interface PiWebSessionLivenessRegistry {
15
+ version: typeof PI_WEB_SESSION_LIVENESS_PROTOCOL_VERSION;
16
+ register(provider: PiWebSessionLivenessProvider): () => void;
17
+ }
18
+
19
+ type SessionLivenessRegistration = Omit<PiWebSessionLivenessProvider, "name">;
20
+
21
+ export interface PiWebSessionLivenessHandle {
22
+ /** True only when the compatible host accepted the provider registration. */
23
+ registered: boolean;
24
+ release: () => void;
25
+ }
26
+
27
+ type LiveWorkState = Pick<SubagentState, "asyncJobs" | "foregroundControls" | "retainedForegroundNestedRoutes">;
28
+
29
+ function resolveRegistry(): PiWebSessionLivenessRegistry | null {
30
+ const value = (globalThis as Record<PropertyKey, unknown>)[Symbol.for(PI_WEB_SESSION_LIVENESS_REGISTRY_KEY)];
31
+ if (!value || typeof value !== "object") return null;
32
+ const registry = value as Partial<PiWebSessionLivenessRegistry>;
33
+ if (registry.version !== PI_WEB_SESSION_LIVENESS_PROTOCOL_VERSION || typeof registry.register !== "function") return null;
34
+ return registry as PiWebSessionLivenessRegistry;
35
+ }
36
+
37
+ export function retainLiveForegroundNestedRoute(state: Pick<SubagentState, "retainedForegroundNestedRoutes">, route: NestedRouteInfo): boolean {
38
+ const nested = projectNestedEvents(route);
39
+ if (!hasLiveNestedDescendants(nested.children)) return false;
40
+ state.retainedForegroundNestedRoutes ??= new Map();
41
+ state.retainedForegroundNestedRoutes.set(route.rootRunId, route);
42
+ return true;
43
+ }
44
+
45
+ export function hasLiveSubagentWork(state: LiveWorkState): boolean {
46
+ for (const job of state.asyncJobs.values()) {
47
+ if (job.status === "queued" || job.status === "running" || hasLiveNestedDescendants(job.nestedChildren)) return true;
48
+ }
49
+ for (const control of state.foregroundControls.values()) {
50
+ if ((control.schedulingOwners ?? 0) > 0
51
+ || (control.activeChildren?.size ?? 0) > 0
52
+ || hasLiveNestedDescendants(control.nestedChildren)) return true;
53
+ }
54
+ return (state.retainedForegroundNestedRoutes?.size ?? 0) > 0;
55
+ }
56
+
57
+ export function registerPiWebSessionLiveness(registration: SessionLivenessRegistration): PiWebSessionLivenessHandle {
58
+ const registry = resolveRegistry();
59
+ if (!registry) return { registered: false, release: () => {} };
60
+ try {
61
+ const release = registry.register({
62
+ name: "pi-subagents",
63
+ sessionId: registration.sessionId,
64
+ ...(registration.sessionFile ? { sessionFile: registration.sessionFile } : {}),
65
+ isActive: registration.isActive,
66
+ });
67
+ if (typeof release === "function") return { registered: true, release };
68
+ console.error("Failed to register pi-web session liveness: host registry returned no release function.");
69
+ } catch (error) {
70
+ console.error("Failed to register pi-web session liveness:", error);
71
+ }
72
+ return { registered: false, release: () => {} };
73
+ }
@@ -2,6 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as os from "node:os";
3
3
  import * as path from "node:path";
4
4
  import type { AgentConfig } from "../agents/agents.ts";
5
+ import { agentDefinitionDigest } from "../shared/launch-contract.ts";
5
6
  import type { ExtensionConfig, IntercomBridgeConfig, IntercomBridgeMode } from "../shared/types.ts";
6
7
  import { getAgentDir } from "../shared/utils.ts";
7
8
 
@@ -18,9 +19,13 @@ function defaultSubagentConfigDir(agentDir = defaultAgentDir()): string {
18
19
  const DEFAULT_INTERCOM_TARGET_PREFIX = "subagent-chat";
19
20
  export const PI_INTERCOM_SESSION_ID_ENV = "PI_INTERCOM_SESSION_ID";
20
21
  export const INTERCOM_BRIDGE_MARKER = "Intercom orchestration channel:";
22
+ const ORCHESTRATOR_TARGET_PLACEHOLDER = "{orchestratorTarget}";
23
+ // The default template must stay session-independent: the child reads the
24
+ // supervisor target from its runtime config, and a prompt that names the
25
+ // parent session would make the launch digest vary per session (#2127).
21
26
  const DEFAULT_INTERCOM_BRIDGE_TEMPLATE = `The inherited thread is reference-only. Do not continue that conversation or send questions, status updates, or completion handoffs to the supervisor in normal assistant text.
22
27
 
23
- Use contact_supervisor first. It resolves the supervisor session "{orchestratorTarget}" and run metadata automatically.
28
+ Use contact_supervisor first. It resolves the supervisor session and run metadata automatically.
24
29
  - Need a decision, blocked, approval, or product/API/scope ambiguity: contact_supervisor({ reason: "need_decision", message: "<question>" })
25
30
  - Need structured supervisor input rather than a freeform reply: contact_supervisor({ reason: "interview_request", message: "<what input is needed>", interview: { title: "...", questions: [] } })
26
31
  - After contact_supervisor with reason "need_decision" or "interview_request", stay alive and continue only after the reply arrives. Do not finish your final response with a choose-one question.
@@ -36,6 +41,32 @@ export interface IntercomBridgeState {
36
41
  orchestratorTarget?: string;
37
42
  extensionDir: string;
38
43
  instruction: string;
44
+ /** True when the instruction template names the supervisor session, which ties the child prompt to the parent session. */
45
+ interpolatesOrchestratorTarget: boolean;
46
+ }
47
+
48
+ export type IntercomBridgeConfigValidation =
49
+ | { ok: true; value: IntercomBridgeConfig }
50
+ | { ok: false; error: string };
51
+
52
+ /** Validates untrusted bridge config from descriptors or delegation requests; `label` prefixes each error. */
53
+ export function validateIntercomBridgeConfig({ value, label }: { value: unknown; label: string }): IntercomBridgeConfigValidation {
54
+ if (!value || typeof value !== "object" || Array.isArray(value)) return { ok: false, error: `${label} must be an object.` };
55
+ const bridge = value as Record<string, unknown>;
56
+ for (const field of Object.keys(bridge)) {
57
+ if (field !== "mode" && field !== "instructionFile" && field !== "resultDelivery") return { ok: false, error: `${label}.${field} is not supported.` };
58
+ }
59
+ if (bridge.mode !== undefined && bridge.mode !== "off" && bridge.mode !== "fork-only" && bridge.mode !== "always") return { ok: false, error: `${label}.mode is invalid.` };
60
+ if (bridge.instructionFile !== undefined && typeof bridge.instructionFile !== "string") return { ok: false, error: `${label}.instructionFile must be a string.` };
61
+ if (bridge.resultDelivery !== undefined && typeof bridge.resultDelivery !== "boolean") return { ok: false, error: `${label}.resultDelivery must be a boolean.` };
62
+ return {
63
+ ok: true,
64
+ value: {
65
+ ...(bridge.mode !== undefined ? { mode: bridge.mode as IntercomBridgeMode } : {}),
66
+ ...(bridge.instructionFile !== undefined ? { instructionFile: bridge.instructionFile as string } : {}),
67
+ ...(bridge.resultDelivery !== undefined ? { resultDelivery: bridge.resultDelivery as boolean } : {}),
68
+ },
69
+ };
39
70
  }
40
71
 
41
72
  export interface IntercomBridgeDiagnostic {
@@ -114,7 +145,7 @@ function resolveInstructionTemplate(instructionFile: string, settingsDir: string
114
145
  }
115
146
 
116
147
  function buildIntercomBridgeInstruction(orchestratorTarget: string, template: string): string {
117
- const instruction = template.replaceAll("{orchestratorTarget}", orchestratorTarget).trim();
148
+ const instruction = template.replaceAll(ORCHESTRATOR_TARGET_PLACEHOLDER, orchestratorTarget).trim();
118
149
  if (instruction.startsWith(INTERCOM_BRIDGE_MARKER)) return instruction;
119
150
  return `${INTERCOM_BRIDGE_MARKER}\n${instruction}`;
120
151
  }
@@ -149,24 +180,34 @@ export function resolveIntercomBridge(input: ResolveIntercomBridgeInput): Interc
149
180
  const orchestratorTarget = input.orchestratorTarget?.trim();
150
181
  const agentDir = path.resolve(input.agentDir ?? defaultAgentDir());
151
182
  const settingsDir = path.resolve(input.settingsDir ?? defaultSubagentConfigDir(agentDir));
152
- const defaultInstruction = buildIntercomBridgeInstruction(
153
- orchestratorTarget || "{orchestratorTarget}",
154
- DEFAULT_INTERCOM_BRIDGE_TEMPLATE,
155
- );
156
183
  const reason = inactiveReason(mode, input.context, orchestratorTarget);
157
184
  if (reason || !orchestratorTarget) {
158
- return { active: false, mode, resultDelivery: config.resultDelivery, extensionDir: NATIVE_INTERCOM_EXTENSION_DIR, instruction: defaultInstruction };
185
+ return {
186
+ active: false,
187
+ mode,
188
+ resultDelivery: config.resultDelivery,
189
+ extensionDir: NATIVE_INTERCOM_EXTENSION_DIR,
190
+ instruction: buildIntercomBridgeInstruction(ORCHESTRATOR_TARGET_PLACEHOLDER, DEFAULT_INTERCOM_BRIDGE_TEMPLATE),
191
+ interpolatesOrchestratorTarget: false,
192
+ };
159
193
  }
194
+ const template = resolveInstructionTemplate(config.instructionFile, settingsDir);
160
195
  return {
161
196
  active: true,
162
197
  mode,
163
198
  resultDelivery: config.resultDelivery,
164
199
  orchestratorTarget,
165
200
  extensionDir: NATIVE_INTERCOM_EXTENSION_DIR,
166
- instruction: buildIntercomBridgeInstruction(orchestratorTarget, resolveInstructionTemplate(config.instructionFile, settingsDir)),
201
+ instruction: buildIntercomBridgeInstruction(orchestratorTarget, template),
202
+ interpolatesOrchestratorTarget: template.includes(ORCHESTRATOR_TARGET_PLACEHOLDER),
167
203
  };
168
204
  }
169
205
 
206
+ /**
207
+ * Rewrites the launch prompt and tools for an active bridge. The parsed
208
+ * definition digest is captured first so launch identity keeps describing the
209
+ * agent file rather than this runtime overlay.
210
+ */
170
211
  export function applyIntercomBridgeToAgent(agent: AgentConfig, bridge: IntercomBridgeState): AgentConfig {
171
212
  if (!bridge.active || !bridge.orchestratorTarget) return agent;
172
213
 
@@ -185,6 +226,7 @@ export function applyIntercomBridgeToAgent(agent: AgentConfig, bridge: IntercomB
185
226
  if (tools === agent.tools && systemPrompt === agent.systemPrompt) return agent;
186
227
  return {
187
228
  ...agent,
229
+ definitionDigest: agentDefinitionDigest(agent),
188
230
  tools,
189
231
  systemPrompt,
190
232
  };