@ymy88/pi-subagents 0.0.0-stage → 0.24.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/CHANGELOG.md +904 -0
- package/CONTRIBUTING.md +72 -0
- package/LICENSE +21 -0
- package/README.md +1170 -2
- package/SECURITY.md +95 -0
- package/dist/abortable.d.ts +12 -0
- package/dist/abortable.js +42 -0
- package/dist/agent-color.d.ts +35 -0
- package/dist/agent-color.js +123 -0
- package/dist/agent-file-toggle.d.ts +133 -0
- package/dist/agent-file-toggle.js +287 -0
- package/dist/agent-manager.d.ts +552 -0
- package/dist/agent-manager.js +1466 -0
- package/dist/agent-record-entry.d.ts +96 -0
- package/dist/agent-record-entry.js +121 -0
- package/dist/agent-runner.d.ts +310 -0
- package/dist/agent-runner.js +1195 -0
- package/dist/agent-source-badge.d.ts +50 -0
- package/dist/agent-source-badge.js +74 -0
- package/dist/agent-types.d.ts +119 -0
- package/dist/agent-types.js +286 -0
- package/dist/child-context.d.ts +2 -0
- package/dist/child-context.js +12 -0
- package/dist/completion-outbox.d.ts +63 -0
- package/dist/completion-outbox.js +104 -0
- package/dist/context.d.ts +12 -0
- package/dist/context.js +56 -0
- package/dist/cross-extension-rpc.d.ts +72 -0
- package/dist/cross-extension-rpc.js +153 -0
- package/dist/custom-agents.d.ts +77 -0
- package/dist/custom-agents.js +396 -0
- package/dist/default-agents.d.ts +7 -0
- package/dist/default-agents.js +121 -0
- package/dist/enabled-models.d.ts +49 -0
- package/dist/enabled-models.js +145 -0
- package/dist/env.d.ts +6 -0
- package/dist/env.js +28 -0
- package/dist/group-join.d.ts +32 -0
- package/dist/group-join.js +116 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.js +4111 -0
- package/dist/invocation-config.d.ts +108 -0
- package/dist/invocation-config.js +83 -0
- package/dist/memory.d.ts +53 -0
- package/dist/memory.js +165 -0
- package/dist/mention-clone.d.ts +79 -0
- package/dist/mention-clone.js +155 -0
- package/dist/mention.d.ts +81 -0
- package/dist/mention.js +131 -0
- package/dist/model-resolver.d.ts +36 -0
- package/dist/model-resolver.js +95 -0
- package/dist/model-scope.d.ts +49 -0
- package/dist/model-scope.js +48 -0
- package/dist/nested-tools.d.ts +57 -0
- package/dist/nested-tools.js +303 -0
- package/dist/output-file.d.ts +43 -0
- package/dist/output-file.js +153 -0
- package/dist/package-resources.d.ts +240 -0
- package/dist/package-resources.js +519 -0
- package/dist/prompts.d.ts +76 -0
- package/dist/prompts.js +121 -0
- package/dist/schedule-store.d.ts +38 -0
- package/dist/schedule-store.js +155 -0
- package/dist/schedule.d.ts +109 -0
- package/dist/schedule.js +359 -0
- package/dist/settings.d.ts +398 -0
- package/dist/settings.js +282 -0
- package/dist/skill-loader.d.ts +24 -0
- package/dist/skill-loader.js +93 -0
- package/dist/status-note.d.ts +61 -0
- package/dist/status-note.js +85 -0
- package/dist/structured-output.d.ts +61 -0
- package/dist/structured-output.js +112 -0
- package/dist/types.d.ts +391 -0
- package/dist/types.js +5 -0
- package/dist/ui/agent-mention.d.ts +82 -0
- package/dist/ui/agent-mention.js +187 -0
- package/dist/ui/agent-widget.d.ts +219 -0
- package/dist/ui/agent-widget.js +585 -0
- package/dist/ui/conversation-viewer.d.ts +177 -0
- package/dist/ui/conversation-viewer.js +905 -0
- package/dist/ui/fleet-list.d.ts +211 -0
- package/dist/ui/fleet-list.js +489 -0
- package/dist/ui/schedule-menu.d.ts +16 -0
- package/dist/ui/schedule-menu.js +94 -0
- package/dist/ui/select-item.d.ts +27 -0
- package/dist/ui/select-item.js +34 -0
- package/dist/ui/viewer-keys.d.ts +22 -0
- package/dist/ui/viewer-keys.js +18 -0
- package/dist/ui/workflow-card.d.ts +175 -0
- package/dist/ui/workflow-card.js +332 -0
- package/dist/ui/workflow-dialog.d.ts +305 -0
- package/dist/ui/workflow-dialog.js +843 -0
- package/dist/ui/workflow-menu.d.ts +60 -0
- package/dist/ui/workflow-menu.js +147 -0
- package/dist/usage.d.ts +135 -0
- package/dist/usage.js +120 -0
- package/dist/workflow/collisions.d.ts +95 -0
- package/dist/workflow/collisions.js +88 -0
- package/dist/workflow/entry.d.ts +32 -0
- package/dist/workflow/entry.js +29 -0
- package/dist/workflow/host.d.ts +62 -0
- package/dist/workflow/host.js +419 -0
- package/dist/workflow/journal.d.ts +97 -0
- package/dist/workflow/journal.js +120 -0
- package/dist/workflow/json-schema.d.ts +52 -0
- package/dist/workflow/json-schema.js +112 -0
- package/dist/workflow/meta.d.ts +67 -0
- package/dist/workflow/meta.js +317 -0
- package/dist/workflow/progress.d.ts +224 -0
- package/dist/workflow/progress.js +361 -0
- package/dist/workflow/runtime.d.ts +334 -0
- package/dist/workflow/runtime.js +830 -0
- package/dist/workflow/saved.d.ts +102 -0
- package/dist/workflow/saved.js +247 -0
- package/dist/workflow/task.d.ts +136 -0
- package/dist/workflow/task.js +207 -0
- package/dist/workflow/tool-description.d.ts +38 -0
- package/dist/workflow/tool-description.js +199 -0
- package/dist/workflow/worker-source.d.ts +47 -0
- package/dist/workflow/worker-source.js +778 -0
- package/dist/worktree.d.ts +52 -0
- package/dist/worktree.js +164 -0
- package/dist/xml.d.ts +10 -0
- package/dist/xml.js +12 -0
- package/docs/packages.md +211 -0
- package/docs/rpc.md +192 -0
- package/docs/workflows.md +447 -0
- package/examples/agent-tool-description.md +42 -0
- package/examples/workflows/compose.js +51 -0
- package/examples/workflows/fan-out-audit.js +47 -0
- package/examples/workflows/gated-fix.js +60 -0
- package/examples/workflows/lib/count-child.js +27 -0
- package/examples/workflows/review-panel.js +63 -0
- package/examples/workflows/structured-findings.js +78 -0
- package/package.json +74 -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 +1735 -0
- package/src/agent-record-entry.ts +153 -0
- package/src/agent-runner.ts +1468 -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/completion-outbox.ts +116 -0
- package/src/context.ts +58 -0
- package/src/cross-extension-rpc.ts +221 -0
- package/src/custom-agents.ts +452 -0
- package/src/default-agents.ts +125 -0
- package/src/enabled-models.ts +180 -0
- package/src/env.ts +33 -0
- package/src/group-join.ts +141 -0
- package/src/index.ts +4433 -0
- package/src/invocation-config.ts +155 -0
- package/src/memory.ts +179 -0
- package/src/mention-clone.ts +195 -0
- package/src/mention.ts +141 -0
- package/src/model-resolver.ts +118 -0
- package/src/model-scope.ts +70 -0
- package/src/nested-tools.ts +426 -0
- package/src/output-file.ts +164 -0
- package/src/package-resources.ts +652 -0
- package/src/prompts.ts +171 -0
- package/src/schedule-store.ts +153 -0
- package/src/schedule.ts +386 -0
- package/src/settings.ts +650 -0
- package/src/skill-loader.ts +102 -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-widget.ts +661 -0
- package/src/ui/conversation-viewer.ts +928 -0
- package/src/ui/fleet-list.ts +559 -0
- package/src/ui/schedule-menu.ts +105 -0
- package/src/ui/select-item.ts +45 -0
- package/src/ui/viewer-keys.ts +43 -0
- package/src/ui/workflow-card.ts +470 -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 +467 -0
- package/src/workflow/journal.ts +164 -0
- package/src/workflow/json-schema.ts +129 -0
- package/src/workflow/meta.ts +325 -0
- package/src/workflow/progress.ts +551 -0
- package/src/workflow/runtime.ts +1219 -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 +205 -0
- package/src/xml.ts +13 -0
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import { defineTool, } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import { abortable } from "./abortable.js";
|
|
4
|
+
import { buildAgentRegistry, getAgentConfigIn, getAvailableTypesIn, resolveEnabledTypeIn, resolveTypeIn, } from "./agent-types.js";
|
|
5
|
+
import { loadCustomAgents } from "./custom-agents.js";
|
|
6
|
+
import { isolationParam, resolveAgentInvocationConfig } from "./invocation-config.js";
|
|
7
|
+
import { resolveModel } from "./model-resolver.js";
|
|
8
|
+
import { checkModelScope } from "./model-scope.js";
|
|
9
|
+
import { createOutputFilePath, getOutputTranscriptDefault, streamToOutputFile, writeInitialEntry, } from "./output-file.js";
|
|
10
|
+
import { getForegroundOutcomeNote, getStatusNote, partialOutputSuffix } from "./status-note.js";
|
|
11
|
+
import { addUsage } from "./usage.js";
|
|
12
|
+
import { isWorktreeIsolationEnabled } from "./worktree.js";
|
|
13
|
+
/**
|
|
14
|
+
* Hard ceiling on nesting for every branch: main session = 0, its subagents = 1,
|
|
15
|
+
* their children = 2. `0`/`1` disables nesting entirely. Set from
|
|
16
|
+
* `subagents.json` (`maxSubagentDepth`). Read when a subagent session is built,
|
|
17
|
+
* so a change applies to sessions started after it.
|
|
18
|
+
*/
|
|
19
|
+
let maxSubagentDepth = 2;
|
|
20
|
+
export function getMaxSubagentDepth() { return maxSubagentDepth; }
|
|
21
|
+
export function setMaxSubagentDepth(n) { maxSubagentDepth = Math.max(0, Math.floor(n)); }
|
|
22
|
+
const NESTED_TOOL_NAMES = ["Agent", "get_subagent_result", "steer_subagent"];
|
|
23
|
+
function textResult(text, isError = false) {
|
|
24
|
+
return { content: [{ type: "text", text }], isError, details: {} };
|
|
25
|
+
}
|
|
26
|
+
function ownsRecord(record, parentAgentId) {
|
|
27
|
+
return record?.parentAgentId === parentAgentId;
|
|
28
|
+
}
|
|
29
|
+
function formatRecord(record, position) {
|
|
30
|
+
if (record.status === "error") {
|
|
31
|
+
return `Agent failed: ${record.error ?? "unknown error"}${partialOutputSuffix(record)}`;
|
|
32
|
+
}
|
|
33
|
+
if (record.status === "queued" || record.status === "running") {
|
|
34
|
+
return `Agent ${record.id} is ${record.status}.`;
|
|
35
|
+
}
|
|
36
|
+
// A truncated run must not read as a finished one. The top-level path carries
|
|
37
|
+
// this in its result headline; a nested result has no headline, so the note
|
|
38
|
+
// leads — appended, it would look like part of the child's own output.
|
|
39
|
+
const text = record.result?.trim() || record.error?.trim() || "No output.";
|
|
40
|
+
const note = position === "inline"
|
|
41
|
+
? getForegroundOutcomeNote(record.status)
|
|
42
|
+
: getStatusNote(record.status);
|
|
43
|
+
return note ? `Nested agent${note}.\n\n${text}` : text;
|
|
44
|
+
}
|
|
45
|
+
/** Build child-safe orchestration tools scoped to one parent agent instance. */
|
|
46
|
+
export function createNestedSubagentTools(context) {
|
|
47
|
+
// Agents resolve from a registry built for THIS branch's config root (under
|
|
48
|
+
// worktree isolation, the copy). Never via registerAgents — that is
|
|
49
|
+
// process-global state shared with the main session and every other agent.
|
|
50
|
+
const loadRegistry = () => buildAgentRegistry(loadCustomAgents(context.configCwd));
|
|
51
|
+
const allowedTypesIn = (registry) => context.allowedSubagents === "all"
|
|
52
|
+
? undefined
|
|
53
|
+
: new Set(context.allowedSubagents.map(name => resolveTypeIn(registry, name) ?? name));
|
|
54
|
+
const availableIn = (registry) => {
|
|
55
|
+
const allowed = allowedTypesIn(registry);
|
|
56
|
+
return getAvailableTypesIn(registry).filter(name => allowed === undefined || allowed.has(name));
|
|
57
|
+
};
|
|
58
|
+
const agentTool = defineTool({
|
|
59
|
+
name: NESTED_TOOL_NAMES[0],
|
|
60
|
+
label: "Agent",
|
|
61
|
+
description: "Launch a child-safe nested subagent for bounded delegated work. " +
|
|
62
|
+
"Only use agent types allowed by this parent agent; nesting is depth-limited.",
|
|
63
|
+
parameters: Type.Object({
|
|
64
|
+
prompt: Type.String({ description: "Self-contained task for the nested agent." }),
|
|
65
|
+
description: Type.String({ description: "Short 3-5 word task description." }),
|
|
66
|
+
subagent_type: Type.String({ description: `Allowed nested agent type. Available: ${availableIn(loadRegistry()).join(", ") || "none"}.` }),
|
|
67
|
+
model: Type.Optional(Type.String({ description: "Optional provider/model override." })),
|
|
68
|
+
thinking: Type.Optional(Type.String({ description: "Optional thinking level." })),
|
|
69
|
+
max_turns: Type.Optional(Type.Number({ minimum: 1 })),
|
|
70
|
+
run_in_background: Type.Optional(Type.Boolean({
|
|
71
|
+
description: "Defaults to false for nested spawns — the call blocks and returns the child's result inline. Set true only for work you will collect later with get_subagent_result; a detached child is stopped when you finish.",
|
|
72
|
+
})),
|
|
73
|
+
resume: Type.Optional(Type.String({ description: "Resume a nested agent owned by this parent." })),
|
|
74
|
+
isolated: Type.Optional(Type.Boolean()),
|
|
75
|
+
inherit_context: Type.Optional(Type.Boolean()),
|
|
76
|
+
...isolationParam(isWorktreeIsolationEnabled()),
|
|
77
|
+
}),
|
|
78
|
+
execute: async (_toolCallId, params, signal, _onUpdate, ctx) => {
|
|
79
|
+
if (params.resume) {
|
|
80
|
+
const existing = context.manager.getRecord(params.resume);
|
|
81
|
+
if (!ownsRecord(existing, context.parentAgentId)) {
|
|
82
|
+
return textResult(`Nested agent not found or not owned by this parent: "${params.resume}".`, true);
|
|
83
|
+
}
|
|
84
|
+
// Frontmatter authoritative, as on the spawn path; the manager falls
|
|
85
|
+
// back to the limit the child was spawned with, then the default.
|
|
86
|
+
const resumed = await context.manager.resume(params.resume, params.prompt, signal, {
|
|
87
|
+
maxTurns: getAgentConfigIn(loadRegistry(), existing.type)?.maxTurns ?? params.max_turns,
|
|
88
|
+
});
|
|
89
|
+
return resumed
|
|
90
|
+
? textResult(formatRecord(resumed, "inline"), resumed.status === "error")
|
|
91
|
+
: textResult(`Failed to resume nested agent "${params.resume}".`, true);
|
|
92
|
+
}
|
|
93
|
+
if (context.depth >= context.maxSubagentDepth) {
|
|
94
|
+
return textResult(`Nested subagent call blocked (depth=${context.depth}, max=${context.maxSubagentDepth}). Complete the task directly.`, true);
|
|
95
|
+
}
|
|
96
|
+
// Reloaded per call so new agent files are picked up without a restart.
|
|
97
|
+
const registry = loadRegistry();
|
|
98
|
+
const rawType = params.subagent_type;
|
|
99
|
+
// Strict resolve, never the fallback policy: a project-level
|
|
100
|
+
// `fallbackSubagent` must not hand a nested caller an agent its allowlist
|
|
101
|
+
// never named. The list stays allowlist-filtered so a typo can't enumerate
|
|
102
|
+
// agents this parent may not reach.
|
|
103
|
+
const resolvedType = resolveEnabledTypeIn(registry, rawType);
|
|
104
|
+
if (resolvedType === undefined) {
|
|
105
|
+
return textResult(`Unknown or disabled nested agent type: "${rawType}". Allowed: ${availableIn(registry).join(", ") || "none"}.`, true);
|
|
106
|
+
}
|
|
107
|
+
const allowed = allowedTypesIn(registry);
|
|
108
|
+
if (allowed !== undefined && !allowed.has(resolvedType)) {
|
|
109
|
+
return textResult(`Nested agent type "${resolvedType}" is not allowed for this parent. Allowed: ${[...allowed].join(", ")}.`, true);
|
|
110
|
+
}
|
|
111
|
+
const config = getAgentConfigIn(registry, resolvedType);
|
|
112
|
+
// Foreground regardless of `backgroundByDefault` — see the reasoning on
|
|
113
|
+
// ResolveOptions. An explicit `true` here still opts in.
|
|
114
|
+
const invocation = resolveAgentInvocationConfig(config, params, {
|
|
115
|
+
worktreeAllowed: isWorktreeIsolationEnabled(),
|
|
116
|
+
defaultRunInBackground: false,
|
|
117
|
+
});
|
|
118
|
+
let model = ctx.model;
|
|
119
|
+
if (invocation.modelInput) {
|
|
120
|
+
const resolvedModel = resolveModel(invocation.modelInput, ctx.modelRegistry);
|
|
121
|
+
if (typeof resolvedModel === "string") {
|
|
122
|
+
if (invocation.modelFromParams)
|
|
123
|
+
return textResult(resolvedModel, true);
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
model = resolvedModel;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
// Same scopeModels policy as the top-level Agent tool — a nested spawn
|
|
130
|
+
// must not escape the allowlist. A "warn" verdict proceeds silently:
|
|
131
|
+
// child sessions have no UI surface to toast to.
|
|
132
|
+
const scopeVerdict = checkModelScope({
|
|
133
|
+
model,
|
|
134
|
+
cwd: context.configCwd,
|
|
135
|
+
modelRegistry: ctx.modelRegistry,
|
|
136
|
+
callerSupplied: invocation.modelFromParams,
|
|
137
|
+
agentLabel: config?.displayName ?? resolvedType,
|
|
138
|
+
modelInput: invocation.modelInput,
|
|
139
|
+
});
|
|
140
|
+
if (scopeVerdict.kind === "error")
|
|
141
|
+
return textResult(scopeVerdict.message, true);
|
|
142
|
+
// The whole branch shares the root session's transcript directory; read it
|
|
143
|
+
// off the owning parent rather than this child session's own id.
|
|
144
|
+
const rootSessionId = context.manager.getRecord(context.parentAgentId)?.rootSessionId;
|
|
145
|
+
const childDepth = context.depth + 1;
|
|
146
|
+
const options = {
|
|
147
|
+
description: params.description,
|
|
148
|
+
model,
|
|
149
|
+
maxTurns: invocation.maxTurns,
|
|
150
|
+
isolated: invocation.isolated,
|
|
151
|
+
inheritContext: invocation.inheritContext,
|
|
152
|
+
thinkingLevel: invocation.thinking,
|
|
153
|
+
isolation: invocation.isolation,
|
|
154
|
+
invocation: {
|
|
155
|
+
thinking: invocation.thinking,
|
|
156
|
+
maxTurns: invocation.maxTurns,
|
|
157
|
+
isolated: invocation.isolated,
|
|
158
|
+
inheritContext: invocation.inheritContext,
|
|
159
|
+
runInBackground: invocation.runInBackground,
|
|
160
|
+
isolation: invocation.isolation,
|
|
161
|
+
},
|
|
162
|
+
// Nested children are hidden from every reporting surface, so their spend
|
|
163
|
+
// would otherwise be unattributable. Fold it into every ancestor's record:
|
|
164
|
+
// the top-level one appears in lifecycle events, completion notifications,
|
|
165
|
+
// and `/agents`, and those all read `lifetimeUsage`. The whole chain is
|
|
166
|
+
// walked, not just the immediate parent — a spawn callback only fires for
|
|
167
|
+
// that child's OWN turns, so stopping at one level would hide a
|
|
168
|
+
// great-grandchild from the only record anyone can see. (The live
|
|
169
|
+
// widget/fleet counters read their own per-agent activity tracker, which
|
|
170
|
+
// still sees only the top-level agent's own turns.)
|
|
171
|
+
onAssistantUsage: (usage) => {
|
|
172
|
+
for (let id = context.parentAgentId; id !== undefined;) {
|
|
173
|
+
const ancestor = context.manager.getRecord(id);
|
|
174
|
+
if (!ancestor)
|
|
175
|
+
break;
|
|
176
|
+
addUsage(ancestor.lifetimeUsage, usage);
|
|
177
|
+
id = ancestor.parentAgentId;
|
|
178
|
+
}
|
|
179
|
+
},
|
|
180
|
+
depth: childDepth,
|
|
181
|
+
parentAgentId: context.parentAgentId,
|
|
182
|
+
maxSubagentDepth: context.maxSubagentDepth,
|
|
183
|
+
configCwd: context.configCwd,
|
|
184
|
+
rootSessionId,
|
|
185
|
+
};
|
|
186
|
+
// Transcript wiring, same gate as the top-level path: the child's
|
|
187
|
+
// `output_transcript` frontmatter wins, else the project default. Without
|
|
188
|
+
// it a nested run leaves no artifact but the string it returned — the
|
|
189
|
+
// parent's own transcript records the call and the answer, never the tool
|
|
190
|
+
// calls in between, which is exactly what a misbehaving child needs to
|
|
191
|
+
// explain itself. Filed under the ROOT session and this branch's config
|
|
192
|
+
// root, so a nested transcript lands in the same `tasks/` directory as its
|
|
193
|
+
// ancestors' rather than in a directory of its own.
|
|
194
|
+
const transcriptSessionId = rootSessionId !== undefined && (config?.outputTranscript ?? getOutputTranscriptDefault())
|
|
195
|
+
? rootSessionId
|
|
196
|
+
: undefined;
|
|
197
|
+
let childId;
|
|
198
|
+
const attachTranscript = (id) => {
|
|
199
|
+
childId = id;
|
|
200
|
+
if (transcriptSessionId === undefined)
|
|
201
|
+
return;
|
|
202
|
+
const rec = context.manager.getRecord(id);
|
|
203
|
+
if (!rec)
|
|
204
|
+
return;
|
|
205
|
+
rec.outputFile = createOutputFilePath(context.configCwd, id, transcriptSessionId);
|
|
206
|
+
writeInitialEntry(rec.outputFile, id, params.prompt, ctx.cwd);
|
|
207
|
+
};
|
|
208
|
+
options.onSessionCreated = (session) => {
|
|
209
|
+
const rec = childId === undefined ? undefined : context.manager.getRecord(childId);
|
|
210
|
+
if (rec?.outputFile && childId !== undefined) {
|
|
211
|
+
rec.outputCleanup = streamToOutputFile(session, rec.outputFile, childId, ctx.cwd);
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
// `ctx` is forwarded to the manager unmodified, never captured at tool-build
|
|
215
|
+
// time: each AgentSession builds its own ExtensionRunner from that session's
|
|
216
|
+
// cwd/sessionManager/modelRegistry, so this is the CHILD's context. Capturing
|
|
217
|
+
// one earlier would silently give a grandchild the wrong worktree base, the
|
|
218
|
+
// wrong conversation under inherit_context, and the wrong inherited model.
|
|
219
|
+
//
|
|
220
|
+
// spawn() throws on strict worktree-isolation failure and cwd validation —
|
|
221
|
+
// report it as a tool error, like the top-level Agent tool does, instead of
|
|
222
|
+
// letting it escape into the child's turn.
|
|
223
|
+
try {
|
|
224
|
+
if (invocation.runInBackground) {
|
|
225
|
+
const id = context.manager.spawn(context.pi, ctx, resolvedType, params.prompt, {
|
|
226
|
+
...options,
|
|
227
|
+
isBackground: true,
|
|
228
|
+
});
|
|
229
|
+
// Synchronous, before the event loop yields — onSessionCreated fires
|
|
230
|
+
// asynchronously inside runAgent, so the file is attached in time.
|
|
231
|
+
attachTranscript(id);
|
|
232
|
+
// Worktree isolation starts the agent asynchronously; surface its
|
|
233
|
+
// failure as a tool error, like the synchronous throw used to.
|
|
234
|
+
await context.manager.awaitStartup(id);
|
|
235
|
+
return textResult(`Nested agent started in background. Agent ID: ${id}`);
|
|
236
|
+
}
|
|
237
|
+
const { record } = await context.manager.spawnAndWait(context.pi, ctx, resolvedType, params.prompt, { ...options, signal }, attachTranscript);
|
|
238
|
+
return textResult(formatRecord(record, "inline"), record.status === "error");
|
|
239
|
+
}
|
|
240
|
+
catch (err) {
|
|
241
|
+
return textResult(err instanceof Error ? err.message : String(err), true);
|
|
242
|
+
}
|
|
243
|
+
},
|
|
244
|
+
});
|
|
245
|
+
const resultTool = defineTool({
|
|
246
|
+
name: NESTED_TOOL_NAMES[1],
|
|
247
|
+
label: "Get Nested Agent Result",
|
|
248
|
+
description: "Check or wait for a background nested agent owned by this parent.",
|
|
249
|
+
parameters: Type.Object({
|
|
250
|
+
agent_id: Type.String(),
|
|
251
|
+
wait: Type.Optional(Type.Boolean()),
|
|
252
|
+
}),
|
|
253
|
+
execute: async (_toolCallId, params, signal) => {
|
|
254
|
+
const record = context.manager.getRecord(params.agent_id);
|
|
255
|
+
if (!ownsRecord(record, context.parentAgentId)) {
|
|
256
|
+
return textResult(`Nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
|
|
257
|
+
}
|
|
258
|
+
// Wait for completion if requested. Cancellation (e.g. the parent's tool
|
|
259
|
+
// call is aborted) stops only this wait; the nested child keeps running and
|
|
260
|
+
// stays unconsumed. Queued records have no promise until the manager starts
|
|
261
|
+
// them, so poll — abortably — until they leave the queue, then await.
|
|
262
|
+
if (params.wait && (record.status === "queued" || record.status === "running")) {
|
|
263
|
+
while (record.status === "queued") {
|
|
264
|
+
await abortable(new Promise(resolve => setTimeout(resolve, 250)), signal);
|
|
265
|
+
}
|
|
266
|
+
if (record.promise)
|
|
267
|
+
await abortable(record.promise, signal);
|
|
268
|
+
}
|
|
269
|
+
return textResult(formatRecord(record, "fetched"), record.status === "error");
|
|
270
|
+
},
|
|
271
|
+
});
|
|
272
|
+
const steerTool = defineTool({
|
|
273
|
+
name: NESTED_TOOL_NAMES[2],
|
|
274
|
+
label: "Steer Nested Agent",
|
|
275
|
+
description: "Send guidance to a running nested agent owned by this parent.",
|
|
276
|
+
parameters: Type.Object({
|
|
277
|
+
agent_id: Type.String(),
|
|
278
|
+
message: Type.String(),
|
|
279
|
+
}),
|
|
280
|
+
execute: async (_toolCallId, params) => {
|
|
281
|
+
const record = context.manager.getRecord(params.agent_id);
|
|
282
|
+
if (!ownsRecord(record, context.parentAgentId) || record.status !== "running") {
|
|
283
|
+
return textResult(`Running nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
|
|
284
|
+
}
|
|
285
|
+
// Session not ready yet — queue the steer. The manager flushes pending
|
|
286
|
+
// steers when the session is created (same contract as the top-level tool).
|
|
287
|
+
if (!record.session) {
|
|
288
|
+
if (!record.pendingSteers)
|
|
289
|
+
record.pendingSteers = [];
|
|
290
|
+
record.pendingSteers.push(params.message);
|
|
291
|
+
return textResult(`Steering message queued for nested agent ${params.agent_id}.`);
|
|
292
|
+
}
|
|
293
|
+
try {
|
|
294
|
+
await record.session.steer(params.message);
|
|
295
|
+
}
|
|
296
|
+
catch (err) {
|
|
297
|
+
return textResult(`Failed to steer nested agent: ${err instanceof Error ? err.message : String(err)}`, true);
|
|
298
|
+
}
|
|
299
|
+
return textResult(`Steering message sent to nested agent ${params.agent_id}.`);
|
|
300
|
+
},
|
|
301
|
+
});
|
|
302
|
+
return [agentTool, resultTool, steerTool];
|
|
303
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
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
|
+
import type { AgentSession } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
export declare function getOutputTranscriptDefault(): boolean;
|
|
9
|
+
export declare function setOutputTranscriptDefault(b: boolean): void;
|
|
10
|
+
/**
|
|
11
|
+
* Encode a cwd path as a filesystem-safe directory name. Handles:
|
|
12
|
+
* - POSIX: "/home/user/project" → "home-user-project"
|
|
13
|
+
* - Windows: "C:\Users\foo\project" → "Users-foo-project"
|
|
14
|
+
* - UNC: "\\\\server\\share\\project" → "server-share-project"
|
|
15
|
+
*/
|
|
16
|
+
export declare function encodeCwd(cwd: string): string;
|
|
17
|
+
/**
|
|
18
|
+
* The per-session scratch directory, created if missing.
|
|
19
|
+
* Mirrors Claude Code's layout: /tmp/{prefix}-{uid}/{encoded-cwd}/{sessionId}/tasks
|
|
20
|
+
*
|
|
21
|
+
* Shared with the workflow tool, which persists each invocation's script here so
|
|
22
|
+
* iterating on one is edit-file-then-rerun — the same convention, one directory.
|
|
23
|
+
*/
|
|
24
|
+
export declare function sessionTaskDir(cwd: string, sessionId: string): string;
|
|
25
|
+
/** Create the output file path, ensuring the directory exists. */
|
|
26
|
+
export declare function createOutputFilePath(cwd: string, agentId: string, sessionId: string): string;
|
|
27
|
+
/**
|
|
28
|
+
* Ensure a transcript file exists without disturbing what is already in it.
|
|
29
|
+
*
|
|
30
|
+
* A resume reuses the agent's existing transcript (same deterministic path), so
|
|
31
|
+
* it must never call `writeInitialEntry` — that truncates, discarding turns the
|
|
32
|
+
* completion notification still points the user at, and any history the session
|
|
33
|
+
* has since compacted away is gone for good. Appending nothing creates the file
|
|
34
|
+
* when this is the agent's first transcript and is a no-op when it is not.
|
|
35
|
+
*/
|
|
36
|
+
export declare function ensureOutputFile(path: string): void;
|
|
37
|
+
/** Write the initial user prompt entry. */
|
|
38
|
+
export declare function writeInitialEntry(path: string, agentId: string, prompt: string, cwd: string): void;
|
|
39
|
+
/**
|
|
40
|
+
* Subscribe to session events and flush new messages to the output file on each turn_end.
|
|
41
|
+
* Returns a cleanup function that does a final flush and unsubscribes.
|
|
42
|
+
*/
|
|
43
|
+
export declare function streamToOutputFile(session: AgentSession, path: string, agentId: string, cwd: string, startIndex?: number): () => void;
|
|
@@ -0,0 +1,153 @@
|
|
|
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
|
+
import { appendFileSync, chmodSync, mkdirSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { tmpdir } from "node:os";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
/**
|
|
11
|
+
* Project/global default for writing a subagent's `.output` transcript; a custom
|
|
12
|
+
* agent's `output_transcript` overrides it per agent.
|
|
13
|
+
*
|
|
14
|
+
* State lives here rather than in an index.ts closure because both spawn paths
|
|
15
|
+
* need it — the top-level Agent tool and the nested delegation tools. Same
|
|
16
|
+
* reason `scopeModels` lives in model-scope.ts: a setting only one path can read
|
|
17
|
+
* is a setting the other path silently ignores.
|
|
18
|
+
*/
|
|
19
|
+
let outputTranscriptDefault = true;
|
|
20
|
+
export function getOutputTranscriptDefault() { return outputTranscriptDefault; }
|
|
21
|
+
export function setOutputTranscriptDefault(b) { outputTranscriptDefault = b; }
|
|
22
|
+
/**
|
|
23
|
+
* Encode a cwd path as a filesystem-safe directory name. Handles:
|
|
24
|
+
* - POSIX: "/home/user/project" → "home-user-project"
|
|
25
|
+
* - Windows: "C:\Users\foo\project" → "Users-foo-project"
|
|
26
|
+
* - UNC: "\\\\server\\share\\project" → "server-share-project"
|
|
27
|
+
*/
|
|
28
|
+
export function encodeCwd(cwd) {
|
|
29
|
+
return cwd
|
|
30
|
+
.replace(/[/\\]/g, "-") // both separators → dash
|
|
31
|
+
.replace(/^[A-Za-z]:-/, "") // strip Windows drive prefix ("C:-")
|
|
32
|
+
.replace(/^-+/, ""); // strip leading dashes (POSIX root, UNC)
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The per-session scratch directory, created if missing.
|
|
36
|
+
* Mirrors Claude Code's layout: /tmp/{prefix}-{uid}/{encoded-cwd}/{sessionId}/tasks
|
|
37
|
+
*
|
|
38
|
+
* Shared with the workflow tool, which persists each invocation's script here so
|
|
39
|
+
* iterating on one is edit-file-then-rerun — the same convention, one directory.
|
|
40
|
+
*/
|
|
41
|
+
export function sessionTaskDir(cwd, sessionId) {
|
|
42
|
+
const encoded = encodeCwd(cwd);
|
|
43
|
+
const root = join(tmpdir(), `pi-subagents-${process.getuid?.() ?? 0}`);
|
|
44
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
45
|
+
// chmod is a no-op on Windows and throws on some Windows filesystems.
|
|
46
|
+
// On Unix we still want to enforce 0o700 past umask, so only swallow on Windows.
|
|
47
|
+
try {
|
|
48
|
+
chmodSync(root, 0o700);
|
|
49
|
+
}
|
|
50
|
+
catch (err) {
|
|
51
|
+
if (process.platform !== "win32")
|
|
52
|
+
throw err;
|
|
53
|
+
}
|
|
54
|
+
const dir = join(root, encoded, sessionId, "tasks");
|
|
55
|
+
mkdirSync(dir, { recursive: true });
|
|
56
|
+
return dir;
|
|
57
|
+
}
|
|
58
|
+
/** Create the output file path, ensuring the directory exists. */
|
|
59
|
+
export function createOutputFilePath(cwd, agentId, sessionId) {
|
|
60
|
+
return join(sessionTaskDir(cwd, sessionId), `${agentId}.output`);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Ensure a transcript file exists without disturbing what is already in it.
|
|
64
|
+
*
|
|
65
|
+
* A resume reuses the agent's existing transcript (same deterministic path), so
|
|
66
|
+
* it must never call `writeInitialEntry` — that truncates, discarding turns the
|
|
67
|
+
* completion notification still points the user at, and any history the session
|
|
68
|
+
* has since compacted away is gone for good. Appending nothing creates the file
|
|
69
|
+
* when this is the agent's first transcript and is a no-op when it is not.
|
|
70
|
+
*/
|
|
71
|
+
export function ensureOutputFile(path) {
|
|
72
|
+
try {
|
|
73
|
+
appendFileSync(path, "", "utf-8");
|
|
74
|
+
}
|
|
75
|
+
catch { /* ignore — streaming writes are best-effort too */ }
|
|
76
|
+
}
|
|
77
|
+
/** Write the initial user prompt entry. */
|
|
78
|
+
export function writeInitialEntry(path, agentId, prompt, cwd) {
|
|
79
|
+
const entry = {
|
|
80
|
+
isSidechain: true,
|
|
81
|
+
agentId,
|
|
82
|
+
type: "user",
|
|
83
|
+
message: { role: "user", content: prompt },
|
|
84
|
+
timestamp: new Date().toISOString(),
|
|
85
|
+
cwd,
|
|
86
|
+
};
|
|
87
|
+
writeFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Subscribe to session events and flush new messages to the output file on each turn_end.
|
|
91
|
+
* Returns a cleanup function that does a final flush and unsubscribes.
|
|
92
|
+
*/
|
|
93
|
+
export function streamToOutputFile(session, path, agentId, cwd, startIndex) {
|
|
94
|
+
// Index of the first message this stream is responsible for. A resume hands
|
|
95
|
+
// in the session's length as of just before the run: the session already
|
|
96
|
+
// holds every prior turn, and re-emitting those would duplicate history that
|
|
97
|
+
// is already in the file. A spawn has already written its prompt as the
|
|
98
|
+
// initial entry, so it starts after the first user message — found on the
|
|
99
|
+
// first flush, because pi puts a system message ahead of it and adds both
|
|
100
|
+
// only once the prompt runs.
|
|
101
|
+
let writtenCount = startIndex;
|
|
102
|
+
const flush = () => {
|
|
103
|
+
const messages = session.messages;
|
|
104
|
+
if (writtenCount === undefined) {
|
|
105
|
+
const prompt = messages.findIndex((m) => m.role === "user");
|
|
106
|
+
if (prompt === -1)
|
|
107
|
+
return;
|
|
108
|
+
writtenCount = prompt + 1;
|
|
109
|
+
}
|
|
110
|
+
while (writtenCount < messages.length) {
|
|
111
|
+
const msg = messages[writtenCount++];
|
|
112
|
+
// Pi's prompt and tool-loadout records; a Claude Code transcript has no
|
|
113
|
+
// such entry.
|
|
114
|
+
if (msg.role === "system")
|
|
115
|
+
continue;
|
|
116
|
+
const entry = {
|
|
117
|
+
isSidechain: true,
|
|
118
|
+
agentId,
|
|
119
|
+
type: msg.role === "assistant" ? "assistant" : msg.role === "user" ? "user" : "toolResult",
|
|
120
|
+
message: msg,
|
|
121
|
+
timestamp: new Date().toISOString(),
|
|
122
|
+
cwd,
|
|
123
|
+
};
|
|
124
|
+
try {
|
|
125
|
+
appendFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
|
|
126
|
+
}
|
|
127
|
+
catch { /* ignore write errors */ }
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
const unsubscribe = session.subscribe((event) => {
|
|
131
|
+
if (event.type === "turn_end")
|
|
132
|
+
flush();
|
|
133
|
+
// Compaction replaces session.messages with a shorter, summarized array,
|
|
134
|
+
// leaving writtenCount past the new end — without re-anchoring, the flush
|
|
135
|
+
// loop would never match again and streaming would halt for good (#145).
|
|
136
|
+
// Flush before it runs so any not-yet-flushed tail still reaches the file,
|
|
137
|
+
// then re-anchor to the rebuilt array once it lands. The re-anchor is
|
|
138
|
+
// deferred a microtask because on the overflow-retry path pi trims the
|
|
139
|
+
// trailing error assistant message AFTER emitting compaction_end —
|
|
140
|
+
// anchoring synchronously would sit one past the trimmed array and skip
|
|
141
|
+
// the first post-compaction message. Aborted/failed compactions leave
|
|
142
|
+
// session.messages untouched, so only successful ones re-anchor.
|
|
143
|
+
if (event.type === "compaction_start")
|
|
144
|
+
flush();
|
|
145
|
+
if (event.type === "compaction_end" && !event.aborted && event.result) {
|
|
146
|
+
queueMicrotask(() => { writtenCount = session.messages.length; });
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
return () => {
|
|
150
|
+
flush();
|
|
151
|
+
unsubscribe();
|
|
152
|
+
};
|
|
153
|
+
}
|