@deathbeam/pi-delegate 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +21 -0
- package/agents/explore.md +17 -0
- package/agents/general.md +15 -0
- package/agents/researcher.md +15 -0
- package/agents/reviewer.md +15 -0
- package/child.ts +248 -0
- package/format.ts +160 -0
- package/index.ts +536 -0
- package/package.json +39 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tomas Slusny
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# @deathbeam/pi-delegate
|
|
2
|
+
|
|
3
|
+
Run focused subagents with `delegate`, `delegate_list`, `delegate_steer`, and `delegate_cancel`.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
# Choose one:
|
|
9
|
+
pi install npm:@deathbeam/pi-delegate # this package
|
|
10
|
+
pi install git:github.com/deathbeam/pi-packages # all four packages
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Development
|
|
14
|
+
|
|
15
|
+
From this package directory:
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npm install
|
|
19
|
+
npm test
|
|
20
|
+
pi install .
|
|
21
|
+
```
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: explore
|
|
3
|
+
description: "Read-only codebase reconnaissance: files, callers, and data flow. Use before editing unfamiliar code."
|
|
4
|
+
tools: read, grep, find, ls
|
|
5
|
+
model: cheap
|
|
6
|
+
thinking: low
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
You are a read-only codebase exploration agent with an isolated context.
|
|
10
|
+
|
|
11
|
+
Trace the flow relevant to the assigned task. Find entry points, callers, important files, existing helpers, and likely risks. Do not modify files.
|
|
12
|
+
|
|
13
|
+
Return a concise report with relevant paths, the data or control flow, findings, and unresolved questions. Prefer evidence from the repository over guesses.
|
|
14
|
+
|
|
15
|
+
Start from the paths, files, or symbols the task names and grow outward; keep searches scoped, and reserve unscoped ones for checking call sites exhaustively. Cite exact paths and line numbers.
|
|
16
|
+
|
|
17
|
+
You have no shell tool: if the task needs shell output (file sizes, git history, test runs), say so once and report what the files themselves show instead of retrying with other tools.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: general
|
|
3
|
+
description: General-purpose agent for multi-step work that would flood the parent context; can inspect, edit, and validate changes.
|
|
4
|
+
tools: read, grep, find, ls, bash, edit, write
|
|
5
|
+
model: balanced
|
|
6
|
+
thinking: high
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
You are a delegated coding agent with an isolated context.
|
|
10
|
+
|
|
11
|
+
Complete the assigned task directly. Inspect the repository before changing it, follow its instructions, keep the diff minimal, and run the smallest useful validation before finishing.
|
|
12
|
+
|
|
13
|
+
The task is authoritative; do not assume you can see the parent conversation. Report what you changed, what you checked, and any remaining uncertainty.
|
|
14
|
+
|
|
15
|
+
If the task expected code or file edits and you made none, do not report success: make the edits or say plainly what blocked you. Do not end your response with a question you could have answered yourself.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: researcher
|
|
3
|
+
description: Web research with cited sources. Use when the answer needs external docs, versions, or current facts.
|
|
4
|
+
tools: read, web_search, web_fetch
|
|
5
|
+
model: balanced
|
|
6
|
+
thinking: medium
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
You are a focused web research agent with an isolated context.
|
|
10
|
+
|
|
11
|
+
Research the assigned question using primary, official, or otherwise authoritative sources. Use search to discover sources, then fetch important pages instead of relying only on search snippets. Distinguish direct evidence from inference and include URLs for material claims.
|
|
12
|
+
|
|
13
|
+
Return a concise answer with a summary, findings, sources, contradictions, and important missing evidence. Never invent citations or unsupported precision.
|
|
14
|
+
|
|
15
|
+
If the first pass leaves a decision-relevant gap, run one tighter follow-up search, then report what is still unknown and stop.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: reviewer
|
|
3
|
+
description: Independent review of a diff, plan, or finished change. Use before claiming work is done.
|
|
4
|
+
tools: read, grep, find, ls, bash
|
|
5
|
+
model: strong
|
|
6
|
+
thinking: high
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
You are a skeptical code reviewer with an isolated context.
|
|
10
|
+
|
|
11
|
+
Inspect the assigned change and enough surrounding code to understand its real behavior. Look for correctness bugs, edge cases, regressions, missing validation or tests, security issues, and unnecessary complexity. Do not modify files.
|
|
12
|
+
|
|
13
|
+
Report only actionable findings, ordered by severity, with precise file and line references. If there are no findings, say what you checked and why it appears sound.
|
|
14
|
+
|
|
15
|
+
Label each finding P0 (blocks the change), P1 (fix before merge), or P2 (note), and end with one verdict line: `Verdict: BLOCK`, `Verdict: OK`, or `Verdict: OK with notes`. When nothing qualifies, say exactly `No issues found.` and list what you checked.
|
package/child.ts
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import type { ChildProcessWithoutNullStreams } from "node:child_process";
|
|
2
|
+
import { limitOutput, resultPreview, toolCallDetail } from "./format.ts";
|
|
3
|
+
|
|
4
|
+
type Child = ChildProcessWithoutNullStreams;
|
|
5
|
+
|
|
6
|
+
function usageTokens(usage: any): number | undefined {
|
|
7
|
+
if (!usage) return undefined;
|
|
8
|
+
const tokens = usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
|
|
9
|
+
return tokens > 0 ? tokens : undefined;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export type ChildUpdate = {
|
|
13
|
+
toolCalls?: number;
|
|
14
|
+
lastTool?: string;
|
|
15
|
+
lastDetail?: string;
|
|
16
|
+
lastResult?: string;
|
|
17
|
+
contextTokens?: number;
|
|
18
|
+
};
|
|
19
|
+
export type ChildUpdateHandler = (update: ChildUpdate) => void;
|
|
20
|
+
|
|
21
|
+
type ChildRun = {
|
|
22
|
+
done: Promise<string>;
|
|
23
|
+
steer: (message: string) => Promise<void>;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** Run one RPC child, keeping its writer serialized so backpressure and EPIPE reach the caller. */
|
|
27
|
+
export function runChild(
|
|
28
|
+
child: Child,
|
|
29
|
+
task: string,
|
|
30
|
+
signal: AbortSignal | undefined,
|
|
31
|
+
onUpdate?: ChildUpdateHandler,
|
|
32
|
+
): ChildRun {
|
|
33
|
+
let buffer = "";
|
|
34
|
+
let liveText = "";
|
|
35
|
+
let toolCalls = 0;
|
|
36
|
+
let stderr = "";
|
|
37
|
+
let childError: string | undefined;
|
|
38
|
+
let childFailure: Error | undefined;
|
|
39
|
+
let aborted = false;
|
|
40
|
+
let settled = false;
|
|
41
|
+
let finishing = false;
|
|
42
|
+
let requestId = 0;
|
|
43
|
+
let writeQueue = Promise.resolve();
|
|
44
|
+
const pending = new Map<
|
|
45
|
+
string,
|
|
46
|
+
{ command: string; resolve: () => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }
|
|
47
|
+
>();
|
|
48
|
+
let send!: (command: Record<string, unknown>) => Promise<void>;
|
|
49
|
+
|
|
50
|
+
const done = new Promise<string>((resolveChild, reject) => {
|
|
51
|
+
const rejectPending = (error: Error) => {
|
|
52
|
+
for (const request of pending.values()) {
|
|
53
|
+
clearTimeout(request.timer);
|
|
54
|
+
request.reject(error);
|
|
55
|
+
}
|
|
56
|
+
pending.clear();
|
|
57
|
+
};
|
|
58
|
+
const finish = (code: number | null, error?: Error) => {
|
|
59
|
+
if (settled || finishing) return;
|
|
60
|
+
finishing = true;
|
|
61
|
+
if (buffer) {
|
|
62
|
+
const lastLine = buffer;
|
|
63
|
+
buffer = "";
|
|
64
|
+
parse(lastLine);
|
|
65
|
+
}
|
|
66
|
+
settled = true;
|
|
67
|
+
if (!child.stdin.destroyed) child.stdin.end();
|
|
68
|
+
signal?.removeEventListener("abort", abort);
|
|
69
|
+
const result = aborted
|
|
70
|
+
? new Error("Delegated agent was aborted")
|
|
71
|
+
: (error ??
|
|
72
|
+
childFailure ??
|
|
73
|
+
(code !== 0
|
|
74
|
+
? new Error(childError || stderr.trim() || `Child exited with status ${code}`)
|
|
75
|
+
: undefined));
|
|
76
|
+
if (result) {
|
|
77
|
+
rejectPending(result);
|
|
78
|
+
reject(result);
|
|
79
|
+
} else if (childError) {
|
|
80
|
+
rejectPending(new Error(childError));
|
|
81
|
+
reject(new Error(childError));
|
|
82
|
+
} else {
|
|
83
|
+
rejectPending(new Error("Delegated agent finished before acknowledging command"));
|
|
84
|
+
resolveChild(limitOutput(liveText.trim() || "(no output)"));
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
const fail = (error: Error) => {
|
|
88
|
+
if (settled || finishing) return;
|
|
89
|
+
childFailure = error;
|
|
90
|
+
child.kill("SIGTERM");
|
|
91
|
+
finish(null, error);
|
|
92
|
+
};
|
|
93
|
+
const parse = (line: string) => {
|
|
94
|
+
if (!line.trim()) return;
|
|
95
|
+
try {
|
|
96
|
+
const event = JSON.parse(line) as any;
|
|
97
|
+
if (event.type === "response" && typeof event.id === "string" && pending.has(event.id)) {
|
|
98
|
+
const request = pending.get(event.id)!;
|
|
99
|
+
pending.delete(event.id);
|
|
100
|
+
clearTimeout(request.timer);
|
|
101
|
+
if (event.success === true && event.command === request.command) {
|
|
102
|
+
request.resolve();
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
const responseError = new Error(
|
|
106
|
+
event.command === request.command
|
|
107
|
+
? event.error || `Child rejected ${request.command}`
|
|
108
|
+
: `Child returned ${event.command || "unknown"} response for ${request.command}`,
|
|
109
|
+
);
|
|
110
|
+
request.reject(responseError);
|
|
111
|
+
if (request.command === "prompt") childFailure ??= responseError;
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
switch (event.type) {
|
|
115
|
+
case "tool_execution_start":
|
|
116
|
+
toolCalls += 1;
|
|
117
|
+
onUpdate?.({
|
|
118
|
+
toolCalls,
|
|
119
|
+
lastTool: event.toolName,
|
|
120
|
+
lastDetail: toolCallDetail(event.toolName, event.args),
|
|
121
|
+
lastResult: "",
|
|
122
|
+
});
|
|
123
|
+
return;
|
|
124
|
+
case "tool_execution_end":
|
|
125
|
+
onUpdate?.({ lastResult: resultPreview(event.result) });
|
|
126
|
+
return;
|
|
127
|
+
case "message_update": {
|
|
128
|
+
const contextTokens = usageTokens(event.usage);
|
|
129
|
+
const delta =
|
|
130
|
+
event.assistantMessageEvent?.type === "text_delta"
|
|
131
|
+
? (event.assistantMessageEvent.delta ?? "")
|
|
132
|
+
: "";
|
|
133
|
+
if (delta) liveText += delta;
|
|
134
|
+
if (contextTokens !== undefined) onUpdate?.({ contextTokens });
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
case "message_end": {
|
|
138
|
+
if (event.message?.role !== "assistant") return;
|
|
139
|
+
childError = event.message.errorMessage;
|
|
140
|
+
const text =
|
|
141
|
+
event.message.content
|
|
142
|
+
?.filter((part: any) => part.type === "text")
|
|
143
|
+
.map((part: any) => part.text ?? "")
|
|
144
|
+
.join("") ?? "";
|
|
145
|
+
if (text) {
|
|
146
|
+
liveText = text;
|
|
147
|
+
onUpdate?.({ contextTokens: usageTokens(event.message.usage) });
|
|
148
|
+
}
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
case "agent_settled":
|
|
152
|
+
finish(0);
|
|
153
|
+
return;
|
|
154
|
+
case "extension_ui_request":
|
|
155
|
+
if (["select", "confirm", "input", "editor"].includes(event.method)) {
|
|
156
|
+
void enqueue({ type: "extension_ui_response", id: event.id, cancelled: true }).catch(
|
|
157
|
+
(error) => fail(error),
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
return;
|
|
161
|
+
default:
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
} catch {
|
|
165
|
+
// Diagnostics on stdout that are not JSON events; ignore those lines.
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
const enqueue = (command: Record<string, unknown>) => {
|
|
169
|
+
const line = `${JSON.stringify(command)}\n`;
|
|
170
|
+
const write = writeQueue.then(
|
|
171
|
+
() =>
|
|
172
|
+
new Promise<void>((resolveWrite, rejectWrite) => {
|
|
173
|
+
if (settled) return rejectWrite(childFailure ?? new Error("Delegated agent has finished"));
|
|
174
|
+
if (child.stdin.destroyed || !child.stdin.writable) {
|
|
175
|
+
return rejectWrite(new Error("Delegated agent stdin is not writable"));
|
|
176
|
+
}
|
|
177
|
+
child.stdin.write(line, (error) => (error ? rejectWrite(error) : resolveWrite()));
|
|
178
|
+
}),
|
|
179
|
+
);
|
|
180
|
+
writeQueue = write.catch(() => {});
|
|
181
|
+
return write;
|
|
182
|
+
};
|
|
183
|
+
send = (command: Record<string, unknown>) => {
|
|
184
|
+
const id = `delegate_${++requestId}`;
|
|
185
|
+
const response = new Promise<void>((resolveResponse, rejectResponse) => {
|
|
186
|
+
const timer = setTimeout(() => {
|
|
187
|
+
pending.delete(id);
|
|
188
|
+
rejectResponse(new Error(`Timed out waiting for ${command.type} acknowledgement`));
|
|
189
|
+
}, 30_000);
|
|
190
|
+
pending.set(id, {
|
|
191
|
+
command: String(command.type),
|
|
192
|
+
resolve: resolveResponse,
|
|
193
|
+
reject: rejectResponse,
|
|
194
|
+
timer,
|
|
195
|
+
});
|
|
196
|
+
});
|
|
197
|
+
void enqueue({ ...command, id }).catch((error) => {
|
|
198
|
+
const request = pending.get(id);
|
|
199
|
+
if (request) {
|
|
200
|
+
pending.delete(id);
|
|
201
|
+
clearTimeout(request.timer);
|
|
202
|
+
request.reject(error);
|
|
203
|
+
}
|
|
204
|
+
if (!settled && !aborted) fail(error);
|
|
205
|
+
});
|
|
206
|
+
return response;
|
|
207
|
+
};
|
|
208
|
+
const abort = () => {
|
|
209
|
+
if (settled || aborted) return;
|
|
210
|
+
aborted = true;
|
|
211
|
+
void send({ type: "abort" }).catch(() => {});
|
|
212
|
+
setTimeout(() => {
|
|
213
|
+
if (!settled) child.kill("SIGKILL");
|
|
214
|
+
}, 5000).unref();
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
child.stdout.setEncoding("utf8");
|
|
218
|
+
child.stdout.on("data", (chunk: string) => {
|
|
219
|
+
buffer += chunk;
|
|
220
|
+
const lines = buffer.split("\n");
|
|
221
|
+
buffer = lines.pop() ?? "";
|
|
222
|
+
for (const line of lines) parse(line);
|
|
223
|
+
});
|
|
224
|
+
child.stderr.setEncoding("utf8");
|
|
225
|
+
child.stderr.on("data", (chunk: string) => {
|
|
226
|
+
stderr += chunk;
|
|
227
|
+
if (stderr.length > 16 * 1024) stderr = stderr.slice(-16 * 1024);
|
|
228
|
+
});
|
|
229
|
+
child.stdin.on("error", fail);
|
|
230
|
+
child.on("error", fail);
|
|
231
|
+
child.on("close", (code: number | null) => finish(code));
|
|
232
|
+
if (signal?.aborted) {
|
|
233
|
+
aborted = true;
|
|
234
|
+
child.kill("SIGTERM");
|
|
235
|
+
finish(null);
|
|
236
|
+
} else {
|
|
237
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
238
|
+
void send({ type: "prompt", message: task }).catch((error) => {
|
|
239
|
+
if (!settled) fail(error);
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
return {
|
|
245
|
+
done,
|
|
246
|
+
steer: (message) => send({ type: "steer", message }),
|
|
247
|
+
};
|
|
248
|
+
}
|
package/format.ts
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/** UI helpers stay Pi-import-free for the native check; Pi's analogous formatters are private. */
|
|
2
|
+
|
|
3
|
+
export const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
4
|
+
export const SPINNER_INTERVAL_MS = 100;
|
|
5
|
+
/** pi slices extension widgets at ten lines and appends its own truncation note. */
|
|
6
|
+
export const WIDGET_MAX_LINES = 10;
|
|
7
|
+
/** Only a few jobs still fit with their tool-call and tool-result lines: 1 tally + 3×3 lines. */
|
|
8
|
+
const WIDGET_MAX_DETAIL_JOBS = 3;
|
|
9
|
+
/** In bulk, one row per job: 1 tally + 8 rows + 1 "more running" footer. */
|
|
10
|
+
const WIDGET_MAX_JOBS = 8;
|
|
11
|
+
const EXPANDED_PAD = " ";
|
|
12
|
+
const TASK_LABEL = "Task: ";
|
|
13
|
+
|
|
14
|
+
export type ProgressInfo = {
|
|
15
|
+
toolCalls?: number;
|
|
16
|
+
contextTokens?: number;
|
|
17
|
+
contextWindow?: number;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export function formatTokens(count: number): string {
|
|
21
|
+
if (count < 1000) return String(count);
|
|
22
|
+
if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
|
|
23
|
+
if (count < 1000000) return `${Math.round(count / 1000)}k`;
|
|
24
|
+
if (count < 10000000) return `${(count / 1000000).toFixed(1)}M`;
|
|
25
|
+
return `${Math.round(count / 1000000)}M`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function formatDuration(ms: number): string {
|
|
29
|
+
const seconds = Math.max(0, Math.floor(ms / 1000));
|
|
30
|
+
if (seconds < 60) return `${seconds}s`;
|
|
31
|
+
const minutes = Math.floor(seconds / 60);
|
|
32
|
+
if (minutes < 60) return `${minutes}m ${String(seconds % 60).padStart(2, "0")}s`;
|
|
33
|
+
return `${Math.floor(minutes / 60)}h ${String(minutes % 60).padStart(2, "0")}m`;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function progressStats(progress: ProgressInfo, elapsedMs: number): string {
|
|
37
|
+
const parts: string[] = [];
|
|
38
|
+
if (progress.toolCalls) parts.push(`${progress.toolCalls} tool ${progress.toolCalls === 1 ? "call" : "calls"}`);
|
|
39
|
+
if (progress.contextTokens) {
|
|
40
|
+
parts.push(
|
|
41
|
+
progress.contextWindow
|
|
42
|
+
? `${formatTokens(progress.contextTokens)}/${formatTokens(progress.contextWindow)}`
|
|
43
|
+
: formatTokens(progress.contextTokens),
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
parts.push(formatDuration(elapsedMs));
|
|
47
|
+
return parts.join(" · ");
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function toolCallDetail(toolName: string, args: unknown): string {
|
|
51
|
+
const input = (args ?? {}) as Record<string, unknown>;
|
|
52
|
+
const value = (key: string) => (typeof input[key] === "string" ? (input[key] as string).trim() : "");
|
|
53
|
+
const path = value("path") || ".";
|
|
54
|
+
switch (toolName) {
|
|
55
|
+
case "bash":
|
|
56
|
+
case "powershell":
|
|
57
|
+
return value("command").split("\n")[0];
|
|
58
|
+
case "read":
|
|
59
|
+
case "write":
|
|
60
|
+
case "edit":
|
|
61
|
+
return value("file_path") || value("path");
|
|
62
|
+
case "grep":
|
|
63
|
+
return `/${value("pattern")}/ in ${path}`;
|
|
64
|
+
case "find":
|
|
65
|
+
return `${value("pattern")} in ${path}`;
|
|
66
|
+
case "ls":
|
|
67
|
+
return path;
|
|
68
|
+
default:
|
|
69
|
+
return "";
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Align multi-line task details under the Task label. */
|
|
74
|
+
export function launchDetails(info: { task?: string; model?: string; tools: string[] }): string[] {
|
|
75
|
+
const lines = [
|
|
76
|
+
`${EXPANDED_PAD}Model: ${info.model ?? "default"}`,
|
|
77
|
+
`${EXPANDED_PAD}Tools: ${info.tools.join(", ") || "all"}`,
|
|
78
|
+
];
|
|
79
|
+
const task = (info.task ?? "").trim();
|
|
80
|
+
if (task) {
|
|
81
|
+
lines.push(
|
|
82
|
+
...task
|
|
83
|
+
.split("\n")
|
|
84
|
+
.map((line, index) => `${EXPANDED_PAD}${index ? " ".repeat(TASK_LABEL.length) : TASK_LABEL}${line}`),
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
return lines;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export const COLLAPSED_OUTPUT_LINES = 10;
|
|
91
|
+
|
|
92
|
+
/** Close dangling Markdown fences so collapsed previews render correctly. */
|
|
93
|
+
export function outputPreview(text: string, maxLines = COLLAPSED_OUTPUT_LINES): { shown: string[]; hidden: number } {
|
|
94
|
+
const lines = text.trim().split("\n");
|
|
95
|
+
if (lines.length <= maxLines) return { shown: lines, hidden: 0 };
|
|
96
|
+
const shown = lines.slice(0, maxLines);
|
|
97
|
+
if (shown.filter((line) => line.trimStart().startsWith("```")).length % 2 === 1) shown.push("```");
|
|
98
|
+
return { shown, hidden: lines.length - maxLines };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export const MAX_OUTPUT_BYTES = 50 * 1024;
|
|
102
|
+
|
|
103
|
+
/** Cap child output without splitting UTF-8 characters. */
|
|
104
|
+
export function limitOutput(text: string, maxBytes = MAX_OUTPUT_BYTES): string {
|
|
105
|
+
const buffer = Buffer.from(text, "utf8");
|
|
106
|
+
if (buffer.length <= maxBytes) return text;
|
|
107
|
+
let end = maxBytes;
|
|
108
|
+
// Back off any continuation byte so the cut lands on a character boundary.
|
|
109
|
+
while (end > 0 && ((buffer[end] ?? 0) & 0xc0) === 0x80) end -= 1;
|
|
110
|
+
return `${buffer.subarray(0, end).toString("utf8")}\n\n[Output truncated: ${buffer.length - end} bytes omitted.]`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function resultPreview(result: unknown, maxChars = 120): string | undefined {
|
|
114
|
+
const content = (result as { content?: unknown })?.content;
|
|
115
|
+
if (!Array.isArray(content)) return undefined;
|
|
116
|
+
const text = content
|
|
117
|
+
.map((part) => (part as { type?: string; text?: string }) ?? {})
|
|
118
|
+
.filter((part) => part.type === "text" && typeof part.text === "string")
|
|
119
|
+
.map((part) => part.text as string)
|
|
120
|
+
.join("\n");
|
|
121
|
+
const line = text
|
|
122
|
+
.split("\n")
|
|
123
|
+
.find((candidate) => candidate.trim())
|
|
124
|
+
?.trim();
|
|
125
|
+
if (!line) return undefined;
|
|
126
|
+
return line.length > maxChars ? `${line.slice(0, maxChars - 1)}…` : line;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export type DelegateReport = {
|
|
130
|
+
id: string;
|
|
131
|
+
agent: string;
|
|
132
|
+
description: string;
|
|
133
|
+
model?: string;
|
|
134
|
+
toolCalls: number;
|
|
135
|
+
contextTokens?: number;
|
|
136
|
+
contextWindow?: number;
|
|
137
|
+
elapsedMs: number;
|
|
138
|
+
output?: string;
|
|
139
|
+
error?: string;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
export function reportText(report: DelegateReport): string {
|
|
143
|
+
const calls = report.toolCalls
|
|
144
|
+
? ` after ${report.toolCalls} tool ${report.toolCalls === 1 ? "call" : "calls"}`
|
|
145
|
+
: "";
|
|
146
|
+
if (report.error) return `Delegated agent "${report.agent}" (job ${report.id}) failed${calls}: ${report.error}`;
|
|
147
|
+
const output = (report.output ?? "").trim();
|
|
148
|
+
return `Delegated agent "${report.agent}" (job ${report.id}) finished${calls}.${output ? `\n\n${output}` : ""}`;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function jobLine(info: { description?: string } & ProgressInfo, elapsedMs: number): string {
|
|
152
|
+
return [info.description?.trim(), progressStats(info, elapsedMs)].filter(Boolean).join(" · ");
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Omit detail rows in bulk so Pi's ten-line widget cap cannot split jobs. */
|
|
156
|
+
export function widgetJobs<T>(jobs: T[]): { shown: T[]; hidden: number; detail: boolean } {
|
|
157
|
+
const detail = jobs.length <= WIDGET_MAX_DETAIL_JOBS;
|
|
158
|
+
const shown = detail ? jobs : jobs.slice(-WIDGET_MAX_JOBS);
|
|
159
|
+
return { shown, hidden: jobs.length - shown.length, detail };
|
|
160
|
+
}
|
package/index.ts
ADDED
|
@@ -0,0 +1,536 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import {
|
|
9
|
+
CONFIG_DIR_NAME,
|
|
10
|
+
getAgentDir,
|
|
11
|
+
getMarkdownTheme,
|
|
12
|
+
keyHint,
|
|
13
|
+
parseFrontmatter,
|
|
14
|
+
} from "@earendil-works/pi-coding-agent";
|
|
15
|
+
import { Container, Markdown, Text } from "@earendil-works/pi-tui";
|
|
16
|
+
import { Type } from "typebox";
|
|
17
|
+
import {
|
|
18
|
+
COLLAPSED_OUTPUT_LINES,
|
|
19
|
+
type DelegateReport,
|
|
20
|
+
jobLine,
|
|
21
|
+
launchDetails,
|
|
22
|
+
outputPreview,
|
|
23
|
+
progressStats,
|
|
24
|
+
reportText,
|
|
25
|
+
SPINNER_FRAMES,
|
|
26
|
+
SPINNER_INTERVAL_MS,
|
|
27
|
+
widgetJobs,
|
|
28
|
+
} from "./format.ts";
|
|
29
|
+
import { runChild } from "./child.ts";
|
|
30
|
+
|
|
31
|
+
type AgentFile = {
|
|
32
|
+
name: string;
|
|
33
|
+
description: string;
|
|
34
|
+
tools?: string[];
|
|
35
|
+
model?: string;
|
|
36
|
+
thinking?: string;
|
|
37
|
+
prompt: string;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
type DelegateDetails = Pick<DelegateJob, "id" | "agent" | "description" | "task" | "model" | "tools"> & {
|
|
41
|
+
/** True when the child keeps running after the tool returns and reports back as a follow-up message. */
|
|
42
|
+
background: boolean;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
type SteerDetails = Pick<
|
|
46
|
+
DelegateJob,
|
|
47
|
+
"id" | "agent" | "description" | "toolCalls" | "contextTokens" | "contextWindow"
|
|
48
|
+
> & {
|
|
49
|
+
message: string;
|
|
50
|
+
elapsedMs: number;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
type DelegateJob = {
|
|
54
|
+
id: string;
|
|
55
|
+
agent: string;
|
|
56
|
+
description: string;
|
|
57
|
+
task: string;
|
|
58
|
+
model: string;
|
|
59
|
+
tools: string[];
|
|
60
|
+
toolCalls: number;
|
|
61
|
+
lastTool?: string;
|
|
62
|
+
lastDetail?: string;
|
|
63
|
+
lastResult?: string;
|
|
64
|
+
contextTokens?: number;
|
|
65
|
+
contextWindow?: number;
|
|
66
|
+
startedAt: number;
|
|
67
|
+
controller: AbortController;
|
|
68
|
+
/** Set once the child is running; rejects when the child exits or rejects the command. */
|
|
69
|
+
steer?: (message: string) => Promise<void>;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
type DelegateConfig = {
|
|
73
|
+
agentDirs?: unknown;
|
|
74
|
+
models?: Record<string, unknown>;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const DEFAULT_AGENT_DIR = "~/.agents/agents";
|
|
78
|
+
const BUNDLED_AGENT_DIR = fileURLToPath(new URL("./agents", import.meta.url));
|
|
79
|
+
/** Exclude our own tools from children to prevent recursive delegation. */
|
|
80
|
+
const DELEGATION_TOOLS = new Set(["delegate", "delegate_list", "delegate_steer", "delegate_cancel"]);
|
|
81
|
+
const MODEL_TIERS = new Set(["cheap", "balanced", "strong"]);
|
|
82
|
+
const WIDGET_KEY = "delegate";
|
|
83
|
+
const RESULT_MESSAGE = "delegate-result";
|
|
84
|
+
|
|
85
|
+
function expandPath(value: string, cwd: string): string {
|
|
86
|
+
return resolve(cwd, value.replace(/^~(?=\/|$)/, homedir()));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function stringList(value: unknown): string[] {
|
|
90
|
+
const values = Array.isArray(value) ? value : typeof value === "string" ? value.split(",") : [];
|
|
91
|
+
return values
|
|
92
|
+
.filter((item): item is string => typeof item === "string")
|
|
93
|
+
.map((item) => item.trim())
|
|
94
|
+
.filter(Boolean);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function readConfig(path: string): DelegateConfig {
|
|
98
|
+
try {
|
|
99
|
+
const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
|
|
100
|
+
if (!parsed || typeof parsed !== "object") return {};
|
|
101
|
+
const delegate = (parsed as { delegate?: unknown }).delegate;
|
|
102
|
+
return delegate && typeof delegate === "object" ? (delegate as DelegateConfig) : {};
|
|
103
|
+
} catch {
|
|
104
|
+
return {};
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function configFor(cwd: string): DelegateConfig {
|
|
109
|
+
const global = readConfig(join(getAgentDir(), "settings.json"));
|
|
110
|
+
const project = readConfig(join(cwd, CONFIG_DIR_NAME, "settings.json"));
|
|
111
|
+
return {
|
|
112
|
+
agentDirs: [...stringList(global.agentDirs), ...stringList(project.agentDirs)],
|
|
113
|
+
models: { ...(global.models ?? {}), ...(project.models ?? {}) },
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function loadAgents(dir: string): AgentFile[] {
|
|
118
|
+
if (!existsSync(dir)) return [];
|
|
119
|
+
const agents: AgentFile[] = [];
|
|
120
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
121
|
+
if (!entry.name.endsWith(".md") || (!entry.isFile() && !entry.isSymbolicLink())) continue;
|
|
122
|
+
try {
|
|
123
|
+
const { frontmatter, body } = parseFrontmatter<Record<string, unknown>>(
|
|
124
|
+
readFileSync(join(dir, entry.name), "utf8"),
|
|
125
|
+
);
|
|
126
|
+
if (typeof frontmatter.name !== "string" || typeof frontmatter.description !== "string") continue;
|
|
127
|
+
agents.push({
|
|
128
|
+
name: frontmatter.name,
|
|
129
|
+
description: frontmatter.description,
|
|
130
|
+
tools: stringList(frontmatter.tools),
|
|
131
|
+
model: typeof frontmatter.model === "string" ? frontmatter.model : undefined,
|
|
132
|
+
thinking: typeof frontmatter.thinking === "string" ? frontmatter.thinking : undefined,
|
|
133
|
+
prompt: body.trim(),
|
|
134
|
+
});
|
|
135
|
+
} catch {
|
|
136
|
+
// One malformed agent file should not disable delegation.
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return agents;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function discoverAgents(cwd: string, configuredDirs: unknown): AgentFile[] {
|
|
143
|
+
const dirs = [BUNDLED_AGENT_DIR, DEFAULT_AGENT_DIR, ...stringList(configuredDirs)].map((dir) =>
|
|
144
|
+
expandPath(dir, cwd),
|
|
145
|
+
);
|
|
146
|
+
const agents = new Map<string, AgentFile>();
|
|
147
|
+
for (const dir of [...new Set(dirs)]) {
|
|
148
|
+
for (const agent of loadAgents(dir)) agents.set(agent.name, agent);
|
|
149
|
+
}
|
|
150
|
+
return [...agents.values()];
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function resolveModel(
|
|
154
|
+
value: string | undefined,
|
|
155
|
+
models: Record<string, unknown>,
|
|
156
|
+
current: ExtensionContext["model"],
|
|
157
|
+
): string | undefined {
|
|
158
|
+
if (value && !MODEL_TIERS.has(value)) return value;
|
|
159
|
+
const configured = value ? models[value] : undefined;
|
|
160
|
+
if (typeof configured === "string" && configured) return configured;
|
|
161
|
+
return current ? `${current.provider}/${current.id}` : undefined;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function contextWindowFor(ctx: ExtensionContext, model: string | undefined): number | undefined {
|
|
165
|
+
const separator = model?.indexOf("/") ?? -1;
|
|
166
|
+
if (!model || separator < 0) return undefined;
|
|
167
|
+
// Model ids may contain "/" themselves, so only the first one separates provider from id.
|
|
168
|
+
return ctx.modelRegistry.find(model.slice(0, separator), model.slice(separator + 1))?.contextWindow;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export default function (pi: ExtensionAPI) {
|
|
172
|
+
const running = new Map<string, DelegateJob>();
|
|
173
|
+
let finished = 0;
|
|
174
|
+
let ticker: ReturnType<typeof setInterval> | undefined;
|
|
175
|
+
|
|
176
|
+
const refreshWidget = (ctx: ExtensionContext) => {
|
|
177
|
+
if (!ctx.hasUI) return;
|
|
178
|
+
if (running.size === 0) {
|
|
179
|
+
ctx.ui.setWidget(WIDGET_KEY, undefined);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
const theme = ctx.ui.theme;
|
|
183
|
+
const now = Date.now();
|
|
184
|
+
const frame = SPINNER_FRAMES[Math.floor(now / SPINNER_INTERVAL_MS) % SPINNER_FRAMES.length]!;
|
|
185
|
+
const { shown, hidden, detail } = widgetJobs([...running.values()]);
|
|
186
|
+
const lines: string[] = [];
|
|
187
|
+
if (running.size > 1 || finished > 0) {
|
|
188
|
+
const counts = `${running.size} running${finished ? ` · ${finished} done` : ""}`;
|
|
189
|
+
lines.push(`${theme.fg("warning", frame)} ${theme.fg("muted", counts)}`);
|
|
190
|
+
}
|
|
191
|
+
for (const job of shown) {
|
|
192
|
+
lines.push(
|
|
193
|
+
`${theme.fg("warning", frame)} ${theme.fg("toolTitle", theme.bold(job.agent))} ${theme.fg("muted", jobLine(job, now - job.startedAt))}`,
|
|
194
|
+
);
|
|
195
|
+
if (!detail) continue;
|
|
196
|
+
if (job.lastTool)
|
|
197
|
+
lines.push(
|
|
198
|
+
` ${theme.fg("toolTitle", theme.bold(job.lastTool))}${job.lastDetail ? ` ${theme.fg("accent", job.lastDetail)}` : ""}`,
|
|
199
|
+
);
|
|
200
|
+
if (job.lastResult) lines.push(` ${theme.fg("muted", "↳")} ${theme.fg("toolOutput", job.lastResult)}`);
|
|
201
|
+
}
|
|
202
|
+
if (hidden) lines.push(` ${theme.fg("muted", `… ${hidden} more running`)}`);
|
|
203
|
+
ctx.ui.setWidget(WIDGET_KEY, lines);
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
const stopTicker = () => {
|
|
207
|
+
if (ticker) clearInterval(ticker);
|
|
208
|
+
ticker = undefined;
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
const finishJob = (ctx: ExtensionContext, job: DelegateJob, output?: string, error?: string) => {
|
|
212
|
+
// Cancellation was already acknowledged; shutdown has no UI to report into.
|
|
213
|
+
if (job.controller.signal.aborted) return;
|
|
214
|
+
running.delete(job.id);
|
|
215
|
+
finished += 1;
|
|
216
|
+
if (running.size === 0) stopTicker();
|
|
217
|
+
refreshWidget(ctx);
|
|
218
|
+
const report: DelegateReport = {
|
|
219
|
+
id: job.id,
|
|
220
|
+
agent: job.agent,
|
|
221
|
+
description: job.description,
|
|
222
|
+
model: job.model,
|
|
223
|
+
toolCalls: job.toolCalls,
|
|
224
|
+
contextTokens: job.contextTokens,
|
|
225
|
+
contextWindow: job.contextWindow,
|
|
226
|
+
elapsedMs: Date.now() - job.startedAt,
|
|
227
|
+
output,
|
|
228
|
+
error,
|
|
229
|
+
};
|
|
230
|
+
// Idle: this starts a new turn. Streaming: steer the report in at the next turn boundary —
|
|
231
|
+
// a follow-up waits for a run end that a parent stuck polling may never reach.
|
|
232
|
+
pi.sendMessage(
|
|
233
|
+
{ customType: RESULT_MESSAGE, content: reportText(report), display: true, details: report },
|
|
234
|
+
{ triggerTurn: true, deliverAs: "steer" },
|
|
235
|
+
);
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
pi.on("session_shutdown", () => {
|
|
239
|
+
stopTicker();
|
|
240
|
+
for (const job of running.values()) job.controller.abort();
|
|
241
|
+
running.clear();
|
|
242
|
+
finished = 0;
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
pi.on("before_agent_start", (event, ctx) => {
|
|
246
|
+
const agents = discoverAgents(ctx.cwd, configFor(ctx.cwd).agentDirs);
|
|
247
|
+
// pi wraps each section in a tag of the same name, so this content stays untagged.
|
|
248
|
+
event.systemPromptOptions.sections.agents = [
|
|
249
|
+
"Available agents:",
|
|
250
|
+
...agents.map((agent) => `- ${agent.name}: ${agent.description}`),
|
|
251
|
+
"Delegation is authorized here: prefer these agents over doing context-heavy work yourself; they run in parallel with isolated contexts and report back as follow-up messages.",
|
|
252
|
+
].join("\n");
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
pi.registerMessageRenderer(RESULT_MESSAGE, (message, { expanded }, theme) => {
|
|
256
|
+
const report = message.details as DelegateReport | undefined;
|
|
257
|
+
if (!report?.agent) return undefined;
|
|
258
|
+
const icon = report.error ? theme.fg("error", "✗") : theme.fg("success", "✓");
|
|
259
|
+
const container = new Container();
|
|
260
|
+
container.addChild(
|
|
261
|
+
new Text(
|
|
262
|
+
`${icon} ${theme.fg("toolTitle", theme.bold(report.agent))} ${theme.fg("muted", report.description)} ${theme.fg("dim", report.id)} ${theme.fg("muted", progressStats(report, report.elapsedMs))}`,
|
|
263
|
+
0,
|
|
264
|
+
0,
|
|
265
|
+
),
|
|
266
|
+
);
|
|
267
|
+
if (report.error) container.addChild(new Text(theme.fg("error", report.error), 0, 0));
|
|
268
|
+
else if (report.output) {
|
|
269
|
+
const { shown, hidden } = outputPreview(report.output, expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
|
|
270
|
+
container.addChild(new Markdown(shown.join("\n"), 0, 0, getMarkdownTheme()));
|
|
271
|
+
if (hidden > 0)
|
|
272
|
+
container.addChild(
|
|
273
|
+
new Text(
|
|
274
|
+
theme.fg("muted", `… ${hidden} more lines, `) + keyHint("app.tools.expand", "to expand"),
|
|
275
|
+
0,
|
|
276
|
+
0,
|
|
277
|
+
),
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
return container;
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
pi.registerTool({
|
|
284
|
+
name: "delegate",
|
|
285
|
+
label: "Delegate",
|
|
286
|
+
description:
|
|
287
|
+
"Delegate one focused task to a background Pi agent using a named Markdown agent definition. Returns immediately; the agent's result arrives later as a follow-up message. `description` labels the delegation in the transcript; `task` is the full instruction the child receives.",
|
|
288
|
+
promptSnippet: "Delegate a focused task to a background agent; the result arrives later as a follow-up message",
|
|
289
|
+
promptGuidelines: [
|
|
290
|
+
"Delegations run in the background and can run in parallel: call `delegate` and keep working instead of waiting for the result.",
|
|
291
|
+
"Never sleep or poll to wait for a delegate: its completion reaches you on its own. End your turn when your next step needs a result; use delegate_list only for a one-shot status, never as a wait loop.",
|
|
292
|
+
],
|
|
293
|
+
parameters: Type.Object({
|
|
294
|
+
agent: Type.String({ description: "Agent name, one of the agents listed in the <agents> prompt section." }),
|
|
295
|
+
description: Type.String({
|
|
296
|
+
description: "Short 3-8 word summary of this delegation, shown in the transcript.",
|
|
297
|
+
}),
|
|
298
|
+
task: Type.String({ description: "The full instruction the delegated agent receives." }),
|
|
299
|
+
model: Type.Optional(
|
|
300
|
+
Type.String({ description: "Model tier (cheap, balanced, strong) or an explicit provider/model." }),
|
|
301
|
+
),
|
|
302
|
+
}),
|
|
303
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
304
|
+
const config = configFor(ctx.cwd);
|
|
305
|
+
const agents = discoverAgents(ctx.cwd, config.agentDirs);
|
|
306
|
+
const agent = agents.find((candidate) => candidate.name === params.agent);
|
|
307
|
+
if (!agent) {
|
|
308
|
+
const names = agents.map((candidate) => candidate.name).join(", ") || "(none)";
|
|
309
|
+
throw new Error(`Unknown agent "${params.agent}". Available agents: ${names}.`);
|
|
310
|
+
}
|
|
311
|
+
const model = resolveModel(params.model ?? agent.model, config.models ?? {}, ctx.model);
|
|
312
|
+
if (!model) throw new Error(`No model found for "${params.agent}".`);
|
|
313
|
+
const tools = (agent.tools?.length ? agent.tools : pi.getActiveTools()).filter(
|
|
314
|
+
(tool) => !DELEGATION_TOOLS.has(tool),
|
|
315
|
+
);
|
|
316
|
+
const job: DelegateJob = {
|
|
317
|
+
id: randomUUID().slice(0, 8),
|
|
318
|
+
agent: agent.name,
|
|
319
|
+
description: params.description.trim(),
|
|
320
|
+
task: params.task,
|
|
321
|
+
model,
|
|
322
|
+
tools,
|
|
323
|
+
toolCalls: 0,
|
|
324
|
+
startedAt: Date.now(),
|
|
325
|
+
contextWindow: contextWindowFor(ctx, model),
|
|
326
|
+
controller: new AbortController(),
|
|
327
|
+
};
|
|
328
|
+
const details: DelegateDetails = {
|
|
329
|
+
id: job.id,
|
|
330
|
+
agent: job.agent,
|
|
331
|
+
description: job.description,
|
|
332
|
+
task: job.task,
|
|
333
|
+
model,
|
|
334
|
+
tools,
|
|
335
|
+
// Only a UI can deliver a result that arrives after the tool returned; headless runs must block.
|
|
336
|
+
background: ctx.hasUI,
|
|
337
|
+
};
|
|
338
|
+
const args = ["--model", model, "--tools", tools.join(",")];
|
|
339
|
+
const thinking = agent.thinking ?? ctx.thinkingLevel;
|
|
340
|
+
if (thinking) args.push("--thinking", thinking);
|
|
341
|
+
if (agent.prompt) args.push("--append-system-prompt", agent.prompt);
|
|
342
|
+
const child = spawn(process.execPath, [process.argv[1]!, "--mode", "rpc", "--no-session", ...args], {
|
|
343
|
+
cwd: ctx.cwd,
|
|
344
|
+
shell: false,
|
|
345
|
+
stdio: "pipe",
|
|
346
|
+
});
|
|
347
|
+
const run = runChild(child, params.task, details.background ? job.controller.signal : signal, (update) => {
|
|
348
|
+
for (const [key, value] of Object.entries(update)) {
|
|
349
|
+
if (value !== undefined) (job as Record<string, unknown>)[key] = value;
|
|
350
|
+
}
|
|
351
|
+
});
|
|
352
|
+
job.steer = run.steer;
|
|
353
|
+
|
|
354
|
+
if (!details.background) {
|
|
355
|
+
const output = await run.done;
|
|
356
|
+
return { content: [{ type: "text", text: output }], details };
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
running.set(job.id, job);
|
|
360
|
+
if (!ticker) ticker = setInterval(() => refreshWidget(ctx), SPINNER_INTERVAL_MS);
|
|
361
|
+
refreshWidget(ctx);
|
|
362
|
+
// The only failure left here is reporting into a session that is being torn down,
|
|
363
|
+
// and an unhandled rejection would crash pi.
|
|
364
|
+
void run.done
|
|
365
|
+
.then(
|
|
366
|
+
(output) => finishJob(ctx, job, output),
|
|
367
|
+
(error) => finishJob(ctx, job, undefined, error instanceof Error ? error.message : String(error)),
|
|
368
|
+
)
|
|
369
|
+
.catch(() => {});
|
|
370
|
+
return {
|
|
371
|
+
content: [
|
|
372
|
+
{
|
|
373
|
+
type: "text",
|
|
374
|
+
text: `Started agent "${job.agent}" in the background (job ${job.id}). Steer it with delegate_steer or stop it with delegate_cancel. Do not sleep or poll: its report arrives automatically unless cancelled.`,
|
|
375
|
+
},
|
|
376
|
+
],
|
|
377
|
+
details,
|
|
378
|
+
};
|
|
379
|
+
},
|
|
380
|
+
|
|
381
|
+
renderCall(args, theme, context) {
|
|
382
|
+
const summary = args.description?.trim() || args.task?.split("\n")[0]?.trim() || "";
|
|
383
|
+
const hint = `${theme.fg("muted", "(")}${keyHint("app.tools.expand", context.expanded ? "to collapse" : "to expand")}${theme.fg("muted", ")")}`;
|
|
384
|
+
return new Text(
|
|
385
|
+
`${theme.fg("toolTitle", theme.bold("delegate "))}${theme.fg("accent", summary)} ${hint}`,
|
|
386
|
+
0,
|
|
387
|
+
0,
|
|
388
|
+
);
|
|
389
|
+
},
|
|
390
|
+
|
|
391
|
+
renderResult(result, { expanded }, theme, context) {
|
|
392
|
+
const details = result.details as DelegateDetails | undefined;
|
|
393
|
+
const body = result.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n");
|
|
394
|
+
if (!details?.agent) return new Text(body || "(no output)", 0, 0);
|
|
395
|
+
|
|
396
|
+
const icon = context.isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
|
|
397
|
+
const status = details.background ? "started in background" : "completed";
|
|
398
|
+
const container = new Container();
|
|
399
|
+
container.addChild(
|
|
400
|
+
new Text(
|
|
401
|
+
`${icon} ${theme.fg("toolTitle", theme.bold(details.agent))} ${theme.fg("muted", details.description)} ${theme.fg("dim", details.id)} ${theme.fg("dim", status)}`,
|
|
402
|
+
0,
|
|
403
|
+
0,
|
|
404
|
+
),
|
|
405
|
+
);
|
|
406
|
+
if (expanded) container.addChild(new Text(theme.fg("dim", launchDetails(details).join("\n")), 0, 0));
|
|
407
|
+
// Background results arrive as their own message; headless runs still show the output here.
|
|
408
|
+
if (!details.background && body) {
|
|
409
|
+
const { shown, hidden } = outputPreview(body, expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
|
|
410
|
+
container.addChild(new Markdown(shown.join("\n"), 0, 0, getMarkdownTheme()));
|
|
411
|
+
if (hidden > 0)
|
|
412
|
+
container.addChild(
|
|
413
|
+
new Text(
|
|
414
|
+
theme.fg("muted", `… ${hidden} more lines, `) + keyHint("app.tools.expand", "to expand"),
|
|
415
|
+
0,
|
|
416
|
+
0,
|
|
417
|
+
),
|
|
418
|
+
);
|
|
419
|
+
}
|
|
420
|
+
return container;
|
|
421
|
+
},
|
|
422
|
+
});
|
|
423
|
+
|
|
424
|
+
pi.registerTool({
|
|
425
|
+
name: "delegate_steer",
|
|
426
|
+
label: "Steer delegate",
|
|
427
|
+
description:
|
|
428
|
+
"Send guidance to a running background delegate. The child receives it after its current tool calls and before its next model request; it cannot revive a finished job. Use delegate_list for the ids of running jobs.",
|
|
429
|
+
promptSnippet: "Send guidance to a running background delegate by job id",
|
|
430
|
+
parameters: Type.Object({
|
|
431
|
+
id: Type.String({
|
|
432
|
+
description: 'Job id from a delegate tool result or a delegate-result message, such as "38631a01".',
|
|
433
|
+
}),
|
|
434
|
+
message: Type.String({ description: "The guidance to deliver to the running child." }),
|
|
435
|
+
}),
|
|
436
|
+
async execute(_toolCallId, params) {
|
|
437
|
+
const id = params.id.trim().replace(/^job\s+/i, "");
|
|
438
|
+
const job = running.get(id);
|
|
439
|
+
if (!job?.steer) throw new Error(`No running delegate job "${id}".`);
|
|
440
|
+
await job.steer(params.message);
|
|
441
|
+
const details: SteerDetails = {
|
|
442
|
+
id: job.id,
|
|
443
|
+
agent: job.agent,
|
|
444
|
+
description: job.description,
|
|
445
|
+
message: params.message,
|
|
446
|
+
toolCalls: job.toolCalls,
|
|
447
|
+
contextTokens: job.contextTokens,
|
|
448
|
+
contextWindow: job.contextWindow,
|
|
449
|
+
elapsedMs: Date.now() - job.startedAt,
|
|
450
|
+
};
|
|
451
|
+
return {
|
|
452
|
+
content: [
|
|
453
|
+
{ type: "text", text: `Steering message delivered to delegate "${job.agent}" (job ${job.id}).` },
|
|
454
|
+
],
|
|
455
|
+
details,
|
|
456
|
+
};
|
|
457
|
+
},
|
|
458
|
+
|
|
459
|
+
renderCall(args, theme, context) {
|
|
460
|
+
const message = args.message?.split("\n")[0]?.trim() ?? "";
|
|
461
|
+
const hint = `${theme.fg("muted", "(")}${keyHint("app.tools.expand", context.expanded ? "to collapse" : "to expand")}${theme.fg("muted", ")")}`;
|
|
462
|
+
return new Text(
|
|
463
|
+
`${theme.fg("toolTitle", theme.bold("delegate_steer "))}${theme.fg("accent", message)} ${hint}`,
|
|
464
|
+
0,
|
|
465
|
+
0,
|
|
466
|
+
);
|
|
467
|
+
},
|
|
468
|
+
|
|
469
|
+
renderResult(result, { expanded }, theme, context) {
|
|
470
|
+
const details = result.details as SteerDetails | undefined;
|
|
471
|
+
const body = result.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n");
|
|
472
|
+
if (!details?.agent) return new Text(body || "(no output)", 0, 0);
|
|
473
|
+
const icon = context.isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
|
|
474
|
+
const container = new Container();
|
|
475
|
+
container.addChild(
|
|
476
|
+
new Text(
|
|
477
|
+
`${icon} ${theme.fg("toolTitle", theme.bold(details.agent))} ${theme.fg("muted", details.description)} ${theme.fg("dim", details.id)} ${theme.fg("muted", progressStats(details, details.elapsedMs))}`,
|
|
478
|
+
0,
|
|
479
|
+
0,
|
|
480
|
+
),
|
|
481
|
+
);
|
|
482
|
+
if (expanded) container.addChild(new Text(theme.fg("dim", details.message), 0, 0));
|
|
483
|
+
return container;
|
|
484
|
+
},
|
|
485
|
+
});
|
|
486
|
+
|
|
487
|
+
pi.registerTool({
|
|
488
|
+
name: "delegate_cancel",
|
|
489
|
+
label: "Cancel delegate",
|
|
490
|
+
description:
|
|
491
|
+
"Cancel a running background delegate by job id. Requests abort now and forcibly kills the child after five seconds if needed. Cancelled jobs send no follow-up report.",
|
|
492
|
+
promptSnippet: "Cancel a running background delegate by job id",
|
|
493
|
+
parameters: Type.Object({
|
|
494
|
+
id: Type.String({ description: "Job id from delegate or delegate_list." }),
|
|
495
|
+
}),
|
|
496
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
497
|
+
const id = params.id.trim().replace(/^job\s+/i, "");
|
|
498
|
+
const job = running.get(id);
|
|
499
|
+
if (!job) throw new Error(`No running delegate job "${id}".`);
|
|
500
|
+
running.delete(id);
|
|
501
|
+
job.controller.abort();
|
|
502
|
+
if (running.size === 0) stopTicker();
|
|
503
|
+
refreshWidget(ctx);
|
|
504
|
+
return {
|
|
505
|
+
content: [
|
|
506
|
+
{ type: "text", text: `Cancellation requested for delegate "${job.agent}" (job ${job.id}).` },
|
|
507
|
+
],
|
|
508
|
+
details: { id: job.id, agent: job.agent },
|
|
509
|
+
};
|
|
510
|
+
},
|
|
511
|
+
});
|
|
512
|
+
|
|
513
|
+
pi.registerTool({
|
|
514
|
+
name: "delegate_list",
|
|
515
|
+
label: "List delegates",
|
|
516
|
+
description:
|
|
517
|
+
"List the background delegates still running, with their job ids and progress, for steering or checking. Finished delegates are not listed; their results arrive as follow-up messages.",
|
|
518
|
+
promptSnippet: "List running background delegates and their job ids",
|
|
519
|
+
parameters: Type.Object({}),
|
|
520
|
+
async execute() {
|
|
521
|
+
const now = Date.now();
|
|
522
|
+
const jobs = [...running.values()];
|
|
523
|
+
if (!jobs.length)
|
|
524
|
+
return { content: [{ type: "text", text: "No delegates are running." }], details: undefined };
|
|
525
|
+
const lastActivity = (job: DelegateJob) =>
|
|
526
|
+
job.lastTool ? ` · ${job.lastTool}${job.lastDetail ? ` ${job.lastDetail}` : ""}` : "";
|
|
527
|
+
const lines = jobs.map(
|
|
528
|
+
(job) => `- ${job.id} ${job.agent} · ${jobLine(job, now - job.startedAt)}${lastActivity(job)}`,
|
|
529
|
+
);
|
|
530
|
+
return {
|
|
531
|
+
content: [{ type: "text", text: `${jobs.length} running:\n${lines.join("\n")}` }],
|
|
532
|
+
details: undefined,
|
|
533
|
+
};
|
|
534
|
+
},
|
|
535
|
+
});
|
|
536
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@deathbeam/pi-delegate",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Run focused Pi subagents as background or foreground tasks",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/deathbeam/pi-packages.git",
|
|
10
|
+
"directory": "packages/pi-delegate"
|
|
11
|
+
},
|
|
12
|
+
"keywords": [
|
|
13
|
+
"pi-package",
|
|
14
|
+
"pi-extension"
|
|
15
|
+
],
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=22.19.0"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"index.ts",
|
|
21
|
+
"child.ts",
|
|
22
|
+
"format.ts",
|
|
23
|
+
"agents",
|
|
24
|
+
"README.md",
|
|
25
|
+
"LICENSE"
|
|
26
|
+
],
|
|
27
|
+
"pi": {
|
|
28
|
+
"extensions": [
|
|
29
|
+
"./index.ts"
|
|
30
|
+
]
|
|
31
|
+
},
|
|
32
|
+
"scripts": {
|
|
33
|
+
"test": "node check.mjs"
|
|
34
|
+
},
|
|
35
|
+
"peerDependencies": {
|
|
36
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
37
|
+
"@earendil-works/pi-tui": "*"
|
|
38
|
+
}
|
|
39
|
+
}
|