@nredd/pi-subagents 0.0.0-stage → 0.22.0-nredd.5
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/LICENSE +21 -0
- package/README.md +1244 -2
- package/package.json +75 -4
- package/src/abortable.ts +43 -0
- package/src/agent-color.ts +161 -0
- package/src/agent-file-toggle.ts +297 -0
- package/src/agent-manager.ts +1874 -0
- package/src/agent-runner.ts +1552 -0
- package/src/agent-source-badge.ts +75 -0
- package/src/agent-types.ts +346 -0
- package/src/child-context.ts +15 -0
- package/src/clock.ts +25 -0
- package/src/completion-outbox.ts +125 -0
- package/src/context.ts +58 -0
- package/src/cross-extension-rpc.ts +221 -0
- package/src/custom-agents.ts +436 -0
- package/src/default-agents.ts +126 -0
- package/src/detached-results.ts +134 -0
- package/src/enabled-models.ts +180 -0
- package/src/enterprise-local.ts +66 -0
- package/src/env.ts +33 -0
- package/src/group-join.ts +148 -0
- package/src/index.ts +4423 -0
- package/src/invocation-config.ts +189 -0
- package/src/memory.ts +179 -0
- package/src/mention-clone.ts +195 -0
- package/src/mention.ts +141 -0
- package/src/model-call.ts +83 -0
- package/src/model-resolver.ts +266 -0
- package/src/model-scope.ts +70 -0
- package/src/nested-tools.ts +448 -0
- package/src/output-file.ts +164 -0
- package/src/package-resources.ts +624 -0
- package/src/prompts.ts +156 -0
- package/src/quota-admission.ts +99 -0
- package/src/schedule-store.ts +153 -0
- package/src/schedule.ts +446 -0
- package/src/settings.ts +728 -0
- package/src/skill-loader.ts +137 -0
- package/src/startup-error.ts +29 -0
- package/src/status-note.ts +90 -0
- package/src/structured-output.ts +130 -0
- package/src/types.ts +404 -0
- package/src/ui/agent-mention.ts +216 -0
- package/src/ui/agent-row.ts +235 -0
- package/src/ui/agent-widget.ts +692 -0
- package/src/ui/conversation-viewer.ts +832 -0
- package/src/ui/fleet-list.ts +675 -0
- package/src/ui/notification-view.ts +120 -0
- package/src/ui/schedule-menu.ts +105 -0
- package/src/ui/select-item.ts +45 -0
- package/src/ui/viewer-keys.ts +39 -0
- package/src/ui/workflow-card.ts +462 -0
- package/src/ui/workflow-dialog.ts +1115 -0
- package/src/ui/workflow-menu.ts +193 -0
- package/src/usage.ts +167 -0
- package/src/workflow/collisions.ts +123 -0
- package/src/workflow/entry.ts +47 -0
- package/src/workflow/host.ts +401 -0
- package/src/workflow/journal.ts +164 -0
- package/src/workflow/json-schema.ts +129 -0
- package/src/workflow/meta.ts +326 -0
- package/src/workflow/progress.ts +549 -0
- package/src/workflow/runtime.ts +1216 -0
- package/src/workflow/saved.ts +259 -0
- package/src/workflow/task.ts +302 -0
- package/src/workflow/tool-description.ts +200 -0
- package/src/workflow/worker-source.ts +781 -0
- package/src/worktree.ts +230 -0
- package/src/xml.ts +13 -0
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
import type { Model } from "@earendil-works/pi-ai";
|
|
2
|
+
import {
|
|
3
|
+
type AgentSession,
|
|
4
|
+
defineTool,
|
|
5
|
+
type ExtensionAPI,
|
|
6
|
+
type ExtensionContext,
|
|
7
|
+
type ToolDefinition,
|
|
8
|
+
} from "@earendil-works/pi-coding-agent";
|
|
9
|
+
import { Type } from "typebox";
|
|
10
|
+
import { abortable } from "./abortable.js";
|
|
11
|
+
import {
|
|
12
|
+
buildAgentRegistry,
|
|
13
|
+
getAgentConfigIn,
|
|
14
|
+
getAvailableTypesIn,
|
|
15
|
+
resolveEnabledTypeIn,
|
|
16
|
+
resolveTypeIn,
|
|
17
|
+
} from "./agent-types.js";
|
|
18
|
+
import { loadCustomAgents } from "./custom-agents.js";
|
|
19
|
+
import { isolationParam, resolveAgentInvocationConfig } from "./invocation-config.js";
|
|
20
|
+
import { resolveModel } from "./model-resolver.js";
|
|
21
|
+
import { checkModelScope } from "./model-scope.js";
|
|
22
|
+
import {
|
|
23
|
+
createOutputFilePath,
|
|
24
|
+
getOutputTranscriptDefault,
|
|
25
|
+
streamToOutputFile,
|
|
26
|
+
writeInitialEntry,
|
|
27
|
+
} from "./output-file.js";
|
|
28
|
+
import { getForegroundOutcomeNote, getStatusNote, partialOutputSuffix } from "./status-note.js";
|
|
29
|
+
import type {
|
|
30
|
+
AgentConfig,
|
|
31
|
+
AgentInvocation,
|
|
32
|
+
AgentRecord,
|
|
33
|
+
IsolationMode,
|
|
34
|
+
ThinkingLevel,
|
|
35
|
+
} from "./types.js";
|
|
36
|
+
import { addUsage } from "./usage.js";
|
|
37
|
+
import { isWorktreeIsolationEnabled } from "./worktree.js";
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Hard ceiling on nesting for every branch: main session = 0, its subagents = 1,
|
|
41
|
+
* their children = 2. `0`/`1` disables nesting entirely. Set from
|
|
42
|
+
* `subagents.json` (`maxSubagentDepth`). Read when a subagent session is built,
|
|
43
|
+
* so a change applies to sessions started after it.
|
|
44
|
+
*/
|
|
45
|
+
let maxSubagentDepth = 2;
|
|
46
|
+
|
|
47
|
+
export function getMaxSubagentDepth(): number { return maxSubagentDepth; }
|
|
48
|
+
export function setMaxSubagentDepth(n: number): void { maxSubagentDepth = Math.max(0, Math.floor(n)); }
|
|
49
|
+
|
|
50
|
+
const NESTED_TOOL_NAMES = ["Agent", "get_subagent_result", "steer_subagent"] as const;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Why a subagent may not start background work. A detached child's completion
|
|
54
|
+
* is delivered as a follow-up to the session that spawned it, and a subagent
|
|
55
|
+
* session ends the moment it returns its answer, so the notice would go to a
|
|
56
|
+
* session that no longer exists and the work would be aborted with its owner.
|
|
57
|
+
*/
|
|
58
|
+
export const NESTED_BACKGROUND_ERROR =
|
|
59
|
+
"Background agents are not available inside a subagent: when you finish, this session ends and nothing is left to receive the result. "
|
|
60
|
+
+ "Omit run_in_background; the call blocks and returns the child's result inline.";
|
|
61
|
+
|
|
62
|
+
/** Same reasoning for workflow tools, which run in the background and notify on completion. */
|
|
63
|
+
export const NESTED_WORKFLOW_ERROR =
|
|
64
|
+
"Workflows are not available inside a subagent: a workflow runs in the background and reports to the session that started it, "
|
|
65
|
+
+ "and this session ends when you return your answer. Do the work directly, or call Agent in the foreground.";
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* `NESTED_WORKFLOW_ERROR` for a child that was never given `Agent` (depth cap,
|
|
69
|
+
* isolation, `disallowed_tools`, or no `allowed_subagents`). Cause-neutral on purpose. Pointing it at a tool it does not have
|
|
70
|
+
* sends it hunting, and then shelling out to a CLI that escapes every limit.
|
|
71
|
+
*/
|
|
72
|
+
export const NESTED_WORKFLOW_NO_AGENT_ERROR =
|
|
73
|
+
"Workflows are not available inside a subagent: a workflow runs in the background and reports to the session that started it, "
|
|
74
|
+
+ "and this session ends when you return your answer. Nested subagents are disabled for this session, so there is no Agent tool either. "
|
|
75
|
+
+ "Do the work directly.";
|
|
76
|
+
|
|
77
|
+
interface NestedSpawnOptions {
|
|
78
|
+
description: string;
|
|
79
|
+
model?: Model<any>;
|
|
80
|
+
maxTurns?: number;
|
|
81
|
+
isolated?: boolean;
|
|
82
|
+
inheritContext?: boolean;
|
|
83
|
+
thinkingLevel?: ThinkingLevel;
|
|
84
|
+
isBackground?: boolean;
|
|
85
|
+
isolation?: IsolationMode;
|
|
86
|
+
invocation?: AgentInvocation;
|
|
87
|
+
signal?: AbortSignal;
|
|
88
|
+
onAssistantUsage?: (usage: { input: number; output: number; cacheWrite: number }) => void;
|
|
89
|
+
onSessionCreated?: (session: AgentSession) => void;
|
|
90
|
+
depth: number;
|
|
91
|
+
parentAgentId: string;
|
|
92
|
+
maxSubagentDepth: number;
|
|
93
|
+
configCwd?: string;
|
|
94
|
+
/** Trust decision for `configCwd`; always set together with it. */
|
|
95
|
+
configProjectTrusted?: boolean;
|
|
96
|
+
rootSessionId?: string;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface NestedAgentManager {
|
|
100
|
+
spawn(
|
|
101
|
+
pi: ExtensionAPI,
|
|
102
|
+
ctx: ExtensionContext,
|
|
103
|
+
type: string,
|
|
104
|
+
prompt: string,
|
|
105
|
+
options: NestedSpawnOptions,
|
|
106
|
+
): string;
|
|
107
|
+
/** Resolves once the spawned agent is running; rejects on a startup failure. */
|
|
108
|
+
awaitStartup(id: string): Promise<void>;
|
|
109
|
+
spawnAndWait(
|
|
110
|
+
pi: ExtensionAPI,
|
|
111
|
+
ctx: ExtensionContext,
|
|
112
|
+
type: string,
|
|
113
|
+
prompt: string,
|
|
114
|
+
options: Omit<NestedSpawnOptions, "isBackground">,
|
|
115
|
+
/** Fires synchronously after spawn, before the session exists — where the transcript is attached. */
|
|
116
|
+
onSpawned?: (id: string) => void,
|
|
117
|
+
): Promise<{ id: string; record: AgentRecord }>;
|
|
118
|
+
getRecord(id: string): AgentRecord | undefined;
|
|
119
|
+
resume(id: string, prompt: string, signal?: AbortSignal, options?: { maxTurns?: number }): Promise<AgentRecord | undefined>;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export interface NestedToolContext {
|
|
123
|
+
manager: NestedAgentManager;
|
|
124
|
+
pi: ExtensionAPI;
|
|
125
|
+
parentAgentId: string;
|
|
126
|
+
depth: number;
|
|
127
|
+
maxSubagentDepth: number;
|
|
128
|
+
/** "all" = any enabled agent; string[] = only those types. Never empty. */
|
|
129
|
+
allowedSubagents: "all" | string[];
|
|
130
|
+
/** Root used for agent/config discovery; may differ from the agent's working directory. */
|
|
131
|
+
configCwd: string;
|
|
132
|
+
/**
|
|
133
|
+
* The spawning session's project-trust decision for `configCwd`, as the runner
|
|
134
|
+
* resolved it for the child's own settings. Gates project agent files in the
|
|
135
|
+
* registry built here; read from the session's state it would answer for the
|
|
136
|
+
* child's cwd, which is untrusted for a cross-directory spawn.
|
|
137
|
+
*/
|
|
138
|
+
projectTrusted: boolean;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function textResult(text: string, isError = false) {
|
|
142
|
+
return { content: [{ type: "text" as const, text }], isError, details: {} };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function ownsRecord(record: AgentRecord | undefined, parentAgentId: string): record is AgentRecord {
|
|
146
|
+
return record?.parentAgentId === parentAgentId;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* How the caller received this record, which decides the outcome wording.
|
|
151
|
+
*
|
|
152
|
+
* - "inline": a foreground spawn or a resume. The full output is in this very
|
|
153
|
+
* result and no agent id was handed back, so the note must say there is
|
|
154
|
+
* nothing left to fetch — otherwise the parent invents an id, calls
|
|
155
|
+
* `get_subagent_result`, and hits "not owned by this parent" (#174, the same
|
|
156
|
+
* trap the top-level foreground path fell into).
|
|
157
|
+
* - "fetched": `get_subagent_result` on a background child. The parent holds a
|
|
158
|
+
* valid id and can poll again, so the background wording applies.
|
|
159
|
+
*/
|
|
160
|
+
type ResultPosition = "inline" | "fetched";
|
|
161
|
+
|
|
162
|
+
function formatRecord(record: AgentRecord, position: ResultPosition): string {
|
|
163
|
+
if (record.status === "error") {
|
|
164
|
+
return `Agent failed: ${record.error ?? "unknown error"}${partialOutputSuffix(record)}`;
|
|
165
|
+
}
|
|
166
|
+
if (record.status === "queued" || record.status === "running") {
|
|
167
|
+
return `Agent ${record.id} is ${record.status}.`;
|
|
168
|
+
}
|
|
169
|
+
// A truncated run must not read as a finished one. The top-level path carries
|
|
170
|
+
// this in its result headline; a nested result has no headline, so the note
|
|
171
|
+
// leads — appended, it would look like part of the child's own output.
|
|
172
|
+
const text = record.result?.trim() || record.error?.trim() || "No output.";
|
|
173
|
+
const note = position === "inline"
|
|
174
|
+
? getForegroundOutcomeNote(record.status)
|
|
175
|
+
: getStatusNote(record.status);
|
|
176
|
+
return note ? `Nested agent${note}.\n\n${text}` : text;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Build child-safe orchestration tools scoped to one parent agent instance. */
|
|
180
|
+
export function createNestedSubagentTools(context: NestedToolContext): ToolDefinition[] {
|
|
181
|
+
// Agents resolve from a registry built for THIS branch's config root (under
|
|
182
|
+
// worktree isolation, the copy). Never via registerAgents — that is
|
|
183
|
+
// process-global state shared with the main session and every other agent.
|
|
184
|
+
const loadRegistry = () => buildAgentRegistry(loadCustomAgents(context.configCwd, false, { projectTrusted: context.projectTrusted }));
|
|
185
|
+
const allowedTypesIn = (registry: Map<string, AgentConfig>): Set<string> | undefined =>
|
|
186
|
+
context.allowedSubagents === "all"
|
|
187
|
+
? undefined
|
|
188
|
+
: new Set(context.allowedSubagents.map(name => resolveTypeIn(registry, name) ?? name));
|
|
189
|
+
const availableIn = (registry: Map<string, AgentConfig>): string[] => {
|
|
190
|
+
const allowed = allowedTypesIn(registry);
|
|
191
|
+
return getAvailableTypesIn(registry).filter(name => allowed === undefined || allowed.has(name));
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
const agentTool = defineTool({
|
|
195
|
+
name: NESTED_TOOL_NAMES[0],
|
|
196
|
+
label: "Agent",
|
|
197
|
+
description:
|
|
198
|
+
"Launch a child-safe nested subagent for bounded delegated work. " +
|
|
199
|
+
"Only use agent types allowed by this parent agent; nesting is depth-limited.",
|
|
200
|
+
parameters: Type.Object({
|
|
201
|
+
prompt: Type.String({ description: "Self-contained task for the nested agent." }),
|
|
202
|
+
description: Type.String({ description: "Short 3-5 word task description." }),
|
|
203
|
+
subagent_type: Type.String({ description: `Allowed nested agent type. Available: ${availableIn(loadRegistry()).join(", ") || "none"}.` }),
|
|
204
|
+
model: Type.Optional(Type.String({ description: "Optional provider/model override." })),
|
|
205
|
+
thinking: Type.Optional(Type.String({ description: "Optional thinking level." })),
|
|
206
|
+
max_turns: Type.Optional(Type.Number({ minimum: 1 })),
|
|
207
|
+
run_in_background: Type.Optional(
|
|
208
|
+
Type.Boolean({
|
|
209
|
+
description: "Not supported inside a subagent: nested spawns always block and return the child's result inline. Passing true returns an error.",
|
|
210
|
+
}),
|
|
211
|
+
),
|
|
212
|
+
resume: Type.Optional(Type.String({ description: "Resume a nested agent owned by this parent." })),
|
|
213
|
+
isolated: Type.Optional(Type.Boolean()),
|
|
214
|
+
inherit_context: Type.Optional(Type.Boolean()),
|
|
215
|
+
...isolationParam(isWorktreeIsolationEnabled()),
|
|
216
|
+
}),
|
|
217
|
+
execute: async (_toolCallId, params, signal, _onUpdate, ctx) => {
|
|
218
|
+
if (params.run_in_background === true) return textResult(NESTED_BACKGROUND_ERROR, true);
|
|
219
|
+
if (params.resume) {
|
|
220
|
+
const existing = context.manager.getRecord(params.resume);
|
|
221
|
+
if (!ownsRecord(existing, context.parentAgentId)) {
|
|
222
|
+
return textResult(`Nested agent not found or not owned by this parent: "${params.resume}".`, true);
|
|
223
|
+
}
|
|
224
|
+
// Frontmatter authoritative, as on the spawn path; the manager falls
|
|
225
|
+
// back to the limit the child was spawned with, then the default.
|
|
226
|
+
const resumed = await context.manager.resume(params.resume, params.prompt, signal, {
|
|
227
|
+
maxTurns: getAgentConfigIn(loadRegistry(), existing.type)?.maxTurns ?? params.max_turns,
|
|
228
|
+
});
|
|
229
|
+
return resumed
|
|
230
|
+
? textResult(formatRecord(resumed, "inline"), resumed.status === "error")
|
|
231
|
+
: textResult(`Failed to resume nested agent "${params.resume}".`, true);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
if (context.depth >= context.maxSubagentDepth) {
|
|
235
|
+
return textResult(
|
|
236
|
+
`Nested subagent call blocked (depth=${context.depth}, max=${context.maxSubagentDepth}). Complete the task directly.`,
|
|
237
|
+
true,
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// Reloaded per call so new agent files are picked up without a restart.
|
|
242
|
+
const registry = loadRegistry();
|
|
243
|
+
const rawType = params.subagent_type;
|
|
244
|
+
// Strict resolve, never the fallback policy: a project-level
|
|
245
|
+
// `fallbackSubagent` must not hand a nested caller an agent its allowlist
|
|
246
|
+
// never named. The list stays allowlist-filtered so a typo can't enumerate
|
|
247
|
+
// agents this parent may not reach.
|
|
248
|
+
const resolvedType = resolveEnabledTypeIn(registry, rawType);
|
|
249
|
+
if (resolvedType === undefined) {
|
|
250
|
+
return textResult(
|
|
251
|
+
`Unknown or disabled nested agent type: "${rawType}". Allowed: ${availableIn(registry).join(", ") || "none"}.`,
|
|
252
|
+
true,
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
const allowed = allowedTypesIn(registry);
|
|
256
|
+
if (allowed !== undefined && !allowed.has(resolvedType)) {
|
|
257
|
+
return textResult(
|
|
258
|
+
`Nested agent type "${resolvedType}" is not allowed for this parent. Allowed: ${[...allowed].join(", ")}.`,
|
|
259
|
+
true,
|
|
260
|
+
);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const config = getAgentConfigIn(registry, resolvedType);
|
|
264
|
+
// Foreground regardless of `backgroundByDefault` — see the reasoning on
|
|
265
|
+
// ResolveOptions. An explicit `true` here still opts in.
|
|
266
|
+
const invocation = resolveAgentInvocationConfig(config, params, {
|
|
267
|
+
agentType: resolvedType,
|
|
268
|
+
worktreeAllowed: isWorktreeIsolationEnabled(),
|
|
269
|
+
defaultRunInBackground: false,
|
|
270
|
+
});
|
|
271
|
+
let model = ctx.model;
|
|
272
|
+
if (invocation.modelInput) {
|
|
273
|
+
const resolvedModel = resolveModel(invocation.modelInput, ctx.modelRegistry);
|
|
274
|
+
if (typeof resolvedModel === "string") {
|
|
275
|
+
if (invocation.modelFromParams) return textResult(resolvedModel, true);
|
|
276
|
+
} else {
|
|
277
|
+
model = resolvedModel;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Same scopeModels policy as the top-level Agent tool — a nested spawn
|
|
282
|
+
// must not escape the allowlist. A "warn" verdict proceeds silently:
|
|
283
|
+
// child sessions have no UI surface to toast to.
|
|
284
|
+
const scopeVerdict = checkModelScope({
|
|
285
|
+
model,
|
|
286
|
+
cwd: context.configCwd,
|
|
287
|
+
modelRegistry: ctx.modelRegistry,
|
|
288
|
+
callerSupplied: invocation.modelFromParams,
|
|
289
|
+
agentLabel: config?.displayName ?? resolvedType,
|
|
290
|
+
modelInput: invocation.modelInput,
|
|
291
|
+
});
|
|
292
|
+
if (scopeVerdict.kind === "error") return textResult(scopeVerdict.message, true);
|
|
293
|
+
|
|
294
|
+
// The whole branch shares the root session's transcript directory; read it
|
|
295
|
+
// off the owning parent rather than this child session's own id.
|
|
296
|
+
const rootSessionId = context.manager.getRecord(context.parentAgentId)?.rootSessionId;
|
|
297
|
+
const childDepth = context.depth + 1;
|
|
298
|
+
const options: NestedSpawnOptions = {
|
|
299
|
+
description: params.description,
|
|
300
|
+
model,
|
|
301
|
+
maxTurns: invocation.maxTurns,
|
|
302
|
+
isolated: invocation.isolated,
|
|
303
|
+
inheritContext: invocation.inheritContext,
|
|
304
|
+
thinkingLevel: invocation.thinking,
|
|
305
|
+
isolation: invocation.isolation,
|
|
306
|
+
invocation: {
|
|
307
|
+
thinking: invocation.thinking,
|
|
308
|
+
maxTurns: invocation.maxTurns,
|
|
309
|
+
isolated: invocation.isolated,
|
|
310
|
+
inheritContext: invocation.inheritContext,
|
|
311
|
+
isolation: invocation.isolation,
|
|
312
|
+
},
|
|
313
|
+
// Nested children are hidden from every reporting surface, so their spend
|
|
314
|
+
// would otherwise be unattributable. Fold it into every ancestor's record:
|
|
315
|
+
// the top-level one appears in lifecycle events, completion notifications,
|
|
316
|
+
// and `/agents`, and those all read `lifetimeUsage`. The whole chain is
|
|
317
|
+
// walked, not just the immediate parent — a spawn callback only fires for
|
|
318
|
+
// that child's OWN turns, so stopping at one level would hide a
|
|
319
|
+
// great-grandchild from the only record anyone can see. (The live
|
|
320
|
+
// widget/fleet counters read their own per-agent activity tracker, which
|
|
321
|
+
// still sees only the top-level agent's own turns.)
|
|
322
|
+
onAssistantUsage: (usage) => {
|
|
323
|
+
for (let id: string | undefined = context.parentAgentId; id !== undefined; ) {
|
|
324
|
+
const ancestor = context.manager.getRecord(id);
|
|
325
|
+
if (!ancestor) break;
|
|
326
|
+
addUsage(ancestor.lifetimeUsage, usage);
|
|
327
|
+
id = ancestor.parentAgentId;
|
|
328
|
+
}
|
|
329
|
+
},
|
|
330
|
+
depth: childDepth,
|
|
331
|
+
parentAgentId: context.parentAgentId,
|
|
332
|
+
maxSubagentDepth: context.maxSubagentDepth,
|
|
333
|
+
configCwd: context.configCwd,
|
|
334
|
+
configProjectTrusted: context.projectTrusted,
|
|
335
|
+
rootSessionId,
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
// Transcript wiring, same gate as the top-level path: the child's
|
|
339
|
+
// `output_transcript` frontmatter wins, else the project default. Without
|
|
340
|
+
// it a nested run leaves no artifact but the string it returned — the
|
|
341
|
+
// parent's own transcript records the call and the answer, never the tool
|
|
342
|
+
// calls in between, which is exactly what a misbehaving child needs to
|
|
343
|
+
// explain itself. Filed under the ROOT session and this branch's config
|
|
344
|
+
// root, so a nested transcript lands in the same `tasks/` directory as its
|
|
345
|
+
// ancestors' rather than in a directory of its own.
|
|
346
|
+
const transcriptSessionId =
|
|
347
|
+
rootSessionId !== undefined && (config?.outputTranscript ?? getOutputTranscriptDefault())
|
|
348
|
+
? rootSessionId
|
|
349
|
+
: undefined;
|
|
350
|
+
let childId: string | undefined;
|
|
351
|
+
const attachTranscript = (id: string): void => {
|
|
352
|
+
childId = id;
|
|
353
|
+
if (transcriptSessionId === undefined) return;
|
|
354
|
+
const rec = context.manager.getRecord(id);
|
|
355
|
+
if (!rec) return;
|
|
356
|
+
rec.outputFile = createOutputFilePath(context.configCwd, id, transcriptSessionId);
|
|
357
|
+
writeInitialEntry(rec.outputFile, id, params.prompt, ctx.cwd);
|
|
358
|
+
};
|
|
359
|
+
options.onSessionCreated = (session) => {
|
|
360
|
+
const rec = childId === undefined ? undefined : context.manager.getRecord(childId);
|
|
361
|
+
if (rec?.outputFile && childId !== undefined) {
|
|
362
|
+
rec.outputCleanup = streamToOutputFile(session, rec.outputFile, childId, ctx.cwd);
|
|
363
|
+
}
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
// `ctx` is forwarded to the manager unmodified, never captured at tool-build
|
|
367
|
+
// time: each AgentSession builds its own ExtensionRunner from that session's
|
|
368
|
+
// cwd/sessionManager/modelRegistry, so this is the CHILD's context. Capturing
|
|
369
|
+
// one earlier would silently give a grandchild the wrong worktree base, the
|
|
370
|
+
// wrong conversation under inherit_context, and the wrong inherited model.
|
|
371
|
+
//
|
|
372
|
+
// spawn() throws on strict worktree-isolation failure and cwd validation —
|
|
373
|
+
// report it as a tool error, like the top-level Agent tool does, instead of
|
|
374
|
+
// letting it escape into the child's turn.
|
|
375
|
+
try {
|
|
376
|
+
const { record } = await context.manager.spawnAndWait(
|
|
377
|
+
context.pi,
|
|
378
|
+
ctx,
|
|
379
|
+
resolvedType,
|
|
380
|
+
params.prompt,
|
|
381
|
+
{ ...options, signal },
|
|
382
|
+
attachTranscript,
|
|
383
|
+
);
|
|
384
|
+
return textResult(formatRecord(record, "inline"), record.status === "error");
|
|
385
|
+
} catch (err) {
|
|
386
|
+
return textResult(err instanceof Error ? err.message : String(err), true);
|
|
387
|
+
}
|
|
388
|
+
},
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
const resultTool = defineTool({
|
|
392
|
+
name: NESTED_TOOL_NAMES[1],
|
|
393
|
+
label: "Get Nested Agent Result",
|
|
394
|
+
description: "Check or wait for a background nested agent owned by this parent.",
|
|
395
|
+
parameters: Type.Object({
|
|
396
|
+
agent_id: Type.String(),
|
|
397
|
+
wait: Type.Optional(Type.Boolean()),
|
|
398
|
+
}),
|
|
399
|
+
execute: async (_toolCallId, params, signal) => {
|
|
400
|
+
const record = context.manager.getRecord(params.agent_id);
|
|
401
|
+
if (!ownsRecord(record, context.parentAgentId)) {
|
|
402
|
+
return textResult(`Nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
|
|
403
|
+
}
|
|
404
|
+
// Wait for completion if requested. Cancellation (e.g. the parent's tool
|
|
405
|
+
// call is aborted) stops only this wait; the nested child keeps running and
|
|
406
|
+
// stays unconsumed. Queued records have no promise until the manager starts
|
|
407
|
+
// them, so poll — abortably — until they leave the queue, then await.
|
|
408
|
+
if (params.wait && (record.status === "queued" || record.status === "running")) {
|
|
409
|
+
while (record.status === "queued") {
|
|
410
|
+
await abortable(new Promise<void>(resolve => setTimeout(resolve, 250)), signal);
|
|
411
|
+
}
|
|
412
|
+
if (record.promise) await abortable(record.promise, signal);
|
|
413
|
+
}
|
|
414
|
+
return textResult(formatRecord(record, "fetched"), record.status === "error");
|
|
415
|
+
},
|
|
416
|
+
});
|
|
417
|
+
|
|
418
|
+
const steerTool = defineTool({
|
|
419
|
+
name: NESTED_TOOL_NAMES[2],
|
|
420
|
+
label: "Steer Nested Agent",
|
|
421
|
+
description: "Send guidance to a running nested agent owned by this parent.",
|
|
422
|
+
parameters: Type.Object({
|
|
423
|
+
agent_id: Type.String(),
|
|
424
|
+
message: Type.String(),
|
|
425
|
+
}),
|
|
426
|
+
execute: async (_toolCallId, params) => {
|
|
427
|
+
const record = context.manager.getRecord(params.agent_id);
|
|
428
|
+
if (!ownsRecord(record, context.parentAgentId) || record.status !== "running") {
|
|
429
|
+
return textResult(`Running nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
|
|
430
|
+
}
|
|
431
|
+
// Session not ready yet — queue the steer. The manager flushes pending
|
|
432
|
+
// steers when the session is created (same contract as the top-level tool).
|
|
433
|
+
if (!record.session) {
|
|
434
|
+
if (!record.pendingSteers) record.pendingSteers = [];
|
|
435
|
+
record.pendingSteers.push(params.message);
|
|
436
|
+
return textResult(`Steering message queued for nested agent ${params.agent_id}.`);
|
|
437
|
+
}
|
|
438
|
+
try {
|
|
439
|
+
await record.session.steer(params.message);
|
|
440
|
+
} catch (err) {
|
|
441
|
+
return textResult(`Failed to steer nested agent: ${err instanceof Error ? err.message : String(err)}`, true);
|
|
442
|
+
}
|
|
443
|
+
return textResult(`Steering message sent to nested agent ${params.agent_id}.`);
|
|
444
|
+
},
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
return [agentTool, resultTool, steerTool];
|
|
448
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* output-file.ts — Streaming JSONL output file for agent transcripts.
|
|
3
|
+
*
|
|
4
|
+
* Creates a per-agent output file that streams conversation turns as JSONL,
|
|
5
|
+
* matching Claude Code's task output file format.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { appendFileSync, chmodSync, mkdirSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { tmpdir } from "node:os";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import type { AgentSession, AgentSessionEvent } from "@earendil-works/pi-coding-agent";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Project/global default for writing a subagent's `.output` transcript; a custom
|
|
15
|
+
* agent's `output_transcript` overrides it per agent.
|
|
16
|
+
*
|
|
17
|
+
* State lives here rather than in an index.ts closure because both spawn paths
|
|
18
|
+
* need it — the top-level Agent tool and the nested delegation tools. Same
|
|
19
|
+
* reason `scopeModels` lives in model-scope.ts: a setting only one path can read
|
|
20
|
+
* is a setting the other path silently ignores.
|
|
21
|
+
*/
|
|
22
|
+
let outputTranscriptDefault = true;
|
|
23
|
+
|
|
24
|
+
export function getOutputTranscriptDefault(): boolean { return outputTranscriptDefault; }
|
|
25
|
+
export function setOutputTranscriptDefault(b: boolean): void { outputTranscriptDefault = b; }
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Encode a cwd path as a filesystem-safe directory name. Handles:
|
|
29
|
+
* - POSIX: "/home/user/project" → "home-user-project"
|
|
30
|
+
* - Windows: "C:\Users\foo\project" → "Users-foo-project"
|
|
31
|
+
* - UNC: "\\\\server\\share\\project" → "server-share-project"
|
|
32
|
+
*/
|
|
33
|
+
export function encodeCwd(cwd: string): string {
|
|
34
|
+
return cwd
|
|
35
|
+
.replace(/[/\\]/g, "-") // both separators → dash
|
|
36
|
+
.replace(/^[A-Za-z]:-/, "") // strip Windows drive prefix ("C:-")
|
|
37
|
+
.replace(/^-+/, ""); // strip leading dashes (POSIX root, UNC)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The per-session scratch directory, created if missing.
|
|
42
|
+
* Mirrors Claude Code's layout: /tmp/{prefix}-{uid}/{encoded-cwd}/{sessionId}/tasks
|
|
43
|
+
*
|
|
44
|
+
* Shared with the workflow tool, which persists each invocation's script here so
|
|
45
|
+
* iterating on one is edit-file-then-rerun — the same convention, one directory.
|
|
46
|
+
*/
|
|
47
|
+
export function sessionTaskDir(cwd: string, sessionId: string): string {
|
|
48
|
+
const encoded = encodeCwd(cwd);
|
|
49
|
+
const root = join(tmpdir(), `pi-subagents-${process.getuid?.() ?? 0}`);
|
|
50
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
51
|
+
// chmod is a no-op on Windows and throws on some Windows filesystems.
|
|
52
|
+
// On Unix we still want to enforce 0o700 past umask, so only swallow on Windows.
|
|
53
|
+
try {
|
|
54
|
+
chmodSync(root, 0o700);
|
|
55
|
+
} catch (err) {
|
|
56
|
+
if (process.platform !== "win32") throw err;
|
|
57
|
+
}
|
|
58
|
+
const dir = join(root, encoded, sessionId, "tasks");
|
|
59
|
+
mkdirSync(dir, { recursive: true });
|
|
60
|
+
return dir;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Create the output file path, ensuring the directory exists. */
|
|
64
|
+
export function createOutputFilePath(cwd: string, agentId: string, sessionId: string): string {
|
|
65
|
+
return join(sessionTaskDir(cwd, sessionId), `${agentId}.output`);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Ensure a transcript file exists without disturbing what is already in it.
|
|
70
|
+
*
|
|
71
|
+
* A resume reuses the agent's existing transcript (same deterministic path), so
|
|
72
|
+
* it must never call `writeInitialEntry` — that truncates, discarding turns the
|
|
73
|
+
* completion notification still points the user at, and any history the session
|
|
74
|
+
* has since compacted away is gone for good. Appending nothing creates the file
|
|
75
|
+
* when this is the agent's first transcript and is a no-op when it is not.
|
|
76
|
+
*/
|
|
77
|
+
export function ensureOutputFile(path: string): void {
|
|
78
|
+
try {
|
|
79
|
+
appendFileSync(path, "", "utf-8");
|
|
80
|
+
} catch { /* ignore — streaming writes are best-effort too */ }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Write the initial user prompt entry. */
|
|
84
|
+
export function writeInitialEntry(path: string, agentId: string, prompt: string, cwd: string): void {
|
|
85
|
+
const entry = {
|
|
86
|
+
isSidechain: true,
|
|
87
|
+
agentId,
|
|
88
|
+
type: "user",
|
|
89
|
+
message: { role: "user", content: prompt },
|
|
90
|
+
timestamp: new Date().toISOString(),
|
|
91
|
+
cwd,
|
|
92
|
+
};
|
|
93
|
+
writeFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Subscribe to session events and flush new messages to the output file on each turn_end.
|
|
98
|
+
* Returns a cleanup function that does a final flush and unsubscribes.
|
|
99
|
+
*/
|
|
100
|
+
export function streamToOutputFile(
|
|
101
|
+
session: AgentSession,
|
|
102
|
+
path: string,
|
|
103
|
+
agentId: string,
|
|
104
|
+
cwd: string,
|
|
105
|
+
startIndex?: number,
|
|
106
|
+
): () => void {
|
|
107
|
+
// Index of the first message this stream is responsible for. A resume hands
|
|
108
|
+
// in the session's length as of just before the run: the session already
|
|
109
|
+
// holds every prior turn, and re-emitting those would duplicate history that
|
|
110
|
+
// is already in the file. A spawn has already written its prompt as the
|
|
111
|
+
// initial entry, so it starts after the first user message — found on the
|
|
112
|
+
// first flush, because pi puts a system message ahead of it and adds both
|
|
113
|
+
// only once the prompt runs.
|
|
114
|
+
let writtenCount = startIndex;
|
|
115
|
+
|
|
116
|
+
const flush = () => {
|
|
117
|
+
const messages = session.messages;
|
|
118
|
+
if (writtenCount === undefined) {
|
|
119
|
+
const prompt = messages.findIndex((m) => m.role === "user");
|
|
120
|
+
if (prompt === -1) return;
|
|
121
|
+
writtenCount = prompt + 1;
|
|
122
|
+
}
|
|
123
|
+
while (writtenCount < messages.length) {
|
|
124
|
+
const msg = messages[writtenCount++];
|
|
125
|
+
// Pi's prompt and tool-loadout records; a Claude Code transcript has no
|
|
126
|
+
// such entry.
|
|
127
|
+
if (msg.role === "system") continue;
|
|
128
|
+
const entry = {
|
|
129
|
+
isSidechain: true,
|
|
130
|
+
agentId,
|
|
131
|
+
type: msg.role === "assistant" ? "assistant" : msg.role === "user" ? "user" : "toolResult",
|
|
132
|
+
message: msg,
|
|
133
|
+
timestamp: new Date().toISOString(),
|
|
134
|
+
cwd,
|
|
135
|
+
};
|
|
136
|
+
try {
|
|
137
|
+
appendFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
|
|
138
|
+
} catch { /* ignore write errors */ }
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const unsubscribe = session.subscribe((event: AgentSessionEvent) => {
|
|
143
|
+
if (event.type === "turn_end") flush();
|
|
144
|
+
// Compaction replaces session.messages with a shorter, summarized array,
|
|
145
|
+
// leaving writtenCount past the new end — without re-anchoring, the flush
|
|
146
|
+
// loop would never match again and streaming would halt for good (#145).
|
|
147
|
+
// Flush before it runs so any not-yet-flushed tail still reaches the file,
|
|
148
|
+
// then re-anchor to the rebuilt array once it lands. The re-anchor is
|
|
149
|
+
// deferred a microtask because on the overflow-retry path pi trims the
|
|
150
|
+
// trailing error assistant message AFTER emitting compaction_end —
|
|
151
|
+
// anchoring synchronously would sit one past the trimmed array and skip
|
|
152
|
+
// the first post-compaction message. Aborted/failed compactions leave
|
|
153
|
+
// session.messages untouched, so only successful ones re-anchor.
|
|
154
|
+
if (event.type === "compaction_start") flush();
|
|
155
|
+
if (event.type === "compaction_end" && !event.aborted && event.result) {
|
|
156
|
+
queueMicrotask(() => { writtenCount = session.messages.length; });
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
return () => {
|
|
161
|
+
flush();
|
|
162
|
+
unsubscribe();
|
|
163
|
+
};
|
|
164
|
+
}
|