@xzzpig/pi-subagents 0.8.0 → 0.10.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 (221) hide show
  1. package/CHANGELOG.md +477 -0
  2. package/README.md +2 -2
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +1 -1
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +195 -39
  12. package/docs/configuration.md +81 -22
  13. package/docs/extension-api.md +69 -14
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +32 -9
  16. package/docs/observability.md +22 -20
  17. package/docs/tool-reference.md +123 -14
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +142 -4
  20. package/install.mjs +1 -1
  21. package/package.json +7 -6
  22. package/prompts/review-loop.md +2 -2
  23. package/skills/council-mode/SKILL.md +48 -243
  24. package/skills/council-mode/references/pass-contracts.md +150 -0
  25. package/skills/pi-subagents/SKILL.md +89 -35
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
  27. package/skills/pi-subagents/references/execution-controls.md +91 -15
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
  31. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  32. package/src/agents/agent-management.ts +384 -115
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +14 -2
  35. package/src/agents/agents.ts +935 -372
  36. package/src/agents/builtin-names.ts +6 -0
  37. package/src/agents/runtime-agent-events.ts +70 -0
  38. package/src/agents/runtime-agent-registry.ts +42 -21
  39. package/src/api/agents.ts +10 -5
  40. package/src/api/background-work.ts +12 -3
  41. package/src/api/capability-ceiling.ts +0 -1
  42. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  43. package/src/api/delegation.ts +0 -7
  44. package/src/api/external-runs.ts +67 -4
  45. package/src/api/preflight.ts +77 -21
  46. package/src/api/shared-types.ts +6 -0
  47. package/src/extension/config.ts +90 -0
  48. package/src/extension/doctor.ts +5 -13
  49. package/src/extension/fanout-child.ts +14 -14
  50. package/src/extension/index.ts +115 -37
  51. package/src/extension/public-execution.ts +103 -15
  52. package/src/extension/rpc.ts +120 -25
  53. package/src/extension/schemas.ts +65 -29
  54. package/src/extension/tool-description.ts +48 -26
  55. package/src/inspectors/herdr/actions.ts +2 -1
  56. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  57. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  58. package/src/integrations/herdr-status.ts +51 -3
  59. package/src/intercom/native-supervisor-channel.ts +138 -60
  60. package/src/intercom/result-intercom.ts +7 -0
  61. package/src/intercom/supervisor-ui.ts +243 -0
  62. package/src/profiles/profiles.ts +5 -6
  63. package/src/runs/background/active-async-capacity.ts +103 -18
  64. package/src/runs/background/async-execution.ts +417 -133
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +60 -28
  67. package/src/runs/background/async-retention.ts +20 -3
  68. package/src/runs/background/async-status-snapshot.ts +23 -261
  69. package/src/runs/background/async-status.ts +204 -14
  70. package/src/runs/background/auto-drain.ts +1 -1
  71. package/src/runs/background/chain-append.ts +8 -3
  72. package/src/runs/background/chain-root-attachment.ts +74 -8
  73. package/src/runs/background/control-channel.ts +4 -205
  74. package/src/runs/background/fleet-view.ts +38 -22
  75. package/src/runs/background/inspect-rpc.ts +8 -8
  76. package/src/runs/background/notify.ts +238 -12
  77. package/src/runs/background/process-terminal.ts +16 -0
  78. package/src/runs/background/result-delivery-ownership.ts +45 -0
  79. package/src/runs/background/result-files.ts +28 -14
  80. package/src/runs/background/result-watcher.ts +39 -16
  81. package/src/runs/background/resume-guidance.ts +2 -2
  82. package/src/runs/background/retained-children.ts +1 -1
  83. package/src/runs/background/run-child-session.ts +613 -0
  84. package/src/runs/background/run-status.ts +84 -17
  85. package/src/runs/background/runner-aliases.ts +125 -0
  86. package/src/runs/background/runner-child-sessions.ts +31 -0
  87. package/src/runs/background/scheduled-runs.ts +174 -18
  88. package/src/runs/background/stale-run-reconciler.ts +10 -4
  89. package/src/runs/background/steering.ts +8 -15
  90. package/src/runs/background/subagent-runner.ts +718 -1161
  91. package/src/runs/background/subagent-wait.ts +86 -31
  92. package/src/runs/background/terminal-run-index.ts +1 -1
  93. package/src/runs/background/wait-completions.ts +43 -2
  94. package/src/runs/background/wait-config.ts +23 -9
  95. package/src/runs/background/wait-tool.ts +26 -19
  96. package/src/runs/foreground/async-steering-action.ts +3 -19
  97. package/src/runs/foreground/execution.ts +489 -499
  98. package/src/runs/foreground/foreground-control.ts +13 -0
  99. package/src/runs/foreground/foreground-history.ts +23 -1
  100. package/src/runs/foreground/subagent-executor.ts +1223 -402
  101. package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
  102. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  103. package/src/runs/shared/abort-recovery.ts +119 -0
  104. package/src/runs/shared/acceptance.ts +138 -36
  105. package/src/runs/shared/async-status-projection.ts +565 -0
  106. package/src/runs/shared/background-process-options.ts +9 -0
  107. package/src/runs/shared/capability-ceiling.ts +2 -2
  108. package/src/runs/shared/child-hooks.ts +25 -0
  109. package/src/runs/shared/child-identity.ts +32 -6
  110. package/src/runs/shared/child-launch-plan.ts +151 -0
  111. package/src/runs/shared/child-launch.ts +364 -0
  112. package/src/runs/shared/child-lifecycle.ts +25 -0
  113. package/src/runs/shared/child-runtime-config.ts +126 -0
  114. package/src/runs/shared/child-session.ts +366 -0
  115. package/src/runs/shared/child-tool-plan.ts +632 -0
  116. package/src/runs/shared/claude-code-adapter.ts +133 -0
  117. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  118. package/src/runs/shared/completion-evidence.ts +89 -0
  119. package/src/runs/shared/completion-guard.ts +6 -5
  120. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  121. package/src/runs/shared/dynamic-fanout.ts +3 -3
  122. package/src/runs/shared/external-cli-contract.ts +167 -0
  123. package/src/runs/shared/external-cli-preflight.ts +138 -0
  124. package/src/runs/shared/external-cli-runner.ts +348 -55
  125. package/src/runs/shared/fast-mode-extension.ts +5 -5
  126. package/src/runs/shared/host-step-status.ts +231 -0
  127. package/src/runs/shared/lane-metadata.ts +126 -0
  128. package/src/runs/shared/launch-cwd.ts +16 -0
  129. package/src/runs/shared/long-running-guard.ts +2 -1
  130. package/src/runs/shared/mcp-config-sources.ts +422 -0
  131. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  132. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  133. package/src/runs/shared/model-exclusions.ts +139 -9
  134. package/src/runs/shared/model-fallback.ts +146 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +99 -77
  137. package/src/runs/shared/nested-path.ts +0 -14
  138. package/src/runs/shared/nested-render.ts +9 -5
  139. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  140. package/src/runs/shared/parallel-handoff.ts +423 -7
  141. package/src/runs/shared/parallel-utils.ts +20 -7
  142. package/src/runs/shared/permissions.ts +1 -14
  143. package/src/runs/shared/pi-spawn.ts +69 -35
  144. package/src/runs/shared/process-signal.ts +16 -0
  145. package/src/runs/shared/run-fanout-budget.ts +0 -13
  146. package/src/runs/shared/run-history.ts +21 -1
  147. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  148. package/src/runs/shared/sandbox-profile-guard.ts +85 -0
  149. package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
  150. package/src/runs/shared/single-output.ts +89 -22
  151. package/src/runs/shared/structured-output.ts +49 -9
  152. package/src/runs/shared/subagent-control.ts +6 -2
  153. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  154. package/src/runs/shared/task-intent.ts +21 -7
  155. package/src/runs/shared/tool-availability.ts +18 -62
  156. package/src/runs/shared/tool-budget.ts +0 -14
  157. package/src/runs/shared/tool-timeout.ts +1 -1
  158. package/src/runs/shared/workflow-graph.ts +16 -0
  159. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  160. package/src/runs/shared/worktree.ts +571 -62
  161. package/src/shared/atomic-json.ts +3 -1
  162. package/src/shared/child-session-name.ts +46 -0
  163. package/src/shared/extension-context.ts +24 -0
  164. package/src/shared/fork-context.ts +21 -12
  165. package/src/shared/fork-session-cwd.ts +27 -0
  166. package/src/shared/formatters.ts +18 -3
  167. package/src/shared/jsonl-writer.ts +11 -0
  168. package/src/shared/launch-contract.ts +11 -1
  169. package/src/shared/pruned-fork.ts +450 -0
  170. package/src/shared/sandbox-profile.ts +23 -0
  171. package/src/shared/session-file-trust.ts +19 -0
  172. package/src/shared/session-tokens.ts +14 -3
  173. package/src/shared/settings.ts +19 -105
  174. package/src/shared/shortcuts.ts +17 -0
  175. package/src/shared/thinking-ceiling.ts +0 -6
  176. package/src/shared/types.ts +545 -70
  177. package/src/shared/utils.ts +60 -93
  178. package/src/shared/workflow-child-permit.ts +207 -0
  179. package/src/slash/delegation-adapters.ts +1 -9
  180. package/src/slash/delegation-request.ts +0 -4
  181. package/src/slash/prompt-template-bridge.ts +37 -1
  182. package/src/slash/slash-bridge.ts +1 -2
  183. package/src/slash/slash-commands.ts +383 -116
  184. package/src/slash/slash-live-state.ts +22 -11
  185. package/src/slash/subagents-admin.ts +29 -12
  186. package/src/tui/fleet-native-transcript.ts +4 -0
  187. package/src/tui/fleet-status.ts +217 -82
  188. package/src/tui/fleet-transcript.ts +11 -5
  189. package/src/tui/fleet.ts +54 -28
  190. package/src/tui/render-helpers.ts +31 -0
  191. package/src/tui/render.ts +1429 -163
  192. package/src/watchdog/change-signature.ts +40 -1
  193. package/src/watchdog/child-status.ts +54 -34
  194. package/src/watchdog/diff-tool.ts +77 -0
  195. package/src/watchdog/emission-guard.ts +5 -3
  196. package/src/watchdog/guidance.ts +20 -0
  197. package/src/watchdog/register-child.ts +28 -25
  198. package/src/watchdog/register-main.ts +10 -9
  199. package/src/watchdog/render.ts +4 -5
  200. package/src/watchdog/review.ts +15 -4
  201. package/src/watchdog/rules.ts +70 -0
  202. package/src/watchdog/runtime.ts +75 -92
  203. package/src/watchdog/scope.ts +0 -11
  204. package/src/watchdog/settings.ts +48 -104
  205. package/src/watchdog/turn-delta.ts +1 -1
  206. package/src/watchdog/types.ts +18 -32
  207. package/src/watchdog/warning-format.ts +0 -1
  208. package/src/workflows/chat-progress.ts +7 -3
  209. package/src/workflows/host-command.ts +235 -0
  210. package/src/workflows/scripted-workflow.ts +988 -59
  211. package/src/workflows/workflow-checklist.ts +439 -0
  212. package/src/workflows/workflow-child-summary.ts +121 -0
  213. package/src/workflows/workflow-preflight.ts +297 -0
  214. package/src/workflows/workflow-receipt.ts +232 -6
  215. package/src/workflows/workflow-resources.ts +150 -0
  216. package/src/workflows/workflow-settlement.ts +246 -0
  217. package/src/runs/shared/child-protocol.ts +0 -401
  218. package/src/runs/shared/pi-args.ts +0 -935
  219. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  220. package/src/runs/shared/turn-budget.ts +0 -98
  221. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -0,0 +1,126 @@
