@aeondave/pi-theme-1337 0.0.0-stage → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +253 -0
- package/LICENSE +21 -0
- package/README.md +159 -2
- package/assets/banner.png +0 -0
- package/assets/palettes.gif +0 -0
- package/docs/architecture.md +167 -0
- package/docs/configuration.md +87 -0
- package/docs/palette-design.md +51 -0
- package/docs/theme-motion.md +88 -0
- package/package.json +68 -4
- package/src/avatar.ts +174 -0
- package/src/background.ts +82 -0
- package/src/config.ts +357 -0
- package/src/diff-spans.ts +77 -0
- package/src/editor.ts +443 -0
- package/src/format.ts +464 -0
- package/src/frame.ts +380 -0
- package/src/index.ts +1195 -0
- package/src/quota.ts +581 -0
- package/src/redraw-guard.ts +79 -0
- package/src/run-summary.ts +623 -0
- package/src/spinner.ts +72 -0
- package/src/terminal-title.ts +67 -0
- package/src/tool-activity.ts +216 -0
- package/src/tool-adapter.ts +491 -0
- package/src/tool-groups.ts +192 -0
- package/src/tool-lexicon.ts +200 -0
- package/src/tool-view.ts +788 -0
- package/src/width.ts +246 -0
- package/themes/1337-amber.json +94 -0
- package/themes/1337-amber.pi1337 +3 -0
- package/themes/1337-cosmos.json +94 -0
- package/themes/1337-cosmos.pi1337 +3 -0
- package/themes/1337-cyber.json +94 -0
- package/themes/1337-cyber.pi1337 +3 -0
- package/themes/1337-cyberpunk-2077-edgerunner.json +94 -0
- package/themes/1337-cyberpunk-2077-edgerunner.pi1337 +7 -0
- package/themes/1337-cyberpunk-2077.json +94 -0
- package/themes/1337-cyberpunk-2077.pi1337 +7 -0
- package/themes/1337-fallout.json +94 -0
- package/themes/1337-fallout.pi1337 +4 -0
- package/themes/1337-ice.json +94 -0
- package/themes/1337-ice.pi1337 +3 -0
- package/themes/1337-magma.json +94 -0
- package/themes/1337-magma.pi1337 +1 -0
- package/themes/1337-neon.json +94 -0
- package/themes/1337-neon.pi1337 +3 -0
- package/themes/1337-poison.json +94 -0
- package/themes/1337-poison.pi1337 +3 -0
- package/themes/1337-skynet-dark.json +94 -0
- package/themes/1337-skynet-dark.pi1337 +4 -0
- package/themes/1337-skynet.json +94 -0
- package/themes/1337-skynet.pi1337 +4 -0
- package/themes/1337.json +95 -0
- package/themes/1337.pi1337 +3 -0
|
@@ -0,0 +1,623 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure end-of-run summary: a collector fed by the agent/tool events index.ts
|
|
3
|
+
* already receives, and the transcript row that paints its result.
|
|
4
|
+
*
|
|
5
|
+
* index.ts appends the collected numbers ONCE, as a custom session entry, when
|
|
6
|
+
* the run settles; the row is rebuilt from that entry on resume and `/tree`,
|
|
7
|
+
* never recomputed. Custom entries never reach the model. The entry is foreign
|
|
8
|
+
* data on the way back in (a session file can be edited), so the row validates
|
|
9
|
+
* every field and renders nothing for anything it does not recognize.
|
|
10
|
+
*
|
|
11
|
+
* Every number comes from live events, because nested (codemode) results are
|
|
12
|
+
* not persisted. Files changed by shell commands are invisible here, so the
|
|
13
|
+
* row says "edited"/"wrote", never "changed".
|
|
14
|
+
*/
|
|
15
|
+
import type { Theme, ThemeColor } from "@earendil-works/pi-coding-agent";
|
|
16
|
+
import type { Component } from "@earendil-works/pi-tui";
|
|
17
|
+
import {
|
|
18
|
+
backgroundDetail, backgroundSummary, backgroundWorkOf, formatDuration, plural, recordOf, sanitizeInlineText, textOf,
|
|
19
|
+
type BackgroundWork,
|
|
20
|
+
} from "./format.ts";
|
|
21
|
+
import { countLines, pathLabel, view, type ViewRow } from "./tool-view.ts";
|
|
22
|
+
|
|
23
|
+
export const RUN_SUMMARY_TYPE = "pi1337-run-summary";
|
|
24
|
+
export const RUN_SUMMARY_VERSION = 1;
|
|
25
|
+
/** Files listed in the entry; the rest are counted in `moreFiles`. */
|
|
26
|
+
export const MAX_SUMMARY_FILES = 50;
|
|
27
|
+
/** Distinct paths tracked per run: past it the file counts become lower bounds, never unbounded memory. */
|
|
28
|
+
const MAX_TRACKED_FILES = 4096;
|
|
29
|
+
/** Calls whose start arguments await their end event; a lost end must not grow the map forever. */
|
|
30
|
+
const MAX_PENDING_CALLS = 256;
|
|
31
|
+
/** Characters of a stored path: sanitized again on render, and bounded here so the entry is too. */
|
|
32
|
+
const MAX_PATH_CHARS = 512;
|
|
33
|
+
|
|
34
|
+
export type RunOutcome = "done" | "interrupted" | "failed";
|
|
35
|
+
|
|
36
|
+
export interface RunSummaryFile {
|
|
37
|
+
/** Display path as the tool rows print it (cwd-relative when inside the run's cwd). */
|
|
38
|
+
path: string;
|
|
39
|
+
/** "write" when any successful write touched it: a written file is reported as written. */
|
|
40
|
+
kind: "edit" | "write";
|
|
41
|
+
/** Exact lines added/removed by its edit calls, from the host's unified patch (edits only). */
|
|
42
|
+
added: number;
|
|
43
|
+
removed: number;
|
|
44
|
+
/** Exact lines its last successful write carried (writes only). */
|
|
45
|
+
lines: number;
|
|
46
|
+
/** Every touch came from a nested (codemode script) call. */
|
|
47
|
+
script: boolean;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The persisted entry: plain JSON, versioned, raw numbers (formatted only when painted). */
|
|
51
|
+
export interface RunSummaryData {
|
|
52
|
+
v: typeof RUN_SUMMARY_VERSION;
|
|
53
|
+
outcome: RunOutcome;
|
|
54
|
+
/** Exact: the run's first agent_start → agent_settled on the injected clock (continuations included). */
|
|
55
|
+
durationMs: number;
|
|
56
|
+
/** Distinct paths changed only by the edit tool (exact for observed calls; shell edits are invisible). */
|
|
57
|
+
edited: number;
|
|
58
|
+
/** Exact +/− lines over those edited paths, from each result's patch. */
|
|
59
|
+
added: number;
|
|
60
|
+
removed: number;
|
|
61
|
+
/** Distinct paths the write tool wrote (exact for observed calls). */
|
|
62
|
+
wrote: number;
|
|
63
|
+
/** Shell tool calls (bash, powershell) that ended, nested ones included, and how many failed. Exact. */
|
|
64
|
+
commands: number;
|
|
65
|
+
commandsFailed: number;
|
|
66
|
+
/** Every tool call that ended, nested ones included, and how many failed. Calls cut off before
|
|
67
|
+
* their end event are not counted, so on an interrupted run this is a lower bound. */
|
|
68
|
+
tools: number;
|
|
69
|
+
toolsFailed: number;
|
|
70
|
+
/** The run's estimated spend: the same delta the status row shows (total − total when the run began);
|
|
71
|
+
* 0 when the run began while the redesign was off and there is no baseline. */
|
|
72
|
+
cost: number;
|
|
73
|
+
files: RunSummaryFile[];
|
|
74
|
+
moreFiles: number;
|
|
75
|
+
// Everything below is optional: entries written before these fields existed
|
|
76
|
+
// carry none of them and render exactly as they always did, and a malformed
|
|
77
|
+
// value is read as absent rather than failing the entry.
|
|
78
|
+
/**
|
|
79
|
+
* pi-persona's background work still running when the run settled (a
|
|
80
|
+
* snapshot of its `persona-background` status, as counts). Present → the row
|
|
81
|
+
* does not claim the work is done.
|
|
82
|
+
*/
|
|
83
|
+
waiting?: BackgroundWork;
|
|
84
|
+
/**
|
|
85
|
+
* Time spent waiting on the model: the sum, over the run's turns, of
|
|
86
|
+
* turn_start → that turn's assistant message_end, on the injected clock.
|
|
87
|
+
* Absent when no turn was measured. Never more than durationMs.
|
|
88
|
+
*/
|
|
89
|
+
modelMs?: number;
|
|
90
|
+
/**
|
|
91
|
+
* Time the model spent thinking: the sum of thinking_start → thinking_end
|
|
92
|
+
* over the run's assistant messages, on the injected clock. A part of
|
|
93
|
+
* modelMs, never beside it. Absent under one second, without a model time,
|
|
94
|
+
* or when it would exceed it (a stream that never closed its block).
|
|
95
|
+
*/
|
|
96
|
+
thinkingMs?: number;
|
|
97
|
+
/**
|
|
98
|
+
* Sum of `usage.output` over the run's assistant messages. Absent when any
|
|
99
|
+
* of them reported none: a partial sum would be a guess.
|
|
100
|
+
*/
|
|
101
|
+
outputTokens?: number;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const SHELL_TOOLS = new Set(["bash", "powershell"]);
|
|
105
|
+
|
|
106
|
+
/** Exact +/− from a unified patch: only lines inside hunks count, so the `---`/`+++` headers never do. */
|
|
107
|
+
export function patchLineCounts(patch: unknown): { added: number; removed: number } {
|
|
108
|
+
const text = textOf(patch);
|
|
109
|
+
let added = 0;
|
|
110
|
+
let removed = 0;
|
|
111
|
+
let inHunk = false;
|
|
112
|
+
for (let start = 0; start < text.length;) {
|
|
113
|
+
const newline = text.indexOf("\n", start);
|
|
114
|
+
const end = newline === -1 ? text.length : newline;
|
|
115
|
+
const first = text.charCodeAt(start);
|
|
116
|
+
// Hunk lines always open with " ", "+", "-" or "\": a line opening with "@@" is a header.
|
|
117
|
+
if (first === 0x40 && text.charCodeAt(start + 1) === 0x40) inHunk = true;
|
|
118
|
+
else if (inHunk && first === 0x2b) added++;
|
|
119
|
+
else if (inHunk && first === 0x2d) removed++;
|
|
120
|
+
start = end + 1;
|
|
121
|
+
}
|
|
122
|
+
return { added, removed };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Same-file detection: tool rows print `src/a.ts` for both `./src/a.ts` and `/work/src/a.ts`. */
|
|
126
|
+
function fileKey(label: string, cwd: string): string {
|
|
127
|
+
const key = label.replace(/^(?:\.\/)+/, "");
|
|
128
|
+
return /^[a-z]:[\\/]/i.test(cwd) || cwd.startsWith("\\\\") || cwd.startsWith("//") ? key.toLowerCase() : key;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
interface PendingCall {
|
|
132
|
+
toolName: string;
|
|
133
|
+
path?: string;
|
|
134
|
+
key?: string;
|
|
135
|
+
lines?: number;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
interface TrackedFile extends RunSummaryFile {
|
|
139
|
+
editAdded: number;
|
|
140
|
+
editRemoved: number;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Event-fed record of one agent run. */
|
|
144
|
+
export interface RunCollector {
|
|
145
|
+
/** The run's first agent_start: begins a fresh record. Pi's in-run continuations must not call it. */
|
|
146
|
+
start(now: number): void;
|
|
147
|
+
toolStart(callId: string, toolName: string, args: unknown, cwd: string): void;
|
|
148
|
+
toolEnd(callId: string, toolName: string, result: unknown, isError: boolean, nested: boolean): void;
|
|
149
|
+
/** turn_start: the model is asked from here until this turn's assistant message ends. */
|
|
150
|
+
turnStart(now: number): void;
|
|
151
|
+
/**
|
|
152
|
+
* message_update: the stream event it carries. `thinking_start` opens a
|
|
153
|
+
* thinking interval and `thinking_end` closes it; every other event (each
|
|
154
|
+
* streamed delta comes through here) is ignored at once.
|
|
155
|
+
*/
|
|
156
|
+
streamEvent(event: unknown, now: number): void;
|
|
157
|
+
/**
|
|
158
|
+
* message_end: an assistant message closes its turn's model interval (and a
|
|
159
|
+
* thinking interval its stream left open) and adds its output tokens. Other
|
|
160
|
+
* roles (user, tool results, custom) are ignored.
|
|
161
|
+
*/
|
|
162
|
+
messageEnd(message: unknown, now: number): void;
|
|
163
|
+
/** turn_end: the run fails when its last assistant message ended in an error. */
|
|
164
|
+
turnEnd(message: unknown): void;
|
|
165
|
+
/** The run's outcome as of now. */
|
|
166
|
+
outcome(aborted: boolean): RunOutcome;
|
|
167
|
+
/**
|
|
168
|
+
* agent_settled: the record, or undefined when no run was started or it is
|
|
169
|
+
* not worth a row (no tool call, not interrupted, not failed). Always resets.
|
|
170
|
+
* `waiting` is the background work still running at this moment, if any; it
|
|
171
|
+
* changes what the row says, never whether there is one.
|
|
172
|
+
*/
|
|
173
|
+
finish(now: number, aborted: boolean, cost: number, waiting?: BackgroundWork): RunSummaryData | undefined;
|
|
174
|
+
reset(): void;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function createRunCollector(): RunCollector {
|
|
178
|
+
let startedAt: number | undefined;
|
|
179
|
+
let turnStartedAt: number | undefined; // set by turn_start, consumed by that turn's assistant message_end
|
|
180
|
+
let modelMs = 0;
|
|
181
|
+
let modelTurns = 0; // turns whose model interval was measured; 0 = model time unknown
|
|
182
|
+
let thinkingStartedAt: number | undefined; // set by thinking_start, consumed by thinking_end or the message's end
|
|
183
|
+
let thinkingMs = 0;
|
|
184
|
+
let outputTokens = 0;
|
|
185
|
+
let assistantMessages = 0;
|
|
186
|
+
let tokensUnknown = false; // an assistant message without a usable usage.output
|
|
187
|
+
let failed = false;
|
|
188
|
+
let commands = 0;
|
|
189
|
+
let commandsFailed = 0;
|
|
190
|
+
let tools = 0;
|
|
191
|
+
let toolsFailed = 0;
|
|
192
|
+
let untracked = 0; // distinct-path overflow past MAX_TRACKED_FILES
|
|
193
|
+
const pending = new Map<string, PendingCall>();
|
|
194
|
+
const files = new Map<string, TrackedFile>(); // insertion order = first-touched order
|
|
195
|
+
|
|
196
|
+
const reset = (): void => {
|
|
197
|
+
startedAt = undefined;
|
|
198
|
+
turnStartedAt = undefined;
|
|
199
|
+
thinkingStartedAt = undefined;
|
|
200
|
+
modelMs = modelTurns = thinkingMs = outputTokens = assistantMessages = 0;
|
|
201
|
+
tokensUnknown = false;
|
|
202
|
+
failed = false;
|
|
203
|
+
commands = commandsFailed = tools = toolsFailed = untracked = 0;
|
|
204
|
+
pending.clear();
|
|
205
|
+
files.clear();
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
const touch = (call: PendingCall, nested: boolean): TrackedFile | undefined => {
|
|
209
|
+
if (!call.key || !call.path) return undefined;
|
|
210
|
+
let file = files.get(call.key);
|
|
211
|
+
if (!file) {
|
|
212
|
+
if (files.size >= MAX_TRACKED_FILES) { untracked++; return undefined; }
|
|
213
|
+
file = { path: call.path, kind: "edit", added: 0, removed: 0, lines: 0, script: true, editAdded: 0, editRemoved: 0 };
|
|
214
|
+
files.set(call.key, file);
|
|
215
|
+
}
|
|
216
|
+
if (!nested) file.script = false;
|
|
217
|
+
return file;
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
const outcomeOf = (aborted: boolean): RunOutcome => aborted ? "interrupted" : failed ? "failed" : "done";
|
|
221
|
+
|
|
222
|
+
const closeThinking = (now: number): void => {
|
|
223
|
+
if (thinkingStartedAt !== undefined && Number.isFinite(now)) thinkingMs += Math.max(0, now - thinkingStartedAt);
|
|
224
|
+
thinkingStartedAt = undefined;
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
return {
|
|
228
|
+
start(now) {
|
|
229
|
+
reset();
|
|
230
|
+
startedAt = now;
|
|
231
|
+
},
|
|
232
|
+
toolStart(callId, toolName, args, cwd) {
|
|
233
|
+
if (!callId || pending.has(callId)) return;
|
|
234
|
+
const call: PendingCall = { toolName };
|
|
235
|
+
if (toolName === "edit" || toolName === "write") {
|
|
236
|
+
const record = recordOf(args);
|
|
237
|
+
const path = pathLabel(record.path, cwd).slice(0, MAX_PATH_CHARS);
|
|
238
|
+
if (path && path !== ".") {
|
|
239
|
+
call.path = path;
|
|
240
|
+
call.key = fileKey(path, cwd);
|
|
241
|
+
}
|
|
242
|
+
// Counted now, so a megabyte of content is never retained until the end event.
|
|
243
|
+
if (toolName === "write") call.lines = countLines(textOf(record.content));
|
|
244
|
+
}
|
|
245
|
+
pending.set(callId, call);
|
|
246
|
+
if (pending.size > MAX_PENDING_CALLS) {
|
|
247
|
+
const oldest = pending.keys().next();
|
|
248
|
+
if (!oldest.done) pending.delete(oldest.value);
|
|
249
|
+
}
|
|
250
|
+
},
|
|
251
|
+
toolEnd(callId, toolName, result, isError, nested) {
|
|
252
|
+
const call = pending.get(callId) ?? { toolName };
|
|
253
|
+
pending.delete(callId);
|
|
254
|
+
tools++;
|
|
255
|
+
if (isError) toolsFailed++;
|
|
256
|
+
if (SHELL_TOOLS.has(toolName)) {
|
|
257
|
+
commands++;
|
|
258
|
+
if (isError) commandsFailed++;
|
|
259
|
+
}
|
|
260
|
+
// A failed edit or write changed nothing worth reporting.
|
|
261
|
+
if (isError || call.toolName !== toolName) return;
|
|
262
|
+
if (toolName === "edit") {
|
|
263
|
+
const file = touch(call, nested);
|
|
264
|
+
if (!file) return;
|
|
265
|
+
const counts = patchLineCounts(recordOf(recordOf(result).details).patch);
|
|
266
|
+
file.editAdded += counts.added;
|
|
267
|
+
file.editRemoved += counts.removed;
|
|
268
|
+
} else if (toolName === "write") {
|
|
269
|
+
const file = touch(call, nested);
|
|
270
|
+
if (!file) return;
|
|
271
|
+
file.kind = "write";
|
|
272
|
+
file.lines = call.lines ?? 0;
|
|
273
|
+
}
|
|
274
|
+
},
|
|
275
|
+
turnStart(now) {
|
|
276
|
+
// Outside a run (a turn before the first agent_start seen) there is nothing to add to.
|
|
277
|
+
if (startedAt !== undefined) turnStartedAt = Number.isFinite(now) ? now : undefined;
|
|
278
|
+
// A block left open by a message that never ended is not carried into the next turn.
|
|
279
|
+
thinkingStartedAt = undefined;
|
|
280
|
+
},
|
|
281
|
+
streamEvent(event, now) {
|
|
282
|
+
if (startedAt === undefined) return;
|
|
283
|
+
const type = recordOf(event).type;
|
|
284
|
+
// A second start before an end keeps the first: overlapping blocks count once.
|
|
285
|
+
if (type === "thinking_start") thinkingStartedAt ??= Number.isFinite(now) ? now : undefined;
|
|
286
|
+
else if (type === "thinking_end") closeThinking(now);
|
|
287
|
+
},
|
|
288
|
+
messageEnd(message, now) {
|
|
289
|
+
const record = recordOf(message);
|
|
290
|
+
if (startedAt === undefined || record.role !== "assistant") return;
|
|
291
|
+
// A stream cut off mid-thought sends no thinking_end: its message's end closes the block.
|
|
292
|
+
closeThinking(now);
|
|
293
|
+
// One assistant message per turn: its end closes the interval turn_start opened.
|
|
294
|
+
if (turnStartedAt !== undefined && Number.isFinite(now)) {
|
|
295
|
+
modelMs += Math.max(0, now - turnStartedAt);
|
|
296
|
+
modelTurns++;
|
|
297
|
+
}
|
|
298
|
+
turnStartedAt = undefined;
|
|
299
|
+
assistantMessages++;
|
|
300
|
+
const output = recordOf(record.usage).output;
|
|
301
|
+
if (typeof output === "number" && Number.isFinite(output) && output >= 0) outputTokens += output;
|
|
302
|
+
else tokensUnknown = true;
|
|
303
|
+
},
|
|
304
|
+
turnEnd(message) {
|
|
305
|
+
const record = recordOf(message);
|
|
306
|
+
// A retry that succeeds after an error turn clears it: only the last word counts.
|
|
307
|
+
if (record.role === "assistant") failed = record.stopReason === "error";
|
|
308
|
+
},
|
|
309
|
+
outcome: outcomeOf,
|
|
310
|
+
finish(now, aborted, cost, waiting) {
|
|
311
|
+
const began = startedAt;
|
|
312
|
+
const outcome = outcomeOf(aborted);
|
|
313
|
+
if (began === undefined || (tools === 0 && outcome === "done")) {
|
|
314
|
+
reset();
|
|
315
|
+
return undefined;
|
|
316
|
+
}
|
|
317
|
+
let edited = 0;
|
|
318
|
+
let added = 0;
|
|
319
|
+
let removed = 0;
|
|
320
|
+
let wrote = 0;
|
|
321
|
+
const listed: RunSummaryFile[] = [];
|
|
322
|
+
for (const file of files.values()) {
|
|
323
|
+
const entry: RunSummaryFile = { path: file.path, kind: file.kind, added: 0, removed: 0, lines: 0, script: file.script };
|
|
324
|
+
if (file.kind === "write") {
|
|
325
|
+
wrote++;
|
|
326
|
+
entry.lines = file.lines;
|
|
327
|
+
} else {
|
|
328
|
+
edited++;
|
|
329
|
+
added += file.editAdded;
|
|
330
|
+
removed += file.editRemoved;
|
|
331
|
+
entry.added = file.editAdded;
|
|
332
|
+
entry.removed = file.editRemoved;
|
|
333
|
+
}
|
|
334
|
+
if (listed.length < MAX_SUMMARY_FILES) listed.push(entry);
|
|
335
|
+
}
|
|
336
|
+
const data: RunSummaryData = {
|
|
337
|
+
v: RUN_SUMMARY_VERSION, outcome,
|
|
338
|
+
durationMs: Math.max(0, now - began),
|
|
339
|
+
edited, added, removed, wrote,
|
|
340
|
+
commands, commandsFailed, tools, toolsFailed,
|
|
341
|
+
cost: Number.isFinite(cost) && cost > 0 ? cost : 0,
|
|
342
|
+
files: listed,
|
|
343
|
+
moreFiles: files.size - listed.length + untracked,
|
|
344
|
+
};
|
|
345
|
+
// Optional fields are added only when known, never as a zero or a guess.
|
|
346
|
+
const stillRunning = backgroundWorkOf(waiting);
|
|
347
|
+
if (stillRunning) data.waiting = stillRunning;
|
|
348
|
+
if (modelTurns > 0) data.modelMs = Math.min(modelMs, data.durationMs);
|
|
349
|
+
// Thinking is part of the model time: more than that is a mismeasure, not a figure.
|
|
350
|
+
if (data.modelMs !== undefined && isThinkingTime(thinkingMs, data.modelMs)) data.thinkingMs = thinkingMs;
|
|
351
|
+
const tokens = Math.round(outputTokens);
|
|
352
|
+
if (assistantMessages > 0 && !tokensUnknown && Number.isSafeInteger(tokens)) data.outputTokens = tokens;
|
|
353
|
+
reset();
|
|
354
|
+
return data;
|
|
355
|
+
},
|
|
356
|
+
reset,
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// ---- the row ---------------------------------------------------------------
|
|
361
|
+
|
|
362
|
+
const isCount = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
363
|
+
const isAmount = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
364
|
+
/** A thinking time worth a place on the row: a second or more, and no more than the model time it is part of. */
|
|
365
|
+
const isThinkingTime = (value: unknown, modelMs: number): value is number => isAmount(value) && value >= 1000 && value <= modelMs;
|
|
366
|
+
|
|
367
|
+
function parseFile(value: unknown): RunSummaryFile | undefined {
|
|
368
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
369
|
+
const f = value as Record<string, unknown>;
|
|
370
|
+
if (typeof f.path !== "string" || (f.kind !== "edit" && f.kind !== "write") || typeof f.script !== "boolean") return undefined;
|
|
371
|
+
if (!isCount(f.added) || !isCount(f.removed) || !isCount(f.lines)) return undefined;
|
|
372
|
+
const path = sanitizeInlineText(f.path.slice(0, MAX_PATH_CHARS));
|
|
373
|
+
if (!path) return undefined;
|
|
374
|
+
return { path, kind: f.kind, added: f.added, removed: f.removed, lines: f.lines, script: f.script };
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** The entry as written by this version, or undefined for anything malformed or foreign. */
|
|
378
|
+
export function parseRunSummary(value: unknown): RunSummaryData | undefined {
|
|
379
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
380
|
+
const d = value as Record<string, unknown>;
|
|
381
|
+
if (d.v !== RUN_SUMMARY_VERSION) return undefined;
|
|
382
|
+
if (d.outcome !== "done" && d.outcome !== "interrupted" && d.outcome !== "failed") return undefined;
|
|
383
|
+
if (!isAmount(d.durationMs) || !isAmount(d.cost)) return undefined;
|
|
384
|
+
for (const key of ["edited", "added", "removed", "wrote", "commands", "commandsFailed", "tools", "toolsFailed", "moreFiles"]) {
|
|
385
|
+
if (!isCount(d[key])) return undefined;
|
|
386
|
+
}
|
|
387
|
+
if (!Array.isArray(d.files) || d.files.length > MAX_SUMMARY_FILES) return undefined;
|
|
388
|
+
const files: RunSummaryFile[] = [];
|
|
389
|
+
for (const item of d.files) {
|
|
390
|
+
const file = parseFile(item);
|
|
391
|
+
if (!file) return undefined;
|
|
392
|
+
files.push(file);
|
|
393
|
+
}
|
|
394
|
+
const data: RunSummaryData = {
|
|
395
|
+
v: RUN_SUMMARY_VERSION, outcome: d.outcome, durationMs: d.durationMs, cost: d.cost,
|
|
396
|
+
edited: d.edited as number, added: d.added as number, removed: d.removed as number, wrote: d.wrote as number,
|
|
397
|
+
commands: d.commands as number, commandsFailed: d.commandsFailed as number,
|
|
398
|
+
tools: d.tools as number, toolsFailed: d.toolsFailed as number,
|
|
399
|
+
files, moreFiles: d.moreFiles as number,
|
|
400
|
+
};
|
|
401
|
+
// Optional fields: absent in older entries, and a malformed one is dropped
|
|
402
|
+
// on its own, so the rest of the row still renders as it always did.
|
|
403
|
+
const waiting = backgroundWorkOf(d.waiting);
|
|
404
|
+
if (waiting) data.waiting = waiting;
|
|
405
|
+
// Model time cannot exceed the run it is part of; one that does is not ours.
|
|
406
|
+
if (isAmount(d.modelMs) && d.modelMs <= d.durationMs) data.modelMs = d.modelMs;
|
|
407
|
+
// Thinking time is read only beside the model time it is a part of.
|
|
408
|
+
if (data.modelMs !== undefined && isThinkingTime(d.thinkingMs, data.modelMs)) data.thinkingMs = d.thinkingMs;
|
|
409
|
+
if (isCount(d.outputTokens)) data.outputTokens = d.outputTokens;
|
|
410
|
+
return data;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** The status row's run delta, spelled as the `~$` estimate it is: cents, nothing below one. */
|
|
414
|
+
export function formatRunCost(cost: number): string {
|
|
415
|
+
if (!Number.isFinite(cost)) return "";
|
|
416
|
+
const cents = Math.round(cost * 100);
|
|
417
|
+
return cents >= 1 ? `~$${(cents / 100).toFixed(2)}` : "";
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
type Span = readonly [ThemeColor, string];
|
|
421
|
+
|
|
422
|
+
const OUTCOME_DOT: Record<RunOutcome, ThemeColor> = { done: "success", interrupted: "warning", failed: "error" };
|
|
423
|
+
const OUTCOME_WORD: Record<RunOutcome, string> = { done: "Done", interrupted: "Interrupted", failed: "Failed" };
|
|
424
|
+
const OUTCOME_LINK: Record<RunOutcome, string> = { done: "in", interrupted: "after", failed: "after" };
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* A run that settled cleanly while background work was still running has not
|
|
428
|
+
* finished the job: its turn ended. The dot recedes with it, so the row never
|
|
429
|
+
* reads as a success it cannot vouch for. Interrupted and failed keep theirs.
|
|
430
|
+
*/
|
|
431
|
+
const PENDING_DOT: ThemeColor = "muted";
|
|
432
|
+
const PENDING_WORD = "Turn ended";
|
|
433
|
+
|
|
434
|
+
/** What a collapsed spelling keeps, from widest to narrowest. */
|
|
435
|
+
interface Shape {
|
|
436
|
+
calls?: "total" | "failed";
|
|
437
|
+
cost?: boolean;
|
|
438
|
+
/** The background work still running: every kind, or the one compact count. */
|
|
439
|
+
waiting?: "detail" | "compact";
|
|
440
|
+
wrote?: boolean;
|
|
441
|
+
counts?: boolean;
|
|
442
|
+
edited?: boolean;
|
|
443
|
+
duration?: boolean;
|
|
444
|
+
word?: boolean;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* The narrowing ladder, as whole spellings. Each step drops one part: the
|
|
449
|
+
* expand hint when there is one (see summarySpellings), the per-kind breakdown
|
|
450
|
+
* of what is awaited (down to one count), the command (or tool-call) total
|
|
451
|
+
* keeping its failures, the cost, "wrote …", the +/− counts, then the
|
|
452
|
+
* failures, "edited …", the waiting clause, and then everything after the
|
|
453
|
+
* outcome; the last two rungs keep even an 8-column row from ever clipping a
|
|
454
|
+
* part. The waiting clause outlasts the cost and every detail of the work:
|
|
455
|
+
* that something is still running matters more than what the turn itself did.
|
|
456
|
+
* A row with nothing awaited spells the same forms it always has (rungs that
|
|
457
|
+
* differ only in the clause collapse into one).
|
|
458
|
+
*/
|
|
459
|
+
const LADDER: readonly Shape[] = [
|
|
460
|
+
{ calls: "total", cost: true, waiting: "detail", wrote: true, counts: true, edited: true, duration: true, word: true },
|
|
461
|
+
{ calls: "total", cost: true, waiting: "compact", wrote: true, counts: true, edited: true, duration: true, word: true },
|
|
462
|
+
{ calls: "failed", cost: true, waiting: "compact", wrote: true, counts: true, edited: true, duration: true, word: true },
|
|
463
|
+
{ calls: "failed", waiting: "compact", wrote: true, counts: true, edited: true, duration: true, word: true },
|
|
464
|
+
{ calls: "failed", waiting: "compact", counts: true, edited: true, duration: true, word: true },
|
|
465
|
+
{ calls: "failed", waiting: "compact", edited: true, duration: true, word: true },
|
|
466
|
+
{ waiting: "compact", edited: true, duration: true, word: true },
|
|
467
|
+
{ waiting: "compact", duration: true, word: true },
|
|
468
|
+
{ duration: true, word: true },
|
|
469
|
+
{ word: true },
|
|
470
|
+
{},
|
|
471
|
+
];
|
|
472
|
+
|
|
473
|
+
function headline(data: RunSummaryData, shape: Shape): Span[][] {
|
|
474
|
+
const parts: Span[][] = [];
|
|
475
|
+
const duration = formatDuration(data.durationMs);
|
|
476
|
+
const pending = data.outcome === "done" && data.waiting !== undefined;
|
|
477
|
+
const word = pending ? PENDING_WORD : OUTCOME_WORD[data.outcome];
|
|
478
|
+
const head: Span[] = [[pending ? PENDING_DOT : OUTCOME_DOT[data.outcome], "●"]];
|
|
479
|
+
if (shape.word) {
|
|
480
|
+
const words = shape.duration && duration ? `${word} ${OUTCOME_LINK[data.outcome]} ${duration}` : word;
|
|
481
|
+
head.push(["muted", ` ${words}`]);
|
|
482
|
+
}
|
|
483
|
+
parts.push(head);
|
|
484
|
+
if (shape.edited && data.edited) {
|
|
485
|
+
const edited: Span[] = [["dim", `edited ${plural(data.edited, "file")}`]];
|
|
486
|
+
if (shape.counts && (data.added || data.removed)) edited.push(["toolDiffAdded", ` +${data.added}`], ["toolDiffRemoved", ` −${data.removed}`]);
|
|
487
|
+
parts.push(edited);
|
|
488
|
+
}
|
|
489
|
+
if (shape.wrote && data.wrote) parts.push([["dim", `wrote ${plural(data.wrote, "file")}`]]);
|
|
490
|
+
// "N tool calls" stands in only when nothing more specific was done.
|
|
491
|
+
const commandsOnly = data.commands > 0;
|
|
492
|
+
const generic = !commandsOnly && !data.edited && !data.wrote;
|
|
493
|
+
const total = commandsOnly ? data.commands : generic ? data.tools : 0;
|
|
494
|
+
const failures = commandsOnly ? data.commandsFailed : generic ? data.toolsFailed : 0;
|
|
495
|
+
// A failed read or edit beside the commands (or with no command at all) is a
|
|
496
|
+
// failure of the run too: the row must not read as clean when a call failed.
|
|
497
|
+
const otherFailures = generic ? 0 : Math.max(0, data.toolsFailed - (commandsOnly ? data.commandsFailed : 0));
|
|
498
|
+
if (shape.calls === "total") {
|
|
499
|
+
if (total) {
|
|
500
|
+
const calls: Span[] = [["dim", commandsOnly ? plural(total, "command") : plural(total, "tool call")]];
|
|
501
|
+
if (failures) calls.push(["dim", ", "], ["error", `${failures} failed`]);
|
|
502
|
+
parts.push(calls);
|
|
503
|
+
}
|
|
504
|
+
// Standing alone a failure count names what failed: "· 1 failed" after
|
|
505
|
+
// "edited 1 file" would read as a failed file.
|
|
506
|
+
if (otherFailures) parts.push([["error", commandsOnly ? `${otherFailures} other failed` : `${plural(otherFailures, "call")} failed`]]);
|
|
507
|
+
} else if (shape.calls === "failed" && failures + otherFailures) {
|
|
508
|
+
// The total is gone, so the count carries its own noun: commands when
|
|
509
|
+
// only commands failed, calls otherwise (a failed read beside them).
|
|
510
|
+
const noun = commandsOnly && otherFailures === 0 ? "command" : "call";
|
|
511
|
+
parts.push([["error", `${plural(failures + otherFailures, noun)} failed`]]);
|
|
512
|
+
}
|
|
513
|
+
const cost = shape.cost ? formatRunCost(data.cost) : "";
|
|
514
|
+
if (cost) parts.push([["muted", cost]]);
|
|
515
|
+
// Last, where the eye lands: what the turn left running. Counts only; the
|
|
516
|
+
// status text they were parsed from is never printed.
|
|
517
|
+
if (shape.waiting && data.waiting) {
|
|
518
|
+
const detail = backgroundDetail(data.waiting);
|
|
519
|
+
const compact = backgroundSummary(data.waiting);
|
|
520
|
+
// The one count stands in only where it is actually shorter: "1 agent, 1
|
|
521
|
+
// timer" already is the narrower way to say "2 background tasks".
|
|
522
|
+
parts.push([["muted", `waiting on ${shape.waiting === "detail" || detail.length <= compact.length ? detail : compact}`]]);
|
|
523
|
+
}
|
|
524
|
+
return parts;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* Where the run's time went, for the expanded row: "model 1m 32s (40s
|
|
529
|
+
* thinking) · tools 42s · 48 tok/s", widest first, narrowing by dropping the
|
|
530
|
+
* rate, then the thinking time, then the tools time. Nothing when the model
|
|
531
|
+
* time is unknown. `tools` is everything in the run that was not waiting on
|
|
532
|
+
* the model (wall time − model time, so it also holds retries' back-off,
|
|
533
|
+
* compaction and prompts), shown from one second up; the rate is output tokens
|
|
534
|
+
* ÷ model time, a whole number, shown only when the model time is at least a
|
|
535
|
+
* second and it rounds to at least one. Thinking is a part of the model time,
|
|
536
|
+
* so it stands in parentheses after it, never as a term of its own: the terms
|
|
537
|
+
* of the line add up to the run.
|
|
538
|
+
*/
|
|
539
|
+
export function timingSpellings(data: RunSummaryData): string[] {
|
|
540
|
+
if (data.modelMs === undefined) return [];
|
|
541
|
+
const model = formatDuration(data.modelMs);
|
|
542
|
+
if (!model) return [];
|
|
543
|
+
const toolsMs = Math.max(0, data.durationMs - data.modelMs);
|
|
544
|
+
const tools = toolsMs >= 1000 ? ` · tools ${formatDuration(toolsMs)}` : "";
|
|
545
|
+
const rate = data.outputTokens !== undefined && data.outputTokens > 0 && data.modelMs >= 1000
|
|
546
|
+
? Math.round(data.outputTokens / (data.modelMs / 1000)) : 0;
|
|
547
|
+
const base = `model ${model}`;
|
|
548
|
+
const thought = isThinkingTime(data.thinkingMs, data.modelMs) ? `${base} (${formatDuration(data.thinkingMs)} thinking)` : base;
|
|
549
|
+
const out = [`${thought}${tools}${rate >= 1 ? ` · ${rate} tok/s` : ""}`, thought + tools, base + tools, base];
|
|
550
|
+
return out.filter((spelling, index) => spelling !== out[index - 1]);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function spell(parts: Span[][], theme: Theme): { plain: string; painted: string } {
|
|
554
|
+
let plain = "";
|
|
555
|
+
let painted = "";
|
|
556
|
+
parts.forEach((part, index) => {
|
|
557
|
+
if (index > 0) {
|
|
558
|
+
plain += " · ";
|
|
559
|
+
painted += theme.fg("dim", " · ");
|
|
560
|
+
}
|
|
561
|
+
for (const [color, text] of part) {
|
|
562
|
+
plain += text;
|
|
563
|
+
painted += theme.fg(color, text);
|
|
564
|
+
}
|
|
565
|
+
});
|
|
566
|
+
return { plain, painted };
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* The collapsed row's spellings, widest first, without duplicates. A `hint`
|
|
571
|
+
* (already sanitized) tops the ladder as the widest form plus ` (hint)` in dim,
|
|
572
|
+
* the way tool rows end, so it is the first thing a narrower row drops.
|
|
573
|
+
*/
|
|
574
|
+
export function summarySpellings(data: RunSummaryData, theme: Theme, hint = ""): { plain: string; painted: string }[] {
|
|
575
|
+
const out: { plain: string; painted: string }[] = [];
|
|
576
|
+
for (const shape of LADDER) {
|
|
577
|
+
const spelled = spell(headline(data, shape), theme);
|
|
578
|
+
if (out.at(-1)?.plain !== spelled.plain) out.push(spelled);
|
|
579
|
+
}
|
|
580
|
+
if (hint) out.unshift({ plain: `${out[0]!.plain} (${hint})`, painted: out[0]!.painted + theme.fg("dim", ` (${hint})`) });
|
|
581
|
+
return out;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function fileSpellings(file: RunSummaryFile, theme: Theme): string[] {
|
|
585
|
+
const path = theme.fg("muted", ` ${file.path}`);
|
|
586
|
+
const detail = file.kind === "write"
|
|
587
|
+
? theme.fg("dim", ` wrote ${plural(file.lines, "line")}`)
|
|
588
|
+
: theme.fg("toolDiffAdded", ` +${file.added}`) + theme.fg("toolDiffRemoved", ` −${file.removed}`);
|
|
589
|
+
const script = file.script ? theme.fg("dim", " (script)") : "";
|
|
590
|
+
return [...(script ? [path + detail + script] : []), path + detail, path];
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
function summaryRows(data: RunSummaryData, theme: Theme, expanded: boolean, expandHint?: () => string): ViewRow[] {
|
|
594
|
+
// Only a row that expanding would change says so, and only while collapsed.
|
|
595
|
+
const expandable = !expanded && !!expandHint && (data.files.length > 0 || data.moreFiles > 0);
|
|
596
|
+
const hint = expandable ? sanitizeInlineText(textOf(expandHint!())) || "expand" : "";
|
|
597
|
+
const spellings = summarySpellings(data, theme, hint);
|
|
598
|
+
const rows: ViewRow[] = [{ text: spellings.at(-1)!.plain, color: "dim", painted: spellings.map(s => s.painted) }];
|
|
599
|
+
if (!expanded) return rows;
|
|
600
|
+
// One dim line under the headline, above the files: expanded only, so the
|
|
601
|
+
// collapsed row (and whether it carries a hint) is exactly what it was.
|
|
602
|
+
// The last, empty rung keeps it whole or absent: a row too narrow for
|
|
603
|
+
// "model 1m 32s" shows no timing at all, never a number cut mid-digit.
|
|
604
|
+
const timing = timingSpellings(data);
|
|
605
|
+
if (timing.length) rows.push({ text: timing.at(-1)!, color: "dim", painted: [...timing.map(spelling => theme.fg("dim", ` ${spelling}`)), ""] });
|
|
606
|
+
for (const file of data.files) rows.push({ text: file.path, color: "muted", painted: fileSpellings(file, theme) });
|
|
607
|
+
if (data.moreFiles) rows.push({ text: ` … ${data.moreFiles} more`, color: "dim" });
|
|
608
|
+
return rows;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/**
|
|
612
|
+
* The transcript row for one entry: one line collapsed; expanded, the timing
|
|
613
|
+
* line (when the entry has one) and a row per file under it. Built on the tool rows' view (indent, width cache, never wraps,
|
|
614
|
+
* never wider than the terminal). Undefined for malformed or foreign data.
|
|
615
|
+
* Pi's entry renderer passes no outputPad, so the transcript's one-cell indent
|
|
616
|
+
* is the default. `expandHint` is the host's key hint, as tool rows receive it
|
|
617
|
+
* (index.ts injects it; this module stays free of runtime Pi imports).
|
|
618
|
+
*/
|
|
619
|
+
export function createRunSummaryRow(value: unknown, expanded: boolean, theme: Theme, outputPad = 1, expandHint?: () => string): Component | undefined {
|
|
620
|
+
const data = parseRunSummary(value);
|
|
621
|
+
if (!data) return undefined;
|
|
622
|
+
return view(theme, { outputPad }, () => summaryRows(data, theme, expanded, expandHint));
|
|
623
|
+
}
|