@loka1/pi-orchestra 0.0.0-stage → 0.5.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.
@@ -0,0 +1,365 @@
1
+ /**
2
+ * Cost and turn accounting for a run: a per-worker table, a chronological
3
+ * timeline with cumulative spend, and an exportable JSONL form.
4
+ *
5
+ * Everything here is derived from `state.json`; no log parsing is involved, so
6
+ * the numbers match what `worker_show` and the widget already report.
7
+ */
8
+
9
+ import { listDispatches, listTasks } from "./state.ts";
10
+ import type { Dispatch, OrchestraState, Run } from "./types.ts";
11
+
12
+ export interface DispatchMetrics {
13
+ id: string;
14
+ agent: string;
15
+ title: string;
16
+ status: string;
17
+ turns: number;
18
+ toolCalls: number;
19
+ input: number;
20
+ output: number;
21
+ cost: number;
22
+ startedAt: string;
23
+ endedAt?: string;
24
+ durationMs?: number;
25
+ }
26
+
27
+ export interface TimelinePoint {
28
+ at: string;
29
+ kind: "start" | "end";
30
+ dispatchId: string;
31
+ label: string;
32
+ /** Cost of this step (the dispatch's total at its end, 0 at its start). */
33
+ cost: number;
34
+ cumCost: number;
35
+ cumTurns: number;
36
+ }
37
+
38
+ export interface MetricsDelta {
39
+ runId: string;
40
+ name: string;
41
+ createdAt: string;
42
+ cost: number;
43
+ turns: number;
44
+ toolCalls: number;
45
+ wallMs: number;
46
+ }
47
+
48
+ export interface RunMetrics {
49
+ runId: string;
50
+ name: string;
51
+ status: string;
52
+ budgetUsd?: number;
53
+ tasks: number;
54
+ done: number;
55
+ failed: number;
56
+ totals: {
57
+ turns: number;
58
+ toolCalls: number;
59
+ input: number;
60
+ output: number;
61
+ cost: number;
62
+ dispatches: number;
63
+ wallMs: number;
64
+ };
65
+ dispatches: DispatchMetrics[];
66
+ timeline: TimelinePoint[];
67
+ /** The previous run with the same template (or name), when there is one. */
68
+ previous?: MetricsDelta;
69
+ }
70
+
71
+ const SPARK = "▁▂▃▄▅▆▇█";
72
+
73
+ export function sparkline(values: number[], width = 24): string {
74
+ if (values.length === 0) return "";
75
+ const max = Math.max(...values, 0);
76
+ const min = Math.min(...values, 0);
77
+ const span = max - min;
78
+ // Collapse to `width` buckets, keeping the last value exact.
79
+ const step = Math.max(1, Math.ceil(values.length / width));
80
+ const buckets: number[] = [];
81
+ for (let index = 0; index < values.length; index += step) {
82
+ const slice = values.slice(index, index + step);
83
+ buckets.push(slice[slice.length - 1] as number);
84
+ }
85
+ if (buckets[buckets.length - 1] !== (values[values.length - 1] as number)) {
86
+ buckets[buckets.length - 1] = values[values.length - 1] as number;
87
+ }
88
+ return buckets
89
+ .map((value) => {
90
+ if (span <= 0) return SPARK[0];
91
+ const ratio = (value - min) / span;
92
+ const position = Math.min(SPARK.length - 1, Math.max(0, Math.round(ratio * (SPARK.length - 1))));
93
+ return SPARK[position];
94
+ })
95
+ .join("");
96
+ }
97
+
98
+ function durationMs(startedAt: string, endedAt?: string): number | undefined {
99
+ const start = Date.parse(startedAt);
100
+ const end = endedAt ? Date.parse(endedAt) : undefined;
101
+ if (Number.isNaN(start) || (end !== undefined && Number.isNaN(end))) return undefined;
102
+ return (end ?? start) - start;
103
+ }
104
+
105
+ /** All numbers a run produced, plus the order in which they arrived. */
106
+ export function runMetrics(
107
+ state: OrchestraState,
108
+ runId: string,
109
+ options: { withPrevious?: boolean } = {},
110
+ ): RunMetrics {
111
+ const run: Run | undefined = state.runs[runId];
112
+ const tasks = listTasks(state, runId);
113
+ const dispatches = listDispatches(state, runId);
114
+
115
+ const rows: DispatchMetrics[] = dispatches.map((dispatch: Dispatch) => {
116
+ const task = dispatch.taskId ? state.tasks[dispatch.taskId] : undefined;
117
+ return {
118
+ id: dispatch.id,
119
+ agent: dispatch.agent,
120
+ title: task?.title ?? dispatch.spec.split("\n")[0]?.slice(0, 80) ?? "(free-form)",
121
+ status: dispatch.status,
122
+ turns: dispatch.usage.turns,
123
+ toolCalls: dispatch.usage.toolCalls,
124
+ input: dispatch.usage.input,
125
+ output: dispatch.usage.output,
126
+ cost: dispatch.usage.cost,
127
+ startedAt: dispatch.startedAt,
128
+ endedAt: dispatch.endedAt,
129
+ durationMs: durationMs(dispatch.startedAt, dispatch.endedAt),
130
+ };
131
+ });
132
+ rows.sort((a, b) => a.startedAt.localeCompare(b.startedAt) || a.id.localeCompare(b.id));
133
+
134
+ const events: Omit<TimelinePoint, "cumCost" | "cumTurns">[] = [];
135
+ for (const row of rows) {
136
+ events.push({
137
+ at: row.startedAt,
138
+ kind: "start",
139
+ dispatchId: row.id,
140
+ label: `${row.agent} started`,
141
+ cost: 0,
142
+ });
143
+ if (row.endedAt) {
144
+ events.push({
145
+ at: row.endedAt,
146
+ kind: "end",
147
+ dispatchId: row.id,
148
+ label: `${row.agent} ${row.status} · ${row.turns} turns · ${formatUsd(row.cost)}`,
149
+ cost: row.cost,
150
+ });
151
+ }
152
+ }
153
+ events.sort((a, b) => a.at.localeCompare(b.at) || (a.kind === b.kind ? 0 : a.kind === "start" ? -1 : 1));
154
+
155
+ const byId = new Map(rows.map((row) => [row.id, row]));
156
+ let cumCost = 0;
157
+ let cumTurns = 0;
158
+ const timeline: TimelinePoint[] = events.map((event) => {
159
+ if (event.kind === "end") {
160
+ const row = byId.get(event.dispatchId);
161
+ cumCost += row?.cost ?? 0;
162
+ cumTurns += row?.turns ?? 0;
163
+ }
164
+ return { ...event, cumCost, cumTurns };
165
+ });
166
+
167
+ const starts = rows.map((row) => Date.parse(row.startedAt)).filter((value) => !Number.isNaN(value));
168
+ const ends = rows.map((row) => Date.parse(row.endedAt ?? row.startedAt)).filter((value) => !Number.isNaN(value));
169
+
170
+ const previous = options.withPrevious === false ? undefined : previousRun(state, runId);
171
+
172
+ return {
173
+ runId,
174
+ name: run?.name ?? runId,
175
+ status: run?.status ?? "unknown",
176
+ budgetUsd: run?.budgetUsd,
177
+ tasks: tasks.length,
178
+ done: tasks.filter((task) => task.status === "done").length,
179
+ failed: tasks.filter((task) => task.status === "failed").length,
180
+ totals: {
181
+ turns: rows.reduce((sum, row) => sum + row.turns, 0),
182
+ toolCalls: rows.reduce((sum, row) => sum + row.toolCalls, 0),
183
+ input: rows.reduce((sum, row) => sum + row.input, 0),
184
+ output: rows.reduce((sum, row) => sum + row.output, 0),
185
+ cost: rows.reduce((sum, row) => sum + row.cost, 0),
186
+ dispatches: rows.length,
187
+ wallMs: starts.length && ends.length ? Math.max(0, Math.max(...ends) - Math.min(...starts)) : 0,
188
+ },
189
+ dispatches: rows,
190
+ timeline,
191
+ previous,
192
+ };
193
+ }
194
+
195
+ /** Same template when known, otherwise the same run name; older than `runId`. */
196
+ function previousRun(state: OrchestraState, runId: string): MetricsDelta | undefined {
197
+ const run = state.runs[runId];
198
+ if (!run) return undefined;
199
+ const candidates = Object.values(state.runs)
200
+ .filter((other) => other.id !== runId && other.createdAt < run.createdAt)
201
+ .filter((other) => (run.template ? other.template === run.template : other.name === run.name))
202
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt));
203
+ const older = candidates[0];
204
+ if (!older) return undefined;
205
+ const other = runMetrics(state, older.id, { withPrevious: false });
206
+ return {
207
+ runId: older.id,
208
+ name: older.name,
209
+ createdAt: older.createdAt,
210
+ cost: other.totals.cost,
211
+ turns: other.totals.turns,
212
+ toolCalls: other.totals.toolCalls,
213
+ wallMs: other.totals.wallMs,
214
+ };
215
+ }
216
+
217
+ function signed(value: number, format: (input: number) => string): string {
218
+ if (value === 0) return "±0";
219
+ return `${value > 0 ? "+" : "−"}${format(Math.abs(value))}`;
220
+ }
221
+
222
+ /** One line comparing the run with its predecessor. */
223
+ export function regressionLine(metrics: RunMetrics): string | undefined {
224
+ const previous = metrics.previous;
225
+ if (!previous) return undefined;
226
+ const cost = metrics.totals.cost - previous.cost;
227
+ const turns = metrics.totals.turns - previous.turns;
228
+ const tools = metrics.totals.toolCalls - previous.toolCalls;
229
+ const wall = metrics.totals.wallMs - previous.wallMs;
230
+ return `vs previous ${previous.name} (${new Date(previous.createdAt).toISOString().slice(0, 10)}): ${signed(cost, formatUsd)} cost · ${signed(turns, (input) => `${Math.round(input)}`)} turns · ${signed(tools, (input) => `${Math.round(input)}`)} tools · ${signed(wall, formatDuration)} wall`;
231
+ }
232
+
233
+ export function formatUsd(value: number): string {
234
+ if (value === 0) return "$0";
235
+ if (value < 0.01) return `$${value.toFixed(4)}`;
236
+ if (value < 1) return `$${value.toFixed(3)}`;
237
+ return `$${value.toFixed(2)}`;
238
+ }
239
+
240
+ export function formatDuration(ms: number | undefined): string {
241
+ if (ms === undefined || Number.isNaN(ms)) return "—";
242
+ const seconds = Math.round(ms / 1000);
243
+ if (seconds < 60) return `${seconds}s`;
244
+ const minutes = Math.floor(seconds / 60);
245
+ if (minutes < 60) return `${minutes}m${String(seconds % 60).padStart(2, "0")}s`;
246
+ return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, "0")}m`;
247
+ }
248
+
249
+ /** Text form used by `action=metrics` and the run detail pane. */
250
+ export function metricsTable(metrics: RunMetrics): string {
251
+ const lines: string[] = [];
252
+ const budget = metrics.budgetUsd ? ` of ${formatUsd(metrics.budgetUsd)}` : "";
253
+ lines.push(
254
+ `${metrics.name} — ${metrics.status} · ${metrics.tasks} tasks (${metrics.done} done${metrics.failed ? `, ${metrics.failed} failed` : ""})`,
255
+ `total: ${formatUsd(metrics.totals.cost)}${budget} · ${metrics.totals.turns} turns · ${metrics.totals.toolCalls} tools · ↑${metrics.totals.input} ↓${metrics.totals.output} tokens · wall ${formatDuration(metrics.totals.wallMs)}`,
256
+ );
257
+ if (metrics.totals.cost > 0) lines.push(`spend: ${sparkline(metrics.timeline.map((point) => point.cumCost))}`);
258
+ const regression = regressionLine(metrics);
259
+ if (regression) lines.push(regression);
260
+ if (metrics.dispatches.length === 0) {
261
+ lines.push("", "No workers yet.");
262
+ return lines.join("\n");
263
+ }
264
+ lines.push("", " dispatch agent status turns tools cost time");
265
+ const width = Math.max(...metrics.dispatches.map((row) => row.agent.length), 10);
266
+ for (const row of metrics.dispatches) {
267
+ lines.push(
268
+ ` ${row.id.slice(-12).padEnd(12)} ${row.agent.padEnd(width)} ${row.status.padEnd(9)} ${String(row.turns).padEnd(5)} ${String(row.toolCalls).padEnd(5)} ${formatUsd(row.cost).padEnd(8)} ${formatDuration(row.durationMs)}`,
269
+ );
270
+ }
271
+ return lines.join("\n");
272
+ }
273
+
274
+ export interface ReportInput {
275
+ /** Extra sections supplied by the caller (diff stats, unresolved questions). */
276
+ notes?: string[];
277
+ /** Diff summary lines per dispatch, keyed by dispatch id. */
278
+ changes?: Record<string, string>;
279
+ }
280
+
281
+ /** Markdown report for a run: goal, task outcome, evidence, cost, changes. */
282
+ export function runReport(state: OrchestraState, metrics: RunMetrics, input: ReportInput = {}): string {
283
+ const lines: string[] = [];
284
+ const run = state.runs[metrics.runId];
285
+ lines.push(`# ${metrics.name} — run report`);
286
+ lines.push("");
287
+ if (run?.goal) lines.push(`**Goal:** ${run.goal}`, "");
288
+ lines.push(
289
+ `**Status:** ${metrics.status} · **Tasks:** ${metrics.tasks} (${metrics.done} done, ${metrics.failed} failed) · **Cost:** ${formatUsd(metrics.totals.cost)}${metrics.budgetUsd ? ` of ${formatUsd(metrics.budgetUsd)}` : ""} · **Turns:** ${metrics.totals.turns} · **Wall:** ${formatDuration(metrics.totals.wallMs)}`,
290
+ );
291
+ const regression = regressionLine(metrics);
292
+ if (regression) lines.push("", `_${regression}_`);
293
+
294
+ const tasks = listTasks(state, metrics.runId);
295
+ lines.push("", "## Tasks", "", "| Task | Status | Agent | Dispatch | Turns | Cost |", "| --- | --- | --- | --- | --- | --- |");
296
+ for (const task of tasks) {
297
+ const dispatch = task.dispatchId ? state.dispatches[task.dispatchId] : undefined;
298
+ lines.push(
299
+ `| ${task.title.replace(/\|/g, "\\|")} | ${task.status} | ${dispatch?.agent ?? task.agent ?? "—"} | ${
300
+ dispatch ? `\`${dispatch.id.slice(-12)}\`` : "—"
301
+ } | ${dispatch?.usage.turns ?? 0} | ${formatUsd(dispatch?.usage.cost ?? 0)} |`,
302
+ );
303
+ }
304
+
305
+ const reported = metrics.dispatches.filter((row) => {
306
+ const dispatch = state.dispatches[row.id];
307
+ return Boolean(dispatch?.summary?.trim());
308
+ });
309
+ if (reported.length > 0) {
310
+ lines.push("", "## Outcome", "");
311
+ for (const row of reported) {
312
+ const dispatch = state.dispatches[row.id];
313
+ const task = dispatch?.taskId ? state.tasks[dispatch.taskId] : undefined;
314
+ const summary = (dispatch?.summary ?? "").trim();
315
+ const clipped = summary.length > 2000 ? `${summary.slice(0, 2000)}\n…[truncated]` : summary;
316
+ lines.push(`### ${task?.title ?? row.title}`, "", `\`${row.id.slice(-12)}\` · ${row.agent} · ${row.status} · ${formatUsd(row.cost)}`, "", clipped, "");
317
+ }
318
+ }
319
+
320
+ const failures = metrics.dispatches.filter((row) => row.status === "failed" || row.status === "timeout");
321
+ if (failures.length > 0) {
322
+ lines.push("## Failures", "");
323
+ for (const row of failures) {
324
+ lines.push(`- \`${row.id.slice(-12)}\` ${row.agent} (${row.status}): ${state.dispatches[row.id]?.error ?? "no error recorded"}`);
325
+ }
326
+ lines.push("");
327
+ }
328
+
329
+ const changes = Object.entries(input.changes ?? {});
330
+ if (changes.length > 0) {
331
+ lines.push("## Changes", "");
332
+ for (const [dispatchId, stat] of changes) {
333
+ lines.push(`\`${dispatchId.slice(-12)}\``, "", "```", stat.trim() || "(no changes)", "```", "");
334
+ }
335
+ }
336
+
337
+ if (input.notes && input.notes.length > 0) {
338
+ lines.push("## Notes", "");
339
+ for (const note of input.notes) lines.push(`- ${note}`);
340
+ lines.push("");
341
+ }
342
+
343
+ lines.push("---", `Generated by pi-orchestra · ${new Date().toISOString()}`);
344
+ return `${lines.join("\n").replace(/\n{3,}/g, "\n\n")}\n`;
345
+ }
346
+
347
+ /** One JSON object per line: a header, a row per worker, then the timeline. */
348
+ export function metricsJsonl(metrics: RunMetrics): string {
349
+ const lines = [
350
+ JSON.stringify({
351
+ type: "run",
352
+ runId: metrics.runId,
353
+ name: metrics.name,
354
+ status: metrics.status,
355
+ budgetUsd: metrics.budgetUsd ?? null,
356
+ tasks: metrics.tasks,
357
+ done: metrics.done,
358
+ failed: metrics.failed,
359
+ ...metrics.totals,
360
+ }),
361
+ ...metrics.dispatches.map((row) => JSON.stringify({ type: "worker", ...row })),
362
+ ...metrics.timeline.map((point) => JSON.stringify({ type: "point", ...point })),
363
+ ];
364
+ return `${lines.join("\n")}\n`;
365
+ }