@deathbeam/pi-delegate 0.0.18 → 0.0.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/agents.ts +115 -0
- package/child.ts +37 -8
- package/format.ts +23 -14
- package/index.ts +114 -454
- package/inspector.ts +235 -0
- package/package.json +5 -2
- package/store.ts +163 -0
package/index.ts
CHANGED
|
@@ -1,57 +1,36 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import {
|
|
4
|
-
import { homedir } from "node:os";
|
|
5
|
-
import { join, resolve } from "node:path";
|
|
6
|
-
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { join } from "node:path";
|
|
7
4
|
import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
|
|
8
|
-
import {
|
|
9
|
-
CONFIG_DIR_NAME,
|
|
10
|
-
getAgentDir,
|
|
11
|
-
getMarkdownTheme,
|
|
12
|
-
keyHint,
|
|
13
|
-
parseFrontmatter,
|
|
14
|
-
rawKeyHint,
|
|
15
|
-
} from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { getAgentDir, getMarkdownTheme, keyHint } from "@earendil-works/pi-coding-agent";
|
|
16
6
|
import {
|
|
17
7
|
type Component,
|
|
18
8
|
Container,
|
|
19
|
-
HStack,
|
|
20
9
|
Markdown,
|
|
21
10
|
Spacer,
|
|
22
11
|
Text,
|
|
23
12
|
TruncatedText,
|
|
24
|
-
matchesKey,
|
|
25
13
|
truncateToWidth,
|
|
26
|
-
wrapTextWithAnsi,
|
|
27
14
|
} from "@earendil-works/pi-tui";
|
|
28
15
|
import { Type } from "typebox";
|
|
29
16
|
import {
|
|
30
17
|
COLLAPSED_OUTPUT_LINES,
|
|
31
18
|
type DelegateReport,
|
|
32
|
-
formatTools,
|
|
33
19
|
jobIdentity,
|
|
34
20
|
jobLine,
|
|
35
|
-
type JobStatus,
|
|
36
21
|
launchDetails,
|
|
37
22
|
outputPreview,
|
|
38
23
|
reportText,
|
|
24
|
+
resumeHint,
|
|
39
25
|
SPINNER_INTERVAL_MS,
|
|
40
|
-
STATUS_COLORS,
|
|
41
26
|
statusText,
|
|
42
27
|
usageStats,
|
|
43
28
|
widgetJobs,
|
|
44
29
|
} from "./format.ts";
|
|
45
|
-
import {
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
description: string;
|
|
50
|
-
tools?: string[];
|
|
51
|
-
model?: string;
|
|
52
|
-
thinking?: string;
|
|
53
|
-
prompt: string;
|
|
54
|
-
};
|
|
30
|
+
import { runChild } from "./child.ts";
|
|
31
|
+
import { createJobStore, resumeDecision, type DelegateJob } from "./store.ts";
|
|
32
|
+
import { registerInspector } from "./inspector.ts";
|
|
33
|
+
import { configFor, contextWindowFor, discoverAgents, resolveModel } from "./agents.ts";
|
|
55
34
|
|
|
56
35
|
type DelegateDetails = Pick<DelegateJob, "id" | "agent" | "description" | "task" | "model" | "tools"> & {
|
|
57
36
|
background: boolean;
|
|
@@ -65,136 +44,15 @@ type SteerDetails = Pick<
|
|
|
65
44
|
elapsedMs: number;
|
|
66
45
|
};
|
|
67
46
|
|
|
68
|
-
type InspectJob = {
|
|
69
|
-
id: string;
|
|
70
|
-
agent: string;
|
|
71
|
-
description: string;
|
|
72
|
-
task: string;
|
|
73
|
-
model: string;
|
|
74
|
-
tools: string[];
|
|
75
|
-
toolCalls: number;
|
|
76
|
-
contextTokens?: number;
|
|
77
|
-
contextWindow?: number;
|
|
78
|
-
startedAt: number;
|
|
79
|
-
endedAt?: number;
|
|
80
|
-
status: JobStatus;
|
|
81
|
-
activity: ChildActivity[];
|
|
82
|
-
};
|
|
83
|
-
|
|
84
|
-
type DelegateJob = InspectJob & {
|
|
85
|
-
lastTool?: string;
|
|
86
|
-
lastDetail?: string;
|
|
87
|
-
lastResult?: string;
|
|
88
|
-
controller: AbortController;
|
|
89
|
-
steer?: (message: string) => Promise<void>;
|
|
90
|
-
};
|
|
91
|
-
|
|
92
|
-
type DelegateConfig = {
|
|
93
|
-
agentDirs?: unknown;
|
|
94
|
-
models?: Record<string, unknown>;
|
|
95
|
-
};
|
|
96
|
-
|
|
97
|
-
const DEFAULT_AGENT_DIR = "~/.agents/agents";
|
|
98
|
-
const BUNDLED_AGENT_DIR = fileURLToPath(new URL("./agents", import.meta.url));
|
|
99
47
|
const DELEGATION_TOOLS = new Set(["delegate", "delegate_list", "delegate_steer", "delegate_cancel"]);
|
|
100
|
-
const MODEL_TIERS = new Set(["cheap", "balanced", "strong"]);
|
|
101
48
|
const WIDGET_KEY = "delegate";
|
|
102
49
|
const RESULT_MESSAGE = "delegate-result";
|
|
103
50
|
const REMINDER_MESSAGE = "delegate-reminder";
|
|
104
|
-
const JOB_ENTRY = "delegate-job";
|
|
105
51
|
const EXPLORATION_TOOLS = new Set(["read", "grep", "find", "ls", "bash", "powershell", "web_search", "web_fetch"]);
|
|
106
52
|
const FIRST_REMINDER_AT = 5;
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
function stringList(value: unknown): string[] {
|
|
113
|
-
const values = Array.isArray(value) ? value : typeof value === "string" ? value.split(",") : [];
|
|
114
|
-
return values
|
|
115
|
-
.filter((item): item is string => typeof item === "string")
|
|
116
|
-
.map((item) => item.trim())
|
|
117
|
-
.filter(Boolean);
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
function readConfig(path: string): DelegateConfig {
|
|
121
|
-
try {
|
|
122
|
-
const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
|
|
123
|
-
if (!parsed || typeof parsed !== "object") return {};
|
|
124
|
-
const delegate = (parsed as { delegate?: unknown }).delegate;
|
|
125
|
-
return delegate && typeof delegate === "object" ? (delegate as DelegateConfig) : {};
|
|
126
|
-
} catch {
|
|
127
|
-
return {};
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
function configFor(cwd: string): DelegateConfig {
|
|
132
|
-
const global = readConfig(join(getAgentDir(), "settings.json"));
|
|
133
|
-
const project = readConfig(join(cwd, CONFIG_DIR_NAME, "settings.json"));
|
|
134
|
-
return {
|
|
135
|
-
agentDirs: [...stringList(global.agentDirs), ...stringList(project.agentDirs)],
|
|
136
|
-
models: { ...(global.models ?? {}), ...(project.models ?? {}) },
|
|
137
|
-
};
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
function loadAgents(dir: string): AgentFile[] {
|
|
141
|
-
if (!existsSync(dir)) return [];
|
|
142
|
-
const agents: AgentFile[] = [];
|
|
143
|
-
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
144
|
-
if (!entry.name.endsWith(".md") || (!entry.isFile() && !entry.isSymbolicLink())) continue;
|
|
145
|
-
try {
|
|
146
|
-
const { frontmatter, body } = parseFrontmatter<Record<string, unknown>>(
|
|
147
|
-
readFileSync(join(dir, entry.name), "utf8"),
|
|
148
|
-
);
|
|
149
|
-
if (typeof frontmatter.name !== "string" || typeof frontmatter.description !== "string") continue;
|
|
150
|
-
agents.push({
|
|
151
|
-
name: frontmatter.name,
|
|
152
|
-
description: frontmatter.description,
|
|
153
|
-
tools: stringList(frontmatter.tools),
|
|
154
|
-
model: typeof frontmatter.model === "string" ? frontmatter.model : undefined,
|
|
155
|
-
thinking: typeof frontmatter.thinking === "string" ? frontmatter.thinking : undefined,
|
|
156
|
-
prompt: body.trim(),
|
|
157
|
-
});
|
|
158
|
-
} catch {
|
|
159
|
-
// One malformed agent file should not disable delegation.
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
return agents;
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
function discoverAgents(cwd: string, configuredDirs: unknown): AgentFile[] {
|
|
166
|
-
const dirs = [BUNDLED_AGENT_DIR, DEFAULT_AGENT_DIR, ...stringList(configuredDirs)].map((dir) =>
|
|
167
|
-
expandPath(dir, cwd),
|
|
168
|
-
);
|
|
169
|
-
const agents = new Map<string, AgentFile>();
|
|
170
|
-
for (const dir of [...new Set(dirs)]) {
|
|
171
|
-
for (const agent of loadAgents(dir)) agents.set(agent.name, agent);
|
|
172
|
-
}
|
|
173
|
-
return [...agents.values()];
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
export function resolveModel(
|
|
177
|
-
value: string | undefined,
|
|
178
|
-
models: Record<string, unknown>,
|
|
179
|
-
current: ExtensionContext["model"],
|
|
180
|
-
): { model?: string; thinking?: string } {
|
|
181
|
-
if (value && !MODEL_TIERS.has(value)) return { model: value };
|
|
182
|
-
const configured = value ? models[value] : undefined;
|
|
183
|
-
const entry =
|
|
184
|
-
configured && typeof configured === "object"
|
|
185
|
-
? (configured as { model?: unknown; thinking?: unknown })
|
|
186
|
-
: undefined;
|
|
187
|
-
const model = typeof configured === "string" ? configured : typeof entry?.model === "string" ? entry.model : "";
|
|
188
|
-
// Tier thinking only applies when the model itself came from the tier entry.
|
|
189
|
-
if (model) return { model, thinking: typeof entry?.thinking === "string" ? entry.thinking : undefined };
|
|
190
|
-
return { model: current ? `${current.provider}/${current.id}` : undefined };
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
function contextWindowFor(ctx: ExtensionContext, model: string | undefined): number | undefined {
|
|
194
|
-
const separator = model?.indexOf("/") ?? -1;
|
|
195
|
-
if (!model || separator < 0) return undefined;
|
|
196
|
-
return ctx.modelRegistry.find(model.slice(0, separator), model.slice(separator + 1))?.contextWindow;
|
|
197
|
-
}
|
|
53
|
+
const DELEGATE_SESSION_DIR = join(getAgentDir(), "sessions", "delegates");
|
|
54
|
+
const RESUME_PROMPT = "Continue the task above from where you left off.";
|
|
55
|
+
const INTERRUPTED_MESSAGE = "delegate-interrupted";
|
|
198
56
|
|
|
199
57
|
function argText(value: unknown): string {
|
|
200
58
|
return typeof value === "string" ? value : "";
|
|
@@ -252,37 +110,12 @@ function toolLayout(toolName: string, identity: string, payload: string, theme:
|
|
|
252
110
|
}
|
|
253
111
|
|
|
254
112
|
export default function (pi: ExtensionAPI) {
|
|
255
|
-
const
|
|
256
|
-
const recent: InspectJob[] = [];
|
|
257
|
-
let viewing: (() => void) | undefined;
|
|
113
|
+
const store = createJobStore(pi.appendEntry);
|
|
258
114
|
let ticker: ReturnType<typeof setInterval> | undefined;
|
|
259
115
|
// Prompts are read once; drift happens one quick search at a time, so count it and nudge at 5, 10, 20, ...
|
|
260
116
|
let directCalls = 0;
|
|
261
117
|
let nextReminder = FIRST_REMINDER_AT;
|
|
262
118
|
|
|
263
|
-
const addActivity = (job: DelegateJob, activity: ChildActivity) => {
|
|
264
|
-
const normalize = (text: string) => text.replace(/\s+/g, " ").trim();
|
|
265
|
-
job.activity.push(
|
|
266
|
-
activity.kind === "assistant" || activity.kind === "user"
|
|
267
|
-
? activity
|
|
268
|
-
: {
|
|
269
|
-
...activity,
|
|
270
|
-
text: normalize(activity.text),
|
|
271
|
-
detail: activity.detail && normalize(activity.detail),
|
|
272
|
-
},
|
|
273
|
-
);
|
|
274
|
-
viewing?.();
|
|
275
|
-
};
|
|
276
|
-
|
|
277
|
-
const remember = (job: DelegateJob, status: JobStatus, detail?: string) => {
|
|
278
|
-
job.status = status;
|
|
279
|
-
if (detail) addActivity(job, { kind: "status", text: detail });
|
|
280
|
-
const { controller, steer, lastTool, lastDetail, lastResult, ...snapshot } = job;
|
|
281
|
-
const entry: InspectJob = { ...snapshot, endedAt: Date.now() };
|
|
282
|
-
recent.unshift(entry);
|
|
283
|
-
pi.appendEntry(JOB_ENTRY, entry);
|
|
284
|
-
};
|
|
285
|
-
|
|
286
119
|
const jobSnapshot = (job: DelegateJob) => ({
|
|
287
120
|
id: job.id,
|
|
288
121
|
agent: job.agent,
|
|
@@ -294,22 +127,23 @@ export default function (pi: ExtensionAPI) {
|
|
|
294
127
|
|
|
295
128
|
const jobTarget = (rawId: unknown, theme: Theme): string => {
|
|
296
129
|
const id = jobId(rawId);
|
|
297
|
-
const job =
|
|
130
|
+
const job = store.find(id);
|
|
298
131
|
return job ? jobIdentity(theme, job) : theme.fg("muted", id || "…");
|
|
299
132
|
};
|
|
300
133
|
|
|
301
134
|
const refreshWidget = (ctx: ExtensionContext) => {
|
|
302
135
|
if (!ctx.hasUI) return;
|
|
303
|
-
|
|
304
|
-
|
|
136
|
+
store.notify();
|
|
137
|
+
const jobs = store.live();
|
|
138
|
+
if (jobs.length === 0) {
|
|
305
139
|
ctx.ui.setWidget(WIDGET_KEY, undefined);
|
|
306
140
|
return;
|
|
307
141
|
}
|
|
308
142
|
const theme = ctx.ui.theme;
|
|
309
143
|
const now = Date.now();
|
|
310
|
-
const { shown, hidden, detail } = widgetJobs(
|
|
144
|
+
const { shown, hidden, detail } = widgetJobs(jobs);
|
|
311
145
|
const lines: string[] = [];
|
|
312
|
-
const counts = `${
|
|
146
|
+
const counts = `${jobs.length} running · ${store.all().length} total`;
|
|
313
147
|
lines.push(`${statusText(theme, "running", now)} ${theme.fg("muted", counts)}`);
|
|
314
148
|
for (const job of shown) {
|
|
315
149
|
lines.push(
|
|
@@ -326,17 +160,18 @@ export default function (pi: ExtensionAPI) {
|
|
|
326
160
|
ctx.ui.setWidget(WIDGET_KEY, lines);
|
|
327
161
|
};
|
|
328
162
|
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
ticker
|
|
163
|
+
// The ticker animates spinners exactly while live jobs exist.
|
|
164
|
+
const syncTicker = (ctx: ExtensionContext) => {
|
|
165
|
+
if (store.live().length > 0) ticker ??= setInterval(() => refreshWidget(ctx), SPINNER_INTERVAL_MS);
|
|
166
|
+
else if (ticker) {
|
|
167
|
+
clearInterval(ticker);
|
|
168
|
+
ticker = undefined;
|
|
169
|
+
}
|
|
332
170
|
};
|
|
333
171
|
|
|
334
172
|
const finishJob = (ctx: ExtensionContext, job: DelegateJob, output?: string, error?: string) => {
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
running.delete(job.id);
|
|
338
|
-
remember(job, error ? "failed" : "done", error ? `Error: ${error}` : undefined);
|
|
339
|
-
if (running.size === 0) stopTicker();
|
|
173
|
+
if (!store.finish(job, error ? "failed" : "done", error ? `Error: ${error}` : undefined)) return;
|
|
174
|
+
syncTicker(ctx);
|
|
340
175
|
refreshWidget(ctx);
|
|
341
176
|
const report: DelegateReport = {
|
|
342
177
|
id: job.id,
|
|
@@ -359,23 +194,28 @@ export default function (pi: ExtensionAPI) {
|
|
|
359
194
|
};
|
|
360
195
|
|
|
361
196
|
pi.on("session_shutdown", () => {
|
|
362
|
-
|
|
363
|
-
for (const job of
|
|
364
|
-
|
|
365
|
-
recent.length = 0;
|
|
366
|
-
viewing = undefined;
|
|
197
|
+
if (ticker) clearInterval(ticker);
|
|
198
|
+
for (const job of store.live()) job.controller.abort();
|
|
199
|
+
store.clear();
|
|
367
200
|
});
|
|
368
201
|
|
|
369
202
|
// Rebuilt from the active branch, like pi's todo example; abandoned branches are alternative histories.
|
|
370
|
-
const
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
203
|
+
const restoreSession = (ctx: ExtensionContext) => {
|
|
204
|
+
const interrupted = store.restore(ctx.sessionManager.getBranch());
|
|
205
|
+
// Custom entries never reach the model, so announce the interrupted jobs as a steered message.
|
|
206
|
+
if (interrupted.length)
|
|
207
|
+
pi.sendMessage(
|
|
208
|
+
{
|
|
209
|
+
customType: INTERRUPTED_MESSAGE,
|
|
210
|
+
content: `<system-reminder>These delegate jobs were interrupted by a restart or crash; their transcripts survive. Resume each with the delegate tool's resume parameter (job id only):\n${interrupted.map((job) => `- ${job.id} ${job.agent}: ${job.description}`).join("\n")}</system-reminder>`,
|
|
211
|
+
display: false,
|
|
212
|
+
},
|
|
213
|
+
{ deliverAs: "steer" },
|
|
214
|
+
);
|
|
376
215
|
};
|
|
377
|
-
|
|
378
|
-
pi.on("
|
|
216
|
+
|
|
217
|
+
pi.on("session_start", (_event, ctx) => restoreSession(ctx));
|
|
218
|
+
pi.on("session_tree", (_event, ctx) => restoreSession(ctx));
|
|
379
219
|
|
|
380
220
|
pi.on("before_agent_start", () => {
|
|
381
221
|
directCalls = 0;
|
|
@@ -425,224 +265,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
425
265
|
return container;
|
|
426
266
|
});
|
|
427
267
|
|
|
428
|
-
pi
|
|
429
|
-
description: "Inspect live and recent delegate activity",
|
|
430
|
-
handler: async (_args, ctx) => {
|
|
431
|
-
if (ctx.mode !== "tui") return;
|
|
432
|
-
if (!running.size && !recent.length) {
|
|
433
|
-
ctx.ui.notify("No delegates in this session yet.", "info");
|
|
434
|
-
return;
|
|
435
|
-
}
|
|
436
|
-
const screen = {
|
|
437
|
-
overlay: true,
|
|
438
|
-
overlayOptions: { width: "100%", maxHeight: "100%", row: 0, col: 0 },
|
|
439
|
-
} as const;
|
|
440
|
-
try {
|
|
441
|
-
await ctx.ui.custom((tui, theme, keys, done) => {
|
|
442
|
-
let selectedId = running.keys().next().value ?? recent[0]!.id;
|
|
443
|
-
let focus: "list" | "history" = "list";
|
|
444
|
-
let top: number | undefined;
|
|
445
|
-
let historyWidth = 1;
|
|
446
|
-
let markdown = new WeakMap<ChildActivity, Markdown>();
|
|
447
|
-
const jobs = () => [...running.values(), ...recent];
|
|
448
|
-
// Fixed rows: title, top rule, bottom rule, footer.
|
|
449
|
-
const bodyHeight = () => Math.max(0, tui.terminal.rows - 4);
|
|
450
|
-
const toolsLines = (job: InspectJob, width: number) =>
|
|
451
|
-
wrapTextWithAnsi(formatTools(job.tools), Math.max(1, width)).map((line) =>
|
|
452
|
-
theme.fg("dim", line),
|
|
453
|
-
);
|
|
454
|
-
// Fixed rows: header, model, description, rule, counter.
|
|
455
|
-
const historyHeight = (job: InspectJob, width: number) =>
|
|
456
|
-
Math.max(0, bodyHeight() - 5 - toolsLines(job, width).length);
|
|
457
|
-
// ScrollView needs fullscreen layout; window the history in regular TUI too.
|
|
458
|
-
const renderJobs = (width: number, items: InspectJob[], selectedIndex: number): string[] => {
|
|
459
|
-
const row = (text: string) =>
|
|
460
|
-
truncateToWidth(text, Math.max(0, width - 1), "…", true) + theme.fg("borderMuted", "│");
|
|
461
|
-
const visible = Math.max(1, Math.floor((bodyHeight() - 1) / 3));
|
|
462
|
-
const start = Math.max(
|
|
463
|
-
0,
|
|
464
|
-
Math.min(selectedIndex - Math.floor(visible / 2), items.length - visible),
|
|
465
|
-
);
|
|
466
|
-
const lines = items
|
|
467
|
-
.slice(start, start + visible)
|
|
468
|
-
.flatMap((item, index) => [
|
|
469
|
-
row(
|
|
470
|
-
`${theme.fg(start + index === selectedIndex && focus === "list" ? "accent" : "text", start + index === selectedIndex ? "›" : " ")} ${statusText(theme, item.status)} ${jobIdentity(theme, item)}`,
|
|
471
|
-
),
|
|
472
|
-
row(theme.fg("muted", ` ${item.description}`)),
|
|
473
|
-
row(
|
|
474
|
-
theme.fg(
|
|
475
|
-
"muted",
|
|
476
|
-
` ${usageStats(item, (item.endedAt ?? Date.now()) - item.startedAt)}`,
|
|
477
|
-
),
|
|
478
|
-
),
|
|
479
|
-
]);
|
|
480
|
-
return [
|
|
481
|
-
...lines,
|
|
482
|
-
...Array(Math.max(0, bodyHeight() - 1 - lines.length)).fill(row("")),
|
|
483
|
-
row(theme.fg("dim", `${selectedIndex + 1}/${items.length}`)),
|
|
484
|
-
].slice(0, bodyHeight());
|
|
485
|
-
};
|
|
486
|
-
const renderEntry = (entry: ChildActivity, width: number): string[] => {
|
|
487
|
-
if (entry.kind === "assistant" || entry.kind === "user") {
|
|
488
|
-
let md = markdown.get(entry);
|
|
489
|
-
if (!md) {
|
|
490
|
-
md = new Markdown(entry.text, 0, 0, getMarkdownTheme());
|
|
491
|
-
markdown.set(entry, md);
|
|
492
|
-
}
|
|
493
|
-
return [theme.fg("accent", entry.kind), ...md.render(width), ""];
|
|
494
|
-
}
|
|
495
|
-
if (entry.kind === "tool")
|
|
496
|
-
return [
|
|
497
|
-
truncateToWidth(
|
|
498
|
-
theme.fg("toolTitle", entry.text) +
|
|
499
|
-
(entry.detail ? ` ${theme.fg("accent", entry.detail)}` : ""),
|
|
500
|
-
width,
|
|
501
|
-
),
|
|
502
|
-
];
|
|
503
|
-
if (entry.kind === "result") return [truncateToWidth(theme.fg("text", entry.text), width)];
|
|
504
|
-
// Only failure detail still says anything; the header icon carries the status.
|
|
505
|
-
if (!entry.text) return [];
|
|
506
|
-
return [truncateToWidth(theme.fg(STATUS_COLORS.failed, entry.text), width)];
|
|
507
|
-
};
|
|
508
|
-
const renderHistory = (width: number, job: InspectJob): string[] => {
|
|
509
|
-
historyWidth = width;
|
|
510
|
-
const tools = toolsLines(job, width);
|
|
511
|
-
const height = historyHeight(job, width);
|
|
512
|
-
const history = job.activity.flatMap((entry) => renderEntry(entry, width));
|
|
513
|
-
const maxTop = Math.max(0, history.length - height);
|
|
514
|
-
const start = Math.min(top ?? maxTop, maxTop);
|
|
515
|
-
const visible = history.slice(start, start + height);
|
|
516
|
-
const shown = visible.length
|
|
517
|
-
? visible
|
|
518
|
-
: height
|
|
519
|
-
? [theme.fg("muted", "Waiting for activity…")]
|
|
520
|
-
: [];
|
|
521
|
-
return [
|
|
522
|
-
truncateToWidth(`${statusText(theme, job.status)} ${jobIdentity(theme, job)}`, width),
|
|
523
|
-
truncateToWidth(theme.fg("dim", job.model), width),
|
|
524
|
-
...tools,
|
|
525
|
-
truncateToWidth(theme.fg("text", theme.bold(job.description)), width),
|
|
526
|
-
theme.fg("borderMuted", "─".repeat(Math.max(0, width))),
|
|
527
|
-
...shown,
|
|
528
|
-
...Array(Math.max(0, height - shown.length)).fill(""),
|
|
529
|
-
truncateToWidth(
|
|
530
|
-
theme.fg(
|
|
531
|
-
"dim",
|
|
532
|
-
`${visible.length ? `${start + 1}–${start + visible.length}` : "0"}/${history.length}`,
|
|
533
|
-
),
|
|
534
|
-
width,
|
|
535
|
-
),
|
|
536
|
-
].slice(0, bodyHeight());
|
|
537
|
-
};
|
|
538
|
-
viewing = () => tui.requestRender();
|
|
539
|
-
return {
|
|
540
|
-
render(width: number) {
|
|
541
|
-
const items = jobs();
|
|
542
|
-
const selectedIndex = Math.max(
|
|
543
|
-
0,
|
|
544
|
-
items.findIndex((item) => item.id === selectedId),
|
|
545
|
-
);
|
|
546
|
-
const selected = items[selectedIndex];
|
|
547
|
-
const title = truncateToWidth(
|
|
548
|
-
`${theme.fg(focus === "list" ? "accent" : "muted", focus === "list" ? "[Jobs]" : "Jobs")} ` +
|
|
549
|
-
`${theme.fg(focus === "history" ? "accent" : "muted", focus === "history" ? "[Activity]" : "Activity")}` +
|
|
550
|
-
theme.fg("dim", ` · ${running.size} running · ${items.length} total`),
|
|
551
|
-
width,
|
|
552
|
-
);
|
|
553
|
-
const footer = truncateToWidth(
|
|
554
|
-
theme.fg(
|
|
555
|
-
"dim",
|
|
556
|
-
`${keyHint("tui.select.up", "up")} · ${keyHint("tui.select.down", "down")} · ${rawKeyHint("←/→", "switch pane")} · ${keyHint("tui.select.cancel", "close")}`,
|
|
557
|
-
),
|
|
558
|
-
width,
|
|
559
|
-
);
|
|
560
|
-
if (!selected)
|
|
561
|
-
return [
|
|
562
|
-
title,
|
|
563
|
-
theme.fg("muted", "No delegates in this session."),
|
|
564
|
-
// Fixed rows: title, top rule, bottom rule, footer.
|
|
565
|
-
...Array(Math.max(0, tui.terminal.rows - 4)).fill(""),
|
|
566
|
-
footer,
|
|
567
|
-
].slice(0, tui.terminal.rows);
|
|
568
|
-
const sidebarWidth = Math.min(
|
|
569
|
-
40,
|
|
570
|
-
Math.max(16, Math.floor(width * 0.35)),
|
|
571
|
-
Math.max(1, width - 2),
|
|
572
|
-
);
|
|
573
|
-
const body = new HStack(
|
|
574
|
-
[
|
|
575
|
-
{
|
|
576
|
-
component: {
|
|
577
|
-
render: (w) => renderJobs(w, items, selectedIndex),
|
|
578
|
-
invalidate() {},
|
|
579
|
-
},
|
|
580
|
-
basis: sidebarWidth,
|
|
581
|
-
shrink: 0,
|
|
582
|
-
},
|
|
583
|
-
{
|
|
584
|
-
component: { render: (w) => renderHistory(w, selected), invalidate() {} },
|
|
585
|
-
basis: 0,
|
|
586
|
-
grow: 1,
|
|
587
|
-
},
|
|
588
|
-
],
|
|
589
|
-
{ gap: 1 },
|
|
590
|
-
).render(width);
|
|
591
|
-
return [
|
|
592
|
-
title,
|
|
593
|
-
theme.fg("borderMuted", "─".repeat(Math.max(0, width))),
|
|
594
|
-
...body,
|
|
595
|
-
theme.fg("borderMuted", "─".repeat(Math.max(0, width))),
|
|
596
|
-
footer,
|
|
597
|
-
].slice(0, tui.terminal.rows);
|
|
598
|
-
},
|
|
599
|
-
invalidate() {
|
|
600
|
-
markdown = new WeakMap();
|
|
601
|
-
},
|
|
602
|
-
handleInput(data: string) {
|
|
603
|
-
if (keys.matches(data, "tui.select.cancel")) done(undefined);
|
|
604
|
-
else if (matchesKey(data, "left")) focus = "list";
|
|
605
|
-
else if (
|
|
606
|
-
matchesKey(data, "right") ||
|
|
607
|
-
(focus === "list" && keys.matches(data, "tui.select.confirm"))
|
|
608
|
-
)
|
|
609
|
-
focus = "history";
|
|
610
|
-
else if (keys.matches(data, "tui.select.up") || keys.matches(data, "tui.select.down")) {
|
|
611
|
-
const up = keys.matches(data, "tui.select.up");
|
|
612
|
-
const items = jobs();
|
|
613
|
-
if (focus === "list") {
|
|
614
|
-
const index = Math.max(
|
|
615
|
-
0,
|
|
616
|
-
items.findIndex((item) => item.id === selectedId),
|
|
617
|
-
);
|
|
618
|
-
selectedId =
|
|
619
|
-
items[Math.max(0, Math.min(items.length - 1, index + (up ? -1 : 1)))]?.id ??
|
|
620
|
-
selectedId;
|
|
621
|
-
top = undefined;
|
|
622
|
-
} else {
|
|
623
|
-
const selected = items.find((item) => item.id === selectedId) ?? items[0];
|
|
624
|
-
const length =
|
|
625
|
-
selected?.activity.reduce(
|
|
626
|
-
(sum, entry) => sum + renderEntry(entry, historyWidth).length,
|
|
627
|
-
0,
|
|
628
|
-
) ?? 0;
|
|
629
|
-
const maxTop = Math.max(
|
|
630
|
-
0,
|
|
631
|
-
length - (selected ? historyHeight(selected, historyWidth) : 0),
|
|
632
|
-
);
|
|
633
|
-
const position = Math.max(0, Math.min(maxTop, top ?? maxTop) + (up ? -1 : 1));
|
|
634
|
-
top = position >= maxTop ? undefined : position;
|
|
635
|
-
}
|
|
636
|
-
}
|
|
637
|
-
tui.requestRender();
|
|
638
|
-
},
|
|
639
|
-
};
|
|
640
|
-
}, screen);
|
|
641
|
-
} finally {
|
|
642
|
-
viewing = undefined;
|
|
643
|
-
}
|
|
644
|
-
},
|
|
645
|
-
});
|
|
268
|
+
registerInspector(pi, store);
|
|
646
269
|
|
|
647
270
|
const cwd = process.cwd();
|
|
648
271
|
const agentList = discoverAgents(cwd, configFor(cwd).agentDirs).map(
|
|
@@ -659,6 +282,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
659
282
|
...agentList,
|
|
660
283
|
"",
|
|
661
284
|
"A delegate gets the project instructions but not this conversation: it cannot see the user's request, the files you read, or your decisions. Write `task` as a self-contained brief: the goal and why, what you already know (paths, symbols, errors), scope and constraints, whether to edit files or only report, and what to return (format, length, path:line evidence).",
|
|
285
|
+
"",
|
|
286
|
+
"An interrupted, failed, or cancelled job can be continued by passing its job id as `resume`. The agent, task, and description come from the original job, and the model may be overridden. Done jobs need no resume: their reports are already in this session.",
|
|
662
287
|
].join("\n"),
|
|
663
288
|
promptSnippet:
|
|
664
289
|
"Delegate a focused task to a background agent with its own context; only its report comes back, as a later follow-up message",
|
|
@@ -671,39 +296,57 @@ export default function (pi: ExtensionAPI) {
|
|
|
671
296
|
"Read every required delegate report before claiming the task is done. Never sleep, poll, or call any tool solely to wait (including `bash` with `true`, `echo`, or `sleep 0`). Use delegate_list only for a one-time status check.",
|
|
672
297
|
],
|
|
673
298
|
parameters: Type.Object({
|
|
674
|
-
agent: Type.String({ description: "Agent name from the list in this tool's description." }),
|
|
675
|
-
description: Type.
|
|
676
|
-
description: "Short 3-8 word summary of this delegation, shown in the transcript.",
|
|
677
|
-
|
|
678
|
-
task: Type.
|
|
299
|
+
agent: Type.Optional(Type.String({ description: "Agent name from the list in this tool's description." })),
|
|
300
|
+
description: Type.Optional(
|
|
301
|
+
Type.String({ description: "Short 3-8 word summary of this delegation, shown in the transcript." }),
|
|
302
|
+
),
|
|
303
|
+
task: Type.Optional(
|
|
304
|
+
Type.String({ description: "Self-contained brief; the delegate cannot see this conversation." }),
|
|
305
|
+
),
|
|
679
306
|
model: Type.Optional(
|
|
680
307
|
Type.String({ description: "Model tier (cheap, balanced, strong) or an explicit provider/model." }),
|
|
681
308
|
),
|
|
309
|
+
resume: Type.Optional(
|
|
310
|
+
Type.String({
|
|
311
|
+
description:
|
|
312
|
+
"Job id of an interrupted, failed, or cancelled delegate to continue; it reuses the original agent, description and task (model may be overridden).",
|
|
313
|
+
}),
|
|
314
|
+
),
|
|
682
315
|
}),
|
|
683
316
|
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
684
317
|
const config = configFor(ctx.cwd);
|
|
685
318
|
const agents = discoverAgents(ctx.cwd, config.agentDirs);
|
|
686
|
-
const
|
|
319
|
+
const resuming = params.resume
|
|
320
|
+
? resumeDecision(jobId(params.resume), store.all(), new Set(store.live().map((job) => job.id)))
|
|
321
|
+
: undefined;
|
|
322
|
+
if (resuming?.error) throw new Error(resuming.error);
|
|
323
|
+
const prior = resuming?.job;
|
|
324
|
+
if (!prior && (!params.agent || !params.description || !params.task))
|
|
325
|
+
throw new Error(
|
|
326
|
+
"agent, description and task are required unless resuming an interrupted, failed, or cancelled job.",
|
|
327
|
+
);
|
|
328
|
+
const agent = agents.find((candidate) => candidate.name === (prior?.agent ?? params.agent));
|
|
687
329
|
if (!agent) {
|
|
688
330
|
const names = agents.map((candidate) => candidate.name).join(", ") || "(none)";
|
|
689
|
-
throw new Error(`Unknown agent "${params.agent}". Available agents: ${names}.`);
|
|
331
|
+
throw new Error(`Unknown agent "${prior?.agent ?? params.agent}". Available agents: ${names}.`);
|
|
690
332
|
}
|
|
691
333
|
const { model, thinking: tierThinking } = resolveModel(
|
|
692
334
|
params.model ?? agent.model,
|
|
693
335
|
config.models ?? {},
|
|
694
336
|
ctx.model,
|
|
695
337
|
);
|
|
696
|
-
if (!model) throw new Error(`No model found for "${
|
|
338
|
+
if (!model) throw new Error(`No model found for "${agent.name}".`);
|
|
697
339
|
const tools = (agent.tools?.length ? agent.tools : pi.getActiveTools()).filter(
|
|
698
340
|
(tool) => !DELEGATION_TOOLS.has(tool),
|
|
699
341
|
);
|
|
700
342
|
const thinking = agent.thinking ?? tierThinking ?? ctx.thinkingLevel;
|
|
701
343
|
const displayModel = thinking ? `${model}:${thinking}` : model;
|
|
702
344
|
const job: DelegateJob = {
|
|
703
|
-
id:
|
|
345
|
+
// A resumed job keeps its id: the pinned child session id reopens the old transcript.
|
|
346
|
+
id: prior?.id ?? randomUUID().slice(0, 8),
|
|
704
347
|
agent: agent.name,
|
|
705
|
-
description: params.description.trim(),
|
|
706
|
-
task: params.task,
|
|
348
|
+
description: (prior?.description ?? params.description ?? "").trim(),
|
|
349
|
+
task: prior?.task ?? params.task ?? "",
|
|
707
350
|
model: displayModel,
|
|
708
351
|
status: "running",
|
|
709
352
|
activity: [],
|
|
@@ -722,33 +365,51 @@ export default function (pi: ExtensionAPI) {
|
|
|
722
365
|
tools,
|
|
723
366
|
background: ctx.hasUI,
|
|
724
367
|
};
|
|
725
|
-
const args = [
|
|
368
|
+
const args = [
|
|
369
|
+
"--session-id",
|
|
370
|
+
`delegate-${job.id}`,
|
|
371
|
+
"--session-dir",
|
|
372
|
+
DELEGATE_SESSION_DIR,
|
|
373
|
+
"--model",
|
|
374
|
+
model,
|
|
375
|
+
"--tools",
|
|
376
|
+
tools.join(","),
|
|
377
|
+
];
|
|
726
378
|
if (thinking) args.push("--thinking", thinking);
|
|
727
379
|
if (agent.prompt) args.push("--append-system-prompt", agent.prompt);
|
|
728
380
|
const entrypoint = process.argv[1];
|
|
729
381
|
if (!entrypoint) throw new Error("Pi CLI entrypoint missing; start Pi from its CLI to delegate.");
|
|
730
|
-
const child = spawn(process.execPath, [entrypoint, "--mode", "rpc",
|
|
382
|
+
const child = spawn(process.execPath, [entrypoint, "--mode", "rpc", ...args], {
|
|
731
383
|
cwd: ctx.cwd,
|
|
732
384
|
shell: false,
|
|
733
385
|
stdio: "pipe",
|
|
734
386
|
});
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
387
|
+
store.launch(job, details.background);
|
|
388
|
+
const run = runChild(
|
|
389
|
+
child,
|
|
390
|
+
prior ? RESUME_PROMPT : job.task,
|
|
391
|
+
details.background ? job.controller.signal : signal,
|
|
392
|
+
(update) => store.record(job, update),
|
|
393
|
+
Boolean(prior),
|
|
394
|
+
);
|
|
743
395
|
job.steer = run.steer;
|
|
744
396
|
|
|
745
397
|
if (!details.background) {
|
|
746
|
-
|
|
747
|
-
|
|
398
|
+
try {
|
|
399
|
+
const output = await run.done;
|
|
400
|
+
store.finish(job, "done");
|
|
401
|
+
return { content: [{ type: "text", text: output }], details };
|
|
402
|
+
} catch (error) {
|
|
403
|
+
// Record the outcome so the launch entry cannot linger as "running".
|
|
404
|
+
const cancelled = error instanceof Error && error.message === "Delegate was aborted";
|
|
405
|
+
store.finish(job, cancelled ? "cancelled" : "failed");
|
|
406
|
+
// Failed jobs are resumable; mirror the failed background report's hint on the thrown error.
|
|
407
|
+
if (!cancelled && error instanceof Error) error.message += `\n${resumeHint(job.id)}`;
|
|
408
|
+
throw error;
|
|
409
|
+
}
|
|
748
410
|
}
|
|
749
411
|
|
|
750
|
-
|
|
751
|
-
if (!ticker) ticker = setInterval(() => refreshWidget(ctx), SPINNER_INTERVAL_MS);
|
|
412
|
+
syncTicker(ctx);
|
|
752
413
|
refreshWidget(ctx);
|
|
753
414
|
void run.done
|
|
754
415
|
.then(
|
|
@@ -829,7 +490,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
829
490
|
}),
|
|
830
491
|
async execute(_toolCallId, params) {
|
|
831
492
|
const id = jobId(params.id);
|
|
832
|
-
const job =
|
|
493
|
+
const job = store.live().find((candidate) => candidate.id === id);
|
|
833
494
|
if (!job?.steer) throw new Error(`No running delegate job "${id}".`);
|
|
834
495
|
await job.steer(params.message);
|
|
835
496
|
const details: SteerDetails = {
|
|
@@ -876,19 +537,18 @@ export default function (pi: ExtensionAPI) {
|
|
|
876
537
|
name: "delegate_cancel",
|
|
877
538
|
label: "Cancel delegate",
|
|
878
539
|
description:
|
|
879
|
-
"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.",
|
|
540
|
+
"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, but can be resumed later with the delegate tool's `resume` parameter.",
|
|
880
541
|
promptSnippet: "Cancel a running background delegate by job id",
|
|
881
542
|
parameters: Type.Object({
|
|
882
543
|
id: Type.String({ description: "Job id from delegate or delegate_list." }),
|
|
883
544
|
}),
|
|
884
545
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
885
546
|
const id = jobId(params.id);
|
|
886
|
-
const job =
|
|
547
|
+
const job = store.live().find((candidate) => candidate.id === id);
|
|
887
548
|
if (!job) throw new Error(`No running delegate job "${id}".`);
|
|
888
|
-
|
|
889
|
-
remember(job, "cancelled");
|
|
549
|
+
store.finish(job, "cancelled");
|
|
890
550
|
job.controller.abort();
|
|
891
|
-
|
|
551
|
+
syncTicker(ctx);
|
|
892
552
|
refreshWidget(ctx);
|
|
893
553
|
return {
|
|
894
554
|
content: [
|
|
@@ -923,7 +583,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
923
583
|
parameters: Type.Object({}),
|
|
924
584
|
async execute() {
|
|
925
585
|
const now = Date.now();
|
|
926
|
-
const jobs =
|
|
586
|
+
const jobs = store.live();
|
|
927
587
|
if (!jobs.length)
|
|
928
588
|
return { content: [{ type: "text", text: "No delegates are running." }], details: undefined };
|
|
929
589
|
const lastActivity = (job: DelegateJob) =>
|