@narumitw/pi-subagents 1.0.0 → 1.0.1

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.
@@ -0,0 +1,132 @@
1
+ import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
2
+ import { cachedModuleLoader, throwIfAborted } from "./cached-module-loader.js";
3
+ import type { RegisterSubagentConsultOptions } from "./consult.js";
4
+ import { renderConsultCall, renderConsultResult } from "./consult-render.js";
5
+ import { type ConsultDetails, SubagentConsultParams } from "./consult-tool.js";
6
+ import {
7
+ DEFAULT_CONSULT_RESOURCE_POLICY,
8
+ DEFAULT_CONSULTATION_CWD_POLICY,
9
+ } from "./settings/inspection.js";
10
+
11
+ interface ConsultExecutionModule {
12
+ executeSubagentConsult: typeof import("./consult.js").executeSubagentConsult;
13
+ }
14
+
15
+ export interface ConsultRegistrationDependencies {
16
+ loadExecution?: () => Promise<ConsultExecutionModule>;
17
+ }
18
+
19
+ export function registerSubagentConsult(
20
+ pi: ExtensionAPI,
21
+ options: RegisterSubagentConsultOptions,
22
+ dependencies: ConsultRegistrationDependencies = {},
23
+ ): (catalog: string) => void {
24
+ const loadExecution = cachedModuleLoader(
25
+ dependencies.loadExecution ?? (() => import("./consult.js")),
26
+ );
27
+ let generation = 0;
28
+ const active = new Set<AbortController>();
29
+ const activeWork = new Set<Promise<unknown>>();
30
+ const cancelActive = (reason: string) => {
31
+ generation++;
32
+ for (const controller of active) {
33
+ controller.abort(new DOMException(reason, "AbortError"));
34
+ }
35
+ active.clear();
36
+ };
37
+ const cancelAndWaitForWork = async (reason: string) => {
38
+ cancelActive(reason);
39
+ await Promise.allSettled([...activeWork]);
40
+ };
41
+ pi.on("session_start", () => cancelAndWaitForWork("Subagent consultation session replaced"));
42
+ pi.on("session_shutdown", () => cancelAndWaitForWork("Subagent consultation session shut down"));
43
+
44
+ const baseDescription = () =>
45
+ `Run one ephemeral subagent synchronously under enforced read-only tool and resource policies and return its answer. The child can use only the effective subset of Pi's built-in read, grep, find, and ls tools. Shell commands, file writes, extension tools, detached lifecycle operations, and persistent agent state are disabled. Working-directory target policy: ${options.getSettings()?.cwdPolicy?.consultation ?? DEFAULT_CONSULTATION_CWD_POLICY}; configured trusted-target resources: ${options.getSettings()?.consult?.resources ?? DEFAULT_CONSULT_RESOURCE_POLICY}; allowed targets without effective trust inherit no target/project resources. This is not a filesystem sandbox.`;
46
+ const definition: ToolDefinition<typeof SubagentConsultParams, ConsultDetails> = {
47
+ name: "subagent_consult",
48
+ label: "Consult Read-only Subagent",
49
+ description: baseDescription(),
50
+ promptSnippet: "Consult one constrained read-only subagent and wait for its answer",
51
+ promptGuidelines: [
52
+ "Use subagent_consult for bounded reconnaissance, planning, or review whose result is required in the current turn.",
53
+ "Set subagent_consult timeoutMs to the shortest realistic work deadline for the task difficulty; split oversized consultations instead of extending the deadline merely to compensate for broad scope.",
54
+ "Implementation-shaped tasks remain read-only and can return only analysis or instructions.",
55
+ ],
56
+ parameters: SubagentConsultParams,
57
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
58
+ const ownerGeneration = generation;
59
+ const ownedController = new AbortController();
60
+ active.add(ownedController);
61
+ const combined = combineAbortSignals(signal, ownedController.signal);
62
+ const work = (async () => {
63
+ throwIfAborted(combined.signal, "Subagent consultation loading was cancelled");
64
+ let executionModule: ConsultExecutionModule;
65
+ try {
66
+ executionModule = await loadExecution();
67
+ } catch (error) {
68
+ throwIfAborted(combined.signal, "Subagent consultation loading was cancelled");
69
+ throw error;
70
+ }
71
+ throwIfAborted(combined.signal, "Subagent consultation loading was cancelled");
72
+ if (ownerGeneration !== generation) {
73
+ throw new DOMException("Subagent consultation owner was replaced", "AbortError");
74
+ }
75
+ return executionModule.executeSubagentConsult(
76
+ params,
77
+ combined.signal,
78
+ onUpdate,
79
+ ctx,
80
+ options,
81
+ () => ownerGeneration === generation,
82
+ );
83
+ })();
84
+ activeWork.add(work);
85
+ try {
86
+ return await work;
87
+ } finally {
88
+ combined.dispose();
89
+ active.delete(ownedController);
90
+ activeWork.delete(work);
91
+ }
92
+ },
93
+ renderCall(args, theme) {
94
+ return renderConsultCall(args, theme);
95
+ },
96
+ renderResult(result, renderOptions, theme, context) {
97
+ return renderConsultResult(result, renderOptions, theme, context);
98
+ },
99
+ };
100
+ pi.registerTool<typeof SubagentConsultParams, ConsultDetails>(definition);
101
+ pi.on("tool_result", (event) => {
102
+ if (event.toolName !== "subagent_consult") return;
103
+ if ((event.details as ConsultDetails | undefined)?.isError) return { isError: true };
104
+ });
105
+ return (catalog: string) => {
106
+ definition.description = catalog ? `${baseDescription()}\n\n${catalog}` : baseDescription();
107
+ pi.registerTool<typeof SubagentConsultParams, ConsultDetails>(definition);
108
+ };
109
+ }
110
+
111
+ function combineAbortSignals(
112
+ external: AbortSignal | undefined,
113
+ owned: AbortSignal,
114
+ ): { signal: AbortSignal; dispose(): void } {
115
+ if (!external) return { signal: owned, dispose() {} };
116
+ const controller = new AbortController();
117
+ const sources = [external, owned];
118
+ const listeners = sources.map((source) => {
119
+ const listener = () => {
120
+ if (!controller.signal.aborted) controller.abort(source.reason);
121
+ };
122
+ if (source.aborted) listener();
123
+ else source.addEventListener("abort", listener, { once: true });
124
+ return { source, listener };
125
+ });
126
+ return {
127
+ signal: controller.signal,
128
+ dispose() {
129
+ for (const { source, listener } of listeners) source.removeEventListener("abort", listener);
130
+ },
131
+ };
132
+ }
@@ -0,0 +1,95 @@
1
+ import { StringEnum } from "@earendil-works/pi-ai";
2
+ import { type Static, Type } from "typebox";
3
+ import type { AgentScope, ConsultResourcePolicy } from "./agents/types.js";
4
+ import { THINKING_LEVELS } from "./agents/types.js";
5
+ import { DEFAULT_MAX_CONTEXT_BYTES, MAX_SUBAGENT_TIMEOUT_MS } from "./limits.js";
6
+
7
+ const ConsultScopeSchema = StringEnum(["user", "project", "both"] as const, {
8
+ default: "user",
9
+ description: "Agent definition scope. Project scopes require a trusted project.",
10
+ });
11
+ const ConsultThinkingSchema = StringEnum(THINKING_LEVELS);
12
+
13
+ export const SubagentConsultParams = Type.Object(
14
+ {
15
+ agent: Type.String({ minLength: 1 }),
16
+ task: Type.String({ minLength: 1, maxLength: DEFAULT_MAX_CONTEXT_BYTES }),
17
+ agentScope: Type.Optional(ConsultScopeSchema),
18
+ confirmProjectAgents: Type.Optional(Type.Boolean({ default: true })),
19
+ cwd: Type.Optional(Type.String({ minLength: 1 })),
20
+ timeoutMs: Type.Optional(
21
+ Type.Number({
22
+ minimum: 1,
23
+ maximum: MAX_SUBAGENT_TIMEOUT_MS,
24
+ description:
25
+ "Work deadline selected for the consultation difficulty. On expiry, Pi aborts the work and makes one separately bounded summary attempt.",
26
+ }),
27
+ ),
28
+ thinkingLevel: Type.Optional(ConsultThinkingSchema),
29
+ },
30
+ { additionalProperties: false },
31
+ );
32
+
33
+ export type SubagentConsultParams = Static<typeof SubagentConsultParams>;
34
+
35
+ export interface ConsultProgressActivity {
36
+ type: "text" | "toolCall";
37
+ text?: string;
38
+ name?: "read" | "grep" | "find" | "ls";
39
+ args?: Record<string, string | number | boolean>;
40
+ }
41
+
42
+ export interface ConsultProgress {
43
+ phase: "starting" | "running";
44
+ recentActivity: ConsultProgressActivity[];
45
+ recentActivityTotal: number;
46
+ actualProvider?: string;
47
+ actualModel?: string;
48
+ usage: {
49
+ input: number;
50
+ output: number;
51
+ cacheRead: number;
52
+ cacheWrite: number;
53
+ cost: number;
54
+ contextTokens: number;
55
+ turns: number;
56
+ };
57
+ }
58
+
59
+ export interface ConsultDetails {
60
+ agent: string;
61
+ agentSource: string;
62
+ agentScope: AgentScope;
63
+ cwd: string;
64
+ model?: string;
65
+ thinkingLevel?: string;
66
+ timeoutMs: number;
67
+ policy: {
68
+ requestedTools: string[] | null;
69
+ effectiveTools: string[];
70
+ cwdBoundary: "current-workspace" | "external";
71
+ targetTrust: {
72
+ kind: string;
73
+ projectTrusted: boolean;
74
+ sourcePath?: string;
75
+ warning?: string;
76
+ };
77
+ requestedResources: ConsultResourcePolicy;
78
+ effectiveResources: {
79
+ policy: ConsultResourcePolicy;
80
+ projectResources: boolean;
81
+ contextFiles: boolean;
82
+ skills: boolean;
83
+ promptTemplates: boolean;
84
+ };
85
+ resourceDowngradeReason?: string;
86
+ extensions: "disabled";
87
+ sessionPersistence: "disabled";
88
+ retainedAgent: false;
89
+ };
90
+ child?: Record<string, unknown>;
91
+ progress?: ConsultProgress;
92
+ cancelled?: boolean;
93
+ isError?: boolean;
94
+ truncated?: boolean;
95
+ }
package/src/consult.ts CHANGED
@@ -1,13 +1,7 @@
1
1
  import * as path from "node:path";
