@lune_99/pi-subagent 0.0.0-stage → 0.1.0

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.
Files changed (46) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +21 -0
  3. package/README.md +169 -2
  4. package/docs/capture.json +30 -0
  5. package/docs/previews.md +22 -0
  6. package/docs/reference.md +240 -0
  7. package/docs/subagent-auto-tiers.png +0 -0
  8. package/docs/subagent-inspector.png +0 -0
  9. package/docs/subagent-overview.png +0 -0
  10. package/package.json +82 -5
  11. package/skills/create-lune-subagent/SKILL.md +186 -0
  12. package/src/auto-model.ts +592 -0
  13. package/src/catalog.ts +111 -0
  14. package/src/definition-file.ts +112 -0
  15. package/src/definitions.ts +324 -0
  16. package/src/dock/dock-alert.ts +78 -0
  17. package/src/dock/dock-contribution.ts +318 -0
  18. package/src/extension-tools.ts +46 -0
  19. package/src/index.ts +168 -0
  20. package/src/inspector/details.ts +113 -0
  21. package/src/inspector/inspector.ts +653 -0
  22. package/src/inspector/layout.ts +119 -0
  23. package/src/inspector/transcript.ts +735 -0
  24. package/src/inspector/viewport.ts +62 -0
  25. package/src/inspector/wrap.ts +136 -0
  26. package/src/models.ts +54 -0
  27. package/src/notify/notification-box.ts +381 -0
  28. package/src/notify/notifier.ts +569 -0
  29. package/src/paths.ts +34 -0
  30. package/src/render/lune-theme.ts +68 -0
  31. package/src/render/text.ts +121 -0
  32. package/src/run/guide.ts +26 -0
  33. package/src/run/report-tool.ts +90 -0
  34. package/src/run/run-file.ts +193 -0
  35. package/src/run/run-manager.ts +838 -0
  36. package/src/run/run-session.ts +307 -0
  37. package/src/run/run.ts +681 -0
  38. package/src/run/session-start.ts +283 -0
  39. package/src/run/types.ts +167 -0
  40. package/src/run/worktree.ts +138 -0
  41. package/src/schema.ts +9 -0
  42. package/src/settings/agents-menu.ts +363 -0
  43. package/src/settings/panel.ts +179 -0
  44. package/src/settings/schema.ts +71 -0
  45. package/src/tools/format.ts +375 -0
  46. package/src/tools/subagent-tools.ts +467 -0
