@deathbeam/pi-delegate 0.0.42 → 0.0.44
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 +44 -48
- package/package.json +2 -7
- package/{agents.ts → src/agents.ts} +10 -10
- package/{child.ts → src/child.ts} +14 -14
- package/{format.ts → src/format.ts} +20 -16
- package/{inspector.ts → src/inspector.ts} +25 -16
- package/{isolation.ts → src/isolation.ts} +3 -1
- package/{store.ts → src/store.ts} +17 -13
package/index.ts
CHANGED
|
@@ -31,9 +31,9 @@ import {
|
|
|
31
31
|
toolLayout,
|
|
32
32
|
toolLines,
|
|
33
33
|
widgetJobs,
|
|
34
|
-
} from "./format.ts";
|
|
35
|
-
import { runChild, sessionMessages } from "./child.ts";
|
|
36
|
-
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";
|
|
37
37
|
import {
|
|
38
38
|
applyClone,
|
|
39
39
|
cloneCwd,
|
|
@@ -41,9 +41,9 @@ import {
|
|
|
41
41
|
isolationSummary,
|
|
42
42
|
removeClone,
|
|
43
43
|
type IsolationState,
|
|
44
|
-
} from "./isolation.ts";
|
|
45
|
-
import { registerInspector } from "./inspector.ts";
|
|
46
|
-
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";
|
|
47
47
|
|
|
48
48
|
type SteerDetails = Pick<
|
|
49
49
|
DelegateJob,
|
|
@@ -112,7 +112,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
112
112
|
const exiting = new Map<string, Promise<void>>();
|
|
113
113
|
|
|
114
114
|
/** Waits for a cancelled child to exit; a child that never closes must not block steering forever. */
|
|
115
|
-
|
|
115
|
+
async function waitForExit(id: string) {
|
|
116
116
|
const closed = exiting.get(id);
|
|
117
117
|
if (!closed) return;
|
|
118
118
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
@@ -123,41 +123,40 @@ export default function (pi: ExtensionAPI) {
|
|
|
123
123
|
const result = await Promise.race([closed.then(() => "closed" as const), timeout]);
|
|
124
124
|
clearTimeout(timer);
|
|
125
125
|
if (result === "timeout") throw new Error(`Delegate job "${id}" is still exiting; call delegate_steer again.`);
|
|
126
|
-
}
|
|
126
|
+
}
|
|
127
127
|
|
|
128
128
|
let ticker: ReturnType<typeof setInterval> | undefined;
|
|
129
129
|
// Prompts are read once; drift happens one quick search at a time, so count it and nudge at 5, 10, 20, ...
|
|
130
130
|
let directCalls = 0;
|
|
131
131
|
let nextReminder = FIRST_REMINDER_AT;
|
|
132
132
|
|
|
133
|
-
|
|
133
|
+
function jobTarget(rawId: unknown, theme: Theme): string {
|
|
134
134
|
const id = jobId(rawId);
|
|
135
135
|
const job = store.find(id);
|
|
136
136
|
return job ? jobIdentity(theme, job) : theme.fg("muted", id || "…");
|
|
137
|
-
}
|
|
137
|
+
}
|
|
138
138
|
|
|
139
139
|
/** The renderCall shared by every delegate tool: identity plus an optional payload. */
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
(args: any, theme: Theme
|
|
140
|
+
function callRenderer(
|
|
141
|
+
toolName: string,
|
|
142
|
+
identity: (args: any, theme: Theme) => string,
|
|
143
|
+
payload: (args: any) => string = () => "",
|
|
144
|
+
) {
|
|
145
|
+
return (args: any, theme: Theme, context: RenderContext) =>
|
|
143
146
|
toolLayout(toolName, identity(args, theme), payload(args), theme, context.expanded, context.keyHint);
|
|
147
|
+
}
|
|
144
148
|
|
|
145
149
|
/** The job-id tools all identify the job the same way. */
|
|
146
|
-
|
|
147
|
-
callRenderer(toolName, (args, theme) => jobTarget(args?.id, theme), payload);
|
|
148
|
-
|
|
149
|
-
/** The mark is the call's outcome, not the job's status; a one-line header covers the simple tools. */
|
|
150
|
-
const headerResult = (tail: string) => (result: any, _options: any, theme: Theme, context: RenderContext) => {
|
|
151
|
-
const details = result.details as { id: string; agent: string } | undefined;
|
|
152
|
-
const body = resultText(result);
|
|
153
|
-
if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
|
|
154
|
-
return new Text(`\n${resultHeader(theme, details, tail)}`, 0, 0);
|
|
155
|
-
};
|
|
150
|
+
function idCall(toolName: string, payload: (args: any) => string = () => "") {
|
|
151
|
+
return callRenderer(toolName, (args, theme) => jobTarget(args?.id, theme), payload);
|
|
152
|
+
}
|
|
156
153
|
|
|
157
154
|
/** The clone is the unit: every job id that ran in it is only a handle, so state changes reach all of them. */
|
|
158
|
-
|
|
155
|
+
function jobsInClone(clone: string) {
|
|
156
|
+
return store.all().filter((job) => job.isolation?.clone === clone);
|
|
157
|
+
}
|
|
159
158
|
|
|
160
|
-
|
|
159
|
+
function clonedJob(id: string) {
|
|
161
160
|
const job = store.findOrThrow(id);
|
|
162
161
|
const isolation = job.isolation;
|
|
163
162
|
if (!isolation)
|
|
@@ -167,26 +166,26 @@ export default function (pi: ExtensionAPI) {
|
|
|
167
166
|
: `Delegate job "${id}" did not run in an isolated clone.`,
|
|
168
167
|
);
|
|
169
168
|
return { job, isolation };
|
|
170
|
-
}
|
|
169
|
+
}
|
|
171
170
|
|
|
172
171
|
/** Closing a clone is a clone-wide operation: every job id that ran in it stops pointing at it. */
|
|
173
|
-
|
|
172
|
+
function closeClone(isolation: IsolationState) {
|
|
174
173
|
removeClone(isolation);
|
|
175
174
|
for (const shared of jobsInClone(isolation.clone)) {
|
|
176
175
|
shared.isolation = undefined;
|
|
177
176
|
shared.cloneClosed = true;
|
|
178
177
|
store.save(shared);
|
|
179
178
|
}
|
|
180
|
-
}
|
|
179
|
+
}
|
|
181
180
|
|
|
182
181
|
/** One job at a time per clone: a shared clone is a shared working directory. */
|
|
183
|
-
|
|
182
|
+
function requireIdleClone(isolation: IsolationState) {
|
|
184
183
|
const busy = store.live().find((job) => job.isolation?.clone === isolation.clone);
|
|
185
184
|
if (busy)
|
|
186
185
|
throw new Error(`Delegate job "${busy.id}" is running in this clone; wait for it or cancel it first.`);
|
|
187
|
-
}
|
|
186
|
+
}
|
|
188
187
|
|
|
189
|
-
|
|
188
|
+
function refreshWidget(ctx: ExtensionContext) {
|
|
190
189
|
if (!ctx.hasUI) return;
|
|
191
190
|
const jobs = store.live();
|
|
192
191
|
if (jobs.length === 0) {
|
|
@@ -216,17 +215,17 @@ export default function (pi: ExtensionAPI) {
|
|
|
216
215
|
for (const line of lines) container.addChild(new Text(line, 1, 0));
|
|
217
216
|
return container;
|
|
218
217
|
});
|
|
219
|
-
}
|
|
218
|
+
}
|
|
220
219
|
|
|
221
|
-
|
|
220
|
+
function syncTicker(ctx: ExtensionContext) {
|
|
222
221
|
if (store.live().length > 0) ticker ??= setInterval(() => refreshWidget(ctx), SPINNER_INTERVAL_MS);
|
|
223
222
|
else if (ticker) {
|
|
224
223
|
clearInterval(ticker);
|
|
225
224
|
ticker = undefined;
|
|
226
225
|
}
|
|
227
|
-
}
|
|
226
|
+
}
|
|
228
227
|
|
|
229
|
-
|
|
228
|
+
function finishJob(ctx: ExtensionContext, job: DelegateJob, output?: string, error?: string) {
|
|
230
229
|
if (!store.finish(job, error ? "failed" : "done", error ? `Error: ${error}` : undefined)) return;
|
|
231
230
|
syncTicker(ctx);
|
|
232
231
|
refreshWidget(ctx);
|
|
@@ -248,10 +247,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
248
247
|
{ customType: RESULT_MESSAGE, content: reportText(report), display: true, details: report },
|
|
249
248
|
{ triggerTurn: true, deliverAs: "steer" },
|
|
250
249
|
);
|
|
251
|
-
}
|
|
250
|
+
}
|
|
252
251
|
|
|
253
252
|
/** Runs one delegate child: foreground runs return their output, background ones report on completion. */
|
|
254
|
-
|
|
253
|
+
async function runDelegate(
|
|
255
254
|
ctx: ExtensionContext,
|
|
256
255
|
agent: AgentFile,
|
|
257
256
|
prior: InspectJob | undefined,
|
|
@@ -259,7 +258,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
259
258
|
task: string,
|
|
260
259
|
signal: AbortSignal | undefined,
|
|
261
260
|
prompt = task,
|
|
262
|
-
)
|
|
261
|
+
) {
|
|
263
262
|
const entrypoint = process.argv[1];
|
|
264
263
|
if (!entrypoint) throw new Error("Pi CLI entrypoint missing; start Pi from its CLI to delegate.");
|
|
265
264
|
const { model, thinking } = mustResolveModel(fields.model, ctx, agent.model);
|
|
@@ -370,10 +369,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
370
369
|
],
|
|
371
370
|
details,
|
|
372
371
|
};
|
|
373
|
-
}
|
|
372
|
+
}
|
|
374
373
|
|
|
375
374
|
/** Swaps a running child's model over the RPC; the child confirms or rejects it, and never restarts. */
|
|
376
|
-
|
|
375
|
+
async function swapModel(job: DelegateJob, request: string, ctx: ExtensionContext) {
|
|
377
376
|
if (!job.swapModel) throw new Error(`Delegate job "${job.id}" cannot switch models.`);
|
|
378
377
|
const { model } = mustResolveModel(request, ctx);
|
|
379
378
|
const [provider, ...rest] = model.split("/");
|
|
@@ -386,7 +385,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
386
385
|
job.contextWindow = contextWindowFor(ctx, model);
|
|
387
386
|
});
|
|
388
387
|
if (level) job.model = `${model}:${level}`;
|
|
389
|
-
}
|
|
388
|
+
}
|
|
390
389
|
|
|
391
390
|
pi.on("session_shutdown", () => {
|
|
392
391
|
if (ticker) clearInterval(ticker);
|
|
@@ -395,7 +394,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
395
394
|
});
|
|
396
395
|
|
|
397
396
|
// Rebuilt from the active branch: abandoned branches are alternative histories.
|
|
398
|
-
|
|
397
|
+
function restoreSession(ctx: ExtensionContext) {
|
|
399
398
|
const interrupted = store.restore(ctx.sessionManager.getBranch());
|
|
400
399
|
// Custom entries never reach the model, so announce the interrupted jobs as a steered message.
|
|
401
400
|
if (interrupted.length)
|
|
@@ -412,7 +411,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
412
411
|
},
|
|
413
412
|
{ deliverAs: "steer" },
|
|
414
413
|
);
|
|
415
|
-
}
|
|
414
|
+
}
|
|
416
415
|
|
|
417
416
|
pi.on("session_start", (_event, ctx) => restoreSession(ctx));
|
|
418
417
|
pi.on("session_tree", (_event, ctx) => restoreSession(ctx));
|
|
@@ -682,8 +681,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
682
681
|
};
|
|
683
682
|
},
|
|
684
683
|
renderCall: idCall("delegate_cancel"),
|
|
685
|
-
|
|
686
|
-
renderResult: headerResult("cancellation requested"),
|
|
687
684
|
});
|
|
688
685
|
|
|
689
686
|
pi.registerTool({
|
|
@@ -773,7 +770,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
773
770
|
};
|
|
774
771
|
},
|
|
775
772
|
renderCall: idCall("delegate_discard"),
|
|
776
|
-
renderResult: headerResult("clone discarded"),
|
|
777
773
|
});
|
|
778
774
|
|
|
779
775
|
pi.registerTool({
|
|
@@ -787,10 +783,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
787
783
|
const jobs = store.all();
|
|
788
784
|
if (!jobs.length) return { content: [{ type: "text", text: "No delegates yet." }], details: undefined };
|
|
789
785
|
const running = jobs.filter((job) => job.status === "running").length;
|
|
790
|
-
|
|
786
|
+
function lastActivity(job: InspectJob) {
|
|
791
787
|
const { tool } = lastToolCall(job);
|
|
792
788
|
return job.status === "running" && tool ? ` · ${tool.name}${tool.detail ? ` ${tool.detail}` : ""}` : "";
|
|
793
|
-
}
|
|
789
|
+
}
|
|
794
790
|
const lines = jobs.map((job) => {
|
|
795
791
|
const tag = isolationWords(job);
|
|
796
792
|
return `- ${job.id} ${job.agent} · ${job.status}${tag ? ` · ${tag}` : ""} · ${jobLine(job, elapsedMs(job, now))}${lastActivity(job)}`;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@deathbeam/pi-delegate",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.44",
|
|
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 {
|
|
@@ -46,15 +46,6 @@ function readConfig(path: string): DelegateConfig {
|
|
|
46
46
|
}
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
-
export function configFor(cwd: string): DelegateConfig {
|
|
50
|
-
const global = readConfig(join(getAgentDir(), "settings.json"));
|
|
51
|
-
const project = readConfig(join(cwd, CONFIG_DIR_NAME, "settings.json"));
|
|
52
|
-
return {
|
|
53
|
-
agentDirs: [...stringList(global.agentDirs), ...stringList(project.agentDirs)],
|
|
54
|
-
models: { ...(global.models ?? {}), ...(project.models ?? {}) },
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
|
|
58
49
|
function loadAgents(dir: string): AgentFile[] {
|
|
59
50
|
if (!existsSync(dir)) return [];
|
|
60
51
|
const agents: AgentFile[] = [];
|
|
@@ -105,6 +96,15 @@ export function agentByName(cwd: string, name: string): AgentFile {
|
|
|
105
96
|
return agent;
|
|
106
97
|
}
|
|
107
98
|
|
|
99
|
+
export function configFor(cwd: string): DelegateConfig {
|
|
100
|
+
const global = readConfig(join(getAgentDir(), "settings.json"));
|
|
101
|
+
const project = readConfig(join(cwd, CONFIG_DIR_NAME, "settings.json"));
|
|
102
|
+
return {
|
|
103
|
+
agentDirs: [...stringList(global.agentDirs), ...stringList(project.agentDirs)],
|
|
104
|
+
models: { ...(global.models ?? {}), ...(project.models ?? {}) },
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
108
|
// Same `:<thinking>` suffix pi's --model takes; only known levels split, so ids like `llama3:8b` stay whole.
|
|
109
109
|
function splitThinking(value: string): { model: string; thinking?: string } {
|
|
110
110
|
const match = /^(.*):(off|minimal|low|medium|high|xhigh|max)$/.exec(value);
|
|
@@ -59,14 +59,14 @@ export function runChild(
|
|
|
59
59
|
let send!: (command: Record<string, unknown>) => Promise<any>;
|
|
60
60
|
|
|
61
61
|
const done = new Promise<string>((resolveChild, reject) => {
|
|
62
|
-
|
|
62
|
+
function rejectPending(error: Error) {
|
|
63
63
|
for (const request of pending.values()) {
|
|
64
64
|
clearTimeout(request.timer);
|
|
65
65
|
request.reject(error);
|
|
66
66
|
}
|
|
67
67
|
pending.clear();
|
|
68
|
-
}
|
|
69
|
-
|
|
68
|
+
}
|
|
69
|
+
function finish(code: number | null, error?: Error) {
|
|
70
70
|
if (settled || finishing) return;
|
|
71
71
|
finishing = true;
|
|
72
72
|
if (buffer) {
|
|
@@ -94,14 +94,14 @@ export function runChild(
|
|
|
94
94
|
rejectPending(new Error("Delegate finished before acknowledging command"));
|
|
95
95
|
resolveChild(limitOutput(liveText.trim() || "(no output)"));
|
|
96
96
|
}
|
|
97
|
-
}
|
|
98
|
-
|
|
97
|
+
}
|
|
98
|
+
function fail(error: Error) {
|
|
99
99
|
if (settled || finishing) return;
|
|
100
100
|
childFailure = error;
|
|
101
101
|
child.kill("SIGTERM");
|
|
102
102
|
finish(null, error);
|
|
103
|
-
}
|
|
104
|
-
|
|
103
|
+
}
|
|
104
|
+
function parse(line: string) {
|
|
105
105
|
if (!line.trim()) return;
|
|
106
106
|
try {
|
|
107
107
|
const event = JSON.parse(line) as any;
|
|
@@ -161,8 +161,8 @@ export function runChild(
|
|
|
161
161
|
} catch {
|
|
162
162
|
// Diagnostics on stdout that are not JSON events; ignore those lines.
|
|
163
163
|
}
|
|
164
|
-
}
|
|
165
|
-
|
|
164
|
+
}
|
|
165
|
+
function enqueue(command: Record<string, unknown>) {
|
|
166
166
|
const line = `${JSON.stringify(command)}\n`;
|
|
167
167
|
const write = writeQueue.then(
|
|
168
168
|
() =>
|
|
@@ -176,7 +176,7 @@ export function runChild(
|
|
|
176
176
|
);
|
|
177
177
|
writeQueue = write.catch(() => {});
|
|
178
178
|
return write;
|
|
179
|
-
}
|
|
179
|
+
}
|
|
180
180
|
send = (command: Record<string, unknown>) => {
|
|
181
181
|
const id = `delegate_${++requestId}`;
|
|
182
182
|
const response = new Promise<any>((resolveResponse, rejectResponse) => {
|
|
@@ -202,14 +202,14 @@ export function runChild(
|
|
|
202
202
|
});
|
|
203
203
|
return response;
|
|
204
204
|
};
|
|
205
|
-
|
|
205
|
+
function abort() {
|
|
206
206
|
if (settled || aborted) return;
|
|
207
207
|
aborted = true;
|
|
208
208
|
void send({ type: "abort" }).catch(() => {});
|
|
209
209
|
setTimeout(() => {
|
|
210
210
|
if (!settled) child.kill("SIGKILL");
|
|
211
211
|
}, 5000).unref();
|
|
212
|
-
}
|
|
212
|
+
}
|
|
213
213
|
|
|
214
214
|
child.stdout.setEncoding("utf8");
|
|
215
215
|
child.stdout.on("data", (chunk: string) => {
|
|
@@ -232,11 +232,11 @@ export function runChild(
|
|
|
232
232
|
finish(null);
|
|
233
233
|
} else {
|
|
234
234
|
signal?.addEventListener("abort", abort, { once: true });
|
|
235
|
-
|
|
235
|
+
function prompt() {
|
|
236
236
|
void send({ type: "prompt", message: task }).catch((error) => {
|
|
237
237
|
if (!settled) fail(error);
|
|
238
238
|
});
|
|
239
|
-
}
|
|
239
|
+
}
|
|
240
240
|
if (revive) {
|
|
241
241
|
// An empty transcript means the pinned session was recreated (e.g. a different cwd); prompting would lose the task.
|
|
242
242
|
void send({ type: "get_state" })
|
|
@@ -30,7 +30,7 @@ export type DelegateReport = {
|
|
|
30
30
|
};
|
|
31
31
|
|
|
32
32
|
/** The isolation state to show for a job: pending means its clone still holds unapplied work. */
|
|
33
|
-
|
|
33
|
+
type IsolationMark = "isolated" | "pending";
|
|
34
34
|
|
|
35
35
|
type IsolationStateFields = {
|
|
36
36
|
isolation?: unknown;
|
|
@@ -61,19 +61,17 @@ const WIDGET_MAX_JOBS = 5;
|
|
|
61
61
|
export const COLLAPSED_OUTPUT_LINES = 10;
|
|
62
62
|
const MAX_OUTPUT_BYTES = 50 * 1024;
|
|
63
63
|
|
|
64
|
-
/** Terminal statuses have static icons; running jobs use statusIcon's clock-driven frame. */
|
|
65
|
-
function statusIcon(status: JobStatus, now = Date.now()): string {
|
|
66
|
-
return status === "running"
|
|
67
|
-
? SPINNER_FRAMES[Math.floor(now / SPINNER_INTERVAL_MS) % SPINNER_FRAMES.length]!
|
|
68
|
-
: STATUS_ICONS[status];
|
|
69
|
-
}
|
|
70
|
-
|
|
71
64
|
export function statusText(theme: Theme, status: JobStatus, now = Date.now()): string {
|
|
72
|
-
|
|
65
|
+
// Terminal statuses have static icons; running jobs use a clock-driven spinner frame.
|
|
66
|
+
const icon =
|
|
67
|
+
status === "running"
|
|
68
|
+
? SPINNER_FRAMES[Math.floor(now / SPINNER_INTERVAL_MS) % SPINNER_FRAMES.length]!
|
|
69
|
+
: STATUS_ICONS[status];
|
|
70
|
+
return theme.fg(STATUS_COLORS[status], icon);
|
|
73
71
|
}
|
|
74
72
|
|
|
75
73
|
/** Derives the mark from a job: an isolation with no clone left, or a still-running one, is not pending. */
|
|
76
|
-
|
|
74
|
+
function isolationMarkOf(job: IsolationStateFields): IsolationMark | undefined {
|
|
77
75
|
if (!job.isolation) return undefined;
|
|
78
76
|
return job.status === "running" ? "isolated" : "pending";
|
|
79
77
|
}
|
|
@@ -103,7 +101,7 @@ function formatTokens(count: number): string {
|
|
|
103
101
|
return `${Math.round(count / 1000000)}M`;
|
|
104
102
|
}
|
|
105
103
|
|
|
106
|
-
|
|
104
|
+
function formatDuration(ms: number): string {
|
|
107
105
|
const seconds = Math.max(0, Math.floor(ms / 1000));
|
|
108
106
|
if (seconds < 60) return `${seconds}s`;
|
|
109
107
|
const minutes = Math.floor(seconds / 60);
|
|
@@ -137,7 +135,9 @@ export function toolLines(theme: Theme, name: string, detail: string, result?: s
|
|
|
137
135
|
|
|
138
136
|
export function toolCallDetail(toolName: string, args: unknown): string {
|
|
139
137
|
const input = (args ?? {}) as Record<string, unknown>;
|
|
140
|
-
|
|
138
|
+
function value(key: string): string {
|
|
139
|
+
return typeof input[key] === "string" ? (input[key] as string).trim() : "";
|
|
140
|
+
}
|
|
141
141
|
const path = value("path") || ".";
|
|
142
142
|
switch (toolName) {
|
|
143
143
|
case "bash":
|
|
@@ -157,6 +157,7 @@ export function toolCallDetail(toolName: string, args: unknown): string {
|
|
|
157
157
|
return "";
|
|
158
158
|
}
|
|
159
159
|
}
|
|
160
|
+
|
|
160
161
|
/** Caps a preview at `maxLines`; callers report the hidden count their own way. */
|
|
161
162
|
export function capLines<T>(lines: T[], maxLines: number): { shown: T[]; hidden: number } {
|
|
162
163
|
if (lines.length <= maxLines) return { shown: lines, hidden: 0 };
|
|
@@ -228,12 +229,15 @@ export function piDiff(unified: string): string {
|
|
|
228
229
|
([, os, oc, ns, nc]) => String(Math.max(+os! + (+oc! || 1), +ns! + (+nc! || 1)) - 1).length,
|
|
229
230
|
),
|
|
230
231
|
);
|
|
231
|
-
|
|
232
|
+
function header() {
|
|
232
233
|
if (!pathShown) {
|
|
233
234
|
out.push(path);
|
|
234
235
|
pathShown = true;
|
|
235
236
|
}
|
|
236
|
-
}
|
|
237
|
+
}
|
|
238
|
+
function num(prefix: string): string {
|
|
239
|
+
return String(prefix === "-" ? oldNum++ : newNum++).padStart(width, " ");
|
|
240
|
+
}
|
|
237
241
|
for (const line of unified.split("\n")) {
|
|
238
242
|
const file = /^diff --git a\/\S+ b\/(.+)$/.exec(line);
|
|
239
243
|
if (file) {
|
|
@@ -258,7 +262,6 @@ export function piDiff(unified: string): string {
|
|
|
258
262
|
continue;
|
|
259
263
|
}
|
|
260
264
|
const content = line.slice(1);
|
|
261
|
-
const num = (prefix: string) => String(prefix === "-" ? oldNum++ : newNum++).padStart(width, " ");
|
|
262
265
|
if (line.startsWith("+")) out.push(`+${num("+")} ${content}`);
|
|
263
266
|
else if (line.startsWith("-")) out.push(`-${num("-")} ${content}`);
|
|
264
267
|
else {
|
|
@@ -296,8 +299,9 @@ export function resultFallback(body: string, theme: Theme, isError: boolean): Te
|
|
|
296
299
|
return new Text(`\n${mark} ${theme.fg(isError ? "error" : "toolOutput", body || "(no output)")}`, 0, 0);
|
|
297
300
|
}
|
|
298
301
|
|
|
302
|
+
/** pi's built-in expand hint; callers place it on its own row, so it carries no leading newline. */
|
|
299
303
|
export function moreLines(theme: Theme, hidden: number, keyHint: KeybindingHints["keyHint"]): string {
|
|
300
|
-
return theme.fg("muted",
|
|
304
|
+
return `${theme.fg("muted", `... (${hidden} more lines,`)} ${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`;
|
|
301
305
|
}
|
|
302
306
|
|
|
303
307
|
export function appendOutput(
|
|
@@ -197,35 +197,44 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore, sessionDir:
|
|
|
197
197
|
let lastWindow = { height: 0, total: 0 };
|
|
198
198
|
const transcripts = new Map<string, Transcript>();
|
|
199
199
|
const loaded = new Set<string>();
|
|
200
|
-
|
|
200
|
+
function jobs() {
|
|
201
|
+
return store.all();
|
|
202
|
+
}
|
|
201
203
|
// Format hints from the injected manager; an imported copy would not see the user's keybindings.
|
|
202
|
-
|
|
203
|
-
rawKeyHint(keys.getKeys(id).join("/"), description);
|
|
204
|
+
function hint(id: Keybinding, description: string) {
|
|
205
|
+
return rawKeyHint(keys.getKeys(id).join("/"), description);
|
|
206
|
+
}
|
|
204
207
|
// Fixed rows: title, top rule, bottom rule, footer.
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
+
function bodyHeight() {
|
|
209
|
+
return Math.max(0, tui.terminal.rows - 4);
|
|
210
|
+
}
|
|
211
|
+
function toolsLines(job: InspectJob, width: number) {
|
|
212
|
+
return wrapTextWithAnsi(formatTools(job.tools), Math.max(1, width)).map((line) =>
|
|
208
213
|
theme.fg("dim", line),
|
|
209
214
|
);
|
|
210
|
-
|
|
215
|
+
}
|
|
216
|
+
function transcript(job: InspectJob) {
|
|
211
217
|
let value = transcripts.get(job.id);
|
|
212
218
|
if (!value) {
|
|
213
219
|
value = new Transcript(theme);
|
|
214
220
|
transcripts.set(job.id, value);
|
|
215
221
|
}
|
|
216
222
|
return value;
|
|
217
|
-
}
|
|
223
|
+
}
|
|
218
224
|
// Restored jobs carry no messages: the child's session file is their history.
|
|
219
|
-
|
|
225
|
+
function messagesOf(job: InspectJob) {
|
|
220
226
|
if (!job.messages.length && job.status !== "running" && !loaded.has(job.id)) {
|
|
221
227
|
loaded.add(job.id);
|
|
222
228
|
job.messages = sessionMessages(sessionDir, job.id);
|
|
223
229
|
}
|
|
224
230
|
return job.messages;
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
231
|
+
}
|
|
232
|
+
function renderJobs(width: number, items: InspectJob[], selectedIndex: number): string[] {
|
|
233
|
+
function row(text: string) {
|
|
234
|
+
return (
|
|
235
|
+
truncateToWidth(text, Math.max(0, width - 1), "…", true) + theme.fg("borderMuted", "│")
|
|
236
|
+
);
|
|
237
|
+
}
|
|
229
238
|
const visible = Math.max(1, Math.floor((bodyHeight() - 1) / 3));
|
|
230
239
|
const start = Math.max(
|
|
231
240
|
0,
|
|
@@ -245,8 +254,8 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore, sessionDir:
|
|
|
245
254
|
...Array(Math.max(0, bodyHeight() - 1 - lines.length)).fill(row("")),
|
|
246
255
|
row(theme.fg("dim", `${selectedIndex + 1}/${items.length}`)),
|
|
247
256
|
].slice(0, bodyHeight());
|
|
248
|
-
}
|
|
249
|
-
|
|
257
|
+
}
|
|
258
|
+
function renderHistory(width: number, job: InspectJob): string[] {
|
|
250
259
|
const tools = toolsLines(job, width);
|
|
251
260
|
// Fixed rows: header, model, description, rule, counter, plus the failure detail.
|
|
252
261
|
const height = Math.max(0, bodyHeight() - 5 - tools.length - (job.detail ? 1 : 0));
|
|
@@ -290,7 +299,7 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore, sessionDir:
|
|
|
290
299
|
// Pad every row so the pane's right edge holds still while the transcript scrolls.
|
|
291
300
|
.map((line) => truncateToWidth(line, width, "…", true))
|
|
292
301
|
);
|
|
293
|
-
}
|
|
302
|
+
}
|
|
294
303
|
stopRedraw = store.subscribe(() => tui.requestRender());
|
|
295
304
|
return {
|
|
296
305
|
render(width: number) {
|
|
@@ -137,7 +137,9 @@ export function removeClone(iso: IsolationState): void {
|
|
|
137
137
|
*/
|
|
138
138
|
export function applyClone(iso: IsolationState): ApplyResult {
|
|
139
139
|
const root = rootOf(iso);
|
|
140
|
-
|
|
140
|
+
function run(args: string[]): string {
|
|
141
|
+
return git(args, { cwd: iso.clone });
|
|
142
|
+
}
|
|
141
143
|
// Commit uncommitted delegate work so the rebase carries it.
|
|
142
144
|
run(["add", "-A"]);
|
|
143
145
|
if (run(["status", "--porcelain"]).trim()) run([...IDENTITY, "commit", "--no-verify", "-m", "delegate work"]);
|
|
@@ -53,30 +53,34 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
|
|
|
53
53
|
const running = new Map<string, DelegateJob>();
|
|
54
54
|
const history: InspectJob[] = [];
|
|
55
55
|
const listeners = new Set<() => void>();
|
|
56
|
-
|
|
56
|
+
function notify() {
|
|
57
57
|
for (const redraw of listeners) redraw();
|
|
58
|
-
}
|
|
58
|
+
}
|
|
59
59
|
// A session_tree rebuild restores old entries; the history keeps one row per id across finish and relaunch.
|
|
60
|
-
|
|
60
|
+
function drop(id: string) {
|
|
61
61
|
const stale = history.findIndex((item) => item.id === id);
|
|
62
62
|
if (stale >= 0) history.splice(stale, 1);
|
|
63
|
-
}
|
|
64
|
-
|
|
63
|
+
}
|
|
64
|
+
function commit(entry: InspectJob) {
|
|
65
65
|
drop(entry.id);
|
|
66
66
|
history.unshift(entry);
|
|
67
67
|
append(JOB_ENTRY, snapshot(entry));
|
|
68
68
|
notify();
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
|
|
69
|
+
}
|
|
70
|
+
function find(id: string) {
|
|
71
|
+
return running.get(id) ?? history.find((item) => item.id === id);
|
|
72
|
+
}
|
|
73
|
+
function plain(job: InspectJob) {
|
|
72
74
|
const { controller, steer, swapModel, ...rest } = job as InspectJob & Partial<DelegateJob>;
|
|
73
75
|
return rest;
|
|
74
|
-
}
|
|
76
|
+
}
|
|
75
77
|
/** The serializable form of a job: runtime handles and the transcript stay out. */
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
78
|
+
function snapshot(job: InspectJob): InspectJob {
|
|
79
|
+
return {
|
|
80
|
+
...plain(job),
|
|
81
|
+
messages: [],
|
|
82
|
+
};
|
|
83
|
+
}
|
|
80
84
|
|
|
81
85
|
return {
|
|
82
86
|
/** Every job a view can show: live first, then history. */
|