1
+ import type { JsonSchemaObject, ResolvedToolBudget, RunFanoutBudgetDescriptor } from "../../shared/types.ts";
2
+ import type { ThinkingLevel } from "../../shared/model-info.ts";
3
+ import type { NestedPathEntry } from "./nested-path.ts";
4
+ import type { PermissionRules } from "./permissions.ts";
5
+ import type { ChildWatchdogConfig, ChildWatchdogStatusEvent } from "../../watchdog/child-status.ts";
6
+ import type { ResolvedWaitToolConfig } from "../background/wait-config.ts";
7
+ import type { ChildToolDiagnostic } from "./tool-availability.ts";
8
+ import type { ResolvedSubagentCapabilityCeiling } from "./capability-ceiling.ts";
9
+
10
+ /**
11
+ * Set in processes that host child sessions (the async runner). The extension
12
+ * entry point registers nothing when it sees it, so an ambient copy of
13
+ * pi-subagents loaded into a child session stays inert.
14
+ */
15
+ export const SUBAGENT_CHILD_ENV = "PI_SUBAGENT_CHILD";
16
+ /** Root parent session id the parent publishes for pi-permission-system ask forwarding. */
17
+ export const SUBAGENT_PARENT_SESSION_ENV = "PI_SUBAGENT_PARENT_SESSION";
18
+
19
+ export interface ChildNestedRoute {
20
+ rootRunId: string;
21
+ eventSink: string;
22
+ controlInbox: string;
23
+ capabilityToken: string;
24
+ }
25
+
26
+ export interface ChildNestedParent {
27
+ parentRunId: string;
28
+ parentChildIndex?: number;
29
+ depth: number;
30
+ path: NestedPathEntry[];
31
+ }
32
+
33
+ export interface ChildPermissions {
34
+ rules: PermissionRules;
35
+ auditPath?: string;
36
+ }
37
+
38
+ export interface ChildStructuredOutput {
39
+ schema: JsonSchemaObject;
40
+ acceptanceReport?: "optional" | "required";
41
+ /** Receives the validated value; `acceptanceReport` is undefined when the child omitted it. */
42
+ capture: (value: unknown, acceptanceReport: unknown | undefined) => void;
43
+ }
44
+
45
+ export interface ChildSupervisorMetadata {
46
+ channelDir: string;
47
+ runId: string;
48
+ agent: string;
49
+ childIndex: number;
50
+ orchestratorTarget?: string;
51
+ orchestratorSessionId: string;
52
+ childTarget?: string;
53
+ }
54
+
55
+ /**
56
+ * Everything the child-side hooks need to know about the launch. The process
57
+ * that hosts the child session builds it and passes it to the hooks directly.
58
+ */
59
+ export interface ChildRuntimeConfig {
60
+ runId?: string;
61
+ agent?: string;
62
+ childIndex?: number;
63
+ fanoutChild: boolean;
64
+ sessionName?: string;
65
+ intercomSessionName?: string;
66
+ orchestratorTarget?: string;
67
+ orchestratorSessionId?: string;
68
+ parentSessionId?: string;
69
+ supervisorChannelDir?: string;
70
+ /** Route the child reports nested runs on; set only for fanout-authorized children. */
71
+ nestedRoute?: ChildNestedRoute;
72
+ nestedParent?: ChildNestedParent;
73
+ runFanoutBudget?: RunFanoutBudgetDescriptor;
74
+ /** Nesting depth of this child (1 for a top-level parent's child). */
75
+ depth: number;
76
+ maxDepth?: number;
77
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
78
+ thinkingCeiling?: ThinkingLevel;
79
+ inheritProjectContext?: boolean;
80
+ inheritGlobalContext?: boolean;
81
+ inheritSkills?: boolean;
82
+ forkCacheKey?: string;
83
+ permissions?: ChildPermissions;
84
+ toolBudget?: ResolvedToolBudget;
85
+ childWatchdog?: ChildWatchdogConfig;
86
+ /** Receives child watchdog status events. */
87
+ watchdogStatus?: (event: ChildWatchdogStatusEvent) => void;
88
+ waitTool: ResolvedWaitToolConfig;
89
+ structuredOutput?: ChildStructuredOutput;
90
+ requiredTools?: string[];
91
+ mcpDirectTools?: string[];
92
+ /** Receives the tool-availability diagnostic at every agent start; undefined when every required tool is present. */
93
+ toolDiagnostic?: (diagnostic: ChildToolDiagnostic | undefined) => void;
94
+ /** Receives the runtime-acknowledged extension ids when the child run ends. */
95
+ runtimeAcknowledgements?: (ids: string[]) => void;
96
+ fast: boolean;
97
+ }
98
+
99
+ export function childSupervisorMetadata(config: ChildRuntimeConfig): ChildSupervisorMetadata | undefined {
100
+ if (!config.supervisorChannelDir || !config.runId || !config.agent || !config.orchestratorSessionId || config.childIndex === undefined) return undefined;
101
+ return {
102
+ channelDir: config.supervisorChannelDir,
103
+ runId: config.runId,
104
+ agent: config.agent,
105
+ childIndex: config.childIndex,
106
+ ...(config.orchestratorTarget ? { orchestratorTarget: config.orchestratorTarget } : {}),
107
+ orchestratorSessionId: config.orchestratorSessionId,
108
+ ...(config.intercomSessionName ? { childTarget: config.intercomSessionName } : {}),
109
+ };
110
+ }
111
+
112
+ /** Compute the child tool-availability diagnostic; undefined when every required tool is present. */
113
+ export function evaluateChildToolDiagnostic(config: Pick<ChildRuntimeConfig, "agent" | "requiredTools" | "mcpDirectTools">, availableTools: string[]): ChildToolDiagnostic | undefined {
114
+ if (!config.requiredTools) return undefined;
115
+ const available = new Set(availableTools);
116
+ const missing = config.requiredTools.filter((name) => !available.has(name));
117
+ if (missing.length === 0) return undefined;
118
+ const missingMcpDirectTools = config.mcpDirectTools?.length ? missing.filter((name) => config.mcpDirectTools!.includes(name)) : [];
119
+ return {
120
+ ...(config.agent ? { agent: config.agent } : {}),
121
+ required: config.requiredTools,
122
+ available: availableTools,
123
+ missing,
124
+ ...(missingMcpDirectTools.length > 0 ? { missingMcpDirectTools } : {}),
125
+ };
126
+ }
@@ -0,0 +1,366 @@
1
+ /**
2
+ * In-process child sessions.
3
+ *
4
+ * A child is a pi `AgentSession` created inside the process that owns it: the
5
+ * parent pi process for foreground children, the detached runner process for
6
+ * background children. The factory is injectable so tests can script a child
7
+ * without the real runtime; the default implementation wraps
8
+ * `createAgentSession` from a pi package module and shares one `ModelRuntime`
9
+ * across every child it creates.
10
+ */
11
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
12
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
13
+ import { getAgentDir } from "../../shared/utils.ts";
14
+ import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
15
+
16
+ export interface ChildSessionEvent {
17
+ type: string;
18
+ [key: string]: unknown;
19
+ }
20
+
21
+ /** Mirror pi's JSON event projection: `message_update` drops the partial message. */
22
+ export function projectChildSessionEventForJson(event: ChildSessionEvent): unknown {
23
+ if (event.type !== "message_update") return event;
24
+ const assistantMessageEvent = event.assistantMessageEvent as Record<string, unknown> | undefined;
25
+ if (!assistantMessageEvent || typeof assistantMessageEvent !== "object") return event;
26
+ const { partial: _partial, ...delta } = assistantMessageEvent;
27
+ return { type: "message_update", usage: (event.message as { usage?: unknown } | undefined)?.usage, assistantMessageEvent: delta };
28
+ }
29
+
30
+ export interface ChildSessionExtensionError {
31
+ extensionPath: string;
32
+ event: string;
33
+ error: unknown;
34
+ }
35
+
36
+ export interface ChildHookExtension {
37
+ name: string;
38
+ factory: (pi: ExtensionAPI) => void;
39
+ }
40
+
41
+ export type ChildSessionStorage =
42
+ | { kind: "file"; sessionFile: string }
43
+ | { kind: "dir"; sessionDir: string }
44
+ | { kind: "default" }
45
+ | { kind: "memory" };
46
+
47
+ export interface ChildSessionLaunch {
48
+ cwd: string;
49
+ storage: ChildSessionStorage;
50
+ /** Model reference as the agent config names it (`provider/id`, optionally `:thinking`). */
51
+ model?: string;
52
+ /** Explicit tool allowlist; undefined keeps pi's defaults. */
53
+ tools?: string[];
54
+ excludeTools?: string[];
55
+ /** Extension files loaded for this child in addition to the inline hooks. */
56
+ extensionPaths: string[];
57
+ /**
58
+ * Discover the ambient extensions (agent dir, project, settings) the way a
59
+ * `pi` process would. False loads only `extensionPaths` and `hooks`.
60
+ */
61
+ ambientExtensions: boolean;
62
+ hooks: ChildHookExtension[];
63
+ noSkills: boolean;
64
+ noContextFiles: boolean;
65
+ systemPrompt?: string;
66
+ appendSystemPrompt?: string;
67
+ /**
68
+ * Environment values that extensions loaded into the child read from
69
+ * `process.env`. Applied to the hosting process while the session is created
70
+ * and its extensions load and start; launches in one process take that
71
+ * window one at a time. An undefined value removes the variable.
72
+ */
73
+ processEnv?: Record<string, string | undefined>;
74
+ /**
75
+ * `processEnv` keys restored to their pre-launch values once the session
76
+ * exists and its extensions have captured them. Sandbox profile selections
77
+ * use this so an in-process child cannot leak its profile into the host
78
+ * process or sibling launches.
79
+ */
80
+ transientProcessEnv?: string[];
81
+ /** The typed runtime config the hooks were built from; informational for factories. */
82
+ runtime: ChildRuntimeConfig;
83
+ onExtensionError?: (error: ChildSessionExtensionError) => void;
84
+ }
85
+
86
+ export interface ChildSession {
87
+ subscribe(listener: (event: ChildSessionEvent) => void): () => void;
88
+ /** Resolves when the run ends, including after abort. */
89
+ prompt(text: string): Promise<void>;
90
+ steer(text: string): Promise<void>;
91
+ followUp(text: string): Promise<void>;
92
+ abort(): Promise<void>;
93
+ /** Emits `session_shutdown` to the child's extensions and disposes the session; resolves once that shutdown work is done. */
94
+ dispose(): Promise<void>;
95
+ readonly messages: readonly AgentMessage[];
96
+ readonly sessionFile: string | undefined;
97
+ readonly sessionId: string;
98
+ readonly modelId: string | undefined;
99
+ /** Set by the foreground host once the run detached; `factory.dispose()` leaves such children running. */
100
+ detached?: boolean;
101
+ /** Set by `factory.dispose()` before it aborts the child, so the host can report the stop truthfully. */
102
+ shutDown?: boolean;
103
+ }
104
+
105
+ export interface ChildSessionFactory {
106
+ create(launch: ChildSessionLaunch): Promise<ChildSession>;
107
+ /** Abort and dispose every live attached child; detached children keep running and hold the shared runtime. */
108
+ dispose(): Promise<void>;
109
+ }
110
+
111
+ export type PiCodingAgentModule = typeof import("@earendil-works/pi-coding-agent");
112
+
113
+ export interface DefaultChildSessionFactoryOptions {
114
+ /**
115
+ * Loads the pi package the sessions are created from. The parent process
116
+ * uses the host's in-process module; the detached runner imports the
117
+ * installed package by absolute path.
118
+ */
119
+ loadPiCodingAgent?: () => Promise<PiCodingAgentModule>;
120
+ /** Upper bound on a disposed child's `session_shutdown` handlers before the session is dropped anyway. */
121
+ shutdownTimeoutMs?: number;
122
+ }
123
+
124
+ type ModelRuntimeInstance = Awaited<ReturnType<PiCodingAgentModule["ModelRuntime"]["create"]>>;
125
+ type QueuedProviderRegistration = { name: string; config: Parameters<ModelRuntimeInstance["registerProvider"]>[1]; extensionPath: string };
126
+ type QueuedNativeProviderRegistration = { provider: Parameters<ModelRuntimeInstance["registerNativeProvider"]>[0]; extensionPath: string };
127
+
128
+ interface LoaderWithExtensions {
129
+ getExtensions(): {
130
+ runtime: {
131
+ pendingProviderRegistrations: QueuedProviderRegistration[];
132
+ pendingNativeProviderRegistrations: QueuedNativeProviderRegistration[];
133
+ };
134
+ };
135
+ }
136
+
137
+ /** One launch at a time from env application through `session_start`, so parallel launches never observe each other's `processEnv` while their extensions load and start. */
138
+ let loading: Promise<unknown> = Promise.resolve();
139
+
140
+ /**
141
+ * pi caches extension factories per process and clears that cache only when a
142
+ * loader reloads a second time, so every child in one process would share each
143
+ * extension's module state. Marking the child's loader as already loaded makes
144
+ * its first `reload()` clear the cache, so the child gets its own instances the
145
+ * way a separate process had them. The flag is a private field of pi's loader.
146
+ */
147
+ function resetExtensionCacheOnReload(loader: object): boolean {
148
+ if (!("loaded" in loader)) return false;
149
+ (loader as { loaded: boolean }).loaded = true;
150
+ return true;
151
+ }
152
+
153
+ function applyProcessEnv(values: Record<string, string | undefined> | undefined): void {
154
+ if (!values) return;
155
+ for (const [name, value] of Object.entries(values)) {
156
+ if (value === undefined) delete process.env[name];
157
+ else process.env[name] = value;
158
+ }
159
+ }
160
+
161
+ function captureProcessEnv(keys: readonly string[] | undefined): Array<[string, string | undefined]> {
162
+ if (!keys?.length) return [];
163
+ return keys.map((key) => [key, process.env[key]]);
164
+ }
165
+
166
+ function restoreProcessEnv(saved: Array<[string, string | undefined]>): void {
167
+ for (const [key, value] of saved) {
168
+ if (value === undefined) delete process.env[key];
169
+ else process.env[key] = value;
170
+ }
171
+ }
172
+
173
+ function flushQueuedProviderRegistrations(loader: object, modelRuntime: ModelRuntimeInstance, onError: ((error: ChildSessionExtensionError) => void) | undefined): void {
174
+ if (!("getExtensions" in loader) || typeof loader.getExtensions !== "function") return;
175
+ const { runtime } = (loader as LoaderWithExtensions).getExtensions();
176
+ for (const { name, config, extensionPath } of runtime.pendingProviderRegistrations) {
177
+ try {
178
+ modelRuntime.registerProvider(name, config);
179
+ } catch (error) {
180
+ onError?.({ extensionPath, event: "register_provider", error });
181
+ }
182
+ }
183
+ runtime.pendingProviderRegistrations = [];
184
+ for (const { provider, extensionPath } of runtime.pendingNativeProviderRegistrations) {
185
+ try {
186
+ modelRuntime.registerNativeProvider(provider);
187
+ } catch (error) {
188
+ onError?.({ extensionPath, event: "register_provider", error });
189
+ }
190
+ }
191
+ runtime.pendingNativeProviderRegistrations = [];
192
+ }
193
+
194
+ /**
195
+ * Default factory: real pi sessions sharing one `ModelRuntime`, created lazily
196
+ * on the first child launch and dropped on `dispose()`.
197
+ */
198
+ export function createDefaultChildSessionFactory(options: DefaultChildSessionFactoryOptions = {}): ChildSessionFactory {
199
+ const loadPiCodingAgent = options.loadPiCodingAgent ?? (() => import("@earendil-works/pi-coding-agent"));
200
+ const shutdownTimeoutMs = options.shutdownTimeoutMs ?? 5_000;
201
+ let runtime: ReturnType<PiCodingAgentModule["ModelRuntime"]["create"]> | undefined;
202
+ const live = new Set<ChildSession>();
203
+ /** Extension shutdowns still running for disposed children; `dispose()` waits for them. */
204
+ const shutdowns = new Set<Promise<void>>();
205
+ const sharedRuntime = async (pi: PiCodingAgentModule) => {
206
+ runtime ??= pi.ModelRuntime.create().catch((error: unknown) => {
207
+ runtime = undefined;
208
+ throw error;
209
+ });
210
+ return runtime;
211
+ };
212
+ return {
213
+ async create(launch) {
214
+ const pi = await loadPiCodingAgent();
215
+ const modelRuntime = await sharedRuntime(pi);
216
+ const agentDir = getAgentDir();
217
+ const settingsManager = pi.SettingsManager.create(launch.cwd, agentDir);
218
+ const loader = new pi.DefaultResourceLoader({
219
+ cwd: launch.cwd,
220
+ agentDir,
221
+ settingsManager,
222
+ noExtensions: !launch.ambientExtensions,
223
+ noSkills: launch.noSkills,
224
+ noPromptTemplates: true,
225
+ noThemes: true,
226
+ noContextFiles: launch.noContextFiles,
227
+ additionalExtensionPaths: launch.extensionPaths,
228
+ extensionFactories: launch.hooks,
229
+ ...(launch.systemPrompt !== undefined ? { systemPrompt: launch.systemPrompt } : {}),
230
+ ...(launch.appendSystemPrompt !== undefined ? { appendSystemPrompt: [launch.appendSystemPrompt] } : {}),
231
+ });
232
+ const open = async () => {
233
+ const savedTransientEnv = captureProcessEnv(launch.transientProcessEnv);
234
+ applyProcessEnv(launch.processEnv);
235
+ if (!resetExtensionCacheOnReload(loader) && (launch.ambientExtensions || launch.extensionPaths.length)) launch.onExtensionError?.({ extensionPath: "<loader>", event: "load", error: new Error("pi's extension cache reset is unavailable; extensions loaded into this child share module state with other sessions in this process.") });
236
+ await loader.reload();
237
+ flushQueuedProviderRegistrations(loader, modelRuntime, launch.onExtensionError);
238
+ const sessionManager = launch.storage.kind === "file"
239
+ ? pi.SessionManager.open(launch.storage.sessionFile, undefined, launch.cwd)
240
+ : launch.storage.kind === "dir"
241
+ ? pi.SessionManager.create(launch.cwd, launch.storage.sessionDir)
242
+ : launch.storage.kind === "memory"
243
+ ? pi.SessionManager.inMemory(launch.cwd)
244
+ : pi.SessionManager.create(launch.cwd);
245
+ const resolvedModel = launch.model
246
+ ? pi.resolveCliModel({ cliModel: launch.model, modelRuntime })
247
+ : undefined;
248
+ if (resolvedModel?.error) throw new Error(resolvedModel.error);
249
+ const { session } = await pi.createAgentSession({
250
+ cwd: launch.cwd,
251
+ agentDir,
252
+ modelRuntime,
253
+ ...(resolvedModel?.model ? { model: resolvedModel.model } : {}),
254
+ ...(resolvedModel?.thinkingLevel ? { thinkingLevel: resolvedModel.thinkingLevel } : {}),
255
+ ...(launch.tools ? { tools: launch.tools } : {}),
256
+ ...(launch.excludeTools?.length ? { excludeTools: launch.excludeTools } : {}),
257
+ resourceLoader: loader,
258
+ sessionManager,
259
+ settingsManager,
260
+ sessionStartEvent: { type: "session_start", reason: "startup" },
261
+ });
262
+ // Extensions captured module state from the launch env window
263
+ // (registration and session_start); restore transient keys so an
264
+ // in-process child cannot leak them into the host process.
265
+ restoreProcessEnv(savedTransientEnv);
266
+ try {
267
+ await session.bindExtensions({
268
+ mode: "print",
269
+ onError: (error) => launch.onExtensionError?.({ extensionPath: error.extensionPath, event: error.event, error: error.error }),
270
+ });
271
+ } catch (error) {
272
+ session.dispose();
273
+ throw error;
274
+ }
275
+ return session;
276
+ };
277
+ const opened = loading.catch(() => {}).then(open);
278
+ loading = opened;
279
+ const session = await opened;
280
+ let pending: Promise<void> | undefined;
281
+ // pi's own hosts emit `session_shutdown` before disposing a session so the
282
+ // extensions loaded into it (ambient extensions included) release their
283
+ // watchers, servers, and timers. Do the same, then dispose.
284
+ const shutdown = async (): Promise<void> => {
285
+ try {
286
+ const runner = session.extensionRunner;
287
+ if (runner.hasHandlers("session_shutdown")) await Promise.race([runner.emit({ type: "session_shutdown", reason: "quit" }), new Promise((resolve) => setTimeout(resolve, shutdownTimeoutMs).unref?.())]);
288
+ } catch (error) {
289
+ launch.onExtensionError?.({ extensionPath: "<session>", event: "session_shutdown", error });
290
+ } finally {
291
+ session.dispose();
292
+ }
293
+ };
294
+ const child: ChildSession = {
295
+ subscribe: (listener) => session.subscribe((event) => listener(event as unknown as ChildSessionEvent)),
296
+ prompt: (text) => session.prompt(text),
297
+ steer: (text) => session.steer(text),
298
+ followUp: (text) => session.followUp(text),
299
+ abort: () => session.abort(),
300
+ dispose: () => {
301
+ if (!pending) {
302
+ live.delete(child);
303
+ const shutdownDone = shutdown();
304
+ pending = shutdownDone;
305
+ shutdowns.add(shutdownDone);
306
+ void shutdownDone.finally(() => shutdowns.delete(shutdownDone));
307
+ }
308
+ return pending;
309
+ },
310
+ get messages() { return session.messages; },
311
+ get sessionFile() { return session.sessionFile; },
312
+ get sessionId() { return session.sessionId; },
313
+ get modelId() { return session.model ? `${session.model.provider}/${session.model.id}` : undefined; },
314
+ };
315
+ live.add(child);
316
+ return child;
317
+ },
318
+ async dispose() {
319
+ const children = [...live].filter((child) => !child.detached);
320
+ for (const child of children) child.shutDown = true;
321
+ await Promise.allSettled(children.map((child) => child.abort()));
322
+ for (const child of children) {
323
+ try { void child.dispose(); } catch { /* best effort */ }
324
+ }
325
+ await Promise.allSettled([...shutdowns]);
326
+ if (live.size === 0) runtime = undefined;
327
+ },
328
+ };
329
+ }
330
+
331
+ let activeFactory: ChildSessionFactory | undefined;
332
+ let activeFactoryModule: string | undefined;
333
+
334
+ /** The process-wide factory foreground runs use unless a run passes its own. */
335
+ export function childSessionFactory(): ChildSessionFactory {
336
+ activeFactory ??= createDefaultChildSessionFactory();
337
+ return activeFactory;
338
+ }
339
+
340
+ /**
341
+ * Replace the process-wide factory. Tests install a scripted factory; passing
342
+ * undefined restores the default on next use.
343
+ */
344
+ export function setChildSessionFactory(factory: ChildSessionFactory | undefined): void {
345
+ activeFactory = factory;
346
+ }
347
+
348
+ /**
349
+ * Module path the detached background runner imports its child session factory
350
+ * from. Tests point it at a scripted factory; production launches leave it
351
+ * unset and the runner creates real sessions from the installed pi package.
352
+ */
353
+ export function childSessionFactoryModule(): string | undefined {
354
+ return activeFactoryModule;
355
+ }
356
+
357
+ export function setChildSessionFactoryModule(modulePath: string | undefined): void {
358
+ activeFactoryModule = modulePath;
359
+ }
360
+
361
+ /** Abort and dispose every live in-process child and release the shared runtime. */
362
+ export async function disposeChildSessions(): Promise<void> {
363
+ const factory = activeFactory;
364
+ if (!factory) return;
365
+ await factory.dispose();
366
+ }