@deathbeam/pi-delegate 0.0.49 → 0.0.51
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 +2 -2
- package/index.ts +50 -19
- package/package.json +1 -1
- package/src/agents.ts +45 -13
- package/src/child.ts +2 -8
- package/src/format.ts +72 -3
- package/src/inspector.ts +21 -7
- package/src/isolation.ts +78 -59
- package/src/store.ts +6 -3
package/README.md
CHANGED
|
@@ -18,7 +18,7 @@ Optional `delegate` settings live in `~/.pi/agent/settings.json` or `.pi/setting
|
|
|
18
18
|
```json
|
|
19
19
|
{
|
|
20
20
|
"delegate": {
|
|
21
|
-
"agentDirs": ["
|
|
21
|
+
"agentDirs": ["../shared/agents"],
|
|
22
22
|
"models": {
|
|
23
23
|
"cheap": "anthropic/claude-haiku-5-5:low",
|
|
24
24
|
"balanced": "anthropic/claude-sonnet-5-5:high",
|
|
@@ -28,7 +28,7 @@ Optional `delegate` settings live in `~/.pi/agent/settings.json` or `.pi/setting
|
|
|
28
28
|
}
|
|
29
29
|
```
|
|
30
30
|
|
|
31
|
-
- `agentDirs` adds directories
|
|
31
|
+
- `agentDirs` adds agent directories on top of the defaults: bundled, `~/.agents/agents`, `~/.pi/agent/agents`, `.agents/agents` from the working directory up to the git root, then `.pi/agents`. Later wins on a name clash. Project dirs and `.pi/settings.json` load only in a trusted project.
|
|
32
32
|
- `models` maps the `cheap`, `balanced`, and `strong` tiers to a `provider/model-id` with an optional `:<thinking>` suffix. A tier without an entry uses the session model.
|
|
33
33
|
|
|
34
34
|
Agents are Markdown files with frontmatter. The body is appended to the delegate's system prompt.
|
package/index.ts
CHANGED
|
@@ -43,7 +43,15 @@ import {
|
|
|
43
43
|
type IsolationState,
|
|
44
44
|
} from "./src/isolation.ts";
|
|
45
45
|
import { registerInspector } from "./src/inspector.ts";
|
|
46
|
-
import {
|
|
46
|
+
import {
|
|
47
|
+
agentByName,
|
|
48
|
+
agentsFor,
|
|
49
|
+
configFor,
|
|
50
|
+
contextWindowFor,
|
|
51
|
+
projectTrusted,
|
|
52
|
+
resolveModel,
|
|
53
|
+
type AgentFile,
|
|
54
|
+
} from "./src/agents.ts";
|
|
47
55
|
|
|
48
56
|
type SteerDetails = Pick<
|
|
49
57
|
DelegateJob,
|
|
@@ -92,8 +100,12 @@ function resultText(result: { content: unknown }): string {
|
|
|
92
100
|
}
|
|
93
101
|
|
|
94
102
|
/** Isolated jobs append the clone location and a change stat so the orchestrator can apply the work. */
|
|
95
|
-
function withIsolation(
|
|
96
|
-
|
|
103
|
+
async function withIsolation(
|
|
104
|
+
output: string,
|
|
105
|
+
isolation: IsolationState | undefined,
|
|
106
|
+
signal?: AbortSignal,
|
|
107
|
+
): Promise<string> {
|
|
108
|
+
return isolation ? [output, await isolationSummary(isolation, signal)].filter(Boolean).join("\n\n") : output;
|
|
97
109
|
}
|
|
98
110
|
|
|
99
111
|
/** Status icon, identity, and the muted detail line: the row the widget and delegate_list both show. */
|
|
@@ -166,8 +178,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
166
178
|
}
|
|
167
179
|
|
|
168
180
|
/** Closing a clone is a clone-wide operation: every job id that ran in it stops pointing at it. */
|
|
169
|
-
function closeClone(isolation: IsolationState) {
|
|
170
|
-
removeClone(isolation);
|
|
181
|
+
async function closeClone(isolation: IsolationState) {
|
|
182
|
+
await removeClone(isolation);
|
|
171
183
|
for (const shared of jobsInClone(isolation.clone)) {
|
|
172
184
|
shared.isolation = undefined;
|
|
173
185
|
shared.cloneClosed = true;
|
|
@@ -184,12 +196,19 @@ export default function (pi: ExtensionAPI) {
|
|
|
184
196
|
for (const job of jobsInClone(isolation.clone)) await waitForExit(job.id);
|
|
185
197
|
}
|
|
186
198
|
|
|
199
|
+
/** The refusal for a clone an apply or discard owns. */
|
|
200
|
+
function closingError(clone: string) {
|
|
201
|
+
return new Error(`The clone at ${clone} is being applied or discarded; wait for it to finish.`);
|
|
202
|
+
}
|
|
203
|
+
|
|
187
204
|
/** Claims the clone before waiting; on success the mark stays as the tombstone a waiting revive checks. */
|
|
188
|
-
async function claimClone<T>(isolation: IsolationState, run: () => T): Promise<T> {
|
|
205
|
+
async function claimClone<T>(isolation: IsolationState, run: () => Promise<T>): Promise<T> {
|
|
206
|
+
// The claim must be exclusive, or a second apply or discard runs git in a clone the first is rewriting.
|
|
207
|
+
if (closing.has(isolation.clone)) throw closingError(isolation.clone);
|
|
189
208
|
closing.add(isolation.clone);
|
|
190
209
|
try {
|
|
191
210
|
await requireIdleClone(isolation);
|
|
192
|
-
return run();
|
|
211
|
+
return await run();
|
|
193
212
|
} catch (error) {
|
|
194
213
|
// A failed operation keeps the clone, so children may still spawn in it.
|
|
195
214
|
closing.delete(isolation.clone);
|
|
@@ -237,7 +256,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
237
256
|
}
|
|
238
257
|
}
|
|
239
258
|
|
|
240
|
-
function finishJob(ctx: ExtensionContext, job: DelegateJob, output?: string, error?: string) {
|
|
259
|
+
async function finishJob(ctx: ExtensionContext, job: DelegateJob, output?: string, error?: string) {
|
|
241
260
|
if (!store.finish(job, error ? "failed" : "done", error ? `Error: ${error}` : undefined)) return;
|
|
242
261
|
syncTicker(ctx);
|
|
243
262
|
refreshWidget(ctx);
|
|
@@ -249,7 +268,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
249
268
|
contextTokens: job.contextTokens,
|
|
250
269
|
contextWindow: job.contextWindow,
|
|
251
270
|
elapsedMs: elapsedMs(job),
|
|
252
|
-
output: withIsolation(output ?? "", job.isolation),
|
|
271
|
+
output: await withIsolation(output ?? "", job.isolation),
|
|
253
272
|
error,
|
|
254
273
|
isolation: job.isolation,
|
|
255
274
|
};
|
|
@@ -274,7 +293,11 @@ export default function (pi: ExtensionAPI) {
|
|
|
274
293
|
const entrypoint = process.argv[1];
|
|
275
294
|
if (!entrypoint) throw new Error("Pi CLI entrypoint missing; start Pi from its CLI to delegate.");
|
|
276
295
|
const requested = fields.model ?? agent.model;
|
|
277
|
-
const { model, thinking } = resolveModel(
|
|
296
|
+
const { model, thinking } = resolveModel(
|
|
297
|
+
requested,
|
|
298
|
+
configFor(ctx.cwd, ctx.isProjectTrusted()).models ?? {},
|
|
299
|
+
ctx,
|
|
300
|
+
);
|
|
278
301
|
if (!model) throw new Error(`No model found for "${requested}".`);
|
|
279
302
|
const tools = (agent.tools?.length ? agent.tools : pi.getActiveTools()).filter(
|
|
280
303
|
(tool) => !DELEGATION_TOOLS.has(tool),
|
|
@@ -282,7 +305,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
282
305
|
const displayModel = thinking ? `${model}:${thinking}` : model;
|
|
283
306
|
const id = prior?.id ?? randomUUID().slice(0, 8);
|
|
284
307
|
const isolation =
|
|
285
|
-
prior?.isolation ??
|
|
308
|
+
prior?.isolation ??
|
|
309
|
+
fields.clone ??
|
|
310
|
+
(fields.isolated ? await createIsolation(ctx.cwd, id, signal) : undefined);
|
|
286
311
|
if (isolation) await requireIdleClone(isolation);
|
|
287
312
|
|
|
288
313
|
const job: DelegateJob = {
|
|
@@ -329,8 +354,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
329
354
|
`You are working in an isolated git clone at ${isolation.clone}. Your working directory is ${cwd}; run every command from it with relative paths. Any path under ${ctx.cwd} means the same file under ${cwd}. Your edits stay in this clone until the orchestrator applies them.${tools.includes("bash") ? " Git commands that write, such as commit and rebase, work here and change only this clone. `git diff main-snapshot` shows every change made in it." : ""}`,
|
|
330
355
|
);
|
|
331
356
|
// Same tick as the spawn: a claim that landed while we waited would delete the clone under a fresh child.
|
|
332
|
-
if (isolation && closing.has(isolation.clone))
|
|
333
|
-
|
|
357
|
+
if (isolation && closing.has(isolation.clone)) throw closingError(isolation.clone);
|
|
358
|
+
// Two revives of one finished job both pass requireIdleClone, so only the first may spawn on that id.
|
|
359
|
+
if (store.liveJob(id))
|
|
360
|
+
throw new Error(`Delegate job "${id}" is already running; wait for it or cancel it first.`);
|
|
334
361
|
const child = spawn(process.execPath, [entrypoint, "--mode", "rpc", ...args], {
|
|
335
362
|
cwd,
|
|
336
363
|
shell: false,
|
|
@@ -357,7 +384,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
357
384
|
const output = await run.done;
|
|
358
385
|
store.finish(job, "done");
|
|
359
386
|
return {
|
|
360
|
-
content: [{ type: "text" as const, text: withIsolation(output, job.isolation) }],
|
|
387
|
+
content: [{ type: "text" as const, text: await withIsolation(output, job.isolation, signal) }],
|
|
361
388
|
details,
|
|
362
389
|
};
|
|
363
390
|
} catch (error) {
|
|
@@ -392,7 +419,11 @@ export default function (pi: ExtensionAPI) {
|
|
|
392
419
|
/** Swaps a running child's model over the RPC; the child confirms or rejects it, and never restarts. */
|
|
393
420
|
async function swapModel(job: DelegateJob, request: string, ctx: ExtensionContext) {
|
|
394
421
|
if (!job.swapModel) throw new Error(`Delegate job "${job.id}" cannot switch models.`);
|
|
395
|
-
const { model, explicit: level } = resolveModel(
|
|
422
|
+
const { model, explicit: level } = resolveModel(
|
|
423
|
+
request,
|
|
424
|
+
configFor(ctx.cwd, ctx.isProjectTrusted()).models ?? {},
|
|
425
|
+
ctx,
|
|
426
|
+
);
|
|
396
427
|
if (!model) throw new Error(`No model found for "${request}".`);
|
|
397
428
|
const [provider, ...rest] = model.split("/");
|
|
398
429
|
if (!rest.length) throw new Error(`Model "${model}" has no provider prefix.`);
|
|
@@ -479,7 +510,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
479
510
|
|
|
480
511
|
registerInspector(pi, store, DELEGATE_SESSION_DIR);
|
|
481
512
|
|
|
482
|
-
const agentList = agentsFor(process.cwd()).map((agent) => {
|
|
513
|
+
const agentList = agentsFor(process.cwd(), projectTrusted(process.cwd())).map((agent) => {
|
|
483
514
|
const qualifiers = [agent.model, agent.isolated ? "isolated" : undefined].filter(Boolean).join(", ");
|
|
484
515
|
return `- ${agent.name}${qualifiers ? ` (${qualifiers})` : ""}: ${agent.description}`;
|
|
485
516
|
});
|
|
@@ -542,7 +573,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
542
573
|
const cloneId = jobId(optional(rawParams.clone));
|
|
543
574
|
if (cloneId && isolated === false) throw new Error("clone always runs isolated; omit isolated: false.");
|
|
544
575
|
const clone = cloneId ? clonedJob(cloneId).isolation : undefined;
|
|
545
|
-
const agent = agentByName(ctx.cwd, agentName);
|
|
576
|
+
const agent = agentByName(ctx.cwd, agentName, ctx.isProjectTrusted());
|
|
546
577
|
const effective = clone ? true : (isolated ?? agent.isolated);
|
|
547
578
|
return runDelegate(ctx, agent, undefined, { description, model, isolated: effective, clone }, task, signal);
|
|
548
579
|
},
|
|
@@ -643,7 +674,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
643
674
|
throw new Error(
|
|
644
675
|
`The isolated clone of delegate job "${id}" was already applied or discarded; delegate_steer cannot continue it. Start a fresh delegate with a condensed brief instead.`,
|
|
645
676
|
);
|
|
646
|
-
const agent = agentByName(ctx.cwd, prior.agent);
|
|
677
|
+
const agent = agentByName(ctx.cwd, prior.agent, ctx.isProjectTrusted());
|
|
647
678
|
return runDelegate(
|
|
648
679
|
ctx,
|
|
649
680
|
agent,
|
|
@@ -729,7 +760,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
729
760
|
}
|
|
730
761
|
const stat = result.kind === "applied" ? `\n${result.stat}` : "";
|
|
731
762
|
const capped = result.kind === "applied" ? capDiff(result.diff) : { diff: undefined, note: undefined };
|
|
732
|
-
closeClone(isolation);
|
|
763
|
+
await closeClone(isolation);
|
|
733
764
|
return {
|
|
734
765
|
content: [
|
|
735
766
|
{
|
package/package.json
CHANGED
package/src/agents.ts
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
|
-
import { join, resolve } from "node:path";
|
|
3
|
+
import { dirname, join, resolve } from "node:path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
5
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
6
|
-
import {
|
|
6
|
+
import {
|
|
7
|
+
CONFIG_DIR_NAME,
|
|
8
|
+
getAgentDir,
|
|
9
|
+
hasTrustRequiringProjectResources,
|
|
10
|
+
parseFrontmatter,
|
|
11
|
+
ProjectTrustStore,
|
|
12
|
+
} from "@earendil-works/pi-coding-agent";
|
|
7
13
|
|
|
8
14
|
export type AgentFile = {
|
|
9
15
|
name: string;
|
|
@@ -19,7 +25,6 @@ type DelegateConfig = {
|
|
|
19
25
|
models?: Record<string, unknown>;
|
|
20
26
|
};
|
|
21
27
|
|
|
22
|
-
const DEFAULT_AGENT_DIR = "~/.agents/agents";
|
|
23
28
|
const BUNDLED_AGENT_DIR = fileURLToPath(new URL("../agents", import.meta.url));
|
|
24
29
|
const MODEL_TIERS = new Set(["cheap", "balanced", "strong"]);
|
|
25
30
|
|
|
@@ -71,10 +76,31 @@ function loadAgents(dir: string): AgentFile[] {
|
|
|
71
76
|
return agents;
|
|
72
77
|
}
|
|
73
78
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
);
|
|
79
|
+
/** pi's user skill dirs (`<agentDir>/skills` then `~/.agents/skills`) with `agents` for `skills`. */
|
|
80
|
+
function userAgentDirs(): string[] {
|
|
81
|
+
// Reversed: pi loads `<agentDir>` first, so it wins.
|
|
82
|
+
return [join(homedir(), ".agents", "agents"), join(getAgentDir(), "agents")];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** pi's project skill dirs: `<cwd>/.pi/skills` plus `.agents/skills` from cwd up to the git root. */
|
|
86
|
+
function projectAgentDirs(cwd: string): string[] {
|
|
87
|
+
const agentsDirs: string[] = [];
|
|
88
|
+
for (let dir = resolve(cwd); ; dir = dirname(dir)) {
|
|
89
|
+
agentsDirs.unshift(join(dir, ".agents", "agents"));
|
|
90
|
+
if (existsSync(join(dir, ".git")) || dirname(dir) === dir) break;
|
|
91
|
+
}
|
|
92
|
+
// Same reversal: pi loads .pi first.
|
|
93
|
+
return [...agentsDirs, join(cwd, CONFIG_DIR_NAME, "agents")];
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Later dirs win; same order as pi's skill discovery.
|
|
97
|
+
function discoverAgents(cwd: string, configuredDirs: unknown, trusted: boolean): AgentFile[] {
|
|
98
|
+
const dirs = [
|
|
99
|
+
BUNDLED_AGENT_DIR,
|
|
100
|
+
...userAgentDirs(),
|
|
101
|
+
...(trusted ? projectAgentDirs(cwd) : []),
|
|
102
|
+
...stringList(configuredDirs),
|
|
103
|
+
].map((dir) => expandPath(dir, cwd));
|
|
78
104
|
const agents = new Map<string, AgentFile>();
|
|
79
105
|
for (const dir of [...new Set(dirs)]) {
|
|
80
106
|
for (const agent of loadAgents(dir)) agents.set(agent.name, agent);
|
|
@@ -82,12 +108,12 @@ function discoverAgents(cwd: string, configuredDirs: unknown): AgentFile[] {
|
|
|
82
108
|
return [...agents.values()];
|
|
83
109
|
}
|
|
84
110
|
|
|
85
|
-
export function agentsFor(cwd: string): AgentFile[] {
|
|
86
|
-
return discoverAgents(cwd, configFor(cwd).agentDirs);
|
|
111
|
+
export function agentsFor(cwd: string, trusted: boolean): AgentFile[] {
|
|
112
|
+
return discoverAgents(cwd, configFor(cwd, trusted).agentDirs, trusted);
|
|
87
113
|
}
|
|
88
114
|
|
|
89
|
-
export function agentByName(cwd: string, name: string): AgentFile {
|
|
90
|
-
const agents = agentsFor(cwd);
|
|
115
|
+
export function agentByName(cwd: string, name: string, trusted: boolean): AgentFile {
|
|
116
|
+
const agents = agentsFor(cwd, trusted);
|
|
91
117
|
const agent = agents.find((candidate) => candidate.name === name);
|
|
92
118
|
if (!agent) {
|
|
93
119
|
const names = agents.map((candidate) => candidate.name).join(", ") || "(none)";
|
|
@@ -96,9 +122,15 @@ export function agentByName(cwd: string, name: string): AgentFile {
|
|
|
96
122
|
return agent;
|
|
97
123
|
}
|
|
98
124
|
|
|
99
|
-
|
|
125
|
+
/** pi's rule without a ctx: a stored decision, else trusted unless project resources need gating. */
|
|
126
|
+
export function projectTrusted(cwd: string): boolean {
|
|
127
|
+
return new ProjectTrustStore(getAgentDir()).get(cwd) ?? !hasTrustRequiringProjectResources(cwd);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function configFor(cwd: string, trusted: boolean): DelegateConfig {
|
|
100
131
|
const global = readConfig(join(getAgentDir(), "settings.json"));
|
|
101
|
-
|
|
132
|
+
// pi ignores project settings in an untrusted project.
|
|
133
|
+
const project = trusted ? readConfig(join(cwd, CONFIG_DIR_NAME, "settings.json")) : {};
|
|
102
134
|
return {
|
|
103
135
|
agentDirs: [...stringList(global.agentDirs), ...stringList(project.agentDirs)],
|
|
104
136
|
models: { ...(global.models ?? {}), ...(project.models ?? {}) },
|
package/src/child.ts
CHANGED
|
@@ -2,7 +2,7 @@ import type { ChildProcessWithoutNullStreams } from "node:child_process";
|
|
|
2
2
|
import { readdirSync } from "node:fs";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { SessionManager, type MessageEndEvent } from "@earendil-works/pi-coding-agent";
|
|
5
|
-
import { limitOutput, textParts } from "./format.ts";
|
|
5
|
+
import { answerTokens, limitOutput, textParts, usageTokens } from "./format.ts";
|
|
6
6
|
|
|
7
7
|
type Child = ChildProcessWithoutNullStreams;
|
|
8
8
|
|
|
@@ -22,12 +22,6 @@ type ChildRun = {
|
|
|
22
22
|
swapModel: (provider: string, modelId: string, level?: string, onModelSet?: () => void) => Promise<void>;
|
|
23
23
|
};
|
|
24
24
|
|
|
25
|
-
function usageTokens(usage: any): number | undefined {
|
|
26
|
-
if (!usage) return undefined;
|
|
27
|
-
const tokens = usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
|
|
28
|
-
return tokens > 0 ? tokens : undefined;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
25
|
/** Run one RPC child, keeping its writer serialized so backpressure and EPIPE reach the caller. */
|
|
32
26
|
export function runChild(
|
|
33
27
|
child: Child,
|
|
@@ -139,7 +133,7 @@ export function runChild(
|
|
|
139
133
|
childError = message.errorMessage;
|
|
140
134
|
const text = textParts(message.content).join("");
|
|
141
135
|
if (text) liveText = text;
|
|
142
|
-
contextTokens =
|
|
136
|
+
contextTokens = answerTokens(message);
|
|
143
137
|
}
|
|
144
138
|
onUpdate?.({ contextTokens, message });
|
|
145
139
|
return;
|
package/src/format.ts
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
calculateContextTokens,
|
|
3
|
+
getMarkdownTheme,
|
|
4
|
+
type KeybindingHints,
|
|
5
|
+
type Theme,
|
|
6
|
+
} from "@earendil-works/pi-coding-agent";
|
|
2
7
|
import {
|
|
3
8
|
type Component,
|
|
4
9
|
Container,
|
|
@@ -9,7 +14,7 @@ import {
|
|
|
9
14
|
truncateToWidth,
|
|
10
15
|
} from "@earendil-works/pi-tui";
|
|
11
16
|
import type { IsolationState } from "./isolation.ts";
|
|
12
|
-
import type { DelegateJob, JobStatus } from "./store.ts";
|
|
17
|
+
import type { DelegateJob, InspectJob, JobStatus } from "./store.ts";
|
|
13
18
|
|
|
14
19
|
type UsageInfo = {
|
|
15
20
|
contextTokens?: number;
|
|
@@ -41,6 +46,16 @@ export type DelegateDetails = Pick<DelegateJob, "id" | "agent" | "model" | "tool
|
|
|
41
46
|
background: boolean;
|
|
42
47
|
};
|
|
43
48
|
|
|
49
|
+
export type JobUsage = {
|
|
50
|
+
input: number;
|
|
51
|
+
output: number;
|
|
52
|
+
cacheRead: number;
|
|
53
|
+
cacheWrite: number;
|
|
54
|
+
cost: number;
|
|
55
|
+
cacheHit?: number;
|
|
56
|
+
contextTokens?: number;
|
|
57
|
+
};
|
|
58
|
+
|
|
44
59
|
const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
45
60
|
export const SPINNER_INTERVAL_MS = 100;
|
|
46
61
|
const STATUS_ICONS = {
|
|
@@ -101,7 +116,7 @@ function formatTokens(count: number): string {
|
|
|
101
116
|
return `${Math.round(count / 1000000)}M`;
|
|
102
117
|
}
|
|
103
118
|
|
|
104
|
-
function formatDuration(ms: number): string {
|
|
119
|
+
export function formatDuration(ms: number): string {
|
|
105
120
|
const seconds = Math.max(0, Math.floor(ms / 1000));
|
|
106
121
|
if (seconds < 60) return `${seconds}s`;
|
|
107
122
|
const minutes = Math.floor(seconds / 60);
|
|
@@ -118,6 +133,60 @@ export function usageStats(usage: UsageInfo, elapsedMs: number): string {
|
|
|
118
133
|
return [tokens, formatDuration(elapsedMs)].filter(Boolean).join(" · ");
|
|
119
134
|
}
|
|
120
135
|
|
|
136
|
+
export function usageTokens(usage: any): number | undefined {
|
|
137
|
+
if (!usage) return undefined;
|
|
138
|
+
const tokens = calculateContextTokens(usage);
|
|
139
|
+
return tokens > 0 ? tokens : undefined;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Context tokens of an answer pi counts: aborted and failed ones carry no usable usage. */
|
|
143
|
+
export function answerTokens(message: { stopReason?: string; usage?: any }): number | undefined {
|
|
144
|
+
if (message.stopReason === "aborted" || message.stopReason === "error") return undefined;
|
|
145
|
+
return usageTokens(message.usage);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Same totals pi's footer builds. */
|
|
149
|
+
export function usageFromMessages(
|
|
150
|
+
messages: readonly { role?: string; usage?: any }[],
|
|
151
|
+
contextTokens?: number,
|
|
152
|
+
): JobUsage {
|
|
153
|
+
const totals: JobUsage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
|
|
154
|
+
for (const message of messages) {
|
|
155
|
+
const usage = message.usage;
|
|
156
|
+
if (!usage) continue;
|
|
157
|
+
totals.input += usage.input ?? 0;
|
|
158
|
+
totals.output += usage.output ?? 0;
|
|
159
|
+
totals.cacheRead += usage.cacheRead ?? 0;
|
|
160
|
+
totals.cacheWrite += usage.cacheWrite ?? 0;
|
|
161
|
+
totals.cost += usage.cost?.total ?? 0;
|
|
162
|
+
if (message.role !== "assistant") continue;
|
|
163
|
+
const prompt = usage.input + usage.cacheRead + usage.cacheWrite;
|
|
164
|
+
totals.cacheHit = prompt > 0 ? (usage.cacheRead / prompt) * 100 : undefined;
|
|
165
|
+
const total = answerTokens(message);
|
|
166
|
+
if (total) totals.contextTokens = total;
|
|
167
|
+
}
|
|
168
|
+
return { ...totals, contextTokens: totals.contextTokens ?? contextTokens };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** pi's footer stats line. */
|
|
172
|
+
export function usageLine(theme: Theme, usage: JobUsage, contextWindow?: number): string {
|
|
173
|
+
const parts: string[] = [];
|
|
174
|
+
if (usage.input) parts.push(`↑${formatTokens(usage.input)}`);
|
|
175
|
+
if (usage.output) parts.push(`↓${formatTokens(usage.output)}`);
|
|
176
|
+
if (usage.cacheRead) parts.push(`R${formatTokens(usage.cacheRead)}`);
|
|
177
|
+
if (usage.cacheWrite) parts.push(`W${formatTokens(usage.cacheWrite)}`);
|
|
178
|
+
if ((usage.cacheRead > 0 || usage.cacheWrite > 0) && usage.cacheHit !== undefined)
|
|
179
|
+
parts.push(`CH${usage.cacheHit.toFixed(1)}%`);
|
|
180
|
+
if (usage.cost) parts.push(`$${usage.cost.toFixed(3)}`);
|
|
181
|
+
const window = contextWindow ?? 0;
|
|
182
|
+
const percent = window && usage.contextTokens !== undefined ? (usage.contextTokens / window) * 100 : undefined;
|
|
183
|
+
const context =
|
|
184
|
+
percent === undefined ? `?/${formatTokens(window)}` : `${percent.toFixed(1)}%/${formatTokens(window)}`;
|
|
185
|
+
const color = percent === undefined ? undefined : percent > 90 ? "error" : percent > 70 ? "warning" : undefined;
|
|
186
|
+
parts.push(color ? theme.fg(color, context) : context);
|
|
187
|
+
return parts.join(" ");
|
|
188
|
+
}
|
|
189
|
+
|
|
121
190
|
export function elapsedMs(job: { startedAt: number; endedAt?: number }, now = Date.now()): number {
|
|
122
191
|
return (job.endedAt ?? now) - job.startedAt;
|
|
123
192
|
}
|
package/src/inspector.ts
CHANGED
|
@@ -13,11 +13,13 @@ import {
|
|
|
13
13
|
Spacer,
|
|
14
14
|
Text,
|
|
15
15
|
truncateToWidth,
|
|
16
|
+
visibleWidth,
|
|
16
17
|
wrapTextWithAnsi,
|
|
17
18
|
} from "@earendil-works/pi-tui";
|
|
18
19
|
import { type ChildMessage, sessionMessages } from "./child.ts";
|
|
19
20
|
import {
|
|
20
21
|
elapsedMs,
|
|
22
|
+
formatDuration,
|
|
21
23
|
formatTools,
|
|
22
24
|
jobIdentity,
|
|
23
25
|
resultPreview,
|
|
@@ -27,6 +29,8 @@ import {
|
|
|
27
29
|
textParts,
|
|
28
30
|
toolCallDetail,
|
|
29
31
|
toolLines,
|
|
32
|
+
usageFromMessages,
|
|
33
|
+
usageLine,
|
|
30
34
|
usageStats,
|
|
31
35
|
} from "./format.ts";
|
|
32
36
|
import type { InspectJob, JobStore } from "./store.ts";
|
|
@@ -257,10 +261,20 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore, sessionDir:
|
|
|
257
261
|
}
|
|
258
262
|
function renderHistory(width: number, job: InspectJob): string[] {
|
|
259
263
|
const tools = toolsLines(job, width);
|
|
260
|
-
// Fixed rows: header, model, description, rule,
|
|
264
|
+
// Fixed rows: header, model, description, rule, footer, plus the failure detail.
|
|
261
265
|
const height = Math.max(0, bodyHeight() - 5 - tools.length - (job.detail ? 1 : 0));
|
|
262
266
|
const view = transcript(job);
|
|
263
|
-
|
|
267
|
+
const messages = messagesOf(job);
|
|
268
|
+
view.sync(messages);
|
|
269
|
+
// A finished job keeps the totals captured at finish; a restored one recounts its transcript.
|
|
270
|
+
const usage = theme.fg(
|
|
271
|
+
"dim",
|
|
272
|
+
usageLine(
|
|
273
|
+
theme,
|
|
274
|
+
job.usage ?? usageFromMessages(messages, job.contextTokens),
|
|
275
|
+
job.contextWindow,
|
|
276
|
+
),
|
|
277
|
+
);
|
|
264
278
|
const window = view.window(width, top, height);
|
|
265
279
|
lastWindow = { height, total: window.total };
|
|
266
280
|
const shown = window.lines.length
|
|
@@ -275,13 +289,13 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore, sessionDir:
|
|
|
275
289
|
),
|
|
276
290
|
]
|
|
277
291
|
: [];
|
|
278
|
-
const
|
|
279
|
-
? `${window.start + 1}–${window.start + window.lines.length}`
|
|
280
|
-
:
|
|
292
|
+
const counterText = window.lines.length
|
|
293
|
+
? `${window.start + 1}–${window.start + window.lines.length}/${window.total}`
|
|
294
|
+
: `0/${window.total}`;
|
|
281
295
|
return (
|
|
282
296
|
[
|
|
283
297
|
truncateToWidth(
|
|
284
|
-
`${statusText(theme, job.status)} ${jobIdentity(theme, job)} ${theme.fg("muted",
|
|
298
|
+
`${statusText(theme, job.status)} ${jobIdentity(theme, job)} ${theme.fg("muted", formatDuration(elapsedMs(job)))}`,
|
|
285
299
|
width,
|
|
286
300
|
),
|
|
287
301
|
truncateToWidth(theme.fg("dim", job.model), width),
|
|
@@ -293,7 +307,7 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore, sessionDir:
|
|
|
293
307
|
...(job.detail
|
|
294
308
|
? [truncateToWidth(theme.fg(STATUS_COLORS.failed, job.detail), width)]
|
|
295
309
|
: []),
|
|
296
|
-
truncateToWidth(theme.fg("dim",
|
|
310
|
+
`${truncateToWidth(usage, Math.max(0, width - visibleWidth(counterText) - 2), "…")} ${theme.fg("dim", counterText)}`,
|
|
297
311
|
]
|
|
298
312
|
.slice(0, bodyHeight())
|
|
299
313
|
// Pad every row so the pane's right edge holds still while the transcript scrolls.
|
package/src/isolation.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { readFile, rm, writeFile } from "node:fs/promises";
|
|
3
3
|
import { join, relative, resolve } from "node:path";
|
|
4
|
+
import { promisify } from "node:util";
|
|
4
5
|
|
|
5
6
|
/** Persisted with the job: where the clone lives and which main-tree snapshot it started from. */
|
|
6
7
|
export type IsolationState = { clone: string; base: string };
|
|
@@ -12,29 +13,41 @@ type ApplyResult =
|
|
|
12
13
|
|
|
13
14
|
const IDENTITY = ["-c", "user.name=pi-delegate", "-c", "user.email=pi-delegate@localhost"];
|
|
14
15
|
const SNAPSHOT_BRANCH = "main-snapshot";
|
|
16
|
+
const execFileAsync = promisify(execFile);
|
|
15
17
|
|
|
16
18
|
/** One git invocation; `indexFile` swaps in a scratch index and `input` feeds stdin (patches). */
|
|
17
|
-
function git(
|
|
19
|
+
async function git(
|
|
18
20
|
args: string[],
|
|
19
|
-
options: {
|
|
20
|
-
|
|
21
|
+
options: {
|
|
22
|
+
cwd?: string;
|
|
23
|
+
gitDir?: string;
|
|
24
|
+
workTree?: string;
|
|
25
|
+
input?: string;
|
|
26
|
+
indexFile?: string;
|
|
27
|
+
signal?: AbortSignal;
|
|
28
|
+
} = {},
|
|
29
|
+
): Promise<string> {
|
|
21
30
|
const command = [
|
|
22
31
|
...(options.gitDir ? ["--git-dir", options.gitDir] : []),
|
|
23
32
|
...(options.workTree ? ["--work-tree", options.workTree] : []),
|
|
24
33
|
...args,
|
|
25
34
|
];
|
|
35
|
+
const pending = execFileAsync("git", command, {
|
|
36
|
+
cwd: options.cwd,
|
|
37
|
+
encoding: "utf8",
|
|
38
|
+
// Binary diffs of real repositories blow past execFile's 1 MiB default.
|
|
39
|
+
maxBuffer: 1024 ** 3,
|
|
40
|
+
signal: options.signal,
|
|
41
|
+
env: options.indexFile ? { ...process.env, GIT_INDEX_FILE: options.indexFile } : process.env,
|
|
42
|
+
});
|
|
43
|
+
// The promisified form has no `input` option, so the patch rides stdin; closing it is also EOF for `git apply -`.
|
|
44
|
+
// A git that exits before reading it (e.g. a rejected patch) would otherwise raise an uncaught EPIPE.
|
|
45
|
+
pending.child.stdin?.on("error", () => {}).end(options.input);
|
|
26
46
|
try {
|
|
27
|
-
return
|
|
28
|
-
cwd: options.cwd,
|
|
29
|
-
input: options.input,
|
|
30
|
-
encoding: "utf8",
|
|
31
|
-
// Without this, git's stderr (rebase hints etc.) leaks onto the TUI.
|
|
32
|
-
stdio: "pipe",
|
|
33
|
-
// Binary diffs of real repositories blow past execFileSync's 1 MiB default.
|
|
34
|
-
maxBuffer: 1024 ** 3,
|
|
35
|
-
env: options.indexFile ? { ...process.env, GIT_INDEX_FILE: options.indexFile } : process.env,
|
|
36
|
-
});
|
|
47
|
+
return (await pending).stdout;
|
|
37
48
|
} catch (error) {
|
|
49
|
+
// An aborted turn is not a git failure; pi marks the cancelled tool call itself.
|
|
50
|
+
if (options.signal?.aborted) throw error;
|
|
38
51
|
const failure = error as { stderr?: string };
|
|
39
52
|
const detail = (failure.stderr ?? "").trim();
|
|
40
53
|
throw new Error(`git ${args[0]} failed${detail ? `: ${detail}` : ""}`);
|
|
@@ -47,58 +60,63 @@ function rootOf(iso: IsolationState): string {
|
|
|
47
60
|
}
|
|
48
61
|
|
|
49
62
|
/** Commits the main tree's current content through a scratch index, so the clone's own checkout and index stay untouched. */
|
|
50
|
-
function snapshotMainTree(iso: IsolationState, root: string): string {
|
|
63
|
+
async function snapshotMainTree(iso: IsolationState, root: string, signal?: AbortSignal): Promise<string> {
|
|
51
64
|
const gitDir = join(iso.clone, ".git");
|
|
52
65
|
const indexFile = join(gitDir, "pi-delegate-snapshot-index");
|
|
53
66
|
try {
|
|
54
|
-
git(["read-tree", iso.base], { gitDir, indexFile });
|
|
55
|
-
git(["add", "-A"], { gitDir, workTree: root, indexFile });
|
|
56
|
-
const tree = git(["write-tree"], { gitDir, indexFile }).trim();
|
|
57
|
-
const snapshot =
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
67
|
+
await git(["read-tree", iso.base], { gitDir, indexFile, signal });
|
|
68
|
+
await git(["add", "-A"], { gitDir, workTree: root, indexFile, signal });
|
|
69
|
+
const tree = (await git(["write-tree"], { gitDir, indexFile, signal })).trim();
|
|
70
|
+
const snapshot = (
|
|
71
|
+
await git([...IDENTITY, "commit-tree", tree, "-p", iso.base, "-m", "main tree snapshot"], {
|
|
72
|
+
gitDir,
|
|
73
|
+
signal,
|
|
74
|
+
})
|
|
75
|
+
).trim();
|
|
76
|
+
await git(["branch", "-f", SNAPSHOT_BRANCH, snapshot], { gitDir, signal });
|
|
61
77
|
return snapshot;
|
|
62
78
|
} finally {
|
|
63
|
-
|
|
79
|
+
await rm(indexFile, { force: true });
|
|
64
80
|
}
|
|
65
81
|
}
|
|
66
82
|
|
|
67
83
|
/** Creates the isolated clone and the base commit capturing the main tree as the user sees it now. */
|
|
68
|
-
export function createIsolation(cwd: string, jobId: string): IsolationState {
|
|
84
|
+
export async function createIsolation(cwd: string, jobId: string, signal?: AbortSignal): Promise<IsolationState> {
|
|
69
85
|
let root: string;
|
|
70
86
|
try {
|
|
71
|
-
root = git(["rev-parse", "--show-toplevel"], { cwd }).trim();
|
|
72
|
-
} catch {
|
|
87
|
+
root = (await git(["rev-parse", "--show-toplevel"], { cwd, signal })).trim();
|
|
88
|
+
} catch (error) {
|
|
89
|
+
if (signal?.aborted) throw error;
|
|
73
90
|
throw new Error("isolated: true requires the session to run inside a git repository.");
|
|
74
91
|
}
|
|
75
92
|
const clone = join(root, ".pi", "worktrees", jobId);
|
|
76
|
-
|
|
77
|
-
git(["clone", "--shared", "--quiet", root, clone]);
|
|
93
|
+
await rm(clone, { recursive: true, force: true });
|
|
78
94
|
try {
|
|
95
|
+
await git(["clone", "--shared", "--quiet", root, clone], { signal });
|
|
79
96
|
// Snapshots use --work-tree=<root>, so the clones themselves must never be picked up; the
|
|
80
97
|
// main repo's local excludes must carry over too, or locally-ignored files land in clones.
|
|
81
98
|
let exclude = "\n.pi/worktrees/\n";
|
|
82
99
|
try {
|
|
83
|
-
const mainExclude = git(["rev-parse", "--git-path", "info/exclude"], { cwd: root }).trim();
|
|
84
|
-
exclude = `${
|
|
100
|
+
const mainExclude = (await git(["rev-parse", "--git-path", "info/exclude"], { cwd: root, signal })).trim();
|
|
101
|
+
exclude = `${await readFile(resolve(root, mainExclude), "utf8")}${exclude}`;
|
|
85
102
|
} catch {
|
|
86
103
|
// No local exclude file; .gitignore still applies.
|
|
87
104
|
}
|
|
88
|
-
|
|
105
|
+
await writeFile(join(clone, ".git", "info", "exclude"), exclude);
|
|
89
106
|
let head: string;
|
|
90
107
|
try {
|
|
91
|
-
head = git(["rev-parse", "HEAD"], { cwd: clone }).trim();
|
|
92
|
-
} catch {
|
|
108
|
+
head = (await git(["rev-parse", "HEAD"], { cwd: clone, signal })).trim();
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (signal?.aborted) throw error;
|
|
93
111
|
throw new Error("cannot isolate a repository with no commits.");
|
|
94
112
|
}
|
|
95
113
|
const iso: IsolationState = { clone, base: head };
|
|
96
|
-
iso.base = snapshotMainTree(iso, root);
|
|
114
|
+
iso.base = await snapshotMainTree(iso, root, signal);
|
|
97
115
|
// The clone's checkout still matches the upstream tip; make it match the snapshot instead.
|
|
98
|
-
git(["reset", "--hard", "--quiet", iso.base], { cwd: clone });
|
|
116
|
+
await git(["reset", "--hard", "--quiet", iso.base], { cwd: clone, signal });
|
|
99
117
|
return iso;
|
|
100
118
|
} catch (error) {
|
|
101
|
-
|
|
119
|
+
await rm(clone, { recursive: true, force: true });
|
|
102
120
|
throw error;
|
|
103
121
|
}
|
|
104
122
|
}
|
|
@@ -110,53 +128,54 @@ export function cloneCwd(iso: IsolationState, cwd: string): string {
|
|
|
110
128
|
}
|
|
111
129
|
|
|
112
130
|
/** Clone location plus a stat of everything the delegate changed, for the job's report. */
|
|
113
|
-
export function isolationSummary(iso: IsolationState): string {
|
|
131
|
+
export async function isolationSummary(iso: IsolationState, signal?: AbortSignal): Promise<string> {
|
|
114
132
|
const lines = [`Isolated clone: ${iso.clone}`];
|
|
115
133
|
const indexFile = join(iso.clone, ".git", "pi-delegate-summary-index");
|
|
116
134
|
try {
|
|
117
135
|
// A scratch index stages uncommitted and untracked changes for the stat without touching the clone's own index.
|
|
118
|
-
git(["read-tree", "HEAD"], { cwd: iso.clone, indexFile });
|
|
119
|
-
git(["add", "-A"], { cwd: iso.clone, indexFile });
|
|
120
|
-
const stat = git(["diff", "--stat", iso.base], { cwd: iso.clone, indexFile }).trimEnd();
|
|
136
|
+
await git(["read-tree", "HEAD"], { cwd: iso.clone, indexFile, signal });
|
|
137
|
+
await git(["add", "-A"], { cwd: iso.clone, indexFile, signal });
|
|
138
|
+
const stat = (await git(["diff", "--stat", iso.base], { cwd: iso.clone, indexFile, signal })).trimEnd();
|
|
121
139
|
if (stat) lines.push(`Changes in this clone:\n${stat}`);
|
|
122
140
|
} catch {
|
|
123
141
|
// The clone may already be applied or gone; the path alone still says where the work lives.
|
|
124
142
|
} finally {
|
|
125
|
-
|
|
143
|
+
await rm(indexFile, { force: true });
|
|
126
144
|
}
|
|
127
145
|
return lines.join("\n");
|
|
128
146
|
}
|
|
129
147
|
|
|
130
|
-
export function removeClone(iso: IsolationState): void {
|
|
131
|
-
|
|
148
|
+
export async function removeClone(iso: IsolationState): Promise<void> {
|
|
149
|
+
await rm(iso.clone, { recursive: true, force: true });
|
|
132
150
|
}
|
|
133
151
|
|
|
134
152
|
/**
|
|
135
153
|
* Merges the clone into the main working tree. Base rule: `base` tracks the newest `main-snapshot`, so a
|
|
136
154
|
* repeat apply is correct whether or not the delegate rebased onto it yet. Only the main tree is written.
|
|
137
155
|
*/
|
|
138
|
-
export function applyClone(iso: IsolationState): ApplyResult {
|
|
156
|
+
export async function applyClone(iso: IsolationState): Promise<ApplyResult> {
|
|
139
157
|
const root = rootOf(iso);
|
|
140
|
-
function run(args: string[]): string {
|
|
158
|
+
function run(args: string[]): Promise<string> {
|
|
141
159
|
return git(args, { cwd: iso.clone });
|
|
142
160
|
}
|
|
143
161
|
// Commit uncommitted delegate work so the rebase carries it.
|
|
144
|
-
run(["add", "-A"]);
|
|
145
|
-
if (run(["status", "--porcelain"]).trim())
|
|
146
|
-
|
|
162
|
+
await run(["add", "-A"]);
|
|
163
|
+
if ((await run(["status", "--porcelain"])).trim())
|
|
164
|
+
await run([...IDENTITY, "commit", "--no-verify", "-m", "delegate work"]);
|
|
165
|
+
const branch = (await run(["rev-parse", "--abbrev-ref", "HEAD"])).trim();
|
|
147
166
|
if (branch === SNAPSHOT_BRANCH)
|
|
148
167
|
throw new Error(
|
|
149
168
|
`the clone is checked out on ${SNAPSHOT_BRANCH}; steer the delegate to move its work onto its own branch, then apply again`,
|
|
150
169
|
);
|
|
151
170
|
// Snapshot the current main tree, then replay the delegate's commits onto it with a real 3-way
|
|
152
171
|
// merge: git tolerates nearby, non-overlapping edits that raw patch context matching rejects.
|
|
153
|
-
const snapshot = snapshotMainTree(iso, root);
|
|
172
|
+
const snapshot = await snapshotMainTree(iso, root);
|
|
154
173
|
try {
|
|
155
|
-
run([...IDENTITY, "rebase", "--empty=drop", SNAPSHOT_BRANCH]);
|
|
174
|
+
await run([...IDENTITY, "rebase", "--empty=drop", SNAPSHOT_BRANCH]);
|
|
156
175
|
} catch (error) {
|
|
157
|
-
const files = run(["diff", "--name-only", "--diff-filter=U"]).trim();
|
|
176
|
+
const files = (await run(["diff", "--name-only", "--diff-filter=U"])).trim();
|
|
158
177
|
try {
|
|
159
|
-
run(["rebase", "--abort"]);
|
|
178
|
+
await run(["rebase", "--abort"]);
|
|
160
179
|
} catch {
|
|
161
180
|
// The rebase failed before starting; there is nothing to abort.
|
|
162
181
|
}
|
|
@@ -165,24 +184,24 @@ export function applyClone(iso: IsolationState): ApplyResult {
|
|
|
165
184
|
return { kind: "conflict", files: files.split("\n"), snapshot };
|
|
166
185
|
}
|
|
167
186
|
// After the rebase this diff is exactly the delegate's work on the current main state.
|
|
168
|
-
const patch = run(["diff", "--binary", SNAPSHOT_BRANCH, "HEAD"]);
|
|
187
|
+
const patch = await run(["diff", "--binary", SNAPSHOT_BRANCH, "HEAD"]);
|
|
169
188
|
if (!patch.trim()) return { kind: "empty" };
|
|
170
189
|
// A changed submodule serializes as a "Subproject commit" hunk that git apply rejects outright.
|
|
171
|
-
if (run(["diff", "--raw", SNAPSHOT_BRANCH, "HEAD"]).match(/^:160000 160000 /m))
|
|
190
|
+
if ((await run(["diff", "--raw", SNAPSHOT_BRANCH, "HEAD"])).match(/^:160000 160000 /m))
|
|
172
191
|
throw new Error("the delegate changed a submodule (gitlink), which git apply cannot carry; apply it manually");
|
|
173
192
|
try {
|
|
174
|
-
git(["apply", "--check", "-"], { cwd: root, input: patch });
|
|
193
|
+
await git(["apply", "--check", "-"], { cwd: root, input: patch });
|
|
175
194
|
} catch (error) {
|
|
176
195
|
// The patch was built on the exact snapshot, so a rejection means the tree moved after it.
|
|
177
196
|
throw new Error(
|
|
178
197
|
`${(error as Error).message} — the main tree changed since the snapshot; call delegate_apply again`,
|
|
179
198
|
);
|
|
180
199
|
}
|
|
181
|
-
git(["apply", "-"], { cwd: root, input: patch });
|
|
200
|
+
await git(["apply", "-"], { cwd: root, input: patch });
|
|
182
201
|
// Without --binary, binary files render as a name-only "Binary files differ" line.
|
|
183
202
|
return {
|
|
184
203
|
kind: "applied",
|
|
185
|
-
stat: run(["diff", "--stat", SNAPSHOT_BRANCH, "HEAD"]).trimEnd(),
|
|
186
|
-
diff: run(["diff", SNAPSHOT_BRANCH, "HEAD"]),
|
|
204
|
+
stat: (await run(["diff", "--stat", SNAPSHOT_BRANCH, "HEAD"])).trimEnd(),
|
|
205
|
+
diff: await run(["diff", SNAPSHOT_BRANCH, "HEAD"]),
|
|
187
206
|
};
|
|
188
207
|
}
|
package/src/store.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ChildMessage, ChildUpdate } from "./child.ts";
|
|
2
|
-
import { resultPreview, toolCallDetail } from "./format.ts";
|
|
2
|
+
import { type JobUsage, resultPreview, toolCallDetail, usageFromMessages } from "./format.ts";
|
|
3
3
|
import type { IsolationState } from "./isolation.ts";
|
|
4
4
|
|
|
5
5
|
export type JobStatus = "running" | "done" | "failed" | "cancelled" | "interrupted";
|
|
@@ -21,6 +21,8 @@ export type InspectJob = {
|
|
|
21
21
|
/** The failure detail shown under a finished job's transcript. */
|
|
22
22
|
detail?: string;
|
|
23
23
|
isolation?: IsolationState;
|
|
24
|
+
/** Usage totals captured at finish: a restored transcript can drop pre-compaction messages. */
|
|
25
|
+
usage?: JobUsage;
|
|
24
26
|
/** Set once an isolated job's clone was applied or discarded, so a steer revive refuses instead of rerunning in the main tree. */
|
|
25
27
|
cloneClosed?: boolean;
|
|
26
28
|
};
|
|
@@ -31,6 +33,8 @@ export type DelegateJob = InspectJob & {
|
|
|
31
33
|
swapModel?: (provider: string, modelId: string, level?: string, onModelSet?: () => void) => Promise<void>;
|
|
32
34
|
};
|
|
33
35
|
|
|
36
|
+
export type JobStore = ReturnType<typeof createJobStore>;
|
|
37
|
+
|
|
34
38
|
const JOB_ENTRY = "delegate-job";
|
|
35
39
|
|
|
36
40
|
/** The latest delegate-job entry per id, newest first: the append-only log's current view. */
|
|
@@ -125,6 +129,7 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
|
|
|
125
129
|
running.delete(job.id);
|
|
126
130
|
job.status = status;
|
|
127
131
|
if (detail) job.detail = detail;
|
|
132
|
+
job.usage = usageFromMessages(job.messages, job.contextTokens);
|
|
128
133
|
commit({ ...plain(job), messages: [], endedAt: Date.now() });
|
|
129
134
|
return true;
|
|
130
135
|
},
|
|
@@ -165,8 +170,6 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
|
|
|
165
170
|
};
|
|
166
171
|
}
|
|
167
172
|
|
|
168
|
-
export type JobStore = ReturnType<typeof createJobStore>;
|
|
169
|
-
|
|
170
173
|
/** The job's latest tool call and its result, once the result arrives. */
|
|
171
174
|
export function lastToolCall(job: InspectJob): {
|
|
172
175
|
tool?: { name: string; detail: string };
|