@@ -0,0 +1,318 @@
1
+ import type { ExtensionContext, Theme, ThemeColor } from "@earendil-works/pi-coding-agent";
2
+ import type { Component } from "@earendil-works/pi-tui";
3
+ import {
4
+ createDockContribution,
5
+ type DockHandle,
6
+ type IndependentDock,
7
+ type LuneDockSnapshot,
8
+ } from "@lune_99/pi-lune-extensions-core/dock";
9
+
10
+ import { fitRanked, type RankedPart } from "../render/text.ts";
11
+ import type { RunManager } from "../run/run-manager.ts";
12
+ import type { Run } from "../run/run.ts";
13
+ import { DockAlerts } from "./dock-alert.ts";
14
+
15
+ export const SUBAGENT_CONTRIBUTION_ID = "subagents";
16
+
17
+ const WIDGET_ID = "pi-subagent";
18
+
19
+ type DockStatus =
20
+ | "running"
21
+ | "needs input"
22
+ | "blocked"
23
+ | "failed"
24
+ | "interrupted"
25
+ | "unreported"
26
+ | "done"
27
+ | "idle";
28
+
29
+ /**
30
+ * The statuses in display order, with their ranks: a narrow cell drops the lowest ranks first, so
31
+ * the counts that need the user stay longest.
32
+ */
33
+ const STATUS_RANKS: ReadonlyArray<readonly [DockStatus, number]> = [
34
+ ["running", 7],
35
+ ["needs input", 8],
36
+ ["blocked", 9],
37
+ ["failed", 10],
38
+ ["interrupted", 5],
39
+ ["unreported", 4],
40
+ ["done", 3],
41
+ ["idle", 2],
42
+ ];
43
+ const ELSEWHERE_RANK = 6;
44
+ const LATEST_RANK = 1;
45
+ const HINT_RANK = 0;
46
+
47
+ /**
48
+ * The Dock item of the runs on the current branch, and of runs on other branches whose ended turn
49
+ * waits for that branch. Its lines count the runs by status and never cut a part: a narrow cell
50
+ * leaves out whole parts, then the title. A failed or blocked turn turns the marker red for a short
51
+ * time, or until the user sees the run in the inspector; a later failure turns it red again.
52
+ */
53
+ export class SubagentDockContribution {
54
+ private ctx: ExtensionContext | undefined;
55
+ private manager: RunManager | undefined;
56
+ private readonly alerts = new DockAlerts(() => this.refresh());
57
+ private readonly standalone: StandaloneDock;
58
+ private readonly dock: DockHandle;
59
+
60
+ constructor(open: (ctx: ExtensionContext) => Promise<void>) {
61
+ this.standalone = new StandaloneDock((theme) => this.row(theme));
62
+ this.dock = createDockContribution({
63
+ id: SUBAGENT_CONTRIBUTION_ID,
64
+ getSnapshot: (ctx) => this.snapshot(ctx.ui.theme),
65
+ activate: (ctx) => open(ctx),
66
+ standalone: this.standalone,
67
+ });
68
+ }
69
+
70
+ attach(ctx: ExtensionContext, manager: RunManager): void {
71
+ this.detach({ retired: true });
72
+ this.ctx = ctx;
73
+ this.manager = manager;
74
+ this.dock.attach(ctx);
75
+ }
76
+
77
+ detach(options?: { retired?: boolean }): void {
78
+ this.ctx = undefined;
79
+ this.manager = undefined;
80
+ this.alerts.clear();
81
+ this.dock.detach(options);
82
+ }
83
+
84
+ refresh(): void {
85
+ if (this.ctx) {
86
+ this.dock.refresh();
87
+ }
88
+ }
89
+
90
+ /** The user saw the run's outcome in the inspector. */
91
+ acknowledge(run: Run): void {
92
+ if (this.alerts.acknowledge(alertKey(run))) {
93
+ this.refresh();
94
+ }
95
+ }
96
+
97
+ /** This branch's runs, and the runs of other branches whose ended turn waits for that branch. */
98
+ private runs(): { here: Run[]; elsewhere: Run[] } {
99
+ const manager = this.manager;
100
+
101
+ if (!manager) {
102
+ return { here: [], elsewhere: [] };
103
+ }
104
+
105
+ const { here, elsewhere } = manager.runsByBranch();
106
+
107
+ return { here, elsewhere: elsewhere.filter((run) => manager.hasDeferred(run)) };
108
+ }
109
+
110
+ private alarming(run: Run): boolean {
111
+ return run.needsAttention && this.alerts.shows(alertKey(run), turnEndedAt(run));
112
+ }
113
+
114
+ /** Base names the item; detail adds the counts; full adds the run that changed last. */
115
+ private snapshot(theme: Theme): LuneDockSnapshot {
116
+ const { here, elsewhere } = this.runs();
117
+ const runs = [...here, ...elsewhere];
118
+ const summary = this.summary(runs, elsewhere.length, theme);
119
+
120
+ return {
121
+ base: this.line(runs, theme, []),
122
+ detail: this.line(runs, theme, summary),
123
+ full: this.line(runs, theme, [...summary, ...this.latest(runs, theme)]),
124
+ };
125
+ }
126
+
127
+ /** The standalone row: the full line and how to open the inspector; undefined hides it. */
128
+ private row(theme: Theme): Component | undefined {
129
+ const { here, elsewhere } = this.runs();
130
+ const runs = [...here, ...elsewhere];
131
+
132
+ if (runs.length === 0) {
133
+ return undefined;
134
+ }
135
+
136
+ return this.line(runs, theme, [
137
+ ...this.summary(runs, elsewhere.length, theme),
138
+ ...this.latest(runs, theme),
139
+ { text: theme.fg("dim", "/agents to open"), rank: HINT_RANK },
140
+ ]);
141
+ }
142
+
143
+ /** `◐ Agents · 2 running · 1 done` with every part that fits, down to the marker alone. */
144
+ private line(runs: readonly Run[], theme: Theme, parts: readonly RankedPart[]): Component {
145
+ const [color, symbol] = this.marker(runs);
146
+ const marker = theme.fg(color, symbol);
147
+ const separator = theme.fg("muted", " · ");
148
+
149
+ return {
150
+ render: (width) => [
151
+ fitRanked(parts, width, (texts) =>
152
+ [`${marker} Agents`, ...texts].join(separator),
153
+ ) ?? marker,
154
+ ],
155
+ invalidate() {},
156
+ };
157
+ }
158
+
159
+ /** `2 running · 1 needs input · 1 on another branch`, and nothing without runs. */
160
+ private summary(runs: readonly Run[], elsewhere: number, theme: Theme): RankedPart[] {
161
+ if (runs.length === 0) {
162
+ return [];
163
+ }
164
+
165
+ const muted = (text: string): string => theme.fg("muted", text);
166
+
167
+ const counts = new Map<DockStatus, number>();
168
+
169
+ for (const run of runs) {
170
+ const status = dockStatus(run);
171
+
172
+ counts.set(status, (counts.get(status) ?? 0) + 1);
173
+ }
174
+
175
+ const parts = STATUS_RANKS.filter(([status]) => counts.has(status)).map(
176
+ ([status, rank]) => ({ text: muted(`${counts.get(status)} ${status}`), rank }),
177
+ );
178
+
179
+ if (elsewhere > 0) {
180
+ parts.push({
181
+ text: muted(
182
+ `${elsewhere} on ${elsewhere === 1 ? "another branch" : "other branches"}`,
183
+ ),
184
+ rank: ELSEWHERE_RANK,
185
+ });
186
+ }
187
+
188
+ return parts;
189
+ }
190
+
191
+ /** `latest: reviewer done`: the run whose turn started or ended last. */
192
+ private latest(runs: readonly Run[], theme: Theme): RankedPart[] {
193
+ let latest: Run | undefined;
194
+ let latestAt = -Infinity;
195
+
196
+ for (const run of runs) {
197
+ const at = lastActivity(run);
198
+
199
+ if (at >= latestAt) {
200
+ latest = run;
201
+ latestAt = at;
202
+ }
203
+ }
204
+
205
+ return latest
206
+ ? [
207
+ {
208
+ text: theme.fg("muted", `latest: ${latest.name} ${dockStatus(latest)}`),
209
+ rank: LATEST_RANK,
210
+ },
211
+ ]
212
+ : [];
213
+ }
214
+
215
+ private marker(runs: readonly Run[]): [ThemeColor, string] {
216
+ if (runs.some((run) => this.alarming(run))) {
217
+ return ["error", "✕"];
218
+ }
219
+
220
+ if (runs.some((run) => run.needsInput)) {
221
+ return ["accent", "?"];
222
+ }
223
+
224
+ if (runs.some((run) => run.state === "running")) {
225
+ return ["warning", "◐"];
226
+ }
227
+
228
+ // Settled with failures: green would claim success, and red stays for new failures.
229
+ if (runs.some((run) => run.needsAttention)) {
230
+ return ["muted", "●"];
231
+ }
232
+
233
+ if (runs.length > 0) {
234
+ return ["success", "●"];
235
+ }
236
+
237
+ return ["dim", "○"];
238
+ }
239
+ }
240
+
241
+ /** One status per run: the session's state, and the last report once the session is idle. */
242
+ function dockStatus(run: Run): DockStatus {
243
+ if (run.state !== "idle") {
244
+ return run.state;
245
+ }
246
+
247
+ switch (run.lastTurn?.report?.status) {
248
+ case "needs_input":
249
+ return "needs input";
250
+ case "blocked":
251
+ return "blocked";
252
+ case "done":
253
+ return "done";
254
+ default:
255
+ return run.lastTurn ? "unreported" : "idle";
256
+ }
257
+ }
258
+
259
+ /** Each ended turn can raise its own alert, so seeing one failure does not hide a later one. */
260
+ function alertKey(run: Run): string {
261
+ return `${run.id}#${run.turns}`;
262
+ }
263
+
264
+ /** A run that failed to load has no turn time; its alert starts when the Dock first shows it. */
265
+ function turnEndedAt(run: Run): number | undefined {
266
+ const time = Date.parse(run.lastTurn?.endedAt ?? "");
267
+
268
+ return Number.isNaN(time) ? undefined : time;
269
+ }
270
+
271
+ function lastActivity(run: Run): number {
272
+ const time = Date.parse(
273
+ run.turnStartedAt ?? run.lastTurn?.endedAt ?? run.snapshot?.createdAt ?? "",
274
+ );
275
+
276
+ return Number.isNaN(time) ? -Infinity : time;
277
+ }
278
+
279
+ /** The row below the editor while no shared Dock is attached. */
280
+ class StandaloneDock implements IndependentDock {
281
+ private ctx: ExtensionContext | undefined;
282
+ private readonly row: (theme: Theme) => Component | undefined;
283
+
284
+ constructor(row: (theme: Theme) => Component | undefined) {
285
+ this.row = row;
286
+ }
287
+
288
+ setCtx(ctx: ExtensionContext | undefined): void {
289
+ this.ctx = ctx;
290
+ }
291
+
292
+ render(): void {
293
+ if (!this.ctx?.hasUI) {
294
+ return;
295
+ }
296
+
297
+ const row = this.row(this.ctx.ui.theme);
298
+
299
+ // Pi pads string rows by one column on each side; this row keeps the same margins.
300
+ this.ctx.ui.setWidget(
301
+ WIDGET_ID,
302
+ row === undefined
303
+ ? undefined
304
+ : () => ({
305
+ render: (width) =>
306
+ row.render(Math.max(0, width - 2)).map((line) => ` ${line}`),
307
+ invalidate() {},
308
+ }),
309
+ { placement: "belowEditor" },
310
+ );
311
+ }
312
+
313
+ clear(): void {
314
+ if (this.ctx?.hasUI) {
315
+ this.ctx.ui.setWidget(WIDGET_ID, undefined);
316
+ }
317
+ }
318
+ }
@@ -0,0 +1,46 @@
1
+ import type { ToolInfo } from "@earendil-works/pi-coding-agent";
2
+
3
+ import { REPORT_TOOL_NAME } from "./run/report-tool.ts";
4
+ import { SUBAGENT_TOOL_NAMES } from "./tools/subagent-tools.ts";
5
+
6
+ /** A tool that one of the parent's user or project extensions registers. */
7
+ export interface ExtensionTool {
8
+ name: string;
9
+ description: string;
10
+ /** The file of the extension that registers it; a run that selects the tool loads it. */
11
+ path: string;
12
+ }
13
+
14
+ /**
15
+ * The parent's tools that a run can get by loading the extension that registers them.
16
+ *
17
+ * Names the run has on its own stay Pi's: a parent extension that replaces `bash` does not replace
18
+ * the run's native one. The subagent tools are left out, so runs cannot start runs.
19
+ */
20
+ export function listExtensionTools(
21
+ tools: readonly ToolInfo[],
22
+ options: { runTools: ReadonlySet<string>; projectTrusted: boolean },
23
+ ): ExtensionTool[] {
24
+ return tools.flatMap((tool) => {
25
+ const { path, scope } = tool.sourceInfo;
26
+
27
+ if (
28
+ isSyntheticPath(path) ||
29
+ tool.exposure === "hidden" ||
30
+ options.runTools.has(tool.name) ||
31
+ tool.name === REPORT_TOOL_NAME ||
32
+ tool.name.startsWith("mcp__") ||
33
+ (SUBAGENT_TOOL_NAMES as readonly string[]).includes(tool.name) ||
34
+ (scope === "project" && !options.projectTrusted)
35
+ ) {
36
+ return [];
37
+ }
38
+
39
+ return [{ name: tool.name, description: tool.description, path }];
40
+ });
41
+ }
42
+
43
+ /** Pi gives tools and extensions without a file a `builtin:<name>` or `<kind:name>` path. */
44
+ export function isSyntheticPath(path: string): boolean {
45
+ return path.startsWith("builtin:") || path.startsWith("<");
46
+ }
package/src/index.ts ADDED
@@ -0,0 +1,168 @@
1
+ import {
2
+ getAgentDir,
3
+ type ExtensionAPI,
4
+ type ExtensionContext,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import { registerSettingsPanel } from "@lune_99/pi-lune-extensions-core/panel";
7
+ import { ResourceScope } from "@lune_99/pi-lune-extensions-core/resources";
8
+ import { bindSettings } from "@lune_99/pi-lune-extensions-core/settings";
9
+
10
+ import { addExtensionTools, loadToolCatalog, type ToolCatalog } from "./catalog.ts";
11
+ import { formatDefinitionProblems, loadAllDefinitions, renderRoster } from "./definitions.ts";
12
+ import { SubagentDockContribution } from "./dock/dock-contribution.ts";
13
+ import { listExtensionTools } from "./extension-tools.ts";
14
+ import { openSubagentInspector } from "./inspector/inspector.ts";
15
+ import { allowedModelRefs } from "./models.ts";
16
+ import { renderRunNotificationBox } from "./notify/notification-box.ts";
17
+ import { RUN_NOTIFICATION_TYPE, type RunNotificationDetails } from "./notify/notifier.ts";
18
+ import { RunManager } from "./run/run-manager.ts";
19
+ import { createSubagentPanel } from "./settings/panel.ts";
20
+ import { autoModelSettings, subagentSettings } from "./settings/schema.ts";
21
+ import { createSubagentTools } from "./tools/subagent-tools.ts";
22
+
23
+ export default function (pi: ExtensionAPI): void {
24
+ let manager: RunManager | undefined;
25
+ let roster: string | undefined;
26
+ let toolCatalog: ToolCatalog | undefined;
27
+ let unsubscribe: (() => void) | undefined;
28
+
29
+ const resources = new ResourceScope();
30
+ const settings = resources.use(bindSettings(pi, subagentSettings));
31
+
32
+ resources.use(
33
+ registerSettingsPanel(
34
+ createSubagentPanel({
35
+ catalog: () => toolCatalog,
36
+ onEdit: (previousFile, edited) =>
37
+ manager?.applyDefinitionEdit(previousFile, edited),
38
+ }),
39
+ settings,
40
+ ),
41
+ );
42
+
43
+ const open = async (ctx: ExtensionContext): Promise<void> => {
44
+ if (ctx.mode !== "tui") {
45
+ return;
46
+ }
47
+
48
+ if (!manager) {
49
+ ctx.ui.notify("Subagents start with the session; there is none yet.", "warning");
50
+ return;
51
+ }
52
+
53
+ await openSubagentInspector({ ctx, manager, onSeen: (run) => dock.acknowledge(run) });
54
+ };
55
+ const dock = new SubagentDockContribution(open);
56
+
57
+ // The transcript looks the renderer up by custom type, so one registration per load is enough.
58
+ pi.registerMessageRenderer<RunNotificationDetails>(
59
+ RUN_NOTIFICATION_TYPE,
60
+ renderRunNotificationBox,
61
+ );
62
+
63
+ pi.registerCommand("agents", {
64
+ description: "Open the subagent inspector",
65
+ handler: async (_args, ctx) => open(ctx),
66
+ });
67
+
68
+ pi.on("session_start", async (_event, ctx) => {
69
+ const agentDir = getAgentDir();
70
+ const { definitions, problems } = loadAllDefinitions({
71
+ agentDir,
72
+ cwd: ctx.cwd,
73
+ projectTrusted: ctx.isProjectTrusted(),
74
+ });
75
+
76
+ if (problems.length > 0) {
77
+ ctx.ui.notify(formatDefinitionProblems(problems), "warning");
78
+ }
79
+
80
+ const catalog = await loadToolCatalog(ctx.cwd, agentDir);
81
+
82
+ if (catalog.errors.length > 0) {
83
+ ctx.ui.notify(
84
+ `Subagent runs cannot load these built-in extensions:\n ${catalog.errors.join("\n ")}`,
85
+ "error",
86
+ );
87
+ }
88
+
89
+ const runTools = new Set(catalog.tools.map((tool) => tool.name));
90
+ // Read again for every start and resume, so tools registered after this handler count.
91
+ const extensionTools = () =>
92
+ listExtensionTools(pi.getAllTools(), {
93
+ runTools,
94
+ projectTrusted: ctx.isProjectTrusted(),
95
+ });
96
+
97
+ manager = new RunManager({
98
+ pi,
99
+ ctx,
100
+ agentDir,
101
+ definitions,
102
+ extensionTools,
103
+ autoModelSettings: async (startCtx) =>
104
+ autoModelSettings((await settings.view(startCtx)).snapshot()),
105
+ });
106
+ manager.restore();
107
+ toolCatalog = addExtensionTools(catalog, extensionTools());
108
+
109
+ // Built once per session: the declarations stay the same for every turn of it. Tools that
110
+ // other extensions register later are missing from the list, but runs can still select them.
111
+ for (const tool of createSubagentTools({
112
+ manager,
113
+ definitions,
114
+ models: allowedModelRefs(ctx),
115
+ catalog: toolCatalog,
116
+ })) {
117
+ pi.registerTool(tool);
118
+ }
119
+
120
+ roster = renderRoster(definitions);
121
+ pi.events.emit(
122
+ "lune-subagent:agents-loaded",
123
+ definitions.map((definition) => definition.name),
124
+ );
125
+ dock.attach(ctx, manager);
126
+ // The Dock shows states and reports only; a refresh per streamed token redraws the whole TUI.
127
+ unsubscribe = manager.subscribe((change) => {
128
+ if (change === "state") {
129
+ dock.refresh();
130
+ }
131
+ });
132
+ });
133
+
134
+ pi.on("before_agent_start", (event) => {
135
+ manager?.resumeNotifications();
136
+
137
+ // The same text on every turn, so Pi's section diff sends no patch and the cache holds.
138
+ if (roster) {
139
+ event.systemPromptOptions.sections.subagents = roster;
140
+ }
141
+ });
142
+
143
+ pi.on("agent_settled", (event) => {
144
+ manager?.mainAgentSettled(event.aborted);
145
+ });
146
+
147
+ pi.on("session_before_tree", async (event, ctx) => manager?.beforeTree(event, ctx));
148
+
149
+ pi.on("session_tree", () => {
150
+ manager?.afterTree();
151
+ dock.refresh();
152
+ });
153
+
154
+ pi.on("session_shutdown", async () => {
155
+ const current = manager;
156
+
157
+ manager = undefined;
158
+ roster = undefined;
159
+ toolCatalog = undefined;
160
+ unsubscribe?.();
161
+ unsubscribe = undefined;
162
+ pi.events.emit("lune-subagent:agents-loaded", []);
163
+ dock.detach({ retired: true });
164
+ await current?.shutdown();
165
+ // Pi replaces the extension runtime after a shutdown, so the settings end with it.
166
+ await resources.dispose();
167
+ });
168
+ }
@@ -0,0 +1,113 @@
1
+ import type { Theme, ThemeColor } from "@earendil-works/pi-coding-agent";
2
+ import { wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
+
4
+ import { displayLines } from "../render/text.ts";
5
+ import type { Run } from "../run/run.ts";
6
+ import { formatDuration, formatTokens, startValueLines, workspaceLines } from "../tools/format.ts";
7
+
8
+ /** The `d` view: the snapshot, start values, workspace, token usage and diagnostics of one run. */
9
+ export function detailRows(run: Run, theme: Theme, width: number): string[] {
10
+ const rows: string[] = [];
11
+ const section = (title: string): void => {
12
+ if (rows.length > 0) {
13
+ rows.push("");
14
+ }
15
+
16
+ rows.push(theme.bold(theme.fg("mdHeading", title)));
17
+ };
18
+ const line = (text: string, color: ThemeColor = "text"): void => {
19
+ for (const part of displayLines(text)) {
20
+ rows.push(
21
+ ...wrapTextWithAnsi(part, Math.max(1, width)).map((row) => theme.fg(color, row)),
22
+ );
23
+ }
24
+ };
25
+
26
+ section("Run");
27
+ line(`${run.name} (${run.id}) · ${run.state}${run.readOnly ? " · read-only" : ""}`);
28
+ line(`File: ${run.file}`, "muted");
29
+
30
+ if (run.readOnly) {
31
+ line(`Inherited from session ${run.parentSessionId} through /fork or /clone.`, "muted");
32
+ }
33
+
34
+ if (run.loadError) {
35
+ line(`The run file could not be read: ${run.loadError}`, "error");
36
+
37
+ return rows;
38
+ }
39
+
40
+ const snapshot = run.snapshot;
41
+
42
+ if (snapshot) {
43
+ line(`Created: ${snapshot.createdAt}`, "muted");
44
+
45
+ if (snapshot.definition) {
46
+ line(`Definition: ${snapshot.definition.file}`, "muted");
47
+ }
48
+
49
+ section("Start values");
50
+ startValueLines(run).forEach((text) => line(text));
51
+
52
+ section("Workspace");
53
+ workspaceLines(run).forEach((text) => line(text));
54
+ }
55
+
56
+ section("Usage");
57
+ line(`Turns: ${run.turns}`);
58
+ line(
59
+ `Input ${formatTokens(run.usage.input)} · output ${formatTokens(run.usage.output)} · ` +
60
+ `cache read ${formatTokens(run.usage.cacheRead)} · cache write ` +
61
+ `${formatTokens(run.usage.cacheWrite)}`,
62
+ );
63
+ line(`Total ${formatTokens(run.usage.total)} tokens · $${run.usage.cost.toFixed(3)}`);
64
+ line("Not included in the main session's totals.", "muted");
65
+
66
+ const turn = run.lastTurn;
67
+
68
+ if (turn) {
69
+ section("Last turn");
70
+
71
+ const duration = Date.parse(turn.endedAt) - Date.parse(turn.startedAt);
72
+
73
+ line(
74
+ `${turn.state} · ${turn.report?.status ?? "unreported"}` +
75
+ (Number.isFinite(duration) ? ` · ${formatDuration(duration)}` : ""),
76
+ );
77
+
78
+ if (turn.stoppedBy) {
79
+ line(`Stopped by: ${turn.stoppedBy}`, "muted");
80
+ }
81
+
82
+ if (turn.error) {
83
+ line(`Error: ${turn.error}`, "error");
84
+ }
85
+ }
86
+
87
+ if (run.diagnostics.length > 0) {
88
+ section("Diagnostics");
89
+
90
+ for (const diagnostic of run.diagnostics) {
91
+ line(
92
+ `${new Date(diagnostic.at).toLocaleTimeString()} ${diagnostic.message}`,
93
+ diagnostic.level === "error"
94
+ ? "error"
95
+ : diagnostic.level === "warning"
96
+ ? "warning"
97
+ : "muted",
98
+ );
99
+ }
100
+ }
101
+
102
+ if (snapshot) {
103
+ section("Task");
104
+ line(snapshot.task);
105
+
106
+ if (snapshot.definition?.body) {
107
+ section("Definition body");
108
+ line(snapshot.definition.body, "muted");
109
+ }
110
+ }
111
+
112
+ return rows;
113
+ }