offgrid-ai 0.8.15 → 0.9.2

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,237 @@
1
+ // ── Benchmark command flows ───────────────────────────────────────────────────
2
+
3
+ import { join } from "node:path";
4
+ import { ensureDirs } from "../config.mjs";
5
+ import { backendFor } from "../backends.mjs";
6
+ import { hasPi, hasPiModel, syncPiConfig } from "../harness-pi.mjs";
7
+ import { serverReady, startServer, waitForReady, stopProfile } from "../process.mjs";
8
+ import { loadProfiles } from "../profiles.mjs";
9
+ import { pc, createPrompt } from "../ui.mjs";
10
+ import { linkBenchmarkRepo } from "./repo.mjs";
11
+ import { loadBenchmarks } from "./shared.mjs";
12
+ import { prepareBenchmarkRun } from "./prepare.mjs";
13
+ import { runBenchmarkInPi } from "./pi-runner.mjs";
14
+ import { queryServerMetrics } from "./metrics.mjs";
15
+ import { unloadModelFromServer } from "./finalize.mjs";
16
+ import { finalizeBenchmarkRun, renderBenchmarkSummary } from "./finalize.mjs";
17
+
18
+ function benchmarkModelSource(profile) {
19
+ if (!profile) return "cloud";
20
+ return profile.providerId === "llama-cpp-mtp" ? "llama-cpp-mtp" : profile.backend === "ollama" ? "ollama" : profile.backend === "omlx" ? "omlx" : "llama-cpp";
21
+ }
22
+
23
+ async function chooseBenchmarkAction(prompt, canRun) {
24
+ const choices = [
25
+ { value: "run", label: "Run Benchmark", hint: "Automated with Pi" },
26
+ { value: "prepare", label: "Prepare Benchmark (manual)", hint: "Copy prompt and run yourself" },
27
+ ];
28
+ return await prompt.choice("Action", canRun ? choices : choices.filter((c) => c.value === "prepare"), canRun ? "run" : "prepare");
29
+ }
30
+
31
+ async function ensureServerForBenchmark(profile) {
32
+ const backend = backendFor(profile.backend);
33
+ if (await serverReady(profile.baseUrl)) {
34
+ console.log(pc.green(`[ready] ${backend.label} at ${profile.baseUrl}`));
35
+ return { started: false };
36
+ }
37
+
38
+ if (backend.type === "managed-server") {
39
+ throw new Error(`${backend.label} is not running at ${profile.baseUrl}. Start it and try again.`);
40
+ }
41
+
42
+ console.log(pc.dim(`Starting ${backend.label} for ${profile.label}...`));
43
+ const state = await startServer(profile);
44
+ await waitForReady(profile, state?.pid, state?.rawLogPath);
45
+ console.log(pc.green(`[ready] ${profile.baseUrl}/models`));
46
+ return { started: true, state };
47
+ }
48
+
49
+ export async function runPreparedBenchmark(profile, runDirectory, options = {}) {
50
+ const controller = new AbortController();
51
+ if (options.signal) {
52
+ options.signal.addEventListener("abort", () => controller.abort(), { once: true });
53
+ }
54
+ let serverStarted = false;
55
+ let metadata = null;
56
+
57
+ const onSigint = () => {
58
+ controller.abort();
59
+ };
60
+ process.on("SIGINT", onSigint);
61
+
62
+ try {
63
+ if (!(await hasPi())) {
64
+ console.log(pc.yellow("\nPi is not installed. Run prepared for manual execution."));
65
+ return metadata;
66
+ }
67
+
68
+ const serverState = await ensureServerForBenchmark(profile);
69
+ serverStarted = serverState.started;
70
+
71
+ if (!(await hasPiModel(profile))) {
72
+ await syncPiConfig(profile);
73
+ }
74
+
75
+ const runResult = await runBenchmarkInPi(profile, runDirectory, { signal: controller.signal });
76
+
77
+ let speedMetrics = null;
78
+ if (!runResult.error) {
79
+ try {
80
+ speedMetrics = await queryServerMetrics(profile);
81
+ } catch (err) {
82
+ runResult.error = { message: `Speed metrics query failed: ${err.message}` };
83
+ }
84
+ }
85
+
86
+ metadata = await finalizeBenchmarkRun(runDirectory, runResult, speedMetrics);
87
+ renderBenchmarkSummary(metadata);
88
+ } catch (err) {
89
+ const failedResult = {
90
+ error: { message: err.message },
91
+ wallClockMs: null,
92
+ agentTurns: 0,
93
+ promptTokens: 0,
94
+ completionTokens: 0,
95
+ totalTokens: 0,
96
+ cacheRead: 0,
97
+ cacheWrite: 0,
98
+ toolCalls: 0,
99
+ toolResults: 0,
100
+ perTurn: [],
101
+ };
102
+ metadata = await finalizeBenchmarkRun(runDirectory, failedResult, null);
103
+ renderBenchmarkSummary(metadata);
104
+ } finally {
105
+ process.removeListener("SIGINT", onSigint);
106
+ if (serverStarted && !options.keepServer) {
107
+ const backend = backendFor(profile.backend);
108
+ if (backend.type !== "managed-server") {
109
+ const result = await stopProfile(profile);
110
+ console.log(result.stopped ? pc.green(`[stop] ${result.message}`) : pc.dim(`[stop] ${result.message}`));
111
+ }
112
+ }
113
+ const unloadResult = await unloadModelFromServer(profile);
114
+ if (!unloadResult.unloaded && unloadResult.error) {
115
+ console.log(pc.yellow(`[unload] ${unloadResult.backend}: ${unloadResult.error}`));
116
+ } else if (!unloadResult.unloaded && unloadResult.reason) {
117
+ console.log(pc.dim(`[unload] ${unloadResult.backend}: ${unloadResult.reason}`));
118
+ }
119
+ }
120
+
121
+ return metadata;
122
+ }
123
+
124
+ // ── Benchmark from a selected profile (from model picker) ────────────────
125
+
126
+ export async function benchmarkForProfile(profile) {
127
+ await ensureDirs();
128
+ const prompt = createPrompt();
129
+ try {
130
+ const repoPath = await linkBenchmarkRepo(prompt);
131
+ if (!repoPath) return;
132
+
133
+ const kind = await prompt.choice("Benchmark category", [
134
+ { value: "visual", label: "Visual Benchmark", hint: "HTML/CSS/JS animation benchmarks" },
135
+ { value: "data-science", label: "Data Science", hint: "Analysis and charting benchmarks" },
136
+ ], "visual");
137
+
138
+ const benchDir = join(repoPath, "benchmarks");
139
+ const benchmarks = (await loadBenchmarks(benchDir)).filter((b) => b.kind === kind);
140
+ if (benchmarks.length === 0) {
141
+ console.log(pc.yellow(`No ${kind} benchmarks found in ${benchDir}`));
142
+ return;
143
+ }
144
+ const benchmarkId = await prompt.choice("Prompt", benchmarks.map((b) => ({
145
+ value: b.id, label: b.title, hint: b.description || b.id,
146
+ })), benchmarks[0].id);
147
+ const selectedBenchmark = benchmarks.find((b) => b.id === benchmarkId);
148
+ if (!selectedBenchmark) return;
149
+
150
+ const modelId = profile.modelAlias;
151
+ const modelSource = benchmarkModelSource(profile);
152
+ const backendLabel = backendFor(profile.backend).label;
153
+
154
+ const canRun = (await hasPi()) && modelSource !== "cloud";
155
+ const action = await chooseBenchmarkAction(prompt, canRun);
156
+
157
+ const runDirectory = await prepareBenchmarkRun({ repoPath, benchmark: selectedBenchmark, kind, modelId, modelSource, backendLabel, profile, showNextSteps: action === "prepare" });
158
+
159
+ if (action === "run") {
160
+ return await runPreparedBenchmark(profile, runDirectory);
161
+ }
162
+
163
+ return runDirectory;
164
+ } finally {
165
+ prompt.close();
166
+ }
167
+ }
168
+
169
+ // ── Standalone benchmark flow (offgrid-ai benchmark) ──────────────────────
170
+
171
+ export async function benchmarkFlow() {
172
+ await ensureDirs();
173
+
174
+ const prompt = createPrompt();
175
+ try {
176
+ const repoPath = await linkBenchmarkRepo(prompt);
177
+ if (!repoPath) return;
178
+
179
+ const kind = await prompt.choice("Benchmark category", [
180
+ { value: "visual", label: "Visual Benchmark", hint: "HTML/CSS/JS animation benchmarks" },
181
+ { value: "data-science", label: "Data Science", hint: "Analysis and charting benchmarks" },
182
+ ], "visual");
183
+
184
+ const benchDir = join(repoPath, "benchmarks");
185
+ const benchmarks = (await loadBenchmarks(benchDir)).filter((b) => b.kind === kind);
186
+ if (benchmarks.length === 0) {
187
+ console.log(pc.yellow(`No ${kind} benchmarks found in ${benchDir}`));
188
+ return;
189
+ }
190
+ const benchmarkId = await prompt.choice("Prompt", benchmarks.map((b) => ({
191
+ value: b.id, label: b.title, hint: b.description || b.id,
192
+ })), benchmarks[0].id);
193
+ const selectedBenchmark = benchmarks.find((b) => b.id === benchmarkId);
194
+ if (!selectedBenchmark) return;
195
+
196
+ const profiles = await loadProfiles();
197
+ const source = await prompt.choice("Model source", [
198
+ { value: "profile", label: "Use existing profile", hint: "Pick a saved offgrid-ai profile" },
199
+ { value: "cloud", label: "Custom / cloud", hint: "Free-form model label for cloud runs" },
200
+ ], "profile");
201
+
202
+ let modelId, modelSource, backendLabel, profile;
203
+
204
+ if (source === "profile") {
205
+ if (profiles.length === 0) {
206
+ console.log(pc.yellow("No profiles yet. Run: offgrid-ai models"));
207
+ return;
208
+ }
209
+ const profileId = await prompt.choice("Profile", profiles.map((p) => ({
210
+ value: p.id, label: p.label, hint: `${backendFor(p.backend).label} · ${p.modelAlias}`,
211
+ })), profiles[0].id);
212
+ profile = profiles.find((p) => p.id === profileId);
213
+ if (!profile) return;
214
+ modelId = profile.modelAlias;
215
+ modelSource = benchmarkModelSource(profile);
216
+ backendLabel = backendFor(profile.backend).label;
217
+ } else {
218
+ backendLabel = await prompt.text("Backend label", "cloud");
219
+ modelId = await prompt.text("Model name", "");
220
+ if (!modelId) { console.log(pc.yellow("Model name is required.")); return; }
221
+ modelSource = "cloud";
222
+ }
223
+
224
+ const canRun = (await hasPi()) && modelSource !== "cloud" && profile != null;
225
+ const action = await chooseBenchmarkAction(prompt, canRun);
226
+
227
+ const runDirectory = await prepareBenchmarkRun({ repoPath, benchmark: selectedBenchmark, kind, modelId, modelSource, backendLabel, profile, showNextSteps: action === "prepare" });
228
+
229
+ if (action === "run" && profile) {
230
+ return await runPreparedBenchmark(profile, runDirectory);
231
+ }
232
+
233
+ return runDirectory;
234
+ } finally {
235
+ prompt.close();
236
+ }
237
+ }
@@ -0,0 +1,152 @@
1
+ // ── Backend-aware server speed metrics ───────────────────────────────────────
2
+
3
+ import { backendFor } from "../backends.mjs";
4
+ import { apiRootUrl } from "../process.mjs";
5
+
6
+ const BENCH_SPEED_PROMPT = "Write a one-sentence summary of machine learning.";
7
+
8
+ export async function queryServerMetrics(profile) {
9
+ const backend = backendFor(profile.backend);
10
+
11
+ if (backend.id === "llama-cpp" || backend.id === "llama-cpp-mtp") {
12
+ return await queryLlamaCppMetrics(profile);
13
+ }
14
+ if (backend.id === "omlx") {
15
+ return await queryOmlxMetrics(profile);
16
+ }
17
+ if (backend.id === "ollama") {
18
+ return await queryOllamaMetrics(profile);
19
+ }
20
+
21
+ throw new Error(`Unsupported backend for benchmark speed metrics: ${backend.id}`);
22
+ }
23
+
24
+ async function queryLlamaCppMetrics(profile) {
25
+ const body = {
26
+ model: profile.modelAlias,
27
+ messages: [{ role: "user", content: BENCH_SPEED_PROMPT }],
28
+ stream: false,
29
+ };
30
+
31
+ const response = await fetch(profile.baseUrl.replace(/\/$/u, "") + "/chat/completions", {
32
+ method: "POST",
33
+ headers: { "Content-Type": "application/json" },
34
+ body: JSON.stringify(body),
35
+ signal: AbortSignal.timeout(60000),
36
+ });
37
+
38
+ if (!response.ok) {
39
+ throw new Error(`llama.cpp speed query failed: ${response.status} ${response.statusText}`);
40
+ }
41
+
42
+ const data = await response.json();
43
+ const timings = data.timings;
44
+ if (!timings || typeof timings.prompt_per_second !== "number" || typeof timings.predicted_per_second !== "number") {
45
+ throw new Error("llama.cpp response did not include usable timings object");
46
+ }
47
+ const draftN = timings.draft_n;
48
+ const draftAccepted = timings.draft_n_accepted;
49
+
50
+ return {
51
+ prefillTokensPerSecond: timings.prompt_per_second ?? null,
52
+ generationTokensPerSecond: timings.predicted_per_second ?? null,
53
+ ttftMs: timings.prompt_ms ?? null,
54
+ modelLoadMs: null,
55
+ speculativeDecodeAcceptance: (draftN && Number.isFinite(draftAccepted) && Number.isFinite(draftN) && draftN > 0)
56
+ ? draftAccepted / draftN
57
+ : null,
58
+ kvCacheTokens: timings.cache_n ?? null,
59
+ metricSource: "llama.cpp /v1/chat/completions timings",
60
+ };
61
+ }
62
+
63
+ async function queryOmlxMetrics(profile) {
64
+ const body = {
65
+ model: profile.modelAlias,
66
+ messages: [{ role: "user", content: BENCH_SPEED_PROMPT }],
67
+ stream: true,
68
+ stream_options: { include_usage: true },
69
+ };
70
+
71
+ const response = await fetch(profile.baseUrl.replace(/\/$/u, "") + "/chat/completions", {
72
+ method: "POST",
73
+ headers: { "Content-Type": "application/json" },
74
+ body: JSON.stringify(body),
75
+ signal: AbortSignal.timeout(60000),
76
+ });
77
+
78
+ if (!response.ok) {
79
+ throw new Error(`oMLX speed query failed: ${response.status} ${response.statusText}`);
80
+ }
81
+
82
+ const text = await response.text();
83
+ let usage = null;
84
+ for (const line of text.split("\n").reverse()) {
85
+ const trimmed = line.trim();
86
+ if (!trimmed || !trimmed.startsWith("data:")) continue;
87
+ const payload = trimmed.slice(5).trim();
88
+ if (payload === "[DONE]") continue;
89
+ try {
90
+ const chunk = JSON.parse(payload);
91
+ if (chunk.usage) {
92
+ usage = chunk.usage;
93
+ break;
94
+ }
95
+ } catch {
96
+ // Ignore malformed SSE chunks.
97
+ }
98
+ }
99
+
100
+ if (!usage) {
101
+ throw new Error("oMLX speed query did not return usage in streaming response");
102
+ }
103
+
104
+ return {
105
+ prefillTokensPerSecond: usage.prompt_tokens_per_second ?? null,
106
+ generationTokensPerSecond: usage.generation_tokens_per_second ?? null,
107
+ ttftMs: usage.time_to_first_token != null ? usage.time_to_first_token * 1000 : null,
108
+ modelLoadMs: null,
109
+ speculativeDecodeAcceptance: null,
110
+ kvCacheTokens: usage.prompt_tokens_details?.cached_tokens ?? null,
111
+ metricSource: "oMLX /v1/chat/completions streaming include_usage",
112
+ };
113
+ }
114
+
115
+ async function queryOllamaMetrics(profile) {
116
+ const body = {
117
+ model: profile.modelAlias,
118
+ prompt: BENCH_SPEED_PROMPT,
119
+ stream: false,
120
+ };
121
+
122
+ const apiBaseUrl = apiRootUrl(profile.baseUrl || backendFor(profile.backend).apiBaseUrl || "");
123
+
124
+ const response = await fetch(`${apiBaseUrl}/api/generate`, {
125
+ method: "POST",
126
+ headers: { "Content-Type": "application/json" },
127
+ body: JSON.stringify(body),
128
+ signal: AbortSignal.timeout(60000),
129
+ });
130
+
131
+ if (!response.ok) {
132
+ throw new Error(`Ollama speed query failed: ${response.status} ${response.statusText}`);
133
+ }
134
+
135
+ const data = await response.json();
136
+ const promptEvalNs = data.prompt_eval_duration ?? 0;
137
+ const evalNs = data.eval_duration ?? 0;
138
+ const loadNs = data.load_duration ?? 0;
139
+
140
+ const promptEvalCount = data.prompt_eval_count ?? 0;
141
+ const evalCount = data.eval_count ?? 0;
142
+
143
+ return {
144
+ prefillTokensPerSecond: promptEvalNs > 0 ? (promptEvalCount / (promptEvalNs / 1e9)) : null,
145
+ generationTokensPerSecond: evalNs > 0 ? (evalCount / (evalNs / 1e9)) : null,
146
+ ttftMs: promptEvalNs / 1e6,
147
+ modelLoadMs: loadNs / 1e6,
148
+ speculativeDecodeAcceptance: null,
149
+ kvCacheTokens: null,
150
+ metricSource: "Ollama /api/generate",
151
+ };
152
+ }
@@ -0,0 +1,252 @@
1
+ // ── Run benchmark in Pi (non-interactive JSON mode) ───────────────────────────
2
+
3
+ import { writeFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { spawn } from "node:child_process";
6
+ import {
7
+ BENCH_COLORS, renderStreamEvent,
8
+ formatToolCall,
9
+ } from "./stream-renderer.mjs";
10
+ import { piModelString } from "./shared.mjs";
11
+
12
+ export async function runBenchmarkInPi(profile, runDirectory, { signal } = {}) {
13
+ const model = piModelString(profile);
14
+ const args = ["--model", model, "--mode", "json", "-p", "@prompt.md"];
15
+
16
+ const child = spawn("pi", args, {
17
+ cwd: runDirectory,
18
+ stdio: ["ignore", "pipe", "pipe"],
19
+ });
20
+
21
+ const runResult = {
22
+ model,
23
+ exitCode: null,
24
+ wallClockMs: null,
25
+ agentTurns: 0,
26
+ promptTokens: 0,
27
+ completionTokens: 0,
28
+ totalTokens: 0,
29
+ cacheRead: 0,
30
+ cacheWrite: 0,
31
+ toolCalls: 0,
32
+ toolResults: 0,
33
+ perTurn: [],
34
+ rawResponseLines: [],
35
+ error: null,
36
+ };
37
+
38
+ let streamBuffer = "";
39
+ let responseBuffer = "";
40
+ let currentTurnStartMs = null;
41
+ let lastTurnEndMs = null;
42
+ let runStartMs = null;
43
+ let firstEventMs = null;
44
+ let lastEventMs = null;
45
+ let cancelled = false;
46
+
47
+ const streamPath = join(runDirectory, "stream.ndjson");
48
+ const stderrPath = join(runDirectory, "stderr.log");
49
+ const responsePath = join(runDirectory, "response.raw.txt");
50
+
51
+ const streamHandle = await openFileHandle(streamPath, "w");
52
+ const stderrHandle = await openFileHandle(stderrPath, "w");
53
+
54
+ const verbose = Boolean(process.env.OFFGRID_BENCHMARK_VERBOSE);
55
+ const renderState = {
56
+ cwd: runDirectory,
57
+ turn: 0,
58
+ turnHadToolError: false,
59
+ modelPrinted: false,
60
+ activeTool: null,
61
+ status: { mode: "idle", toolName: null, bytes: 0, tokens: 0 },
62
+ };
63
+
64
+ function appendResponse(text) {
65
+ responseBuffer += text;
66
+ }
67
+
68
+ function flushResponse() {
69
+ if (responseBuffer) {
70
+ runResult.rawResponseLines.push(responseBuffer);
71
+ responseBuffer = "";
72
+ }
73
+ }
74
+
75
+ function updateTimeBounds(timestamp) {
76
+ if (!timestamp) return;
77
+ if (firstEventMs === null) firstEventMs = timestamp;
78
+ lastEventMs = timestamp;
79
+ }
80
+
81
+ function beginTurn() {
82
+ runResult.agentTurns += 1;
83
+ currentTurnStartMs = lastTurnEndMs ?? runStartMs ?? null;
84
+ }
85
+
86
+ function endTurn(usage, timestamp) {
87
+ const turnEndMs = timestamp ?? null;
88
+ const wallClockMs = currentTurnStartMs && turnEndMs ? turnEndMs - currentTurnStartMs : null;
89
+ runResult.perTurn.push({
90
+ turn: runResult.agentTurns,
91
+ inputTokens: usage?.input ?? 0,
92
+ outputTokens: usage?.output ?? 0,
93
+ cacheRead: usage?.cacheRead ?? 0,
94
+ cacheWrite: usage?.cacheWrite ?? 0,
95
+ wallClockMs,
96
+ toolCalls: 0,
97
+ });
98
+ if (turnEndMs) lastTurnEndMs = turnEndMs;
99
+ currentTurnStartMs = null;
100
+ }
101
+
102
+ function processLine(line) {
103
+ if (!line.trim()) return;
104
+ streamHandle.write(line + "\n");
105
+ let parsed;
106
+ try {
107
+ parsed = JSON.parse(line);
108
+ } catch (err) {
109
+ console.log(BENCH_COLORS.error(`[parse error] ${err.message}`));
110
+ return;
111
+ }
112
+
113
+ const timestamp = extractTimestamp(parsed);
114
+ updateTimeBounds(timestamp);
115
+
116
+ renderStreamEvent(parsed, renderState, { verbose });
117
+
118
+ if (parsed.type === "session" || parsed.type === "agent_start") {
119
+ if (timestamp && runStartMs === null) runStartMs = timestamp;
120
+ }
121
+
122
+ if (parsed.type === "turn_start") {
123
+ beginTurn();
124
+ }
125
+
126
+ if (parsed.type === "turn_end" && parsed.message?.usage) {
127
+ const usage = parsed.message.usage;
128
+ runResult.promptTokens += usage.input ?? 0;
129
+ runResult.completionTokens += usage.output ?? 0;
130
+ runResult.cacheRead += usage.cacheRead ?? 0;
131
+ runResult.cacheWrite += usage.cacheWrite ?? 0;
132
+ endTurn(usage, timestamp);
133
+ }
134
+
135
+ if (parsed.type === "message_update" && parsed.assistantMessageEvent) {
136
+ const evt = parsed.assistantMessageEvent;
137
+ const subtype = String(evt.type ?? "").replace(/_/gu, "");
138
+ if (subtype === "thinkingdelta" || subtype === "textdelta") {
139
+ appendResponse(evt.delta || "");
140
+ }
141
+ }
142
+
143
+ if (parsed.type === "message_end" && parsed.message?.role === "assistant") {
144
+ flushResponse();
145
+ const content = parsed.message.content ?? [];
146
+ for (const item of content) {
147
+ if (item.type === "toolCall") {
148
+ runResult.toolCalls += 1;
149
+ appendResponse(`\n${formatToolCall(item)}\n`);
150
+ const currentTurn = runResult.perTurn[runResult.perTurn.length - 1];
151
+ if (currentTurn) currentTurn.toolCalls += 1;
152
+ }
153
+ }
154
+ }
155
+
156
+ if (parsed.type === "toolResult") {
157
+ runResult.toolResults += 1;
158
+ const status = parsed.isError ? "error" : "ok";
159
+ appendResponse(`\n[toolResult] ${parsed.toolName} (${status})\n`);
160
+ }
161
+
162
+ if (parsed.type === "agent_end") {
163
+ flushResponse();
164
+ }
165
+ }
166
+
167
+ child.stdout.setEncoding("utf8");
168
+ child.stdout.on("data", (chunk) => {
169
+ streamBuffer += chunk;
170
+ const lines = streamBuffer.split("\n");
171
+ streamBuffer = lines.pop();
172
+ for (const line of lines) {
173
+ processLine(line);
174
+ }
175
+ });
176
+
177
+ child.stderr.setEncoding("utf8");
178
+ child.stderr.on("data", (chunk) => {
179
+ stderrHandle.write(chunk);
180
+ });
181
+
182
+ const abortListener = () => {
183
+ if (cancelled) return;
184
+ cancelled = true;
185
+ console.log(BENCH_COLORS.error("\n\n[Cancelled by user]"));
186
+ child.kill("SIGTERM");
187
+ };
188
+
189
+ if (signal) {
190
+ signal.addEventListener("abort", abortListener);
191
+ }
192
+
193
+ return new Promise((resolve) => {
194
+ child.on("exit", async (code) => {
195
+ if (signal) signal.removeEventListener("abort", abortListener);
196
+ if (streamBuffer.trim()) {
197
+ processLine(streamBuffer);
198
+ }
199
+ flushResponse();
200
+ await streamHandle.close();
201
+ await stderrHandle.close();
202
+ await writeFile(responsePath, runResult.rawResponseLines.join(""), "utf8");
203
+
204
+ runResult.exitCode = code ?? 0;
205
+ if (firstEventMs !== null && lastEventMs !== null) {
206
+ runResult.wallClockMs = lastEventMs - firstEventMs;
207
+ }
208
+
209
+ if (cancelled) {
210
+ runResult.error = { message: "Cancelled by user" };
211
+ resolve(runResult);
212
+ return;
213
+ }
214
+
215
+ if (runResult.exitCode !== 0) {
216
+ runResult.error = { message: `Pi exited with code ${runResult.exitCode}` };
217
+ resolve(runResult);
218
+ return;
219
+ }
220
+
221
+ resolve(runResult);
222
+ });
223
+
224
+ child.on("error", async (err) => {
225
+ if (signal) signal.removeEventListener("abort", abortListener);
226
+ await streamHandle.close();
227
+ await stderrHandle.close();
228
+ runResult.error = { message: err.message };
229
+ resolve(runResult);
230
+ });
231
+ });
232
+ }
233
+
234
+ function extractTimestamp(event) {
235
+ const raw = event?.message?.timestamp ?? event?.timestamp ?? event?.assistantMessageEvent?.partial?.timestamp;
236
+ if (typeof raw === "number") return raw;
237
+ if (typeof raw === "string") {
238
+ const parsed = Date.parse(raw);
239
+ if (Number.isFinite(parsed)) return parsed;
240
+ }
241
+ const iso = event?.message?.createdAt ?? event?.createdAt ?? event?.created_at;
242
+ if (typeof iso === "string") {
243
+ const parsed = Date.parse(iso);
244
+ if (Number.isFinite(parsed)) return parsed;
245
+ }
246
+ return null;
247
+ }
248
+
249
+ async function openFileHandle(path, flags) {
250
+ const { open } = await import("node:fs/promises");
251
+ return open(path, flags);
252
+ }