@deathbeam/pi-delegate 0.0.41 → 0.0.43
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/index.ts +15 -26
- package/package.json +2 -7
- package/{agents.ts → src/agents.ts} +1 -1
- package/{child.ts → src/child.ts} +20 -91
- package/{format.ts → src/format.ts} +14 -20
- package/src/inspector.ts +378 -0
- package/{isolation.ts → src/isolation.ts} +3 -8
- package/{store.ts → src/store.ts} +53 -34
- package/inspector.ts +0 -248
package/index.ts
CHANGED
|
@@ -29,10 +29,11 @@ import {
|
|
|
29
29
|
tally,
|
|
30
30
|
textParts,
|
|
31
31
|
toolLayout,
|
|
32
|
+
toolLines,
|
|
32
33
|
widgetJobs,
|
|
33
|
-
} from "./format.ts";
|
|
34
|
-
import {
|
|
35
|
-
import { createJobStore, type DelegateJob, lastToolCall, type InspectJob } from "./store.ts";
|
|
34
|
+
} from "./src/format.ts";
|
|
35
|
+
import { runChild, sessionMessages } from "./src/child.ts";
|
|
36
|
+
import { createJobStore, type DelegateJob, lastToolCall, type InspectJob } from "./src/store.ts";
|
|
36
37
|
import {
|
|
37
38
|
applyClone,
|
|
38
39
|
cloneCwd,
|
|
@@ -40,9 +41,9 @@ import {
|
|
|
40
41
|
isolationSummary,
|
|
41
42
|
removeClone,
|
|
42
43
|
type IsolationState,
|
|
43
|
-
} from "./isolation.ts";
|
|
44
|
-
import { registerInspector } from "./inspector.ts";
|
|
45
|
-
import { agentByName, agentsFor, configFor, contextWindowFor, resolveModel, type AgentFile } from "./agents.ts";
|
|
44
|
+
} from "./src/isolation.ts";
|
|
45
|
+
import { registerInspector } from "./src/inspector.ts";
|
|
46
|
+
import { agentByName, agentsFor, configFor, contextWindowFor, resolveModel, type AgentFile } from "./src/agents.ts";
|
|
46
47
|
|
|
47
48
|
type SteerDetails = Pick<
|
|
48
49
|
DelegateJob,
|
|
@@ -156,7 +157,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
156
157
|
/** The clone is the unit: every job id that ran in it is only a handle, so state changes reach all of them. */
|
|
157
158
|
const jobsInClone = (clone: string) => store.all().filter((job) => job.isolation?.clone === clone);
|
|
158
159
|
|
|
159
|
-
/** A job that still has a clone; throws explaining why it has none. */
|
|
160
160
|
const clonedJob = (id: string) => {
|
|
161
161
|
const job = store.findOrThrow(id);
|
|
162
162
|
const isolation = job.isolation;
|
|
@@ -188,7 +188,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
188
188
|
|
|
189
189
|
const refreshWidget = (ctx: ExtensionContext) => {
|
|
190
190
|
if (!ctx.hasUI) return;
|
|
191
|
-
store.notify();
|
|
192
191
|
const jobs = store.live();
|
|
193
192
|
if (jobs.length === 0) {
|
|
194
193
|
ctx.ui.setWidget(WIDGET_KEY, undefined);
|
|
@@ -204,11 +203,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
204
203
|
const { tool, result } = lastToolCall(job);
|
|
205
204
|
if (tool)
|
|
206
205
|
lines.push(
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
lines.push(
|
|
211
|
-
` ${theme.fg("muted", "↳")} ${theme.fg(result.isError ? "error" : "toolOutput", result.text)}`,
|
|
206
|
+
...toolLines(theme, tool.name, tool.detail, result?.text, result?.isError).map(
|
|
207
|
+
(line) => ` ${line}`,
|
|
208
|
+
),
|
|
212
209
|
);
|
|
213
210
|
}
|
|
214
211
|
if (hidden) lines.push(` ${theme.fg("muted", `… ${hidden} more running · /delegate to view all`)}`);
|
|
@@ -237,16 +234,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
237
234
|
id: job.id,
|
|
238
235
|
agent: job.agent,
|
|
239
236
|
description: job.description,
|
|
240
|
-
model: job.model,
|
|
241
237
|
toolCalls: job.toolCalls,
|
|
242
238
|
contextTokens: job.contextTokens,
|
|
243
239
|
contextWindow: job.contextWindow,
|
|
244
240
|
elapsedMs: elapsedMs(job),
|
|
245
241
|
output: withIsolation(output ?? "", job.isolation),
|
|
246
242
|
error,
|
|
247
|
-
status: job.status,
|
|
248
243
|
isolation: job.isolation,
|
|
249
|
-
cloneClosed: job.cloneClosed,
|
|
250
244
|
};
|
|
251
245
|
// Idle: this starts a new turn. Streaming: steer the report in at the next turn boundary;
|
|
252
246
|
// a follow-up waits for a run end that a parent stuck polling may never reach.
|
|
@@ -286,7 +280,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
286
280
|
task,
|
|
287
281
|
model: displayModel,
|
|
288
282
|
status: "running",
|
|
289
|
-
|
|
283
|
+
messages: prior ? sessionMessages(DELEGATE_SESSION_DIR, prior.id) : [],
|
|
290
284
|
tools,
|
|
291
285
|
toolCalls: 0,
|
|
292
286
|
startedAt: Date.now(),
|
|
@@ -297,14 +291,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
297
291
|
const details: DelegateDetails = {
|
|
298
292
|
id: job.id,
|
|
299
293
|
agent: job.agent,
|
|
300
|
-
description: job.description,
|
|
301
|
-
task: job.task,
|
|
302
294
|
model: displayModel,
|
|
303
295
|
tools,
|
|
304
296
|
background: ctx.hasUI,
|
|
305
|
-
status: job.status,
|
|
306
297
|
isolation: job.isolation,
|
|
307
|
-
cloneClosed: job.cloneClosed,
|
|
308
298
|
};
|
|
309
299
|
const args = [
|
|
310
300
|
"--session-id",
|
|
@@ -404,7 +394,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
404
394
|
store.clear();
|
|
405
395
|
});
|
|
406
396
|
|
|
407
|
-
// Rebuilt from the active branch
|
|
397
|
+
// Rebuilt from the active branch: abandoned branches are alternative histories.
|
|
408
398
|
const restoreSession = (ctx: ExtensionContext) => {
|
|
409
399
|
const interrupted = store.restore(ctx.sessionManager.getBranch());
|
|
410
400
|
// Custom entries never reach the model, so announce the interrupted jobs as a steered message.
|
|
@@ -470,7 +460,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
470
460
|
return container;
|
|
471
461
|
});
|
|
472
462
|
|
|
473
|
-
registerInspector(pi, store);
|
|
463
|
+
registerInspector(pi, store, DELEGATE_SESSION_DIR);
|
|
474
464
|
|
|
475
465
|
const agentList = agentsFor(process.cwd()).map((agent) => {
|
|
476
466
|
const qualifiers = [agent.model, agent.isolated ? "isolated" : undefined].filter(Boolean).join(", ");
|
|
@@ -799,7 +789,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
799
789
|
const running = jobs.filter((job) => job.status === "running").length;
|
|
800
790
|
const lastActivity = (job: InspectJob) => {
|
|
801
791
|
const { tool } = lastToolCall(job);
|
|
802
|
-
return job.status === "running" && tool ? ` · ${tool.
|
|
792
|
+
return job.status === "running" && tool ? ` · ${tool.name}${tool.detail ? ` ${tool.detail}` : ""}` : "";
|
|
803
793
|
};
|
|
804
794
|
const lines = jobs.map((job) => {
|
|
805
795
|
const tag = isolationWords(job);
|
|
@@ -809,8 +799,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
809
799
|
content: [
|
|
810
800
|
{ type: "text", text: `${jobs.length} delegates (${running} running):\n${lines.join("\n")}` },
|
|
811
801
|
],
|
|
812
|
-
|
|
813
|
-
details: { jobs: jobs.map(store.summary) },
|
|
802
|
+
details: { jobs: jobs.map(store.snapshot) },
|
|
814
803
|
};
|
|
815
804
|
},
|
|
816
805
|
renderResult(result, _options, theme, context) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@deathbeam/pi-delegate",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.43",
|
|
4
4
|
"description": "Minimal extension for delegating tasks to subagents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -18,12 +18,7 @@
|
|
|
18
18
|
},
|
|
19
19
|
"files": [
|
|
20
20
|
"index.ts",
|
|
21
|
-
"
|
|
22
|
-
"inspector.ts",
|
|
23
|
-
"agents.ts",
|
|
24
|
-
"child.ts",
|
|
25
|
-
"format.ts",
|
|
26
|
-
"isolation.ts",
|
|
21
|
+
"src",
|
|
27
22
|
"agents",
|
|
28
23
|
"README.md",
|
|
29
24
|
"LICENSE"
|
|
@@ -20,7 +20,7 @@ type DelegateConfig = {
|
|
|
20
20
|
};
|
|
21
21
|
|
|
22
22
|
const DEFAULT_AGENT_DIR = "~/.agents/agents";
|
|
23
|
-
const BUNDLED_AGENT_DIR = fileURLToPath(new URL("
|
|
23
|
+
const BUNDLED_AGENT_DIR = fileURLToPath(new URL("../agents", import.meta.url));
|
|
24
24
|
const MODEL_TIERS = new Set(["cheap", "balanced", "strong"]);
|
|
25
25
|
|
|
26
26
|
function expandPath(value: string, cwd: string): string {
|
|
@@ -1,20 +1,18 @@
|
|
|
1
1
|
import type { ChildProcessWithoutNullStreams } from "node:child_process";
|
|
2
|
-
import { readdirSync
|
|
2
|
+
import { readdirSync } from "node:fs";
|
|
3
3
|
import { join } from "node:path";
|
|
4
|
-
import {
|
|
4
|
+
import { SessionManager, type MessageEndEvent } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { limitOutput, textParts } from "./format.ts";
|
|
5
6
|
|
|
6
7
|
type Child = ChildProcessWithoutNullStreams;
|
|
7
8
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
text: string;
|
|
11
|
-
detail?: string;
|
|
12
|
-
isError?: boolean;
|
|
13
|
-
};
|
|
9
|
+
/** A child message in the shape pi's chat components render. */
|
|
10
|
+
export type ChildMessage = MessageEndEvent["message"];
|
|
14
11
|
export type ChildUpdate = {
|
|
15
12
|
toolCalls?: number;
|
|
16
13
|
contextTokens?: number;
|
|
17
|
-
|
|
14
|
+
/** A message the child finished; the store appends it to the job's transcript. */
|
|
15
|
+
message?: ChildMessage;
|
|
18
16
|
};
|
|
19
17
|
type ChildUpdateHandler = (update: ChildUpdate) => void;
|
|
20
18
|
|
|
@@ -127,46 +125,23 @@ export function runChild(
|
|
|
127
125
|
switch (event.type) {
|
|
128
126
|
case "tool_execution_start": {
|
|
129
127
|
toolCalls += 1;
|
|
130
|
-
|
|
131
|
-
onUpdate?.({
|
|
132
|
-
toolCalls,
|
|
133
|
-
activity: { kind: "tool", text: event.toolName, detail },
|
|
134
|
-
});
|
|
135
|
-
return;
|
|
136
|
-
}
|
|
137
|
-
case "tool_execution_end": {
|
|
138
|
-
const preview = resultPreview(event.result);
|
|
139
|
-
onUpdate?.({
|
|
140
|
-
activity: {
|
|
141
|
-
kind: "result",
|
|
142
|
-
text: preview ?? "",
|
|
143
|
-
...(event.isError ? { isError: true } : {}),
|
|
144
|
-
},
|
|
145
|
-
});
|
|
128
|
+
onUpdate?.({ toolCalls });
|
|
146
129
|
return;
|
|
147
130
|
}
|
|
148
131
|
case "message_update": {
|
|
149
|
-
const delta =
|
|
150
|
-
event.assistantMessageEvent?.type === "text_delta"
|
|
151
|
-
? (event.assistantMessageEvent.delta ?? "")
|
|
152
|
-
: "";
|
|
153
|
-
if (delta) liveText += delta;
|
|
154
132
|
onUpdate?.({ contextTokens: usageTokens(event.usage) });
|
|
155
133
|
return;
|
|
156
134
|
}
|
|
157
135
|
case "message_end": {
|
|
158
|
-
const
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
136
|
+
const message = event.message as ChildMessage;
|
|
137
|
+
let contextTokens: number | undefined;
|
|
138
|
+
if (message.role === "assistant") {
|
|
139
|
+
childError = message.errorMessage;
|
|
140
|
+
const text = textParts(message.content).join("");
|
|
163
141
|
if (text) liveText = text;
|
|
142
|
+
contextTokens = usageTokens(message.usage);
|
|
164
143
|
}
|
|
165
|
-
|
|
166
|
-
onUpdate?.({
|
|
167
|
-
contextTokens: usageTokens(event.message.usage),
|
|
168
|
-
activity: { kind: role, text },
|
|
169
|
-
});
|
|
144
|
+
onUpdate?.({ contextTokens, message });
|
|
170
145
|
return;
|
|
171
146
|
}
|
|
172
147
|
case "agent_settled":
|
|
@@ -263,7 +238,7 @@ export function runChild(
|
|
|
263
238
|
});
|
|
264
239
|
};
|
|
265
240
|
if (revive) {
|
|
266
|
-
// An empty transcript means the pinned session was recreated (e.g. a different cwd)
|
|
241
|
+
// An empty transcript means the pinned session was recreated (e.g. a different cwd); prompting would lose the task.
|
|
267
242
|
void send({ type: "get_state" })
|
|
268
243
|
.then((data) => {
|
|
269
244
|
if (!settled && !aborted && !data?.messageCount) {
|
|
@@ -299,11 +274,10 @@ export function runChild(
|
|
|
299
274
|
}
|
|
300
275
|
|
|
301
276
|
/**
|
|
302
|
-
*
|
|
303
|
-
*
|
|
304
|
-
* itself still works.
|
|
277
|
+
* The child's persisted transcript, for a job whose messages are not in memory. A missing or
|
|
278
|
+
* unreadable session seeds nothing: the job still renders, just without history.
|
|
305
279
|
*/
|
|
306
|
-
export function
|
|
280
|
+
export function sessionMessages(sessionDir: string, id: string): ChildMessage[] {
|
|
307
281
|
let sessionFile: string | undefined;
|
|
308
282
|
try {
|
|
309
283
|
// Sessions are <timestamp>_<sessionId>.jsonl; a recreated pinned session is the newest one.
|
|
@@ -315,54 +289,9 @@ export function priorActivity(sessionDir: string, id: string): ChildActivity[] {
|
|
|
315
289
|
return [];
|
|
316
290
|
}
|
|
317
291
|
if (!sessionFile) return [];
|
|
318
|
-
let lines: string[];
|
|
319
292
|
try {
|
|
320
|
-
|
|
293
|
+
return SessionManager.open(join(sessionDir, sessionFile)).buildSessionContext().messages;
|
|
321
294
|
} catch {
|
|
322
295
|
return [];
|
|
323
296
|
}
|
|
324
|
-
const normalize = (text: string) => text.replace(/\s+/g, " ").trim();
|
|
325
|
-
const activity: ChildActivity[] = [];
|
|
326
|
-
for (const line of lines) {
|
|
327
|
-
if (!line.trim()) continue;
|
|
328
|
-
let entry: { type?: string; message?: unknown };
|
|
329
|
-
try {
|
|
330
|
-
entry = JSON.parse(line);
|
|
331
|
-
} catch {
|
|
332
|
-
continue; // Same tolerance pi's session reader has for malformed lines.
|
|
333
|
-
}
|
|
334
|
-
const message =
|
|
335
|
-
entry?.type === "message"
|
|
336
|
-
? (entry.message as {
|
|
337
|
-
role?: "assistant" | "user" | "toolResult";
|
|
338
|
-
content?: unknown;
|
|
339
|
-
isError?: boolean;
|
|
340
|
-
})
|
|
341
|
-
: undefined;
|
|
342
|
-
if (!message?.role) continue;
|
|
343
|
-
if (message.role === "toolResult") {
|
|
344
|
-
const preview = resultPreview({ content: message.content });
|
|
345
|
-
activity.push({
|
|
346
|
-
kind: "result",
|
|
347
|
-
text: normalize(preview ?? ""),
|
|
348
|
-
...(message.isError ? { isError: true } : {}),
|
|
349
|
-
});
|
|
350
|
-
continue;
|
|
351
|
-
}
|
|
352
|
-
// Assistant text lands before its tool calls, matching the live event order.
|
|
353
|
-
const text = textParts(message.content).join("");
|
|
354
|
-
if (text) activity.push({ kind: message.role, text });
|
|
355
|
-
if (message.role !== "assistant") continue;
|
|
356
|
-
for (const part of Array.isArray(message.content) ? message.content : []) {
|
|
357
|
-
const call =
|
|
358
|
-
part && typeof part === "object" ? (part as { type?: string; name?: string; arguments?: unknown }) : {};
|
|
359
|
-
if (call.type !== "toolCall" || !call.name) continue;
|
|
360
|
-
activity.push({
|
|
361
|
-
kind: "tool",
|
|
362
|
-
text: normalize(call.name),
|
|
363
|
-
detail: normalize(toolCallDetail(call.name, call.arguments)) || undefined,
|
|
364
|
-
});
|
|
365
|
-
}
|
|
366
|
-
}
|
|
367
|
-
return activity;
|
|
368
297
|
}
|
|
@@ -20,16 +20,13 @@ export type DelegateReport = {
|
|
|
20
20
|
id: string;
|
|
21
21
|
agent: string;
|
|
22
22
|
description: string;
|
|
23
|
-
model?: string;
|
|
24
23
|
toolCalls: number;
|
|
25
24
|
contextTokens?: number;
|
|
26
25
|
contextWindow?: number;
|
|
27
26
|
elapsedMs: number;
|
|
28
27
|
output?: string;
|
|
29
28
|
error?: string;
|
|
30
|
-
status: JobStatus;
|
|
31
29
|
isolation?: IsolationState;
|
|
32
|
-
cloneClosed?: boolean;
|
|
33
30
|
};
|
|
34
31
|
|
|
35
32
|
/** The isolation state to show for a job: pending means its clone still holds unapplied work. */
|
|
@@ -37,14 +34,12 @@ export type IsolationMark = "isolated" | "pending";
|
|
|
37
34
|
|
|
38
35
|
type IsolationStateFields = {
|
|
39
36
|
isolation?: unknown;
|
|
40
|
-
cloneClosed?: boolean;
|
|
41
37
|
status?: string;
|
|
42
38
|
};
|
|
43
39
|
|
|
44
|
-
export type DelegateDetails = Pick<
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
> & { background: boolean };
|
|
40
|
+
export type DelegateDetails = Pick<DelegateJob, "id" | "agent" | "model" | "tools" | "isolation"> & {
|
|
41
|
+
background: boolean;
|
|
42
|
+
};
|
|
48
43
|
|
|
49
44
|
const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
50
45
|
export const SPINNER_INTERVAL_MS = 100;
|
|
@@ -80,7 +75,7 @@ export function statusText(theme: Theme, status: JobStatus, now = Date.now()): s
|
|
|
80
75
|
/** Derives the mark from a job: an isolation with no clone left, or a still-running one, is not pending. */
|
|
81
76
|
export function isolationMarkOf(job: IsolationStateFields): IsolationMark | undefined {
|
|
82
77
|
if (!job.isolation) return undefined;
|
|
83
|
-
return job.
|
|
78
|
+
return job.status === "running" ? "isolated" : "pending";
|
|
84
79
|
}
|
|
85
80
|
|
|
86
81
|
/** `⎇`, warning-colored while the clone's work is still unapplied. */
|
|
@@ -134,6 +129,12 @@ export function tally(running: number, all: { startedAt: number; endedAt?: numbe
|
|
|
134
129
|
return `${running} running · ${all.length} total · ${formatDuration(total)}`;
|
|
135
130
|
}
|
|
136
131
|
|
|
132
|
+
/** A tool call's call row and, once it arrives, its result preview row; shared by the widget and the inspector. */
|
|
133
|
+
export function toolLines(theme: Theme, name: string, detail: string, result?: string, isError?: boolean): string[] {
|
|
134
|
+
const call = `${theme.fg("toolTitle", theme.bold(name))}${detail ? ` ${theme.fg("accent", detail)}` : ""}`;
|
|
135
|
+
return result ? [call, `${theme.fg("muted", "↳")} ${theme.fg(isError ? "error" : "toolOutput", result)}`] : [call];
|
|
136
|
+
}
|
|
137
|
+
|
|
137
138
|
export function toolCallDetail(toolName: string, args: unknown): string {
|
|
138
139
|
const input = (args ?? {}) as Record<string, unknown>;
|
|
139
140
|
const value = (key: string) => (typeof input[key] === "string" ? (input[key] as string).trim() : "");
|
|
@@ -187,7 +188,6 @@ export function capDiff(text: string): { diff: string; note?: string } {
|
|
|
187
188
|
return { diff: capped.slice(0, at), note: capped.slice(at + 2) };
|
|
188
189
|
}
|
|
189
190
|
|
|
190
|
-
/** The text parts of a message or tool result's content, in order. */
|
|
191
191
|
export function textParts(content: unknown): string[] {
|
|
192
192
|
if (typeof content === "string") return [content];
|
|
193
193
|
if (!Array.isArray(content)) return [];
|
|
@@ -212,12 +212,7 @@ export function reviveHint(id: string): string {
|
|
|
212
212
|
return `To continue this job, call delegate_steer with id ${id} and a message.`;
|
|
213
213
|
}
|
|
214
214
|
|
|
215
|
-
/**
|
|
216
|
-
* Converts a git unified diff into pi's own diff format (`+12 content` / `-12 content` / ` 12 content`,
|
|
217
|
-
* prefix, padded line number, space, content), which is what pi's renderDiff colors; a raw unified
|
|
218
|
-
* diff renders as flat context. Line numbers come from the @@ headers (- uses the old side, + and
|
|
219
|
-
* context the new side); the file path heads each file and `...` separates its hunks.
|
|
220
|
-
*/
|
|
215
|
+
/** Converts a git unified diff into pi's `+12 content` format, which renderDiff colors; a raw unified diff renders flat. */
|
|
221
216
|
export function piDiff(unified: string): string {
|
|
222
217
|
const out: string[] = [];
|
|
223
218
|
let path = "";
|
|
@@ -280,10 +275,9 @@ export function reportText(report: DelegateReport): string {
|
|
|
280
275
|
if (report.error) return `${head} failed: ${report.error}\n${reviveHint(report.id)}`;
|
|
281
276
|
const output = (report.output ?? "").trim();
|
|
282
277
|
// The apply hint is for the model only: the transcript renders `output`, so users never see it.
|
|
283
|
-
const hint =
|
|
284
|
-
report.
|
|
285
|
-
|
|
286
|
-
: "";
|
|
278
|
+
const hint = report.isolation
|
|
279
|
+
? `\n\nCall delegate_apply with job ${report.id} to land its changes, or delegate_discard to drop them. Call one, not both: a successful apply removes the clone.`
|
|
280
|
+
: "";
|
|
287
281
|
return `${head} finished.${output ? `\n\n${output}` : ""}${hint}`;
|
|
288
282
|
}
|
|
289
283
|
|
package/src/inspector.ts
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AssistantMessageComponent,
|
|
3
|
+
type ExtensionAPI,
|
|
4
|
+
rawKeyHint,
|
|
5
|
+
type Theme,
|
|
6
|
+
UserMessageComponent,
|
|
7
|
+
} from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import {
|
|
9
|
+
Box,
|
|
10
|
+
type Component,
|
|
11
|
+
type Keybinding,
|
|
12
|
+
matchesKey,
|
|
13
|
+
Spacer,
|
|
14
|
+
Text,
|
|
15
|
+
truncateToWidth,
|
|
16
|
+
wrapTextWithAnsi,
|
|
17
|
+
} from "@earendil-works/pi-tui";
|
|
18
|
+
import { type ChildMessage, sessionMessages } from "./child.ts";
|
|
19
|
+
import {
|
|
20
|
+
elapsedMs,
|
|
21
|
+
formatTools,
|
|
22
|
+
jobIdentity,
|
|
23
|
+
resultPreview,
|
|
24
|
+
STATUS_COLORS,
|
|
25
|
+
statusText,
|
|
26
|
+
tally,
|
|
27
|
+
textParts,
|
|
28
|
+
toolCallDetail,
|
|
29
|
+
toolLines,
|
|
30
|
+
usageStats,
|
|
31
|
+
} from "./format.ts";
|
|
32
|
+
import type { InspectJob, JobStore } from "./store.ts";
|
|
33
|
+
|
|
34
|
+
type Entry = { component: Component; lines?: string[] };
|
|
35
|
+
|
|
36
|
+
// pi's chat components prefix lines with OSC 133 prompt markers; past the sidebar the terminal would read one as a new prompt.
|
|
37
|
+
const OSC133 = /^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;
|
|
38
|
+
|
|
39
|
+
/** Rendered transcript rows, cached per width so a frame only renders rows it has never seen. */
|
|
40
|
+
export class History {
|
|
41
|
+
private readonly entries: Entry[] = [];
|
|
42
|
+
private width = 0;
|
|
43
|
+
|
|
44
|
+
add(component: Component): Entry {
|
|
45
|
+
const entry: Entry = { component };
|
|
46
|
+
this.entries.push(entry);
|
|
47
|
+
return entry;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
invalidate() {
|
|
51
|
+
for (const entry of this.entries) {
|
|
52
|
+
entry.component.invalidate?.();
|
|
53
|
+
entry.lines = undefined;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
window(width: number, top: number | undefined, height: number) {
|
|
58
|
+
if (this.width !== width) {
|
|
59
|
+
this.width = width;
|
|
60
|
+
for (const entry of this.entries) entry.lines = undefined;
|
|
61
|
+
}
|
|
62
|
+
const all = this.entries.flatMap(
|
|
63
|
+
(entry) => (entry.lines ??= entry.component.render(width).map((line) => line.replace(OSC133, ""))),
|
|
64
|
+
);
|
|
65
|
+
const start = Math.min(top ?? Infinity, Math.max(0, all.length - height));
|
|
66
|
+
return { lines: all.slice(start, start + height), start, total: all.length };
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** One tool call as a compact pi-style box: the call row plus the result's first line. */
|
|
71
|
+
class ToolRow implements Component {
|
|
72
|
+
private readonly theme: Theme;
|
|
73
|
+
private readonly name: string;
|
|
74
|
+
private readonly detail: string;
|
|
75
|
+
private result?: string;
|
|
76
|
+
private done = false;
|
|
77
|
+
private error = false;
|
|
78
|
+
|
|
79
|
+
constructor(theme: Theme, name: string, detail: string) {
|
|
80
|
+
this.theme = theme;
|
|
81
|
+
this.name = name;
|
|
82
|
+
this.detail = detail;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
invalidate() {}
|
|
86
|
+
|
|
87
|
+
setResult(message: Extract<ChildMessage, { role: "toolResult" }>) {
|
|
88
|
+
this.result = resultPreview(message);
|
|
89
|
+
this.done = true;
|
|
90
|
+
this.error = message.isError === true;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
render(width: number) {
|
|
94
|
+
const theme = this.theme;
|
|
95
|
+
// The box's own horizontal padding leaves width - 2 for each truncated row.
|
|
96
|
+
const inner = Math.max(1, width - 2);
|
|
97
|
+
const text = toolLines(theme, this.name, this.detail, this.result, this.error)
|
|
98
|
+
.map((line) => truncateToWidth(line, inner))
|
|
99
|
+
.join("\n");
|
|
100
|
+
const bg = this.error ? "toolErrorBg" : this.done ? "toolSuccessBg" : "toolPendingBg";
|
|
101
|
+
// pi's own tool box and spacing; only the content is compact.
|
|
102
|
+
const box = new Box(1, 1, (line) => theme.bg(bg, line));
|
|
103
|
+
box.addChild(new Text(text, 0, 0));
|
|
104
|
+
return ["", ...box.render(width)];
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** One job's transcript, built from pi's chat components and kept in sync as messages arrive. */
|
|
109
|
+
export class Transcript {
|
|
110
|
+
private history = new History();
|
|
111
|
+
private messages?: ChildMessage[];
|
|
112
|
+
private count = 0;
|
|
113
|
+
private readonly pending = new Map<string, Entry>();
|
|
114
|
+
private readonly theme: Theme;
|
|
115
|
+
|
|
116
|
+
constructor(theme: Theme) {
|
|
117
|
+
this.theme = theme;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
sync(messages: ChildMessage[]) {
|
|
121
|
+
// The store swaps a finished job's live array for the session file's, so a different array is a new transcript.
|
|
122
|
+
if (messages !== this.messages) {
|
|
123
|
+
this.messages = messages;
|
|
124
|
+
this.history = new History();
|
|
125
|
+
this.count = 0;
|
|
126
|
+
this.pending.clear();
|
|
127
|
+
}
|
|
128
|
+
while (this.count < messages.length) this.add(messages[this.count++]!);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
window(width: number, top: number | undefined, height: number) {
|
|
132
|
+
return this.history.window(width, top, height);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
invalidate() {
|
|
136
|
+
this.history.invalidate();
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
private add(message: ChildMessage) {
|
|
140
|
+
if (message.role === "user") {
|
|
141
|
+
const text = textParts(message.content).join("");
|
|
142
|
+
if (!text) return;
|
|
143
|
+
// pi's chat spaces user messages itself; the component carries no margin.
|
|
144
|
+
this.history.add(new Spacer(1));
|
|
145
|
+
this.history.add(new UserMessageComponent(text));
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
if (message.role === "assistant") {
|
|
149
|
+
// Thinking blocks are the child's scratchpad; the inspector shows what it said and did.
|
|
150
|
+
this.history.add(new AssistantMessageComponent(message, true, undefined, ""));
|
|
151
|
+
for (const part of message.content) {
|
|
152
|
+
if (part.type !== "toolCall") continue;
|
|
153
|
+
const row = new ToolRow(this.theme, part.name, toolCallDetail(part.name, part.arguments));
|
|
154
|
+
this.pending.set(part.id, this.history.add(row));
|
|
155
|
+
}
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (message.role === "toolResult") {
|
|
159
|
+
const entry = this.pending.get(message.toolCallId);
|
|
160
|
+
if (!entry) return;
|
|
161
|
+
(entry.component as ToolRow).setResult(message);
|
|
162
|
+
entry.lines = undefined;
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
// display: false marks model-only context (e.g. pi-archive's recent sessions); pi's chat hides it too.
|
|
166
|
+
if ((message as { display?: boolean }).display === false) return;
|
|
167
|
+
const text =
|
|
168
|
+
message.role === "compactionSummary"
|
|
169
|
+
? message.summary
|
|
170
|
+
: textParts((message as { content?: unknown }).content).join("");
|
|
171
|
+
if (!text) return;
|
|
172
|
+
this.history.add(new Spacer(1));
|
|
173
|
+
this.history.add(new Text(text, 1, 0));
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** The /delegate command: a full-screen inspector over the job store. */
|
|
178
|
+
export function registerInspector(pi: ExtensionAPI, store: JobStore, sessionDir: string) {
|
|
179
|
+
pi.registerCommand("delegate", {
|
|
180
|
+
description: "Inspect live and recent delegate activity",
|
|
181
|
+
handler: async (_args, ctx) => {
|
|
182
|
+
if (ctx.mode !== "tui") return;
|
|
183
|
+
if (!store.all().length) {
|
|
184
|
+
ctx.ui.notify("No delegates in this session yet.", "info");
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
const screen = {
|
|
188
|
+
overlay: true,
|
|
189
|
+
overlayOptions: { width: "100%", maxHeight: "100%", row: 0, col: 0 },
|
|
190
|
+
} as const;
|
|
191
|
+
let stopRedraw: (() => void) | undefined;
|
|
192
|
+
try {
|
|
193
|
+
await ctx.ui.custom((tui, theme, keys, done) => {
|
|
194
|
+
let selectedId = store.all()[0]!.id;
|
|
195
|
+
let focus: "list" | "history" = "list";
|
|
196
|
+
let top: number | undefined;
|
|
197
|
+
let lastWindow = { height: 0, total: 0 };
|
|
198
|
+
const transcripts = new Map<string, Transcript>();
|
|
199
|
+
const loaded = new Set<string>();
|
|
200
|
+
const jobs = () => store.all();
|
|
201
|
+
// Format hints from the injected manager; an imported copy would not see the user's keybindings.
|
|
202
|
+
const hint = (id: Keybinding, description: string) =>
|
|
203
|
+
rawKeyHint(keys.getKeys(id).join("/"), description);
|
|
204
|
+
// Fixed rows: title, top rule, bottom rule, footer.
|
|
205
|
+
const bodyHeight = () => Math.max(0, tui.terminal.rows - 4);
|
|
206
|
+
const toolsLines = (job: InspectJob, width: number) =>
|
|
207
|
+
wrapTextWithAnsi(formatTools(job.tools), Math.max(1, width)).map((line) =>
|
|
208
|
+
theme.fg("dim", line),
|
|
209
|
+
);
|
|
210
|
+
const transcript = (job: InspectJob) => {
|
|
211
|
+
let value = transcripts.get(job.id);
|
|
212
|
+
if (!value) {
|
|
213
|
+
value = new Transcript(theme);
|
|
214
|
+
transcripts.set(job.id, value);
|
|
215
|
+
}
|
|
216
|
+
return value;
|
|
217
|
+
};
|
|
218
|
+
// Restored jobs carry no messages: the child's session file is their history.
|
|
219
|
+
const messagesOf = (job: InspectJob) => {
|
|
220
|
+
if (!job.messages.length && job.status !== "running" && !loaded.has(job.id)) {
|
|
221
|
+
loaded.add(job.id);
|
|
222
|
+
job.messages = sessionMessages(sessionDir, job.id);
|
|
223
|
+
}
|
|
224
|
+
return job.messages;
|
|
225
|
+
};
|
|
226
|
+
const renderJobs = (width: number, items: InspectJob[], selectedIndex: number): string[] => {
|
|
227
|
+
const row = (text: string) =>
|
|
228
|
+
truncateToWidth(text, Math.max(0, width - 1), "…", true) + theme.fg("borderMuted", "│");
|
|
229
|
+
const visible = Math.max(1, Math.floor((bodyHeight() - 1) / 3));
|
|
230
|
+
const start = Math.max(
|
|
231
|
+
0,
|
|
232
|
+
Math.min(selectedIndex - Math.floor(visible / 2), items.length - visible),
|
|
233
|
+
);
|
|
234
|
+
const lines = items
|
|
235
|
+
.slice(start, start + visible)
|
|
236
|
+
.flatMap((item, index) => [
|
|
237
|
+
row(
|
|
238
|
+
`${theme.fg(start + index === selectedIndex && focus === "list" ? "accent" : "text", start + index === selectedIndex ? "›" : " ")} ${statusText(theme, item.status)} ${jobIdentity(theme, item)}`,
|
|
239
|
+
),
|
|
240
|
+
row(theme.fg("muted", ` ${item.description}`)),
|
|
241
|
+
row(theme.fg("muted", ` ${usageStats(item, elapsedMs(item))}`)),
|
|
242
|
+
]);
|
|
243
|
+
return [
|
|
244
|
+
...lines,
|
|
245
|
+
...Array(Math.max(0, bodyHeight() - 1 - lines.length)).fill(row("")),
|
|
246
|
+
row(theme.fg("dim", `${selectedIndex + 1}/${items.length}`)),
|
|
247
|
+
].slice(0, bodyHeight());
|
|
248
|
+
};
|
|
249
|
+
const renderHistory = (width: number, job: InspectJob): string[] => {
|
|
250
|
+
const tools = toolsLines(job, width);
|
|
251
|
+
// Fixed rows: header, model, description, rule, counter, plus the failure detail.
|
|
252
|
+
const height = Math.max(0, bodyHeight() - 5 - tools.length - (job.detail ? 1 : 0));
|
|
253
|
+
const view = transcript(job);
|
|
254
|
+
view.sync(messagesOf(job));
|
|
255
|
+
const window = view.window(width, top, height);
|
|
256
|
+
lastWindow = { height, total: window.total };
|
|
257
|
+
const shown = window.lines.length
|
|
258
|
+
? window.lines
|
|
259
|
+
: height
|
|
260
|
+
? [
|
|
261
|
+
theme.fg(
|
|
262
|
+
"muted",
|
|
263
|
+
job.status === "interrupted"
|
|
264
|
+
? "Interrupted by a crash before activity was recorded."
|
|
265
|
+
: "Waiting for activity…",
|
|
266
|
+
),
|
|
267
|
+
]
|
|
268
|
+
: [];
|
|
269
|
+
const counter = window.lines.length
|
|
270
|
+
? `${window.start + 1}–${window.start + window.lines.length}`
|
|
271
|
+
: "0";
|
|
272
|
+
return (
|
|
273
|
+
[
|
|
274
|
+
truncateToWidth(
|
|
275
|
+
`${statusText(theme, job.status)} ${jobIdentity(theme, job)} ${theme.fg("muted", usageStats(job, elapsedMs(job)))}`,
|
|
276
|
+
width,
|
|
277
|
+
),
|
|
278
|
+
truncateToWidth(theme.fg("dim", job.model), width),
|
|
279
|
+
...tools,
|
|
280
|
+
truncateToWidth(theme.fg("text", theme.bold(job.description)), width),
|
|
281
|
+
theme.fg("borderMuted", "─".repeat(Math.max(0, width))),
|
|
282
|
+
...shown,
|
|
283
|
+
...Array(Math.max(0, height - shown.length)).fill(""),
|
|
284
|
+
...(job.detail
|
|
285
|
+
? [truncateToWidth(theme.fg(STATUS_COLORS.failed, job.detail), width)]
|
|
286
|
+
: []),
|
|
287
|
+
truncateToWidth(theme.fg("dim", `${counter}/${window.total}`), width),
|
|
288
|
+
]
|
|
289
|
+
.slice(0, bodyHeight())
|
|
290
|
+
// Pad every row so the pane's right edge holds still while the transcript scrolls.
|
|
291
|
+
.map((line) => truncateToWidth(line, width, "…", true))
|
|
292
|
+
);
|
|
293
|
+
};
|
|
294
|
+
stopRedraw = store.subscribe(() => tui.requestRender());
|
|
295
|
+
return {
|
|
296
|
+
render(width: number) {
|
|
297
|
+
const items = jobs();
|
|
298
|
+
const selectedIndex = Math.max(
|
|
299
|
+
0,
|
|
300
|
+
items.findIndex((item) => item.id === selectedId),
|
|
301
|
+
);
|
|
302
|
+
const selected = items[selectedIndex];
|
|
303
|
+
const title = truncateToWidth(
|
|
304
|
+
`${theme.fg(focus === "list" ? "accent" : "muted", focus === "list" ? "[Jobs]" : "Jobs")} ` +
|
|
305
|
+
`${theme.fg(focus === "history" ? "accent" : "muted", focus === "history" ? "[Activity]" : "Activity")}` +
|
|
306
|
+
theme.fg("dim", ` · ${tally(store.live().length, items)}`),
|
|
307
|
+
width,
|
|
308
|
+
"…",
|
|
309
|
+
true,
|
|
310
|
+
);
|
|
311
|
+
const footer = truncateToWidth(
|
|
312
|
+
theme.fg(
|
|
313
|
+
"dim",
|
|
314
|
+
`${hint("tui.select.up", "up")} · ${hint("tui.select.down", "down")} · ${rawKeyHint("←/→", "switch pane")} · ${hint("tui.select.cancel", "close")}`,
|
|
315
|
+
),
|
|
316
|
+
width,
|
|
317
|
+
"…",
|
|
318
|
+
true,
|
|
319
|
+
);
|
|
320
|
+
const rule = theme.fg("borderMuted", "─".repeat(Math.max(0, width)));
|
|
321
|
+
if (!selected)
|
|
322
|
+
return [
|
|
323
|
+
title,
|
|
324
|
+
theme.fg("muted", "No delegates in this session."),
|
|
325
|
+
...Array(Math.max(0, tui.terminal.rows - 4)).fill(" ".repeat(Math.max(0, width))),
|
|
326
|
+
footer,
|
|
327
|
+
].slice(0, tui.terminal.rows);
|
|
328
|
+
const sidebarWidth = Math.min(
|
|
329
|
+
40,
|
|
330
|
+
Math.max(16, Math.floor(width * 0.35)),
|
|
331
|
+
Math.max(1, width - 2),
|
|
332
|
+
);
|
|
333
|
+
const historyWidth = Math.max(1, width - sidebarWidth - 1);
|
|
334
|
+
// HStack measures a child at the full width first, so composing the panes here keeps one render per frame.
|
|
335
|
+
const left = renderJobs(sidebarWidth, items, selectedIndex);
|
|
336
|
+
const right = renderHistory(historyWidth, selected);
|
|
337
|
+
const body = left.map((line, index) => `${line} ${right[index] ?? ""}`);
|
|
338
|
+
return [title, rule, ...body, rule, footer].slice(0, tui.terminal.rows);
|
|
339
|
+
},
|
|
340
|
+
invalidate() {
|
|
341
|
+
for (const value of transcripts.values()) value.invalidate();
|
|
342
|
+
},
|
|
343
|
+
handleInput(data: string) {
|
|
344
|
+
if (keys.matches(data, "tui.select.cancel")) done(undefined);
|
|
345
|
+
else if (matchesKey(data, "left")) focus = "list";
|
|
346
|
+
else if (
|
|
347
|
+
matchesKey(data, "right") ||
|
|
348
|
+
(focus === "list" && keys.matches(data, "tui.select.confirm"))
|
|
349
|
+
)
|
|
350
|
+
focus = "history";
|
|
351
|
+
else if (keys.matches(data, "tui.select.up") || keys.matches(data, "tui.select.down")) {
|
|
352
|
+
const up = keys.matches(data, "tui.select.up");
|
|
353
|
+
const items = jobs();
|
|
354
|
+
if (focus === "list") {
|
|
355
|
+
const index = Math.max(
|
|
356
|
+
0,
|
|
357
|
+
items.findIndex((item) => item.id === selectedId),
|
|
358
|
+
);
|
|
359
|
+
selectedId =
|
|
360
|
+
items[Math.max(0, Math.min(items.length - 1, index + (up ? -1 : 1)))]?.id ??
|
|
361
|
+
selectedId;
|
|
362
|
+
top = undefined;
|
|
363
|
+
} else {
|
|
364
|
+
const maxTop = Math.max(0, lastWindow.total - lastWindow.height);
|
|
365
|
+
const position = Math.max(0, Math.min(maxTop, top ?? maxTop) + (up ? -1 : 1));
|
|
366
|
+
top = position >= maxTop ? undefined : position;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
tui.requestRender();
|
|
370
|
+
},
|
|
371
|
+
};
|
|
372
|
+
}, screen);
|
|
373
|
+
} finally {
|
|
374
|
+
stopRedraw?.();
|
|
375
|
+
}
|
|
376
|
+
},
|
|
377
|
+
});
|
|
378
|
+
}
|
|
@@ -46,11 +46,7 @@ function rootOf(iso: IsolationState): string {
|
|
|
46
46
|
return resolve(iso.clone, "..", "..", "..");
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
-
/**
|
|
50
|
-
* Commits the main tree's current content (committed, uncommitted, and untracked files, honoring
|
|
51
|
-
* .gitignore) with the recorded base as parent, through a scratch index so the clone's own checkout
|
|
52
|
-
* and index stay untouched. Updates and returns the `main-snapshot` branch.
|
|
53
|
-
*/
|
|
49
|
+
/** Commits the main tree's current content through a scratch index, so the clone's own checkout and index stay untouched. */
|
|
54
50
|
function snapshotMainTree(iso: IsolationState, root: string): string {
|
|
55
51
|
const gitDir = join(iso.clone, ".git");
|
|
56
52
|
const indexFile = join(gitDir, "pi-delegate-snapshot-index");
|
|
@@ -136,9 +132,8 @@ export function removeClone(iso: IsolationState): void {
|
|
|
136
132
|
}
|
|
137
133
|
|
|
138
134
|
/**
|
|
139
|
-
* Merges the
|
|
140
|
-
*
|
|
141
|
-
* The main repository's .git is never written to; only its working tree receives the final patch.
|
|
135
|
+
* Merges the clone into the main working tree. Base rule: `base` tracks the newest `main-snapshot`, so a
|
|
136
|
+
* repeat apply is correct whether or not the delegate rebased onto it yet. Only the main tree is written.
|
|
142
137
|
*/
|
|
143
138
|
export function applyClone(iso: IsolationState): ApplyResult {
|
|
144
139
|
const root = rootOf(iso);
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ChildMessage, ChildUpdate } from "./child.ts";
|
|
2
|
+
import { resultPreview, toolCallDetail } from "./format.ts";
|
|
2
3
|
import type { IsolationState } from "./isolation.ts";
|
|
3
4
|
|
|
4
5
|
export type JobStatus = "running" | "done" | "failed" | "cancelled" | "interrupted";
|
|
@@ -15,7 +16,10 @@ export type InspectJob = {
|
|
|
15
16
|
startedAt: number;
|
|
16
17
|
endedAt?: number;
|
|
17
18
|
status: JobStatus;
|
|
18
|
-
|
|
19
|
+
/** The child's transcript, kept in memory only: its session file is the source of truth. */
|
|
20
|
+
messages: ChildMessage[];
|
|
21
|
+
/** The failure detail shown under a finished job's transcript. */
|
|
22
|
+
detail?: string;
|
|
19
23
|
isolation?: IsolationState;
|
|
20
24
|
/** Set once an isolated job's clone was applied or discarded, so a steer revive refuses instead of rerunning in the main tree. */
|
|
21
25
|
cloneClosed?: boolean;
|
|
@@ -68,25 +72,11 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
|
|
|
68
72
|
const { controller, steer, swapModel, ...rest } = job as InspectJob & Partial<DelegateJob>;
|
|
69
73
|
return rest;
|
|
70
74
|
};
|
|
71
|
-
/** The serializable form of a job: runtime handles stay out. */
|
|
72
|
-
const snapshot = (job: InspectJob): InspectJob => {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
};
|
|
77
|
-
const addActivity = (job: DelegateJob, activity: ChildActivity) => {
|
|
78
|
-
const normalize = (text: string) => text.replace(/\s+/g, " ").trim();
|
|
79
|
-
job.activity.push(
|
|
80
|
-
activity.kind === "assistant" || activity.kind === "user"
|
|
81
|
-
? activity
|
|
82
|
-
: {
|
|
83
|
-
...activity,
|
|
84
|
-
text: normalize(activity.text),
|
|
85
|
-
detail: activity.detail && normalize(activity.detail),
|
|
86
|
-
},
|
|
87
|
-
);
|
|
88
|
-
notify();
|
|
89
|
-
};
|
|
75
|
+
/** The serializable form of a job: runtime handles and the transcript stay out. */
|
|
76
|
+
const snapshot = (job: InspectJob): InspectJob => ({
|
|
77
|
+
...plain(job),
|
|
78
|
+
messages: [],
|
|
79
|
+
});
|
|
90
80
|
|
|
91
81
|
return {
|
|
92
82
|
/** Every job a view can show: live first, then history. */
|
|
@@ -94,8 +84,6 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
|
|
|
94
84
|
live: (): DelegateJob[] => [...running.values()],
|
|
95
85
|
find,
|
|
96
86
|
snapshot,
|
|
97
|
-
/** A row for delegate_list: the snapshot without the activity history a list result never renders. */
|
|
98
|
-
summary: (job: InspectJob): InspectJob => ({ ...plain(job), activity: [] }),
|
|
99
87
|
/** A job by id; the common "unknown delegate job" failure lives here so every tool phrases it alike. */
|
|
100
88
|
findOrThrow: (id: string): InspectJob => {
|
|
101
89
|
const job = find(id);
|
|
@@ -111,9 +99,20 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
|
|
|
111
99
|
},
|
|
112
100
|
record: (job: DelegateJob, update: ChildUpdate) => {
|
|
113
101
|
if (job.status !== "running") return;
|
|
114
|
-
|
|
115
|
-
if (update.
|
|
116
|
-
|
|
102
|
+
let changed = false;
|
|
103
|
+
if (update.toolCalls !== undefined && update.toolCalls !== job.toolCalls) {
|
|
104
|
+
job.toolCalls = update.toolCalls;
|
|
105
|
+
changed = true;
|
|
106
|
+
}
|
|
107
|
+
if (update.contextTokens !== undefined && update.contextTokens !== job.contextTokens) {
|
|
108
|
+
job.contextTokens = update.contextTokens;
|
|
109
|
+
changed = true;
|
|
110
|
+
}
|
|
111
|
+
if (update.message) {
|
|
112
|
+
job.messages.push(update.message);
|
|
113
|
+
changed = true;
|
|
114
|
+
}
|
|
115
|
+
if (changed) notify();
|
|
117
116
|
},
|
|
118
117
|
/** Leaves the live set and writes the completion entry; false when the job was cancelled. */
|
|
119
118
|
finish: (job: DelegateJob, status: JobStatus, detail?: string): boolean => {
|
|
@@ -121,8 +120,8 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
|
|
|
121
120
|
if (job.controller.signal.aborted) return false;
|
|
122
121
|
running.delete(job.id);
|
|
123
122
|
job.status = status;
|
|
124
|
-
if (detail)
|
|
125
|
-
commit({ ...
|
|
123
|
+
if (detail) job.detail = detail;
|
|
124
|
+
commit({ ...plain(job), messages: [], endedAt: Date.now() });
|
|
126
125
|
return true;
|
|
127
126
|
},
|
|
128
127
|
/** Appends a corrected entry for a finished job changed after completion (isolation applied, discarded, or re-based). */
|
|
@@ -133,7 +132,11 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
|
|
|
133
132
|
// Skip live jobs' launch entries (the live set renders them); copy so session entries stay append-only.
|
|
134
133
|
const restored = restoredJobs(branch)
|
|
135
134
|
.filter((job) => !running.has(job.id))
|
|
136
|
-
.map((job) =>
|
|
135
|
+
.map((job) => {
|
|
136
|
+
// Drop the legacy activity field: the child's session file owns the transcript.
|
|
137
|
+
const { activity: _legacy, ...rest } = job as InspectJob & { activity?: unknown };
|
|
138
|
+
return { ...rest, messages: [] };
|
|
139
|
+
});
|
|
137
140
|
// A restored running job no live job owns means the parent crashed; the child exits on its own when
|
|
138
141
|
// the parent's stdin pipe closes, so only the job state needs fixing.
|
|
139
142
|
const interrupted = restored.filter((job) => job.status === "running");
|
|
@@ -145,7 +148,6 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
|
|
|
145
148
|
history.push(...restored);
|
|
146
149
|
return interrupted;
|
|
147
150
|
},
|
|
148
|
-
/** Drops all jobs and view subscriptions; called on session shutdown. */
|
|
149
151
|
clear: () => {
|
|
150
152
|
running.clear();
|
|
151
153
|
history.length = 0;
|
|
@@ -162,8 +164,25 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
|
|
|
162
164
|
export type JobStore = ReturnType<typeof createJobStore>;
|
|
163
165
|
|
|
164
166
|
/** The job's latest tool call and its result, once the result arrives. */
|
|
165
|
-
export function lastToolCall(job: InspectJob): {
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
167
|
+
export function lastToolCall(job: InspectJob): {
|
|
168
|
+
tool?: { name: string; detail: string };
|
|
169
|
+
result?: { text?: string; isError?: boolean };
|
|
170
|
+
} {
|
|
171
|
+
for (let i = job.messages.length - 1; i >= 0; i--) {
|
|
172
|
+
const message = job.messages[i]!;
|
|
173
|
+
if (message.role !== "assistant") continue;
|
|
174
|
+
for (let j = message.content.length - 1; j >= 0; j--) {
|
|
175
|
+
const part = message.content[j]!;
|
|
176
|
+
if (part.type !== "toolCall") continue;
|
|
177
|
+
const result = job.messages.find(
|
|
178
|
+
(m): m is Extract<ChildMessage, { role: "toolResult" }> =>
|
|
179
|
+
m.role === "toolResult" && m.toolCallId === part.id,
|
|
180
|
+
);
|
|
181
|
+
return {
|
|
182
|
+
tool: { name: part.name, detail: toolCallDetail(part.name, part.arguments) },
|
|
183
|
+
result: result ? { text: resultPreview(result), isError: result.isError } : undefined,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return {};
|
|
169
188
|
}
|
package/inspector.ts
DELETED
|
@@ -1,248 +0,0 @@
|
|
|
1
|
-
import { type ExtensionAPI, getMarkdownTheme, rawKeyHint } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import {
|
|
3
|
-
HStack,
|
|
4
|
-
type Keybinding,
|
|
5
|
-
Markdown,
|
|
6
|
-
matchesKey,
|
|
7
|
-
truncateToWidth,
|
|
8
|
-
wrapTextWithAnsi,
|
|
9
|
-
} from "@earendil-works/pi-tui";
|
|
10
|
-
import type { ChildActivity } from "./child.ts";
|
|
11
|
-
import { elapsedMs, formatTools, jobIdentity, STATUS_COLORS, statusText, tally, usageStats } from "./format.ts";
|
|
12
|
-
import type { InspectJob, JobStore } from "./store.ts";
|
|
13
|
-
|
|
14
|
-
/** The /delegate command: a full-screen inspector over the job store. */
|
|
15
|
-
export function registerInspector(pi: ExtensionAPI, store: JobStore) {
|
|
16
|
-
pi.registerCommand("delegate", {
|
|
17
|
-
description: "Inspect live and recent delegate activity",
|
|
18
|
-
handler: async (_args, ctx) => {
|
|
19
|
-
if (ctx.mode !== "tui") return;
|
|
20
|
-
if (!store.all().length) {
|
|
21
|
-
ctx.ui.notify("No delegates in this session yet.", "info");
|
|
22
|
-
return;
|
|
23
|
-
}
|
|
24
|
-
const screen = {
|
|
25
|
-
overlay: true,
|
|
26
|
-
overlayOptions: { width: "100%", maxHeight: "100%", row: 0, col: 0 },
|
|
27
|
-
} as const;
|
|
28
|
-
let stopRedraw: (() => void) | undefined;
|
|
29
|
-
try {
|
|
30
|
-
await ctx.ui.custom((tui, theme, keys, done) => {
|
|
31
|
-
let selectedId = store.all()[0]!.id;
|
|
32
|
-
let focus: "list" | "history" = "list";
|
|
33
|
-
let top: number | undefined;
|
|
34
|
-
let historyWidth = 1;
|
|
35
|
-
let markdown = new WeakMap<ChildActivity, Markdown>();
|
|
36
|
-
const jobs = () => store.all();
|
|
37
|
-
// Format hints from the injected manager; an imported copy would not see the user's keybindings.
|
|
38
|
-
const hint = (id: Keybinding, description: string) =>
|
|
39
|
-
rawKeyHint(keys.getKeys(id).join("/"), description);
|
|
40
|
-
// Fixed rows: title, top rule, bottom rule, footer.
|
|
41
|
-
const bodyHeight = () => Math.max(0, tui.terminal.rows - 4);
|
|
42
|
-
const toolsLines = (job: InspectJob, width: number) =>
|
|
43
|
-
wrapTextWithAnsi(formatTools(job.tools), Math.max(1, width)).map((line) =>
|
|
44
|
-
theme.fg("dim", line),
|
|
45
|
-
);
|
|
46
|
-
// Fixed rows: header, model, description, rule, counter.
|
|
47
|
-
const historyHeight = (job: InspectJob, width: number) =>
|
|
48
|
-
Math.max(0, bodyHeight() - 5 - toolsLines(job, width).length);
|
|
49
|
-
// ScrollView needs fullscreen layout; window the history in regular TUI too.
|
|
50
|
-
const renderJobs = (width: number, items: InspectJob[], selectedIndex: number): string[] => {
|
|
51
|
-
const row = (text: string) =>
|
|
52
|
-
truncateToWidth(text, Math.max(0, width - 1), "…", true) + theme.fg("borderMuted", "│");
|
|
53
|
-
const visible = Math.max(1, Math.floor((bodyHeight() - 1) / 3));
|
|
54
|
-
const start = Math.max(
|
|
55
|
-
0,
|
|
56
|
-
Math.min(selectedIndex - Math.floor(visible / 2), items.length - visible),
|
|
57
|
-
);
|
|
58
|
-
const lines = items
|
|
59
|
-
.slice(start, start + visible)
|
|
60
|
-
.flatMap((item, index) => [
|
|
61
|
-
row(
|
|
62
|
-
`${theme.fg(start + index === selectedIndex && focus === "list" ? "accent" : "text", start + index === selectedIndex ? "›" : " ")} ${statusText(theme, item.status)} ${jobIdentity(theme, item)}`,
|
|
63
|
-
),
|
|
64
|
-
row(theme.fg("muted", ` ${item.description}`)),
|
|
65
|
-
row(theme.fg("muted", ` ${usageStats(item, elapsedMs(item))}`)),
|
|
66
|
-
]);
|
|
67
|
-
return [
|
|
68
|
-
...lines,
|
|
69
|
-
...Array(Math.max(0, bodyHeight() - 1 - lines.length)).fill(row("")),
|
|
70
|
-
row(theme.fg("dim", `${selectedIndex + 1}/${items.length}`)),
|
|
71
|
-
].slice(0, bodyHeight());
|
|
72
|
-
};
|
|
73
|
-
const renderEntry = (entry: ChildActivity, width: number): string[] => {
|
|
74
|
-
if (entry.kind === "assistant" || entry.kind === "user") {
|
|
75
|
-
let md = markdown.get(entry);
|
|
76
|
-
if (!md) {
|
|
77
|
-
md = new Markdown(entry.text, 0, 0, getMarkdownTheme());
|
|
78
|
-
markdown.set(entry, md);
|
|
79
|
-
}
|
|
80
|
-
return [theme.fg("accent", entry.kind), ...md.render(width), ""];
|
|
81
|
-
}
|
|
82
|
-
if (entry.kind === "tool")
|
|
83
|
-
return [
|
|
84
|
-
truncateToWidth(
|
|
85
|
-
theme.fg("toolTitle", theme.bold(entry.text)) +
|
|
86
|
-
(entry.detail ? ` ${theme.fg("accent", entry.detail)}` : ""),
|
|
87
|
-
width,
|
|
88
|
-
),
|
|
89
|
-
];
|
|
90
|
-
if (entry.kind === "result")
|
|
91
|
-
return [
|
|
92
|
-
truncateToWidth(
|
|
93
|
-
` ${theme.fg("muted", "↳")} ${theme.fg(entry.isError ? "error" : "toolOutput", entry.text || "(no text output)")}`,
|
|
94
|
-
width,
|
|
95
|
-
),
|
|
96
|
-
];
|
|
97
|
-
// Only failure detail still says anything; the header icon carries the status.
|
|
98
|
-
if (!entry.text) return [];
|
|
99
|
-
return [truncateToWidth(theme.fg(STATUS_COLORS.failed, entry.text), width)];
|
|
100
|
-
};
|
|
101
|
-
const renderHistory = (width: number, job: InspectJob): string[] => {
|
|
102
|
-
historyWidth = width;
|
|
103
|
-
const tools = toolsLines(job, width);
|
|
104
|
-
const height = historyHeight(job, width);
|
|
105
|
-
const history = job.activity.flatMap((entry) => renderEntry(entry, width));
|
|
106
|
-
const maxTop = Math.max(0, history.length - height);
|
|
107
|
-
const start = Math.min(top ?? maxTop, maxTop);
|
|
108
|
-
const visible = history.slice(start, start + height);
|
|
109
|
-
const shown = visible.length
|
|
110
|
-
? visible
|
|
111
|
-
: height
|
|
112
|
-
? [
|
|
113
|
-
theme.fg(
|
|
114
|
-
"muted",
|
|
115
|
-
job.status === "interrupted"
|
|
116
|
-
? "Interrupted by a crash before activity was recorded."
|
|
117
|
-
: "Waiting for activity…",
|
|
118
|
-
),
|
|
119
|
-
]
|
|
120
|
-
: [];
|
|
121
|
-
return [
|
|
122
|
-
truncateToWidth(
|
|
123
|
-
`${statusText(theme, job.status)} ${jobIdentity(theme, job)} ${theme.fg("muted", usageStats(job, elapsedMs(job)))}`,
|
|
124
|
-
width,
|
|
125
|
-
),
|
|
126
|
-
truncateToWidth(theme.fg("dim", job.model), width),
|
|
127
|
-
...tools,
|
|
128
|
-
truncateToWidth(theme.fg("text", theme.bold(job.description)), width),
|
|
129
|
-
theme.fg("borderMuted", "─".repeat(Math.max(0, width))),
|
|
130
|
-
...shown,
|
|
131
|
-
...Array(Math.max(0, height - shown.length)).fill(""),
|
|
132
|
-
truncateToWidth(
|
|
133
|
-
theme.fg(
|
|
134
|
-
"dim",
|
|
135
|
-
`${visible.length ? `${start + 1}–${start + visible.length}` : "0"}/${history.length}`,
|
|
136
|
-
),
|
|
137
|
-
width,
|
|
138
|
-
),
|
|
139
|
-
].slice(0, bodyHeight());
|
|
140
|
-
};
|
|
141
|
-
stopRedraw = store.subscribe(() => tui.requestRender());
|
|
142
|
-
return {
|
|
143
|
-
render(width: number) {
|
|
144
|
-
const items = jobs();
|
|
145
|
-
const selectedIndex = Math.max(
|
|
146
|
-
0,
|
|
147
|
-
items.findIndex((item) => item.id === selectedId),
|
|
148
|
-
);
|
|
149
|
-
const selected = items[selectedIndex];
|
|
150
|
-
const title = truncateToWidth(
|
|
151
|
-
`${theme.fg(focus === "list" ? "accent" : "muted", focus === "list" ? "[Jobs]" : "Jobs")} ` +
|
|
152
|
-
`${theme.fg(focus === "history" ? "accent" : "muted", focus === "history" ? "[Activity]" : "Activity")}` +
|
|
153
|
-
theme.fg("dim", ` · ${tally(store.live().length, items)}`),
|
|
154
|
-
width,
|
|
155
|
-
);
|
|
156
|
-
const footer = truncateToWidth(
|
|
157
|
-
theme.fg(
|
|
158
|
-
"dim",
|
|
159
|
-
`${hint("tui.select.up", "up")} · ${hint("tui.select.down", "down")} · ${rawKeyHint("←/→", "switch pane")} · ${hint("tui.select.cancel", "close")}`,
|
|
160
|
-
),
|
|
161
|
-
width,
|
|
162
|
-
);
|
|
163
|
-
if (!selected)
|
|
164
|
-
return [
|
|
165
|
-
title,
|
|
166
|
-
theme.fg("muted", "No delegates in this session."),
|
|
167
|
-
...Array(Math.max(0, tui.terminal.rows - 4)).fill(""),
|
|
168
|
-
footer,
|
|
169
|
-
].slice(0, tui.terminal.rows);
|
|
170
|
-
const sidebarWidth = Math.min(
|
|
171
|
-
40,
|
|
172
|
-
Math.max(16, Math.floor(width * 0.35)),
|
|
173
|
-
Math.max(1, width - 2),
|
|
174
|
-
);
|
|
175
|
-
const body = new HStack(
|
|
176
|
-
[
|
|
177
|
-
{
|
|
178
|
-
component: {
|
|
179
|
-
render: (w) => renderJobs(w, items, selectedIndex),
|
|
180
|
-
invalidate() {},
|
|
181
|
-
},
|
|
182
|
-
basis: sidebarWidth,
|
|
183
|
-
shrink: 0,
|
|
184
|
-
},
|
|
185
|
-
{
|
|
186
|
-
component: { render: (w) => renderHistory(w, selected), invalidate() {} },
|
|
187
|
-
basis: 0,
|
|
188
|
-
grow: 1,
|
|
189
|
-
},
|
|
190
|
-
],
|
|
191
|
-
{ gap: 1 },
|
|
192
|
-
).render(width);
|
|
193
|
-
return [
|
|
194
|
-
title,
|
|
195
|
-
theme.fg("borderMuted", "─".repeat(Math.max(0, width))),
|
|
196
|
-
...body,
|
|
197
|
-
theme.fg("borderMuted", "─".repeat(Math.max(0, width))),
|
|
198
|
-
footer,
|
|
199
|
-
].slice(0, tui.terminal.rows);
|
|
200
|
-
},
|
|
201
|
-
invalidate() {
|
|
202
|
-
markdown = new WeakMap();
|
|
203
|
-
},
|
|
204
|
-
handleInput(data: string) {
|
|
205
|
-
if (keys.matches(data, "tui.select.cancel")) done(undefined);
|
|
206
|
-
else if (matchesKey(data, "left")) focus = "list";
|
|
207
|
-
else if (
|
|
208
|
-
matchesKey(data, "right") ||
|
|
209
|
-
(focus === "list" && keys.matches(data, "tui.select.confirm"))
|
|
210
|
-
)
|
|
211
|
-
focus = "history";
|
|
212
|
-
else if (keys.matches(data, "tui.select.up") || keys.matches(data, "tui.select.down")) {
|
|
213
|
-
const up = keys.matches(data, "tui.select.up");
|
|
214
|
-
const items = jobs();
|
|
215
|
-
if (focus === "list") {
|
|
216
|
-
const index = Math.max(
|
|
217
|
-
0,
|
|
218
|
-
items.findIndex((item) => item.id === selectedId),
|
|
219
|
-
);
|
|
220
|
-
selectedId =
|
|
221
|
-
items[Math.max(0, Math.min(items.length - 1, index + (up ? -1 : 1)))]?.id ??
|
|
222
|
-
selectedId;
|
|
223
|
-
top = undefined;
|
|
224
|
-
} else {
|
|
225
|
-
const selected = items.find((item) => item.id === selectedId) ?? items[0];
|
|
226
|
-
const length =
|
|
227
|
-
selected?.activity.reduce(
|
|
228
|
-
(sum, entry) => sum + renderEntry(entry, historyWidth).length,
|
|
229
|
-
0,
|
|
230
|
-
) ?? 0;
|
|
231
|
-
const maxTop = Math.max(
|
|
232
|
-
0,
|
|
233
|
-
length - (selected ? historyHeight(selected, historyWidth) : 0),
|
|
234
|
-
);
|
|
235
|
-
const position = Math.max(0, Math.min(maxTop, top ?? maxTop) + (up ? -1 : 1));
|
|
236
|
-
top = position >= maxTop ? undefined : position;
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
tui.requestRender();
|
|
240
|
-
},
|
|
241
|
-
};
|
|
242
|
-
}, screen);
|
|
243
|
-
} finally {
|
|
244
|
-
stopRedraw?.();
|
|
245
|
-
}
|
|
246
|
-
},
|
|
247
|
-
});
|
|
248
|
-
}
|