@zew1me/pi-subagents 0.0.0-stage → 0.1.0-alpha.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.
- package/README.md +8 -2
- package/dist/ATTRIBUTION.md +320 -0
- package/dist/LICENSE +21 -0
- package/dist/extensions/subagents/auth-bridge.ts +52 -0
- package/dist/extensions/subagents/helpers.ts +251 -0
- package/dist/extensions/subagents/index.ts +727 -0
- package/dist/extensions/subagents/rpc.ts +845 -0
- package/package.json +40 -4
|
@@ -0,0 +1,727 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { mkdir } from "node:fs/promises";
|
|
3
|
+
import { basename, dirname, join } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
import { completeSimple, StringEnum } from "@earendil-works/pi-ai/compat";
|
|
7
|
+
import type { Api, Model } from "@earendil-works/pi-ai/compat";
|
|
8
|
+
import {
|
|
9
|
+
buildSessionContext,
|
|
10
|
+
createAgentSession,
|
|
11
|
+
DefaultResourceLoader,
|
|
12
|
+
getAgentDir,
|
|
13
|
+
SessionManager,
|
|
14
|
+
SettingsManager,
|
|
15
|
+
} from "@earendil-works/pi-coding-agent";
|
|
16
|
+
import type { ExtensionAPI, ExtensionContext, ModelRuntime } from "@earendil-works/pi-coding-agent";
|
|
17
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
18
|
+
import { Type } from "typebox";
|
|
19
|
+
import {
|
|
20
|
+
CONTEXT_MODES,
|
|
21
|
+
THINKING_LEVELS,
|
|
22
|
+
boundContextForModel,
|
|
23
|
+
clampThinkingLevel,
|
|
24
|
+
excludeCurrentDelegationTurn,
|
|
25
|
+
extractTextContent,
|
|
26
|
+
findRequestedModel,
|
|
27
|
+
formatModelCatalog,
|
|
28
|
+
parseClassifierDecision,
|
|
29
|
+
parseModelRequest,
|
|
30
|
+
safeTerminalText,
|
|
31
|
+
truncateMiddle,
|
|
32
|
+
} from "./helpers.ts";
|
|
33
|
+
import type { ThinkingLevel } from "./helpers.ts";
|
|
34
|
+
import { ManagedSubagent } from "./rpc.ts";
|
|
35
|
+
import type { ChildSnapshot } from "./rpc.ts";
|
|
36
|
+
|
|
37
|
+
const MAX_CLASSIFIER_CONTEXT_CHARS = 24_000;
|
|
38
|
+
const MAX_STATUS_TEXT_CHARS = 45_000;
|
|
39
|
+
const MAX_ROOT_CHILDREN = 8;
|
|
40
|
+
const MAX_NESTED_CHILDREN = 2;
|
|
41
|
+
const MAX_RETAINED_CHILDREN = 32;
|
|
42
|
+
const MAX_DEPTH = 3;
|
|
43
|
+
const DEPTH_ENV = "PI_SIMPLE_SUBAGENT_DEPTH";
|
|
44
|
+
const AUTH_PROVIDER_ENV = "PI_SIMPLE_SUBAGENT_AUTH_PROVIDER";
|
|
45
|
+
const AUTH_KEY_ENV = "PI_SIMPLE_SUBAGENT_API_KEY";
|
|
46
|
+
const AUTH_HEADERS_ENV = "PI_SIMPLE_SUBAGENT_AUTH_HEADERS";
|
|
47
|
+
const SELF_EXTENSION_PATH = fileURLToPath(import.meta.url);
|
|
48
|
+
const AUTH_BRIDGE_PATH = join(dirname(SELF_EXTENSION_PATH), "auth-bridge.ts");
|
|
49
|
+
|
|
50
|
+
const SubagentParameters = Type.Object({
|
|
51
|
+
action: StringEnum(["create", "list", "status", "wait", "steer", "follow_up", "interrupt", "stop"] as const, {
|
|
52
|
+
description:
|
|
53
|
+
"create a child; inspect it; explicitly wait for it; steer now; queue follow_up; interrupt its current operation; or stop its process",
|
|
54
|
+
}),
|
|
55
|
+
task: Type.Optional(
|
|
56
|
+
Type.String({
|
|
57
|
+
description: "For create: the complete task. For steer/follow_up: the additional message.",
|
|
58
|
+
}),
|
|
59
|
+
),
|
|
60
|
+
id: Type.Optional(Type.String({ description: "Direct child id for status/control actions" })),
|
|
61
|
+
name: Type.Optional(
|
|
62
|
+
Type.String({ description: "Optional human-readable name when creating a child", maxLength: 120 }),
|
|
63
|
+
),
|
|
64
|
+
model: Type.Optional(
|
|
65
|
+
Type.String({
|
|
66
|
+
description:
|
|
67
|
+
"Optional model request, such as gpt-5.6-luna or openai/gpt-5.6-luna. Preserve a model explicitly requested by the user.",
|
|
68
|
+
}),
|
|
69
|
+
),
|
|
70
|
+
effort: Type.Optional(
|
|
71
|
+
StringEnum(THINKING_LEVELS, {
|
|
72
|
+
description: "Optional reasoning effort. Preserve an effort explicitly requested by the user, for example high.",
|
|
73
|
+
}),
|
|
74
|
+
),
|
|
75
|
+
contextMode: Type.Optional(
|
|
76
|
+
StringEnum(CONTEXT_MODES, {
|
|
77
|
+
description:
|
|
78
|
+
"For create: task_compacted (default) seeds task-specific parent conversation context; none skips parent conversation and compaction, starting with only the task. This does not isolate files, credentials, project instructions, settings, skills, or extensions.",
|
|
79
|
+
}),
|
|
80
|
+
),
|
|
81
|
+
timeoutMs: Type.Optional(
|
|
82
|
+
Type.Integer({
|
|
83
|
+
description:
|
|
84
|
+
"For wait only: maximum time in milliseconds without stopping the child. Use 120000 for 120 seconds (default 120000, max 600000).",
|
|
85
|
+
minimum: 1,
|
|
86
|
+
maximum: 600_000,
|
|
87
|
+
}),
|
|
88
|
+
),
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
type PiModel = NonNullable<ExtensionContext["model"]>;
|
|
92
|
+
|
|
93
|
+
type Selection = {
|
|
94
|
+
model: PiModel;
|
|
95
|
+
effort: ThinkingLevel;
|
|
96
|
+
source: "explicit" | "classified" | "fallback";
|
|
97
|
+
rationale?: string;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
function currentDepth(): number {
|
|
101
|
+
const value = Number(process.env[DEPTH_ENV] ?? "0");
|
|
102
|
+
return Number.isInteger(value) && value >= 0 ? value : 0;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function throwIfAborted(signal: AbortSignal | undefined): void {
|
|
106
|
+
signal?.throwIfAborted();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function modelRuntimeFromContext(ctx: ExtensionContext): ModelRuntime {
|
|
110
|
+
// Pi exposes a compatibility ModelRegistry facade to extensions while
|
|
111
|
+
// createAgentSession accepts its underlying canonical ModelRuntime.
|
|
112
|
+
const runtime = Reflect.get(ctx.modelRegistry, "runtime") as unknown;
|
|
113
|
+
if (!runtime) throw new Error("Pi did not expose the active model runtime.");
|
|
114
|
+
return runtime as ModelRuntime;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function textFromAssistant(response: { content: unknown }): string {
|
|
118
|
+
return extractTextContent(response.content).trim();
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function parentThinking(pi: ExtensionAPI): ThinkingLevel {
|
|
122
|
+
const value = pi.getThinkingLevel();
|
|
123
|
+
return THINKING_LEVELS.includes(value) ? value : "off";
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function utilityCompletion(
|
|
127
|
+
pi: ExtensionAPI,
|
|
128
|
+
ctx: ExtensionContext,
|
|
129
|
+
prompt: string,
|
|
130
|
+
maxTokens: number,
|
|
131
|
+
signal: AbortSignal | undefined,
|
|
132
|
+
): Promise<string> {
|
|
133
|
+
throwIfAborted(signal);
|
|
134
|
+
if (!ctx.model) throw new Error("The parent session has no selected model.");
|
|
135
|
+
const parentModel = ctx.model as unknown as Model<Api>;
|
|
136
|
+
const auth = await ctx.modelRegistry.getApiKeyAndHeaders(parentModel);
|
|
137
|
+
throwIfAborted(signal);
|
|
138
|
+
if (!auth.ok) throw new Error(auth.error);
|
|
139
|
+
const effort = clampThinkingLevel(parentThinking(pi), parentModel);
|
|
140
|
+
const response = await completeSimple(
|
|
141
|
+
parentModel,
|
|
142
|
+
{
|
|
143
|
+
messages: [
|
|
144
|
+
{
|
|
145
|
+
role: "user",
|
|
146
|
+
content: [{ type: "text", text: prompt }],
|
|
147
|
+
timestamp: Date.now(),
|
|
148
|
+
},
|
|
149
|
+
],
|
|
150
|
+
},
|
|
151
|
+
{
|
|
152
|
+
maxTokens,
|
|
153
|
+
...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
|
|
154
|
+
...(auth.headers ? { headers: auth.headers } : {}),
|
|
155
|
+
...(auth.env ? { env: auth.env } : {}),
|
|
156
|
+
...(signal ? { signal } : {}),
|
|
157
|
+
...(effort === "off" ? {} : { reasoning: effort }),
|
|
158
|
+
},
|
|
159
|
+
);
|
|
160
|
+
throwIfAborted(signal);
|
|
161
|
+
const text = textFromAssistant(response);
|
|
162
|
+
if (!text) throw new Error("Utility model returned an empty response.");
|
|
163
|
+
return text;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function compactContextForTask(
|
|
167
|
+
pi: ExtensionAPI,
|
|
168
|
+
ctx: ExtensionContext,
|
|
169
|
+
task: string,
|
|
170
|
+
signal: AbortSignal | undefined,
|
|
171
|
+
): Promise<{ summary: string; fallback: boolean }> {
|
|
172
|
+
throwIfAborted(signal);
|
|
173
|
+
const built = buildSessionContext(ctx.sessionManager.getEntries(), ctx.sessionManager.getLeafId());
|
|
174
|
+
// The current turn contains the user's orchestration request and this
|
|
175
|
+
// subagent tool call. The delegated task is supplied separately; including
|
|
176
|
+
// this turn in the seed can make a child recursively repeat orchestration.
|
|
177
|
+
const parentMessages = excludeCurrentDelegationTurn(built.messages);
|
|
178
|
+
if (parentMessages.length === 0) return { summary: "", fallback: false };
|
|
179
|
+
|
|
180
|
+
const sessionManager = SessionManager.inMemory(ctx.cwd);
|
|
181
|
+
for (const message of parentMessages) {
|
|
182
|
+
if (message.role === "branchSummary" || message.role === "compactionSummary") {
|
|
183
|
+
sessionManager.appendCustomMessageEntry("subagent-context-summary", message.summary, false);
|
|
184
|
+
} else {
|
|
185
|
+
sessionManager.appendMessage(message);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
// Pi compaction retains a recent boundary. A synthetic final boundary lets the
|
|
189
|
+
// compactor summarize all real parent messages even when the parent is small.
|
|
190
|
+
sessionManager.appendMessage({
|
|
191
|
+
role: "user",
|
|
192
|
+
content: [{ type: "text", text: "Compaction boundary for delegated work." }],
|
|
193
|
+
timestamp: Date.now(),
|
|
194
|
+
});
|
|
195
|
+
const settingsManager = SettingsManager.inMemory({
|
|
196
|
+
compaction: { enabled: true, reserveTokens: 8_192, keepRecentTokens: 1 },
|
|
197
|
+
});
|
|
198
|
+
const resourceLoader = new DefaultResourceLoader({
|
|
199
|
+
cwd: ctx.cwd,
|
|
200
|
+
agentDir: getAgentDir(),
|
|
201
|
+
settingsManager,
|
|
202
|
+
noExtensions: true,
|
|
203
|
+
noSkills: true,
|
|
204
|
+
noPromptTemplates: true,
|
|
205
|
+
noThemes: true,
|
|
206
|
+
noContextFiles: true,
|
|
207
|
+
});
|
|
208
|
+
let compactSession: Awaited<ReturnType<typeof createAgentSession>>["session"] | undefined;
|
|
209
|
+
let abortCompaction: (() => void) | undefined;
|
|
210
|
+
try {
|
|
211
|
+
await resourceLoader.reload();
|
|
212
|
+
throwIfAborted(signal);
|
|
213
|
+
const created = await createAgentSession({
|
|
214
|
+
cwd: ctx.cwd,
|
|
215
|
+
agentDir: getAgentDir(),
|
|
216
|
+
...(ctx.model ? { model: ctx.model } : {}),
|
|
217
|
+
thinkingLevel: parentThinking(pi),
|
|
218
|
+
modelRuntime: modelRuntimeFromContext(ctx),
|
|
219
|
+
resourceLoader,
|
|
220
|
+
sessionManager,
|
|
221
|
+
settingsManager,
|
|
222
|
+
noTools: "all",
|
|
223
|
+
});
|
|
224
|
+
throwIfAborted(signal);
|
|
225
|
+
compactSession = created.session;
|
|
226
|
+
abortCompaction = () => compactSession?.abortCompaction();
|
|
227
|
+
signal?.addEventListener("abort", abortCompaction, { once: true });
|
|
228
|
+
const result = await compactSession.compact(
|
|
229
|
+
`Create context specifically for this delegated task:\n\n${task}\n\nPreserve relevant user requirements, constraints, decisions and rationale, exact file paths and symbols, commands and results, repository state, unresolved questions, and failures. Omit unrelated discussion. Do not solve the task or add a persona.`,
|
|
230
|
+
);
|
|
231
|
+
throwIfAborted(signal);
|
|
232
|
+
return { summary: result.summary, fallback: false };
|
|
233
|
+
} catch (error) {
|
|
234
|
+
if (signal?.aborted) throw error;
|
|
235
|
+
// Context seeding is an optimization, not a launch dependency. Fail open
|
|
236
|
+
// with a truly fresh child rather than forwarding an unreviewed raw transcript.
|
|
237
|
+
return { summary: "", fallback: true };
|
|
238
|
+
} finally {
|
|
239
|
+
if (abortCompaction) signal?.removeEventListener("abort", abortCompaction);
|
|
240
|
+
compactSession?.dispose();
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function resolveRequestedModel(
|
|
245
|
+
ctx: ExtensionContext,
|
|
246
|
+
request: string,
|
|
247
|
+
): { model?: PiModel; effort?: ThinkingLevel; error?: string } {
|
|
248
|
+
const available = ctx.modelRegistry.getAvailable();
|
|
249
|
+
const parsed = parseModelRequest(request);
|
|
250
|
+
const result = findRequestedModel(parsed.reference, available, ctx.model?.provider);
|
|
251
|
+
if (!result.model) return { error: result.error ?? `Model '${request}' was not found.` };
|
|
252
|
+
const resolvedModel = result.model as unknown as Model<Api>;
|
|
253
|
+
if (!ctx.modelRegistry.hasConfiguredAuth(resolvedModel)) {
|
|
254
|
+
return { error: `Model '${resolvedModel.provider}/${resolvedModel.id}' is not authenticated.` };
|
|
255
|
+
}
|
|
256
|
+
return {
|
|
257
|
+
model: resolvedModel,
|
|
258
|
+
...(parsed.effort ? { effort: parsed.effort } : {}),
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function parentFallback(
|
|
263
|
+
pi: ExtensionAPI,
|
|
264
|
+
ctx: ExtensionContext,
|
|
265
|
+
explicitRequestedModel?: PiModel,
|
|
266
|
+
explicitRequestedEffort?: ThinkingLevel,
|
|
267
|
+
): Selection {
|
|
268
|
+
const fallbackModel = explicitRequestedModel ?? ctx.model;
|
|
269
|
+
if (!fallbackModel) throw new Error("Cannot create a subagent because the parent has no selected model.");
|
|
270
|
+
|
|
271
|
+
const fallbackEffort = clampThinkingLevel(explicitRequestedEffort ?? parentThinking(pi), fallbackModel);
|
|
272
|
+
|
|
273
|
+
return {
|
|
274
|
+
model: fallbackModel,
|
|
275
|
+
effort: fallbackEffort,
|
|
276
|
+
source: "fallback",
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// Model routing deliberately keeps explicit, classified, and fallback paths together.
|
|
281
|
+
// eslint-disable-next-line sonarjs/cognitive-complexity
|
|
282
|
+
async function selectModel(
|
|
283
|
+
pi: ExtensionAPI,
|
|
284
|
+
ctx: ExtensionContext,
|
|
285
|
+
task: string,
|
|
286
|
+
contextSummary: string,
|
|
287
|
+
explicitModel?: string,
|
|
288
|
+
explicitEffort?: ThinkingLevel,
|
|
289
|
+
signal?: AbortSignal,
|
|
290
|
+
): Promise<Selection> {
|
|
291
|
+
throwIfAborted(signal);
|
|
292
|
+
let requestedModel: PiModel | undefined;
|
|
293
|
+
let suffixEffort: ThinkingLevel | undefined;
|
|
294
|
+
if (explicitModel) {
|
|
295
|
+
const resolved = resolveRequestedModel(ctx, explicitModel);
|
|
296
|
+
if (!resolved.model) throw new Error(resolved.error);
|
|
297
|
+
requestedModel = resolved.model;
|
|
298
|
+
suffixEffort = resolved.effort;
|
|
299
|
+
}
|
|
300
|
+
const requestedEffort = explicitEffort ?? suffixEffort;
|
|
301
|
+
if (requestedModel && requestedEffort) {
|
|
302
|
+
return {
|
|
303
|
+
model: requestedModel,
|
|
304
|
+
effort: clampThinkingLevel(requestedEffort, requestedModel),
|
|
305
|
+
source: "explicit",
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// Classification is optional. A newer pi runtime can expose a registry
|
|
310
|
+
// facade before its runtime is initialized; do not make delegation fail on
|
|
311
|
+
// this best-effort lookup.
|
|
312
|
+
let available: ReturnType<typeof ctx.modelRegistry.getAvailable>;
|
|
313
|
+
try {
|
|
314
|
+
available = ctx.modelRegistry.getAvailable();
|
|
315
|
+
} catch {
|
|
316
|
+
return parentFallback(pi, ctx, requestedModel, requestedEffort);
|
|
317
|
+
}
|
|
318
|
+
if (available.length === 0) return parentFallback(pi, ctx, requestedModel, requestedEffort);
|
|
319
|
+
const catalog = formatModelCatalog(available);
|
|
320
|
+
const fixedChoice = [
|
|
321
|
+
requestedModel ? `model=${requestedModel.provider}/${requestedModel.id}` : undefined,
|
|
322
|
+
requestedEffort ? `effort=${requestedEffort}` : undefined,
|
|
323
|
+
]
|
|
324
|
+
.filter(Boolean)
|
|
325
|
+
.join(", ");
|
|
326
|
+
const classifierPrompt = `Classify the difficulty and complexity of a delegated coding-agent task, then choose the best authenticated model and reasoning effort from the exact catalog below. Balance capability, reliability, context needs, latency, and cost. Hard architecture, debugging, security, or broad implementation work generally deserves a stronger model and higher effort; simple lookups and mechanical edits do not. ${fixedChoice ? `The user fixed ${fixedChoice}; preserve those values and classify only what is missing. ` : ""}Return one JSON object only: {"model":"provider/id","effort":"off|minimal|low|medium|high|xhigh|max","rationale":"one short sentence"}.
|
|
327
|
+
|
|
328
|
+
Task:
|
|
329
|
+
${task}
|
|
330
|
+
|
|
331
|
+
Task-targeted context the child will receive:
|
|
332
|
+
${truncateMiddle(contextSummary, MAX_CLASSIFIER_CONTEXT_CHARS)}
|
|
333
|
+
|
|
334
|
+
Available authenticated models:
|
|
335
|
+
${catalog}`;
|
|
336
|
+
try {
|
|
337
|
+
const raw = await utilityCompletion(pi, ctx, classifierPrompt, 1_024, signal);
|
|
338
|
+
throwIfAborted(signal);
|
|
339
|
+
const decision = parseClassifierDecision(raw);
|
|
340
|
+
if (!decision) throw new Error("Classifier did not return valid JSON.");
|
|
341
|
+
let model = requestedModel;
|
|
342
|
+
if (!model) {
|
|
343
|
+
const classified = resolveRequestedModel(ctx, decision.model);
|
|
344
|
+
if (!classified.model) throw new Error(classified.error);
|
|
345
|
+
model = classified.model;
|
|
346
|
+
}
|
|
347
|
+
const effort = requestedEffort ?? decision.effort;
|
|
348
|
+
return {
|
|
349
|
+
model,
|
|
350
|
+
effort: clampThinkingLevel(effort, model),
|
|
351
|
+
source: "classified",
|
|
352
|
+
...(decision.rationale ? { rationale: decision.rationale } : {}),
|
|
353
|
+
};
|
|
354
|
+
// This catch deliberately also covers resolving the classifier's chosen
|
|
355
|
+
// model: that resolution reads the registry again, which can throw on an
|
|
356
|
+
// uninitialized facade, and a hallucinated model name is a classifier
|
|
357
|
+
// failure. The caller's own explicit model resolves earlier and still
|
|
358
|
+
// propagates. Do not narrow this to the completion call.
|
|
359
|
+
} catch (error) {
|
|
360
|
+
if (signal?.aborted) throw error;
|
|
361
|
+
const fallback = parentFallback(pi, ctx, requestedModel, requestedEffort);
|
|
362
|
+
return {
|
|
363
|
+
model: fallback.model,
|
|
364
|
+
effort: fallback.effort,
|
|
365
|
+
source: "fallback",
|
|
366
|
+
rationale: `Classification failed; used the ${requestedModel ? "requested" : "parent"} model and the ${requestedEffort ? "requested" : "parent"} effort (${error instanceof Error ? error.message : String(error)}).`,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function resolvePiInvocation(args: string[]): { command: string; args: string[] } {
|
|
372
|
+
const currentScript = process.argv[1];
|
|
373
|
+
if (currentScript && !currentScript.startsWith("/$bunfs/root/") && existsSync(currentScript)) {
|
|
374
|
+
return { command: process.execPath, args: [currentScript, ...args] };
|
|
375
|
+
}
|
|
376
|
+
const executable = basename(process.execPath).toLowerCase();
|
|
377
|
+
if (!/^(node|bun)(\.exe)?$/.test(executable)) return { command: process.execPath, args };
|
|
378
|
+
return { command: "pi", args };
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function stringProviderHeaders(headers: Record<string, string | null> | undefined): Record<string, string> | undefined {
|
|
382
|
+
if (!headers) return undefined;
|
|
383
|
+
const strings = Object.fromEntries(
|
|
384
|
+
Object.entries(headers).filter((entry): entry is [string, string] => entry[1] !== null),
|
|
385
|
+
);
|
|
386
|
+
return Object.keys(strings).length > 0 ? strings : undefined;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function childEnvironment(
|
|
390
|
+
depth: number,
|
|
391
|
+
provider: string,
|
|
392
|
+
auth: { apiKey?: string; headers?: Record<string, string> },
|
|
393
|
+
): NodeJS.ProcessEnv {
|
|
394
|
+
const env = Object.fromEntries(
|
|
395
|
+
Object.entries(process.env).filter(
|
|
396
|
+
([key]) =>
|
|
397
|
+
!key.startsWith("PI_SUBAGENT_") &&
|
|
398
|
+
!key.startsWith("PI_INTERCOM_") &&
|
|
399
|
+
key !== AUTH_PROVIDER_ENV &&
|
|
400
|
+
key !== AUTH_KEY_ENV &&
|
|
401
|
+
key !== AUTH_HEADERS_ENV,
|
|
402
|
+
),
|
|
403
|
+
);
|
|
404
|
+
env[DEPTH_ENV] = String(depth);
|
|
405
|
+
// Bridge the API key together with the resolved request headers: registering a
|
|
406
|
+
// provider replaces its whole stored request config, so an API key alone would
|
|
407
|
+
// drop configured (or `authHeader`-derived) headers in the child.
|
|
408
|
+
if (auth.apiKey || auth.headers) {
|
|
409
|
+
env[AUTH_PROVIDER_ENV] = provider;
|
|
410
|
+
if (auth.apiKey) env[AUTH_KEY_ENV] = auth.apiKey;
|
|
411
|
+
if (auth.headers) env[AUTH_HEADERS_ENV] = JSON.stringify(auth.headers);
|
|
412
|
+
}
|
|
413
|
+
return env;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function shortId(): string {
|
|
417
|
+
return randomUUID().replaceAll("-", "").slice(0, 10);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function childName(requested: string | undefined, id: string): string {
|
|
421
|
+
const trimmed = requested?.trim();
|
|
422
|
+
return trimmed && trimmed.length > 0 ? trimmed : `subagent-${id}`;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function snapshotSummary(
|
|
426
|
+
snapshot: ChildSnapshot,
|
|
427
|
+
): Omit<ChildSnapshot, "transcriptTail" | "stderr"> & { transcriptPreview?: string; stderrPreview?: string } {
|
|
428
|
+
const { transcriptTail, stderr, ...rest } = snapshot;
|
|
429
|
+
return {
|
|
430
|
+
...rest,
|
|
431
|
+
...(transcriptTail.trim() ? { transcriptPreview: truncateMiddle(transcriptTail.trim(), 1_000) } : {}),
|
|
432
|
+
...(stderr ? { stderrPreview: truncateMiddle(stderr, 500) } : {}),
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
function formatTokenCount(value: number): string {
|
|
437
|
+
if (value < 1_000) return String(value);
|
|
438
|
+
if (value < 1_000_000) return `${(value / 1_000).toFixed(value < 10_000 ? 1 : 0)}k`;
|
|
439
|
+
return `${(value / 1_000_000).toFixed(1)}m`;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// Status formatting conditionally includes every independently optional field.
|
|
443
|
+
// eslint-disable-next-line sonarjs/cognitive-complexity
|
|
444
|
+
function formatSnapshot(snapshot: ChildSnapshot): string {
|
|
445
|
+
const age = Math.max(0, Math.round((Date.now() - snapshot.startedAt) / 1000));
|
|
446
|
+
const lines = [
|
|
447
|
+
`Subagent ${snapshot.id} (${truncateMiddle(snapshot.name, 200)})`,
|
|
448
|
+
`state=${snapshot.state} model=${snapshot.model} effort=${snapshot.effort} age=${String(age)}s turns=${String(snapshot.turns)} tools=${String(snapshot.toolCalls)} queued=${String(snapshot.pendingMessages)}`,
|
|
449
|
+
`contextMode=${snapshot.contextMode}`,
|
|
450
|
+
`selection=${snapshot.classification}${snapshot.classificationRationale ? ` — ${snapshot.classificationRationale}` : ""}`,
|
|
451
|
+
`task: ${truncateMiddle(snapshot.task, 4_000)}`,
|
|
452
|
+
];
|
|
453
|
+
if (snapshot.currentTool) {
|
|
454
|
+
lines.push(`current tool: ${snapshot.currentTool.name} ${snapshot.currentTool.argsPreview}`);
|
|
455
|
+
}
|
|
456
|
+
if (snapshot.stats) {
|
|
457
|
+
const context = snapshot.stats.contextUsage
|
|
458
|
+
? ` context=${snapshot.stats.contextUsage.tokens === null ? "?" : formatTokenCount(snapshot.stats.contextUsage.tokens)}/${formatTokenCount(snapshot.stats.contextUsage.contextWindow)} (${snapshot.stats.contextUsage.percent === null ? "?" : `${snapshot.stats.contextUsage.percent.toFixed(1)}%`})`
|
|
459
|
+
: "";
|
|
460
|
+
lines.push(
|
|
461
|
+
`usage: tokens=${formatTokenCount(snapshot.stats.tokens.total)} input=${formatTokenCount(snapshot.stats.tokens.input)} output=${formatTokenCount(snapshot.stats.tokens.output)} cost=$${snapshot.stats.cost.toFixed(4)}${context} compactions=${String(snapshot.compactions)}`,
|
|
462
|
+
);
|
|
463
|
+
} else if (snapshot.compactions > 0) {
|
|
464
|
+
lines.push(`compactions=${String(snapshot.compactions)}`);
|
|
465
|
+
}
|
|
466
|
+
if (snapshot.sessionFile) lines.push(`session: ${snapshot.sessionFile}`);
|
|
467
|
+
if (snapshot.error) lines.push(`error: ${snapshot.error}`);
|
|
468
|
+
if (snapshot.stderr) lines.push(`stderr:\n${truncateMiddle(snapshot.stderr, 4_000)}`);
|
|
469
|
+
if (snapshot.transcriptTail.trim())
|
|
470
|
+
lines.push(`transcript tail:\n${truncateMiddle(snapshot.transcriptTail.trim(), MAX_STATUS_TEXT_CHARS)}`);
|
|
471
|
+
else lines.push("transcript tail: (no output yet)");
|
|
472
|
+
return lines.join("\n");
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
export default function subagentsExtension(pi: ExtensionAPI) {
|
|
476
|
+
const children = new Map<string, ManagedSubagent>();
|
|
477
|
+
let pendingCreates = 0;
|
|
478
|
+
let shuttingDown = false;
|
|
479
|
+
|
|
480
|
+
const assertCreationActive = () => {
|
|
481
|
+
if (shuttingDown) throw new Error("Session shutdown interrupted subagent creation.");
|
|
482
|
+
};
|
|
483
|
+
|
|
484
|
+
const pruneChildren = () => {
|
|
485
|
+
if (children.size <= MAX_RETAINED_CHILDREN) return;
|
|
486
|
+
const removable = [...children.entries()]
|
|
487
|
+
.filter(([, child]) => !child.isAlive())
|
|
488
|
+
.sort((left, right) => left[1].snapshot().updatedAt - right[1].snapshot().updatedAt);
|
|
489
|
+
for (const [id] of removable) {
|
|
490
|
+
if (children.size <= MAX_RETAINED_CHILDREN) break;
|
|
491
|
+
children.delete(id);
|
|
492
|
+
}
|
|
493
|
+
};
|
|
494
|
+
|
|
495
|
+
pi.registerTool({
|
|
496
|
+
name: "subagent",
|
|
497
|
+
label: "Subagent",
|
|
498
|
+
description:
|
|
499
|
+
"Create and control isolated, asynchronous child Pi sessions. Use action=create whenever the user naturally asks to create a subagent, ask a subagent to do work, or delegate work. Preserve any user-requested model and effort. Creation defaults to contextMode=task_compacted for task-specific parent conversation context; contextMode=none skips parent conversation and compaction, starting with only the supplied task. Neither mode isolates files, credentials, project instructions, settings, skills, or extensions. Creation automatically classifies model/effort when either is omitted and returns immediately with an id. Use status to spy on a direct child's transcript and usage, wait only when the current request needs its result synchronously, steer to interrupt its direction at the next turn boundary, follow_up to queue later work, interrupt to abort the current operation while retaining the session, and stop to terminate it. Each process can see and control only children it created; child results never enter the parent context unless status or wait is explicitly requested.",
|
|
500
|
+
promptSnippet:
|
|
501
|
+
"Create, inspect, wait for, steer, queue messages for, interrupt, or stop isolated asynchronous child Pi sessions",
|
|
502
|
+
promptGuidelines: [
|
|
503
|
+
"Use subagent with action=create when the user asks in natural language to create, ask, launch, or delegate to a subagent; pass through any explicit model and reasoning effort.",
|
|
504
|
+
"For creation without parent conversation, set contextMode=none and supply the complete task. The default task_compacted preserves task-specific context; none skips compaction but does not isolate files, credentials, project instructions, settings, skills, or extensions.",
|
|
505
|
+
"Use subagent status to inspect child work; use subagent wait only when this turn must consume the result. Child completion is intentionally not pushed into the parent conversation.",
|
|
506
|
+
],
|
|
507
|
+
parameters: SubagentParameters,
|
|
508
|
+
|
|
509
|
+
// This is a tagged action dispatcher; splitting it would obscure the shared ownership checks.
|
|
510
|
+
// eslint-disable-next-line sonarjs/cognitive-complexity
|
|
511
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
512
|
+
if (params.action === "create") {
|
|
513
|
+
pruneChildren();
|
|
514
|
+
if (!params.task?.trim()) throw new Error("Creating a subagent requires a non-empty task.");
|
|
515
|
+
assertCreationActive();
|
|
516
|
+
const depth = currentDepth();
|
|
517
|
+
if (depth >= MAX_DEPTH) throw new Error(`Subagent depth limit (${String(MAX_DEPTH)}) reached.`);
|
|
518
|
+
const childLimit = depth === 0 ? MAX_ROOT_CHILDREN : MAX_NESTED_CHILDREN;
|
|
519
|
+
// Count live OS processes, including one still exiting after failure.
|
|
520
|
+
// Reserve a slot before the first await so parallel create tool calls
|
|
521
|
+
// cannot bypass the cap.
|
|
522
|
+
const active = [...children.values()].filter((child) => child.isAlive());
|
|
523
|
+
if (active.length + pendingCreates >= childLimit) {
|
|
524
|
+
throw new Error(
|
|
525
|
+
`This session already has ${String(childLimit)} active or starting direct children; stop one before creating another.`,
|
|
526
|
+
);
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
pendingCreates++;
|
|
530
|
+
try {
|
|
531
|
+
const task = params.task.trim();
|
|
532
|
+
const contextMode = params.contextMode ?? "task_compacted";
|
|
533
|
+
const compacted =
|
|
534
|
+
contextMode === "none"
|
|
535
|
+
? { summary: "", fallback: false }
|
|
536
|
+
: await compactContextForTask(pi, ctx, task, signal);
|
|
537
|
+
throwIfAborted(signal);
|
|
538
|
+
assertCreationActive();
|
|
539
|
+
const routingContext = truncateMiddle(compacted.summary, MAX_CLASSIFIER_CONTEXT_CHARS);
|
|
540
|
+
const selection = await selectModel(pi, ctx, task, routingContext, params.model, params.effort, signal);
|
|
541
|
+
throwIfAborted(signal);
|
|
542
|
+
assertCreationActive();
|
|
543
|
+
// ExtensionContext exposes models as Model<any>, while the registry accepts Model<Api>.
|
|
544
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
|
545
|
+
const childAuth = await ctx.modelRegistry.getApiKeyAndHeaders(selection.model);
|
|
546
|
+
throwIfAborted(signal);
|
|
547
|
+
if (!childAuth.ok) throw new Error(`Could not resolve child model auth: ${childAuth.error}`);
|
|
548
|
+
const childHeaders = stringProviderHeaders(childAuth.headers);
|
|
549
|
+
const id = shortId();
|
|
550
|
+
const name = childName(params.name, id);
|
|
551
|
+
const existingSessionId = ctx.sessionManager.getSessionId();
|
|
552
|
+
const parentSessionId = existingSessionId ? existingSessionId : "ephemeral";
|
|
553
|
+
const sessionDir = join(getAgentDir(), "subagents", parentSessionId, id);
|
|
554
|
+
await mkdir(sessionDir, { recursive: true, mode: 0o700 });
|
|
555
|
+
throwIfAborted(signal);
|
|
556
|
+
assertCreationActive();
|
|
557
|
+
const args = [
|
|
558
|
+
"--mode",
|
|
559
|
+
"rpc",
|
|
560
|
+
"--session-dir",
|
|
561
|
+
sessionDir,
|
|
562
|
+
"--name",
|
|
563
|
+
name,
|
|
564
|
+
"--model",
|
|
565
|
+
`${selection.model.provider}/${selection.model.id}`,
|
|
566
|
+
"--thinking",
|
|
567
|
+
selection.effort,
|
|
568
|
+
"--extension",
|
|
569
|
+
SELF_EXTENSION_PATH,
|
|
570
|
+
"--extension",
|
|
571
|
+
AUTH_BRIDGE_PATH,
|
|
572
|
+
ctx.isProjectTrusted() ? "--approve" : "--no-approve",
|
|
573
|
+
];
|
|
574
|
+
const invocation = resolvePiInvocation(args);
|
|
575
|
+
throwIfAborted(signal);
|
|
576
|
+
const child = new ManagedSubagent({
|
|
577
|
+
id,
|
|
578
|
+
name,
|
|
579
|
+
task,
|
|
580
|
+
model: `${selection.model.provider}/${selection.model.id}`,
|
|
581
|
+
effort: selection.effort,
|
|
582
|
+
contextMode,
|
|
583
|
+
contextSummary: boundContextForModel(routingContext, task, selection.model, MAX_CLASSIFIER_CONTEXT_CHARS),
|
|
584
|
+
cwd: ctx.cwd,
|
|
585
|
+
command: invocation.command,
|
|
586
|
+
args: invocation.args,
|
|
587
|
+
env: childEnvironment(depth + 1, selection.model.provider, {
|
|
588
|
+
...(childAuth.apiKey ? { apiKey: childAuth.apiKey } : {}),
|
|
589
|
+
...(childHeaders ? { headers: childHeaders } : {}),
|
|
590
|
+
}),
|
|
591
|
+
ownsProcessGroup: depth === 0,
|
|
592
|
+
classification: selection.source,
|
|
593
|
+
...(selection.rationale ? { classificationRationale: selection.rationale } : {}),
|
|
594
|
+
});
|
|
595
|
+
throwIfAborted(signal);
|
|
596
|
+
children.set(id, child);
|
|
597
|
+
try {
|
|
598
|
+
throwIfAborted(signal);
|
|
599
|
+
await child.start();
|
|
600
|
+
throwIfAborted(signal);
|
|
601
|
+
assertCreationActive();
|
|
602
|
+
} catch (error) {
|
|
603
|
+
await child.stop();
|
|
604
|
+
throw error;
|
|
605
|
+
}
|
|
606
|
+
const warning = compacted.fallback
|
|
607
|
+
? " Targeted compaction failed open, so the child started with fresh context."
|
|
608
|
+
: "";
|
|
609
|
+
return {
|
|
610
|
+
content: [
|
|
611
|
+
{
|
|
612
|
+
type: "text",
|
|
613
|
+
text: `Created ${id} (${name}) with ${selection.model.provider}/${selection.model.id} at ${selection.effort} effort.${warning} It is running asynchronously; use subagent status with id=${id} to spy, or wait only when this turn needs the result.`,
|
|
614
|
+
},
|
|
615
|
+
],
|
|
616
|
+
details: {
|
|
617
|
+
action: "create",
|
|
618
|
+
child: snapshotSummary(child.snapshot()),
|
|
619
|
+
contextMode,
|
|
620
|
+
compactionFallback: compacted.fallback,
|
|
621
|
+
},
|
|
622
|
+
};
|
|
623
|
+
} finally {
|
|
624
|
+
pendingCreates--;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
if (params.action === "list") {
|
|
629
|
+
pruneChildren();
|
|
630
|
+
const snapshots = [...children.values()].map((child) => snapshotSummary(child.snapshot()));
|
|
631
|
+
const text = snapshots.length
|
|
632
|
+
? snapshots
|
|
633
|
+
.map(
|
|
634
|
+
(child) =>
|
|
635
|
+
`${child.id} ${child.state} ${child.model} ${child.effort} contextMode=${child.contextMode} — ${truncateMiddle(child.task, 500)}`,
|
|
636
|
+
)
|
|
637
|
+
.join("\n")
|
|
638
|
+
: "No direct subagents have been created by this session.";
|
|
639
|
+
return { content: [{ type: "text", text }], details: { action: "list", children: snapshots } };
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
if (!params.id) throw new Error(`${params.action} requires a direct child id.`);
|
|
643
|
+
const child = children.get(params.id);
|
|
644
|
+
if (!child)
|
|
645
|
+
throw new Error(
|
|
646
|
+
`Unknown direct child '${params.id}'. Use subagent list to see children owned by this session.`,
|
|
647
|
+
);
|
|
648
|
+
|
|
649
|
+
if (params.action === "status") {
|
|
650
|
+
await child.refresh();
|
|
651
|
+
const snapshot = child.snapshot();
|
|
652
|
+
return {
|
|
653
|
+
content: [{ type: "text", text: formatSnapshot(snapshot) }],
|
|
654
|
+
details: { action: "status", child: snapshot },
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
if (params.action === "wait") {
|
|
658
|
+
const settled = await child.waitForIdle(params.timeoutMs ?? 120_000, signal);
|
|
659
|
+
await child.refresh();
|
|
660
|
+
const snapshot = child.snapshot();
|
|
661
|
+
const heading = settled
|
|
662
|
+
? `Subagent ${params.id} settled.`
|
|
663
|
+
: `Wait timed out; subagent ${params.id} is still active.`;
|
|
664
|
+
return {
|
|
665
|
+
content: [{ type: "text", text: `${heading}\n\n${formatSnapshot(snapshot)}` }],
|
|
666
|
+
details: { action: "wait", settled, child: snapshot },
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
if (params.action === "steer" || params.action === "follow_up") {
|
|
670
|
+
if (!params.task?.trim()) throw new Error(`${params.action} requires a non-empty task/message.`);
|
|
671
|
+
if (params.action === "steer") await child.steer(params.task.trim());
|
|
672
|
+
else await child.followUp(params.task.trim());
|
|
673
|
+
return {
|
|
674
|
+
content: [
|
|
675
|
+
{ type: "text", text: `${params.action === "steer" ? "Steered" : "Queued a follow-up for"} ${params.id}.` },
|
|
676
|
+
],
|
|
677
|
+
details: { action: params.action, child: snapshotSummary(child.snapshot()) },
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
if (params.action === "interrupt") {
|
|
681
|
+
await child.interrupt();
|
|
682
|
+
return {
|
|
683
|
+
content: [
|
|
684
|
+
{
|
|
685
|
+
type: "text",
|
|
686
|
+
text: `Interrupted ${params.id}; its isolated session remains available for steering or follow-up.`,
|
|
687
|
+
},
|
|
688
|
+
],
|
|
689
|
+
details: { action: "interrupt", child: snapshotSummary(child.snapshot()) },
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
await child.stop();
|
|
693
|
+
const stoppedSnapshot = snapshotSummary(child.snapshot());
|
|
694
|
+
pruneChildren();
|
|
695
|
+
return {
|
|
696
|
+
content: [{ type: "text", text: `Stopped ${params.id}.` }],
|
|
697
|
+
details: { action: "stop", child: stoppedSnapshot },
|
|
698
|
+
};
|
|
699
|
+
},
|
|
700
|
+
|
|
701
|
+
renderCall(args, theme) {
|
|
702
|
+
const rawTarget = args.id ? ` ${args.id}` : args.name ? ` ${args.name}` : "";
|
|
703
|
+
const target = safeTerminalText(rawTarget);
|
|
704
|
+
return new Text(
|
|
705
|
+
`${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", args.action)}${theme.fg("muted", target)}`,
|
|
706
|
+
0,
|
|
707
|
+
0,
|
|
708
|
+
);
|
|
709
|
+
},
|
|
710
|
+
|
|
711
|
+
renderResult(result, _options, theme) {
|
|
712
|
+
const content = result.content.find((entry) => entry.type === "text");
|
|
713
|
+
return new Text(
|
|
714
|
+
theme.fg("toolOutput", safeTerminalText(content?.type === "text" ? content.text : "(no output)")),
|
|
715
|
+
0,
|
|
716
|
+
0,
|
|
717
|
+
);
|
|
718
|
+
},
|
|
719
|
+
});
|
|
720
|
+
|
|
721
|
+
pi.on("session_shutdown", async () => {
|
|
722
|
+
if (shuttingDown) return;
|
|
723
|
+
shuttingDown = true;
|
|
724
|
+
await Promise.allSettled([...children.values()].map((child) => child.stop()));
|
|
725
|
+
children.clear();
|
|
726
|
+
});
|
|
727
|
+
}
|