2
2
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
3
- import { StringEnum, type Usage } from "@earendil-works/pi-ai";
4
- import {
5
- CONFIG_DIR_NAME,
6
- type ExtensionAPI,
7
- type ExtensionContext,
8
- type ToolDefinition,
9
- } from "@earendil-works/pi-coding-agent";
10
- import { type Static, Type } from "typebox";
3
+ import type { Usage } from "@earendil-works/pi-ai";
4
+ import { CONFIG_DIR_NAME, type ExtensionContext } from "@earendil-works/pi-coding-agent";
11
5
  import { DEFAULT_AGENT_CATALOG_MAX_ITEMS } from "./agents/catalog.js";
12
6
  import { type AgentDiscoveryResult, discoverAgents } from "./agents/discovery.js";
13
7
  import {
@@ -16,11 +10,16 @@ import {
16
10
  type ConsultResourcePolicy,
17
11
  isThinkingLevel,
18
12
  type SubagentSettings,
19
- THINKING_LEVELS,
13
+ type THINKING_LEVELS,
20
14
  } from "./agents/types.js";
21
15
  import { resolveConsultTools } from "./consult-policy.js";
22
- import { renderConsultCall, renderConsultResult } from "./consult-render.js";
23
16
  import { resolveConsultResourceLaunchPolicy } from "./consult-resources.js";
17
+ import type {
18
+ ConsultDetails,
19
+ ConsultProgress,
20
+ ConsultProgressActivity,
21
+ SubagentConsultParams,
22
+ } from "./consult-tool.js";
24
23
  import {
25
24
  assertConsultationTargetAllowed,
26
25
  type ResolvedSubagentTarget,
@@ -50,33 +49,13 @@ import {
50
49
  } from "./settings/inspection.js";
51
50
  import { resolveSubagentThinkingLevel } from "./settings.js";
52
51
 
53
- const ConsultScopeSchema = StringEnum(["user", "project", "both"] as const, {
54
- default: "user",
55
- description: "Agent definition scope. Project scopes require a trusted project.",
56
- });
57
- const ConsultThinkingSchema = StringEnum(THINKING_LEVELS);
58
-
59
- export const SubagentConsultParams = Type.Object(
60
- {
61
- agent: Type.String({ minLength: 1 }),
62
- task: Type.String({ minLength: 1, maxLength: DEFAULT_MAX_CONTEXT_BYTES }),
63
- agentScope: Type.Optional(ConsultScopeSchema),
64
- confirmProjectAgents: Type.Optional(Type.Boolean({ default: true })),
65
- cwd: Type.Optional(Type.String({ minLength: 1 })),
66
- timeoutMs: Type.Optional(
67
- Type.Number({
68
- minimum: 1,
69
- maximum: MAX_SUBAGENT_TIMEOUT_MS,
70
- description:
71
- "Work deadline selected for the consultation difficulty. On expiry, Pi aborts the work and makes one separately bounded summary attempt.",
72
- }),
73
- ),
74
- thinkingLevel: Type.Optional(ConsultThinkingSchema),
75
- },
76
- { additionalProperties: false },
77
- );
78
-
79
- export type SubagentConsultParams = Static<typeof SubagentConsultParams>;
52
+ export { registerSubagentConsult } from "./consult-registration.js";
53
+ export type {
54
+ ConsultDetails,
55
+ ConsultProgress,
56
+ ConsultProgressActivity,
57
+ } from "./consult-tool.js";
58
+ export { SubagentConsultParams } from "./consult-tool.js";
80
59
 
81
60
  export interface ConsultChildRequest {
82
61
  agent: AgentConfig;
@@ -99,68 +78,6 @@ export interface RegisterSubagentConsultOptions {
99
78
  resolveResourceLaunchPolicy?: typeof resolveConsultResourceLaunchPolicy;
100
79
  }
101
80
 
102
- export interface ConsultProgressActivity {
103
- type: "text" | "toolCall";
104
- text?: string;
105
- name?: "read" | "grep" | "find" | "ls";
106
- args?: Record<string, string | number | boolean>;
107
- }
108
-
109
- export interface ConsultProgress {
110
- phase: "starting" | "running";
111
- recentActivity: ConsultProgressActivity[];
112
- recentActivityTotal: number;
113
- actualProvider?: string;
114
- actualModel?: string;
115
- usage: {
116
- input: number;
117
- output: number;
118
- cacheRead: number;
119
- cacheWrite: number;
120
- cost: number;
121
- contextTokens: number;
122
- turns: number;
123
- };
124
- }
125
-
126
- export interface ConsultDetails {
127
- agent: string;
128
- agentSource: string;
129
- agentScope: AgentScope;
130
- cwd: string;
131
- model?: string;
132
- thinkingLevel?: string;
133
- timeoutMs: number;
134
- policy: {
135
- requestedTools: string[] | null;
136
- effectiveTools: string[];
137
- cwdBoundary: "current-workspace" | "external";
138
- targetTrust: {
139
- kind: string;
140
- projectTrusted: boolean;
141
- sourcePath?: string;
142
- warning?: string;
143
- };
144
- requestedResources: ConsultResourcePolicy;
145
- effectiveResources: {
146
- policy: ConsultResourcePolicy;
147
- projectResources: boolean;
148
- contextFiles: boolean;
149
- skills: boolean;
150
- promptTemplates: boolean;
151
- };
152
- resourceDowngradeReason?: string;
153
- extensions: "disabled";
154
- sessionPersistence: "disabled";
155
- retainedAgent: false;
156
- };
157
- child?: Record<string, unknown>;
158
- progress?: ConsultProgress;
159
- cancelled?: boolean;
160
- isError?: boolean;
161
- truncated?: boolean;
162
- }
163
-
164
81
  const READ_ONLY_INSTRUCTION = [
165
82
  "This is a read-only consultation.",
166
83
  "Use only the tools made available by the executor to inspect and reason about existing content.",
@@ -170,88 +87,29 @@ const READ_ONLY_INSTRUCTION = [
170
87
 
171
88
  const MAX_UNKNOWN_AGENT_NAME_BYTES = 128;
172
89
 
173
- export function registerSubagentConsult(
174
- pi: ExtensionAPI,
90
+ export async function executeSubagentConsult(
91
+ params: SubagentConsultParams,
92
+ signal: AbortSignal,
93
+ onUpdate: ((partial: AgentToolResult<ConsultDetails>) => void) | undefined,
94
+ ctx: ExtensionContext,
175
95
  options: RegisterSubagentConsultOptions,
176
- ): (catalog: string) => void {
177
- let generation = 0;
178
- const active = new Set<AbortController>();
179
- const activeWork = new Set<Promise<unknown>>();
180
- const cancelActive = (reason: string) => {
181
- generation++;
182
- for (const controller of active) {
183
- controller.abort(new DOMException(reason, "AbortError"));
184
- }
185
- active.clear();
186
- };
187
- const cancelAndWaitForWork = async (reason: string) => {
188
- cancelActive(reason);
189
- await Promise.allSettled([...activeWork]);
190
- };
191
- pi.on("session_start", () => cancelAndWaitForWork("Subagent consultation session replaced"));
192
- pi.on("session_shutdown", () => cancelAndWaitForWork("Subagent consultation session shut down"));
193
-
194
- const baseDescription = () =>
195
- `Run one ephemeral subagent synchronously under enforced read-only tool and resource policies and return its answer. The child can use only the effective subset of Pi's built-in read, grep, find, and ls tools. Shell commands, file writes, extension tools, detached lifecycle operations, and persistent agent state are disabled. Working-directory target policy: ${options.getSettings()?.cwdPolicy?.consultation ?? DEFAULT_CONSULTATION_CWD_POLICY}; configured trusted-target resources: ${options.getSettings()?.consult?.resources ?? DEFAULT_CONSULT_RESOURCE_POLICY}; allowed targets without effective trust inherit no target/project resources. This is not a filesystem sandbox.`;
196
- const definition: ToolDefinition<typeof SubagentConsultParams, ConsultDetails> = {
197
- name: "subagent_consult",
198
- label: "Consult Read-only Subagent",
199
- description: baseDescription(),
200
- promptSnippet: "Consult one constrained read-only subagent and wait for its answer",
201
- promptGuidelines: [
202
- "Use subagent_consult for bounded reconnaissance, planning, or review whose result is required in the current turn.",
203
- "Set subagent_consult timeoutMs to the shortest realistic work deadline for the task difficulty; split oversized consultations instead of extending the deadline merely to compensate for broad scope.",
204
- "Implementation-shaped tasks remain read-only and can return only analysis or instructions.",
205
- ],
206
- parameters: SubagentConsultParams,
207
- async execute(_toolCallId, params, signal, onUpdate, ctx) {
208
- const operation = validateConsultParams(params);
209
- assertSubagentDepthAllowed();
210
- if (signal?.aborted) throw abortError("Subagent consultation was aborted before start");
211
- const ownerGeneration = generation;
212
- const ownedController = new AbortController();
213
- active.add(ownedController);
214
- const combined = combineAbortSignals(signal, ownedController.signal);
215
- try {
216
- return await executeConsult(
217
- operation,
218
- ctx,
219
- combined.signal,
220
- options,
221
- (partial) => {
222
- if (ownerGeneration !== generation || combined.signal.aborted) return;
223
- onUpdate?.(partial);
224
- },
225
- () => ownerGeneration === generation,
226
- (work) => {
227
- activeWork.add(work);
228
- void work.then(
229
- () => activeWork.delete(work),
230
- () => activeWork.delete(work),
231
- );
232
- },
233
- );
234
- } finally {
235
- combined.dispose();
236
- active.delete(ownedController);
237
- }
238
- },
239
- renderCall(args, theme) {
240
- return renderConsultCall(args, theme);
241
- },
242
- renderResult(result, renderOptions, theme, context) {
243
- return renderConsultResult(result, renderOptions, theme, context);
96
+ isCurrent: () => boolean = () => true,
97
+ ): Promise<AgentToolResult<ConsultDetails>> {
98
+ const operation = validateConsultParams(params);
99
+ assertSubagentDepthAllowed();
100
+ if (signal.aborted) throw abortError("Subagent consultation was aborted before start");
101
+ return executeConsult(
102
+ operation,
103
+ ctx,
104
+ signal,
105
+ options,
106
+ (partial) => {
107
+ if (signal.aborted || !isCurrent()) return;
108
+ onUpdate?.(partial);
244
109
  },
245
- };
246
- pi.registerTool<typeof SubagentConsultParams, ConsultDetails>(definition);
247
- pi.on("tool_result", (event) => {
248
- if (event.toolName !== "subagent_consult") return;
249
- if ((event.details as ConsultDetails | undefined)?.isError) return { isError: true };
250
- });
251
- return (catalog: string) => {
252
- definition.description = catalog ? `${baseDescription()}\n\n${catalog}` : baseDescription();
253
- pi.registerTool<typeof SubagentConsultParams, ConsultDetails>(definition);
254
- };
110
+ isCurrent,
111
+ () => undefined,
112
+ );
255
113
  }
256
114
 
257
115
  function formatAvailableConsultAgents(discovery: AgentDiscoveryResult): string {
@@ -699,31 +557,6 @@ function abortError(message: string): Error {
699
557
  return error;
700
558
  }
701
559
 
702
- function combineAbortSignals(
703
- external: AbortSignal | undefined,
704
- owned: AbortSignal,
705
- ): { signal: AbortSignal; dispose(): void } {
706
- const controller = new AbortController();
707
- const signals = [external, owned].filter((value): value is AbortSignal => value !== undefined);
708
- const abort = (signal: AbortSignal) => {
709
- if (!controller.signal.aborted) controller.abort(signal.reason);
710
- };
711
- const listeners = signals.map((signal) => {
712
- const listener = () => abort(signal);
713
- if (signal.aborted) abort(signal);
714
- else signal.addEventListener("abort", listener, { once: true });
715
- return { signal, listener };
716
- });
717
- return {
718
- signal: controller.signal,
719
- dispose() {
720
- for (const { signal, listener } of listeners) {
721
- signal.removeEventListener("abort", listener);
722
- }
723
- },
724
- };
725
- }
726
-
727
560
  function requiredString(value: unknown, name: string): string {
728
561
  if (typeof value !== "string" || !value.trim()) {
729
562
  throw new Error(`subagent_consult requires ${name}`);
@@ -1,15 +1,10 @@
1
1
  import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
2
- import { discoverAgents } from "./agents/discovery.js";
3
2
  import type { SubagentSettings, SubagentTransportKind } from "./agents/types.js";
4
- import { AutoTransport } from "./auto-transport.js";
5
- import {
6
- type ChildSessionFactory,
7
- InProcessTransport,
8
- type ParentRuntimeSnapshot,
9
- } from "./in-process-transport.js";
10
- import { RpcTransport } from "./rpc-transport.js";
11
- import { SubprocessTransport } from "./subprocess-transport.js";
3
+ import { cachedModuleLoader, throwIfAborted } from "./cached-module-loader.js";
4
+ import type { ChildSessionFactory, ParentRuntimeSnapshot } from "./in-process-transport.js";
5
+ import type { ManagedAgent, TurnOutcome } from "./registry.js";
12
6
  import type { SubagentTransport } from "./transport.js";
7
+ import type { TransportProgressCallback } from "./transport-types.js";
13
8
 
14
9
  export interface CreateStatefulTransportOptions {
15
10
  kind: SubagentTransportKind;
@@ -17,14 +12,102 @@ export interface CreateStatefulTransportOptions {
17
12
  getParentRuntime(): ParentRuntimeSnapshot;
18
13
  getSettings(): SubagentSettings | undefined;
19
14
  createInProcessSession?: ChildSessionFactory;
15
+ loadTransport?: () => Promise<SubagentTransport>;
20
16
  }
21
17
 
22
18
  export function createStatefulTransport(
23
19
  options: CreateStatefulTransportOptions,
24
20
  ): SubagentTransport {
25
- const subprocess = () => new SubprocessTransport({ getSettings: options.getSettings });
26
- const inProcess = () =>
27
- new InProcessTransport({
21
+ return new LazyStatefulTransport(
22
+ options.kind,
23
+ cachedModuleLoader(options.loadTransport ?? (() => loadStatefulTransport(options))),
24
+ );
25
+ }
26
+
27
+ class LazyStatefulTransport implements SubagentTransport {
28
+ private loaded: SubagentTransport | undefined;
29
+ private loading: Promise<SubagentTransport> | undefined;
30
+ private closed = false;
31
+ private shutdownPromise: Promise<void> | undefined;
32
+
33
+ constructor(
34
+ readonly kind: SubagentTransportKind,
35
+ private readonly loadImplementation: () => Promise<SubagentTransport>,
36
+ ) {}
37
+
38
+ async runTurn(
39
+ agent: ManagedAgent,
40
+ task: string,
41
+ signal: AbortSignal,
42
+ onProgress?: TransportProgressCallback,
43
+ ): Promise<TurnOutcome> {
44
+ if (this.closed) throw new Error("Subagent transport is shut down");
45
+ throwIfAborted(signal, "Subagent transport loading was cancelled");
46
+ let transport: SubagentTransport;
47
+ try {
48
+ transport = await this.load();
49
+ } catch (error) {
50
+ throwIfAborted(signal, "Subagent transport loading was cancelled");
51
+ throw error;
52
+ }
53
+ throwIfAborted(signal, "Subagent transport loading was cancelled");
54
+ if (this.closed) {
55
+ await this.shutdownLoaded();
56
+ throw new Error("Subagent transport shut down while loading");
57
+ }
58
+ return transport.runTurn(agent, task, signal, onProgress);
59
+ }
60
+
61
+ async release(agent: ManagedAgent): Promise<void> {
62
+ const transport =
63
+ this.loaded ?? (this.loading ? await this.loading.catch(() => undefined) : undefined);
64
+ if (!transport || this.closed) return;
65
+ await transport.release?.(agent);
66
+ }
67
+
68
+ async shutdown(): Promise<void> {
69
+ this.closed = true;
70
+ if (this.loading && !this.loaded) await this.loading.catch(() => undefined);
71
+ await this.shutdownLoaded();
72
+ }
73
+
74
+ private async load(): Promise<SubagentTransport> {
75
+ if (this.loaded) return this.loaded;
76
+ if (!this.loading) {
77
+ this.loading = this.loadImplementation()
78
+ .then((transport) => {
79
+ this.loaded = transport;
80
+ return transport;
81
+ })
82
+ .finally(() => {
83
+ this.loading = undefined;
84
+ });
85
+ }
86
+ return this.loading;
87
+ }
88
+
89
+ private async shutdownLoaded(): Promise<void> {
90
+ if (!this.loaded) return;
91
+ if (!this.shutdownPromise) {
92
+ this.shutdownPromise = Promise.resolve(this.loaded.shutdown?.());
93
+ }
94
+ await this.shutdownPromise;
95
+ }
96
+ }
97
+
98
+ async function loadStatefulTransport(
99
+ options: CreateStatefulTransportOptions,
100
+ ): Promise<SubagentTransport> {
101
+ const subprocess = async () => {
102
+ const { SubprocessTransport } = await import("./subprocess-transport.js");
103
+ return new SubprocessTransport({ getSettings: options.getSettings });
104
+ };
105
+ const inProcess = async () => {
106
+ const [{ discoverAgents }, { InProcessTransport }] = await Promise.all([
107
+ import("./agents/discovery.js"),
108
+ import("./in-process-transport.js"),
109
+ ]);
110
+ return new InProcessTransport({
28
111
  modelRegistry: options.modelRegistry,
29
112
  getParentRuntime: options.getParentRuntime,
30
113
  createSession: options.createInProcessSession,
@@ -33,11 +116,14 @@ export function createStatefulTransport(
33
116
  (candidate) => candidate.name === agent.agent,
34
117
  ),
35
118
  });
36
- const rpc = () =>
37
- new RpcTransport({
119
+ };
120
+ const rpc = async () => {
121
+ const { RpcTransport } = await import("./rpc-transport.js");
122
+ return new RpcTransport({
38
123
  getSettings: options.getSettings,
39
124
  getParentRuntime: options.getParentRuntime,
40
125
  });
126
+ };
41
127
  switch (options.kind) {
42
128
  case "subprocess":
43
129
  return subprocess();
@@ -45,12 +131,14 @@ export function createStatefulTransport(
45
131
  return inProcess();
46
132
  case "rpc":
47
133
  return rpc();
48
- case "auto":
134
+ case "auto": {
135
+ const { AutoTransport } = await import("./auto-transport.js");
49
136
  return new AutoTransport({
50
- subprocess: subprocess(),
51
- inProcess: inProcess(),
52
- rpc: rpc(),
137
+ subprocess: new LazyStatefulTransport("subprocess", cachedModuleLoader(subprocess)),
138
+ inProcess: new LazyStatefulTransport("in-process", cachedModuleLoader(inProcess)),
139
+ rpc: new LazyStatefulTransport("rpc", cachedModuleLoader(rpc)),
53
140
  getSettings: options.getSettings,
54
141
  });
142
+ }
55
143
  }
56
144
  }