@rejacky/opencode-insights 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.
package/dist/cli.js ADDED
@@ -0,0 +1,1360 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ resolveCapturePath
4
+ } from "./chunk-G7E4J6OW.js";
5
+
6
+ // src/cli.ts
7
+ import { execFile as execFile2 } from "child_process";
8
+ import { existsSync as existsSync2 } from "fs";
9
+ import { mkdir, readFile as readFile2, writeFile } from "fs/promises";
10
+ import { dirname, join } from "path";
11
+ import { homedir } from "os";
12
+ import { pathToFileURL } from "url";
13
+ import { promisify as promisify2 } from "util";
14
+
15
+ // src/inspect.ts
16
+ import { readFile } from "fs/promises";
17
+ import { existsSync } from "fs";
18
+ import { execFile } from "child_process";
19
+ import { promisify } from "util";
20
+ var execFileAsync = promisify(execFile);
21
+ function parseJsonlRecords(input) {
22
+ return input.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).map((line) => JSON.parse(line));
23
+ }
24
+ function formatCaptureSummary(records) {
25
+ if (records.length === 0) return "No capture records found.";
26
+ const rows = records.map((record) => {
27
+ const at = new Date(record.timestamp).toISOString();
28
+ const providerModel = [record.providerID, record.modelID].filter(Boolean).join("/");
29
+ return [
30
+ at,
31
+ record.kind.padEnd(20),
32
+ (record.sessionID ?? "-").padEnd(16),
33
+ (record.messageID ?? "-").padEnd(16),
34
+ providerModel || "-"
35
+ ].join(" ");
36
+ });
37
+ return [
38
+ ["timestamp".padEnd(24), "kind".padEnd(20), "session".padEnd(16), "message".padEnd(16), "provider/model"].join(" "),
39
+ ...rows
40
+ ].join("\n");
41
+ }
42
+ async function readRecentCaptures(options = {}) {
43
+ const dbPath = resolveCapturePath(options);
44
+ const sqliteRecords = await readSqliteCaptures(dbPath, options.limit ?? 20);
45
+ if (sqliteRecords) return sqliteRecords;
46
+ const jsonlPath = dbPath.endsWith(".sqlite") ? `${dbPath}.jsonl` : dbPath;
47
+ if (!existsSync(jsonlPath)) return [];
48
+ const records = parseJsonlRecords(await readFile(jsonlPath, "utf8"));
49
+ return records.slice(-Math.max(1, options.limit ?? 20)).reverse();
50
+ }
51
+ function buildRequestHistory(records) {
52
+ const sessions = /* @__PURE__ */ new Map();
53
+ const messages = /* @__PURE__ */ new Map();
54
+ const responses = /* @__PURE__ */ new Map();
55
+ const responseByParent = /* @__PURE__ */ new Map();
56
+ const requests = [];
57
+ const getSession = (sessionID) => {
58
+ const existing = sessions.get(sessionID);
59
+ if (existing) return existing;
60
+ const created = { id: sessionID, messages: [], requests: [] };
61
+ sessions.set(sessionID, created);
62
+ return created;
63
+ };
64
+ const getMessage = (sessionID, messageID, role = "unknown") => {
65
+ const key = `${sessionID}:${messageID}`;
66
+ const existing = messages.get(key);
67
+ if (existing) {
68
+ if (existing.role === "unknown" && role !== "unknown") existing.role = role;
69
+ return existing;
70
+ }
71
+ const created = { id: messageID, sessionID, role, text: "", requests: [] };
72
+ messages.set(key, created);
73
+ getSession(sessionID).messages.push(created);
74
+ return created;
75
+ };
76
+ const getResponse = (sessionID, messageID, role = "assistant") => {
77
+ const key = `${sessionID}:${messageID}`;
78
+ const existing = responses.get(key);
79
+ if (existing) {
80
+ if (existing.role === "unknown" && role !== "unknown") existing.role = role;
81
+ return existing;
82
+ }
83
+ const created = { id: messageID, sessionID, role, text: "", reasoning: "", events: [] };
84
+ responses.set(key, created);
85
+ return created;
86
+ };
87
+ for (const record of records.slice().sort((a, b) => a.timestamp - b.timestamp)) {
88
+ if (record.sessionID) getSession(record.sessionID);
89
+ if (record.kind === "chat.message") {
90
+ const message = historyMessageFromChatMessage(record);
91
+ if (message) {
92
+ const existing = getMessage(message.sessionID, message.id, message.role);
93
+ existing.createdAt = message.createdAt ?? existing.createdAt;
94
+ existing.text = message.text || existing.text;
95
+ }
96
+ }
97
+ if (record.kind === "chat.params" || record.kind === "experimental.chat.messages.transform" || record.kind === "experimental.chat.system.transform") {
98
+ const request = historyRequestFromCapture(record);
99
+ if (!request.messageID && request.sessionID) {
100
+ request.messageID = latestUserMessageBefore(messages, request.sessionID, request.timestamp)?.id;
101
+ }
102
+ requests.push(request);
103
+ if (request.sessionID) {
104
+ getSession(request.sessionID).requests.push(request);
105
+ if (request.messageID) getMessage(request.sessionID, request.messageID, "user").requests.push(request);
106
+ }
107
+ }
108
+ if (record.kind === "chat.headers") {
109
+ attachHeadersToRequest(requests, record);
110
+ }
111
+ if (record.kind !== "event") continue;
112
+ const event = record.payload.event;
113
+ if (!isRecord(event)) continue;
114
+ const type = optionalString(event.type);
115
+ const properties = isRecord(event.properties) ? event.properties : {};
116
+ if (type === "session.updated" || type === "session.created") {
117
+ const info = isRecord(properties.info) ? properties.info : {};
118
+ const sessionID = optionalString(info.id) ?? optionalString(properties.sessionID);
119
+ if (!sessionID) continue;
120
+ const session = getSession(sessionID);
121
+ session.title = optionalString(info.title) ?? session.title;
122
+ session.updatedAt = numberFromPath(info.time, "updated") ?? session.updatedAt;
123
+ continue;
124
+ }
125
+ if (type === "message.updated") {
126
+ const info = isRecord(properties.info) ? properties.info : {};
127
+ const sessionID = optionalString(info.sessionID) ?? optionalString(properties.sessionID);
128
+ const messageID = optionalString(info.id);
129
+ if (!sessionID || !messageID) continue;
130
+ const role = optionalString(info.role) ?? "unknown";
131
+ if (role === "assistant") {
132
+ const response = getResponse(sessionID, messageID, role);
133
+ response.createdAt = numberFromPath(info.time, "created") ?? response.createdAt;
134
+ response.completedAt = numberFromPath(info.time, "completed") ?? response.completedAt;
135
+ response.parentID = optionalString(info.parentID) ?? response.parentID;
136
+ response.tokens = info.tokens ?? response.tokens;
137
+ response.cost = typeof info.cost === "number" ? info.cost : response.cost;
138
+ response.finish = optionalString(info.finish) ?? response.finish;
139
+ response.events.push(record.payload);
140
+ if (response.parentID) responseByParent.set(`${sessionID}:${response.parentID}`, response);
141
+ continue;
142
+ }
143
+ const message = getMessage(sessionID, messageID, role);
144
+ message.createdAt = numberFromPath(info.time, "created") ?? message.createdAt;
145
+ message.completedAt = numberFromPath(info.time, "completed") ?? message.completedAt;
146
+ continue;
147
+ }
148
+ if (type === "message.part.updated" || type === "message.part.delta") {
149
+ const part = isRecord(properties.part) ? properties.part : {};
150
+ const sessionID = optionalString(part.sessionID) ?? optionalString(properties.sessionID);
151
+ const messageID = optionalString(part.messageID) ?? optionalString(properties.messageID);
152
+ if (!sessionID || !messageID) continue;
153
+ const partType = optionalString(part.type);
154
+ const field = optionalString(properties.field);
155
+ const delta = optionalString(properties.delta);
156
+ const text = optionalString(part.text);
157
+ const reasonText = optionalString(part.text) ?? optionalString(part.markdown);
158
+ const targetResponse = responses.get(`${sessionID}:${messageID}`);
159
+ if (targetResponse) {
160
+ targetResponse.events.push(record.payload);
161
+ if (partType === "text" && text !== void 0) targetResponse.text = text;
162
+ if (partType === "reasoning" && reasonText !== void 0) targetResponse.reasoning = reasonText;
163
+ if (type === "message.part.delta" && field === "text" && delta !== void 0) targetResponse.text += delta;
164
+ continue;
165
+ }
166
+ if (partType !== "text" && partType !== "reasoning") continue;
167
+ if (text === void 0) continue;
168
+ const message = getMessage(sessionID, messageID);
169
+ message.text = text;
170
+ }
171
+ }
172
+ for (const session of sessions.values()) {
173
+ for (const message of session.messages) {
174
+ message.response = responseByParent.get(`${message.sessionID}:${message.id}`);
175
+ for (const request of message.requests) {
176
+ if (requestShouldOwnAssistantResponse(request)) request.response = message.response;
177
+ }
178
+ }
179
+ session.messages.sort((a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0));
180
+ session.requests.sort((a, b) => a.timestamp - b.timestamp);
181
+ }
182
+ return {
183
+ sessions: [...sessions.values()].sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0)),
184
+ requests: requests.sort((a, b) => b.timestamp - a.timestamp)
185
+ };
186
+ }
187
+ async function readSqliteCaptures(path, limit) {
188
+ if (!existsSync(path)) return void 0;
189
+ try {
190
+ const mod = await import("bun:sqlite").catch(() => void 0);
191
+ if (!mod) return readSqliteCapturesWithCli(path, limit);
192
+ const db = new mod.Database(path, { readonly: true });
193
+ try {
194
+ const rows = db.query(recentCaptureSql(Math.max(1, limit))).all();
195
+ return dedupeRows(rows).map(rowToCapture);
196
+ } finally {
197
+ db.close();
198
+ }
199
+ } catch {
200
+ return readSqliteCapturesWithCli(path, limit);
201
+ }
202
+ }
203
+ async function readSqliteCapturesWithCli(path, limit) {
204
+ if (!existsSync(path)) return void 0;
205
+ try {
206
+ const { stdout } = await execFileAsync("sqlite3", ["-json", path, recentCaptureSql(Math.max(1, Math.trunc(limit)))], {
207
+ maxBuffer: 128 * 1024 * 1024
208
+ });
209
+ if (!stdout.trim()) return [];
210
+ return dedupeRows(JSON.parse(stdout)).map(rowToCapture);
211
+ } catch {
212
+ return void 0;
213
+ }
214
+ }
215
+ function recentCaptureSql(limit) {
216
+ return `select id, kind, timestamp, session_id, message_id, provider_id, model_id, payload_json
217
+ from captures
218
+ where id in (
219
+ select id from captures order by timestamp desc limit ${limit}
220
+ )
221
+ or id in (
222
+ select id from captures
223
+ where kind in (
224
+ 'chat.params',
225
+ 'chat.message',
226
+ 'experimental.chat.messages.transform',
227
+ 'experimental.chat.system.transform'
228
+ )
229
+ order by timestamp desc
230
+ limit ${limit}
231
+ )
232
+ or id in (
233
+ select id from captures
234
+ where kind = 'event'
235
+ and json_extract(payload_json, '$.event.type') in ('message.updated', 'message.part.updated', 'message.part.delta')
236
+ order by timestamp desc
237
+ limit ${limit}
238
+ )
239
+ order by timestamp desc`;
240
+ }
241
+ function dedupeRows(rows) {
242
+ const seen = /* @__PURE__ */ new Set();
243
+ return rows.filter((row) => {
244
+ if (seen.has(row.id)) return false;
245
+ seen.add(row.id);
246
+ return true;
247
+ });
248
+ }
249
+ function rowToCapture(row) {
250
+ return {
251
+ id: row.id,
252
+ kind: row.kind,
253
+ timestamp: row.timestamp,
254
+ sessionID: row.session_id ?? void 0,
255
+ messageID: row.message_id ?? void 0,
256
+ providerID: row.provider_id ?? void 0,
257
+ modelID: row.model_id ?? void 0,
258
+ payload: JSON.parse(row.payload_json)
259
+ };
260
+ }
261
+ function isRecord(value) {
262
+ return !!value && typeof value === "object" && !Array.isArray(value);
263
+ }
264
+ function optionalString(value) {
265
+ return typeof value === "string" && value.length > 0 ? value : void 0;
266
+ }
267
+ function historyRequestFromCapture(record) {
268
+ const input = isRecord(record.payload.input) ? record.payload.input : {};
269
+ const agent = agentFromCapture(record, input);
270
+ return {
271
+ id: record.id,
272
+ sessionID: record.sessionID,
273
+ messageID: messageIDForCapture(record, input),
274
+ timestamp: record.timestamp,
275
+ agent,
276
+ purpose: purposeFromAgent(agent),
277
+ providerID: record.providerID,
278
+ modelID: record.modelID,
279
+ summary: summarizePayload(record.payload),
280
+ payload: record.payload
281
+ };
282
+ }
283
+ function requestShouldOwnAssistantResponse(request) {
284
+ return request.agent !== "title";
285
+ }
286
+ function purposeFromAgent(agent) {
287
+ if (agent === "title") return "Generate or update the session title. This is not the assistant reply shown in the conversation.";
288
+ if (agent === "build") return "Generate the assistant response for the user message.";
289
+ if (agent === "messages.transform") return "Capture the final conversation messages OpenCode prepared before model execution.";
290
+ if (agent === "system.transform") return "Capture the system prompt strings OpenCode prepared before model execution.";
291
+ if (agent) return `Run the ${agent} agent for this message.`;
292
+ return "Run an OpenCode model request for this message.";
293
+ }
294
+ function agentFromCapture(record, input) {
295
+ if (record.kind === "experimental.chat.messages.transform") return "messages.transform";
296
+ if (record.kind === "experimental.chat.system.transform") return "system.transform";
297
+ return optionalString(input.agent);
298
+ }
299
+ function messageIDForCapture(record, input) {
300
+ if (record.kind === "experimental.chat.messages.transform") {
301
+ return latestUserMessageIDFromTransform(record.payload.output) ?? record.messageID;
302
+ }
303
+ return record.messageID ?? messageIDFromPayload(input.message);
304
+ }
305
+ function latestUserMessageIDFromTransform(output) {
306
+ if (!isRecord(output) || !Array.isArray(output.messages)) return void 0;
307
+ for (const message of output.messages.slice().reverse()) {
308
+ if (!isRecord(message) || !isRecord(message.info)) continue;
309
+ if (optionalString(message.info.role) === "user") return optionalString(message.info.id);
310
+ }
311
+ return void 0;
312
+ }
313
+ function latestUserMessageBefore(messages, sessionID, timestamp) {
314
+ let latest;
315
+ for (const message of messages.values()) {
316
+ if (message.sessionID !== sessionID || message.role !== "user") continue;
317
+ if ((message.createdAt ?? Number.NEGATIVE_INFINITY) > timestamp) continue;
318
+ if (!latest || (message.createdAt ?? 0) > (latest.createdAt ?? 0)) latest = message;
319
+ }
320
+ return latest;
321
+ }
322
+ function summarizePayload(payload) {
323
+ const input = isRecord(payload.input) ? payload.input : {};
324
+ const message = isRecord(input.message) ? input.message : {};
325
+ const text = textFromMessagePayload(message) ?? findFirstString(input, ["prompt", "input"]);
326
+ if (!text) return "LLM request";
327
+ return text.replace(/\s+/g, " ").trim().slice(0, 160);
328
+ }
329
+ function historyMessageFromChatMessage(record) {
330
+ const output = isRecord(record.payload.output) ? record.payload.output : {};
331
+ const message = isRecord(output.message) ? output.message : {};
332
+ const sessionID = record.sessionID ?? optionalString(message.sessionID);
333
+ const messageID = optionalString(message.id);
334
+ if (!sessionID || !messageID) return void 0;
335
+ return {
336
+ id: messageID,
337
+ sessionID,
338
+ role: optionalString(message.role) ?? "user",
339
+ createdAt: numberFromPath(message.time, "created") ?? record.timestamp,
340
+ completedAt: numberFromPath(message.time, "completed"),
341
+ text: textFromChatMessageOutput(output),
342
+ requests: []
343
+ };
344
+ }
345
+ function attachHeadersToRequest(requests, record) {
346
+ const input = isRecord(record.payload.input) ? record.payload.input : {};
347
+ const agent = optionalString(input.agent);
348
+ const messageID = record.messageID ?? messageIDFromPayload(input.message);
349
+ const match = requests.slice().reverse().find((request) => {
350
+ return request.sessionID === record.sessionID && request.messageID === messageID && request.agent === agent && request.providerID === record.providerID && request.modelID === record.modelID && request.timestamp <= record.timestamp && !request.headers;
351
+ });
352
+ if (!match) return;
353
+ match.headers = { id: record.id, timestamp: record.timestamp, payload: record.payload };
354
+ }
355
+ function textFromChatMessageOutput(output) {
356
+ const parts = Array.isArray(output.parts) ? output.parts : [];
357
+ return parts.map((part) => isRecord(part) ? optionalString(part.text) ?? optionalString(part.content) : void 0).filter((text) => !!text).join("\n");
358
+ }
359
+ function textFromMessagePayload(message) {
360
+ const direct = findFirstString(message, ["text", "content"]);
361
+ if (direct) return direct;
362
+ const parts = Array.isArray(message.parts) ? message.parts : [];
363
+ const joined = parts.map((part) => isRecord(part) ? optionalString(part.text) ?? optionalString(part.content) : void 0).filter((text) => !!text).join("\n");
364
+ return joined || void 0;
365
+ }
366
+ function messageIDFromPayload(message) {
367
+ return isRecord(message) ? optionalString(message.id) ?? optionalString(message.messageID) ?? optionalString(message.messageId) : void 0;
368
+ }
369
+ function findFirstString(value, keys) {
370
+ for (const key of keys) {
371
+ const item = value[key];
372
+ if (typeof item === "string" && item.length > 0) return item;
373
+ }
374
+ return void 0;
375
+ }
376
+ function numberFromPath(value, key) {
377
+ if (!isRecord(value)) return void 0;
378
+ const item = value[key];
379
+ return typeof item === "number" && Number.isFinite(item) ? item : void 0;
380
+ }
381
+
382
+ // src/viewer.ts
383
+ import { createServer } from "http";
384
+ async function serveViewer(options = {}) {
385
+ const host = options.host ?? "127.0.0.1";
386
+ const port = options.port ?? 8765;
387
+ const server = createServer(async (request, response) => {
388
+ const url = new URL(request.url ?? "/", `http://${host}:${port}`);
389
+ if (url.pathname === "/api/history") {
390
+ const history = await readHistory(options);
391
+ sendJson(response, history);
392
+ return;
393
+ }
394
+ if (url.pathname === "/" || url.pathname === "/index.html") {
395
+ sendHtml(response, renderViewerHtml(resolveCapturePath(options)));
396
+ return;
397
+ }
398
+ response.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
399
+ response.end("Not found");
400
+ });
401
+ await new Promise((resolve, reject) => {
402
+ server.once("error", reject);
403
+ server.listen(port, host, () => {
404
+ server.off("error", reject);
405
+ resolve();
406
+ });
407
+ });
408
+ return {
409
+ url: `http://${host}:${port}`,
410
+ close: () => new Promise((resolve) => server.close(() => resolve()))
411
+ };
412
+ }
413
+ async function readHistory(options = {}) {
414
+ const readOptions = {
415
+ dataDir: options.dataDir,
416
+ dbPath: options.dbPath,
417
+ limit: options.limit ?? 5e3
418
+ };
419
+ const records = await readRecentCaptures(readOptions);
420
+ return buildRequestHistory(records);
421
+ }
422
+ function sendJson(response, value) {
423
+ response.writeHead(200, { "content-type": "application/json; charset=utf-8" });
424
+ response.end(JSON.stringify(value));
425
+ }
426
+ function sendHtml(response, html) {
427
+ response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
428
+ response.end(html);
429
+ }
430
+ function renderViewerHtml(dbPath) {
431
+ const escapedDbPath = escapeHtml(dbPath);
432
+ return `<!doctype html>
433
+ <html lang="en">
434
+ <head>
435
+ <meta charset="utf-8">
436
+ <meta name="viewport" content="width=device-width, initial-scale=1">
437
+ <title>OpenCode Insights</title>
438
+ <style>
439
+ :root {
440
+ color-scheme: dark;
441
+ --bg: #101214;
442
+ --panel: #171a1d;
443
+ --panel-2: #20242a;
444
+ --line: #30363d;
445
+ --text: #eef2f5;
446
+ --muted: #9aa6b2;
447
+ --accent: #7dd3fc;
448
+ --ok: #86efac;
449
+ --warn: #fbbf24;
450
+ --bad: #fca5a5;
451
+ }
452
+ * { box-sizing: border-box; }
453
+ body {
454
+ margin: 0;
455
+ min-height: 100vh;
456
+ background: var(--bg);
457
+ color: var(--text);
458
+ font: 13px/1.45 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
459
+ }
460
+ header {
461
+ height: 56px;
462
+ display: flex;
463
+ align-items: center;
464
+ justify-content: space-between;
465
+ gap: 16px;
466
+ padding: 0 18px;
467
+ border-bottom: 1px solid var(--line);
468
+ background: #0d0f11;
469
+ }
470
+ h1 { margin: 0; font-size: 15px; font-weight: 700; }
471
+ main {
472
+ display: grid;
473
+ grid-template-columns: 300px minmax(340px, 0.95fr) minmax(460px, 1.25fr);
474
+ height: calc(100vh - 56px);
475
+ min-height: 540px;
476
+ }
477
+ section { min-width: 0; overflow: auto; border-right: 1px solid var(--line); }
478
+ section:last-child { border-right: 0; }
479
+ .toolbar {
480
+ position: sticky;
481
+ top: 0;
482
+ display: flex;
483
+ gap: 8px;
484
+ padding: 10px;
485
+ background: var(--panel);
486
+ border-bottom: 1px solid var(--line);
487
+ z-index: 2;
488
+ }
489
+ input {
490
+ width: 100%;
491
+ border: 1px solid var(--line);
492
+ background: #0d0f11;
493
+ color: var(--text);
494
+ border-radius: 6px;
495
+ padding: 8px 10px;
496
+ font: inherit;
497
+ }
498
+ button {
499
+ border: 1px solid var(--line);
500
+ background: var(--panel-2);
501
+ color: var(--text);
502
+ border-radius: 6px;
503
+ padding: 8px 10px;
504
+ font: inherit;
505
+ cursor: pointer;
506
+ }
507
+ button:hover { border-color: var(--accent); }
508
+ button:disabled { cursor: wait; opacity: 0.6; }
509
+ .item {
510
+ width: 100%;
511
+ display: block;
512
+ border: 0;
513
+ border-bottom: 1px solid var(--line);
514
+ border-radius: 0;
515
+ background: transparent;
516
+ text-align: left;
517
+ padding: 11px 12px;
518
+ }
519
+ .item:hover, .item.active { background: var(--panel-2); }
520
+ .request-item { padding-left: 28px; }
521
+ .title { color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
522
+ .meta {
523
+ margin-top: 4px;
524
+ color: var(--muted);
525
+ white-space: nowrap;
526
+ overflow: hidden;
527
+ text-overflow: ellipsis;
528
+ }
529
+ .muted { color: var(--muted); }
530
+ .pill {
531
+ color: #0d0f11;
532
+ background: var(--accent);
533
+ border-radius: 999px;
534
+ padding: 1px 6px;
535
+ font-weight: 700;
536
+ }
537
+ .pill.msg { background: var(--ok); }
538
+ .pill.missing { background: var(--warn); }
539
+ .detail { padding: 14px; }
540
+ .tabs { display: flex; gap: 6px; margin-bottom: 10px; flex-wrap: wrap; }
541
+ .tabs button.active { border-color: var(--accent); color: var(--accent); }
542
+ .tabs .json-control { display: none; margin-left: auto; }
543
+ .tabs .json-control + .json-control { margin-left: 0; }
544
+ .tabs.json-mode .json-control { display: inline-block; }
545
+ .panel, pre {
546
+ margin: 0;
547
+ padding: 14px;
548
+ overflow: auto;
549
+ white-space: pre-wrap;
550
+ word-break: break-word;
551
+ background: #0b0d0f;
552
+ border: 1px solid var(--line);
553
+ border-radius: 8px;
554
+ min-height: 220px;
555
+ }
556
+ .empty { color: var(--muted); padding: 16px; }
557
+ .status { color: var(--muted); min-width: 220px; text-align: right; }
558
+ .status.error { color: var(--bad); }
559
+ .kv { display: grid; grid-template-columns: 140px minmax(0, 1fr); gap: 8px 12px; }
560
+ .kv div:nth-child(odd) { color: var(--muted); }
561
+ .explain {
562
+ margin: 0 0 12px;
563
+ color: var(--muted);
564
+ }
565
+ .subhead {
566
+ margin: 16px 0 8px;
567
+ color: var(--text);
568
+ font-weight: 700;
569
+ }
570
+ .json-tree { font-size: 12px; line-height: 1.55; }
571
+ .json-tree details { margin-left: 14px; }
572
+ .json-tree summary { cursor: pointer; color: var(--accent); }
573
+ .json-tree .leaf { margin-left: 14px; }
574
+ .json-key { color: #bae6fd; }
575
+ .json-string { color: #bbf7d0; }
576
+ .json-number { color: #fde68a; }
577
+ .json-boolean { color: #f0abfc; }
578
+ .json-null { color: var(--muted); }
579
+ @media (max-width: 1000px) {
580
+ main { grid-template-columns: 1fr; height: auto; }
581
+ section { min-height: 360px; border-right: 0; border-bottom: 1px solid var(--line); }
582
+ }
583
+ </style>
584
+ </head>
585
+ <body>
586
+ <header>
587
+ <h1>OpenCode Insights</h1>
588
+ <div>
589
+ <div class="meta">${escapedDbPath}</div>
590
+ <div id="status" class="status">Loading history...</div>
591
+ </div>
592
+ </header>
593
+ <main>
594
+ <section>
595
+ <div class="toolbar"><input id="session-filter" placeholder="Filter sessions"></div>
596
+ <div id="sessions"></div>
597
+ </section>
598
+ <section>
599
+ <div class="toolbar"><input id="timeline-filter" placeholder="Filter messages and hooks"></div>
600
+ <div id="timeline"></div>
601
+ </section>
602
+ <section>
603
+ <div class="toolbar">
604
+ <button id="copy">Copy JSON</button>
605
+ <button id="refresh">Refresh</button>
606
+ </div>
607
+ <div class="detail">
608
+ <div class="tabs">
609
+ <button data-tab="summary" class="active">Summary</button>
610
+ <button data-tab="request">Request</button>
611
+ <button data-tab="response">Response</button>
612
+ <button data-tab="raw">Raw</button>
613
+ <button id="expand-json" class="json-control">Expand All</button>
614
+ <button id="collapse-json" class="json-control">Collapse All</button>
615
+ </div>
616
+ <div id="detail" class="panel">Select a message or request.</div>
617
+ </div>
618
+ </section>
619
+ </main>
620
+ <script>
621
+ const state = {
622
+ history: { sessions: [], requests: [] },
623
+ sessionID: null,
624
+ messageID: null,
625
+ requestID: null,
626
+ tab: "summary",
627
+ loading: true,
628
+ error: null,
629
+ loadedMs: 0
630
+ };
631
+
632
+ const qs = (id) => document.getElementById(id);
633
+ const fmt = (ms) => ms ? new Date(ms).toLocaleString() : "-";
634
+ const short = (value, size = 90) => {
635
+ const text = String(value || "").replace(/\\s+/g, " ").trim();
636
+ return text.length > size ? text.slice(0, size - 1) + "..." : text;
637
+ };
638
+
639
+ async function load() {
640
+ state.loading = true;
641
+ state.error = null;
642
+ renderStatus();
643
+ qs("sessions").innerHTML = '<div class="empty">Loading sessions and hooks...</div>';
644
+ qs("timeline").innerHTML = '<div class="empty">Waiting for history data...</div>';
645
+ try {
646
+ const started = performance.now();
647
+ const res = await fetch("/api/history");
648
+ if (!res.ok) throw new Error("HTTP " + res.status + " " + res.statusText);
649
+ state.history = await res.json();
650
+ state.loadedMs = Math.round(performance.now() - started);
651
+ if (!state.sessionID && state.history.sessions[0]) state.sessionID = state.history.sessions[0].id;
652
+ if (state.sessionID && !state.history.sessions.some((session) => session.id === state.sessionID)) {
653
+ state.sessionID = state.history.sessions[0]?.id || null;
654
+ state.messageID = null;
655
+ state.requestID = null;
656
+ }
657
+ const session = selectedSession();
658
+ if (session && !state.messageID && session.messages[0]) state.messageID = session.messages[0].id;
659
+ } catch (error) {
660
+ state.error = error instanceof Error ? error.message : String(error);
661
+ } finally {
662
+ state.loading = false;
663
+ render();
664
+ }
665
+ }
666
+
667
+ function selectedSession() {
668
+ return state.history.sessions.find((session) => session.id === state.sessionID);
669
+ }
670
+
671
+ function selectedMessage() {
672
+ const session = selectedSession();
673
+ return session?.messages.find((message) => message.id === state.messageID) || null;
674
+ }
675
+
676
+ function selectedRequest() {
677
+ const message = selectedMessage();
678
+ return message?.requests.find((request) => request.id === state.requestID)
679
+ || state.history.requests.find((request) => request.id === state.requestID)
680
+ || null;
681
+ }
682
+
683
+ function activeContext() {
684
+ const message = selectedMessage();
685
+ const request = selectedRequest();
686
+ return { message, request: request || message?.requests[0] || null };
687
+ }
688
+
689
+ function render() {
690
+ renderStatus();
691
+ if (state.error) {
692
+ qs("sessions").innerHTML = '<div class="empty">Failed to load history.</div>';
693
+ qs("timeline").innerHTML = '<div class="empty">' + escapeHtml(state.error) + '</div>';
694
+ qs("detail").textContent = "Refresh after checking the viewer server.";
695
+ return;
696
+ }
697
+ renderSessions();
698
+ renderTimeline();
699
+ renderDetail();
700
+ }
701
+
702
+ function renderStatus() {
703
+ const status = qs("status");
704
+ status.classList.toggle("error", Boolean(state.error));
705
+ if (state.error) status.textContent = "Load failed";
706
+ else if (state.loading) status.textContent = "Loading history...";
707
+ else status.textContent = state.history.sessions.length + " sessions \xB7 " + state.history.requests.length + " hooks \xB7 " + state.loadedMs + "ms";
708
+ qs("refresh").disabled = state.loading;
709
+ qs("refresh").textContent = state.loading ? "Loading..." : "Refresh";
710
+ }
711
+
712
+ function renderSessions() {
713
+ const filter = qs("session-filter").value.toLowerCase();
714
+ const sessions = state.history.sessions.filter((session) =>
715
+ [session.id, session.title].filter(Boolean).join(" ").toLowerCase().includes(filter)
716
+ );
717
+ qs("sessions").innerHTML = sessions.length ? sessions.map((session) =>
718
+ '<button class="item ' + (session.id === state.sessionID ? "active" : "") + '" data-session="' + escapeAttr(session.id) + '">' +
719
+ '<div class="title">' + escapeHtml(session.title || session.id) + '</div>' +
720
+ '<div class="meta">' + session.messages.length + ' messages \xB7 ' + session.requests.length + ' hooks \xB7 ' + fmt(session.updatedAt) + '</div>' +
721
+ '</button>'
722
+ ).join("") : '<div class="empty">No sessions found.</div>';
723
+ for (const item of document.querySelectorAll("[data-session]")) {
724
+ item.onclick = () => {
725
+ state.sessionID = item.dataset.session;
726
+ const session = selectedSession();
727
+ state.messageID = session?.messages[0]?.id || null;
728
+ state.requestID = null;
729
+ render();
730
+ };
731
+ }
732
+ }
733
+
734
+ function renderTimeline() {
735
+ const session = selectedSession();
736
+ if (!session) {
737
+ qs("timeline").innerHTML = '<div class="empty">Select a session.</div>';
738
+ return;
739
+ }
740
+ const filter = qs("timeline-filter").value.toLowerCase();
741
+ const blocks = [];
742
+ for (const message of session.messages) {
743
+ const searchable = JSON.stringify(message).toLowerCase();
744
+ if (filter && !searchable.includes(filter)) continue;
745
+ blocks.push(
746
+ '<button class="item ' + (message.id === state.messageID && !state.requestID ? "active" : "") + '" data-message="' + escapeAttr(message.id) + '">' +
747
+ '<div class="title"><span class="pill msg">MSG</span> ' + escapeHtml(message.role) + ' \xB7 ' + escapeHtml(short(message.text || message.id, 110)) + '</div>' +
748
+ '<div class="meta">' + message.requests.length + ' hooks \xB7 response ' + (message.response?.text ? "captured" : "missing") + ' \xB7 ' + fmt(message.createdAt) + '</div>' +
749
+ '</button>'
750
+ );
751
+ for (const request of message.requests) {
752
+ blocks.push(
753
+ '<button class="item request-item ' + (request.id === state.requestID ? "active" : "") + '" data-message="' + escapeAttr(message.id) + '" data-request="' + escapeAttr(request.id) + '">' +
754
+ '<div class="title"><span class="pill">HOOK</span> ' + escapeHtml(request.agent || "agent") + ' \xB7 ' + escapeHtml([request.providerID, request.modelID].filter(Boolean).join("/") || "-") + '</div>' +
755
+ '<div class="meta">' + escapeHtml(short(request.summary, 120)) + ' \xB7 ' + (request.headers ? "headers" : "no headers") + ' \xB7 ' + (request.response?.text ? "response" : "no response") + '</div>' +
756
+ '</button>'
757
+ );
758
+ }
759
+ }
760
+ qs("timeline").innerHTML = blocks.length ? blocks.join("") : '<div class="empty">No messages or hooks found.</div>';
761
+ for (const item of document.querySelectorAll("[data-message]")) {
762
+ item.onclick = () => {
763
+ state.messageID = item.dataset.message;
764
+ state.requestID = item.dataset.request || null;
765
+ render();
766
+ };
767
+ }
768
+ }
769
+
770
+ function renderDetail() {
771
+ const { message, request } = activeContext();
772
+ document.querySelector(".tabs").classList.toggle("json-mode", state.tab !== "summary");
773
+ if (!message && !request) {
774
+ qs("detail").textContent = "Select a message or request.";
775
+ return;
776
+ }
777
+
778
+ if (state.tab === "summary") {
779
+ const response = request?.response || message?.response;
780
+ qs("detail").innerHTML = '<div class="kv">' +
781
+ kv("Message", message?.id || "-") +
782
+ kv("Message text", message?.text || "(no user text captured)") +
783
+ kv("Selected hook", request?.id || "-") +
784
+ kv("Agent", request?.agent || "-") +
785
+ kv("Purpose", request?.purpose || "-") +
786
+ kv("Provider/model", [request?.providerID, request?.modelID].filter(Boolean).join("/") || "-") +
787
+ kv("Request time", fmt(request?.timestamp)) +
788
+ kv("Headers hook", request?.headers ? "captured" : "empty / not captured") +
789
+ kv("Direct response", request?.response?.text ? "captured" : request ? "none for this hook" : "-") +
790
+ kv("Message response", response?.id || "-") +
791
+ kv("Response text", response?.text || "(no assistant text captured)") +
792
+ kv("Finish", response?.finish || "-") +
793
+ kv("Cost", response?.cost === undefined ? "-" : String(response.cost)) +
794
+ '</div>';
795
+ return;
796
+ }
797
+
798
+ if (state.tab === "request") {
799
+ renderRequestDetail(request);
800
+ return;
801
+ }
802
+
803
+ if (state.tab === "response") {
804
+ const response = state.requestID ? request?.response : message?.response;
805
+ renderJson(response || {
806
+ status: "missing",
807
+ note: request?.agent === "title"
808
+ ? "The title request does not produce the assistant reply. Select the build request or MSG row to inspect the conversation response."
809
+ : "No assistant response events were captured for this message yet."
810
+ });
811
+ return;
812
+ }
813
+
814
+ renderJson({ message, request });
815
+ }
816
+
817
+ function kv(key, value) {
818
+ return '<div>' + escapeHtml(key) + '</div><div>' + escapeHtml(value) + '</div>';
819
+ }
820
+
821
+ function renderJson(value) {
822
+ qs("detail").innerHTML = '<div class="json-tree">' + jsonNode(value, "root", true) + '</div>';
823
+ }
824
+
825
+ function renderRequestDetail(request) {
826
+ if (!request) {
827
+ renderJson({ status: "missing", note: "Select a hook row to inspect hook details." });
828
+ return;
829
+ }
830
+ const payload = request.payload || {};
831
+ const hookInput = payload.input || {};
832
+ const hookOutput = payload.output || {};
833
+ const headerOutput = request.headers?.payload?.output || null;
834
+ qs("detail").innerHTML =
835
+ '<p class="explain">These are OpenCode plugin hook values, not a raw HTTP request. <b>Hook input</b> is the context OpenCode passed to the plugin before the model call. <b>Hook output</b> is the model settings returned by the plugin hook. <b>Headers output</b> is the provider headers hook result.</p>' +
836
+ '<div class="kv">' +
837
+ kv("Hook id", request.id) +
838
+ kv("Agent", request.agent || "-") +
839
+ kv("Purpose", request.purpose || "-") +
840
+ kv("Provider/model", [request.providerID, request.modelID].filter(Boolean).join("/") || "-") +
841
+ kv("User message id", request.messageID || "-") +
842
+ kv("Time", fmt(request.timestamp)) +
843
+ '</div>' +
844
+ '<div class="subhead">Hook Input: context OpenCode supplied</div>' +
845
+ '<div class="json-tree">' + jsonNode(summarizeHookInput(hookInput), "hookInput", true) + '</div>' +
846
+ '<div class="subhead">Hook Output: model-call settings</div>' +
847
+ '<div class="json-tree">' + jsonNode(hookOutput, "hookOutput", true) + '</div>' +
848
+ '<div class="subhead">Headers Hook Output</div>' +
849
+ '<div class="json-tree">' + jsonNode(headerOutput, "headersOutput", true) + '</div>' +
850
+ '<div class="subhead">Raw Full-Fidelity Payload</div>' +
851
+ '<div class="json-tree">' + jsonNode({ params: request.payload, headers: request.headers?.payload || null }, "raw", false) + '</div>';
852
+ }
853
+
854
+ function summarizeHookInput(input) {
855
+ return {
856
+ sessionID: input?.sessionID,
857
+ agent: input?.agent,
858
+ model: input?.model ? {
859
+ id: input.model.id,
860
+ providerID: input.model.providerID,
861
+ name: input.model.name,
862
+ family: input.model.family,
863
+ api: input.model.api,
864
+ limit: input.model.limit,
865
+ capabilities: input.model.capabilities,
866
+ cost: input.model.cost
867
+ } : null,
868
+ provider: input?.provider ? {
869
+ id: input.provider.id,
870
+ source: input.provider.source,
871
+ name: input.provider.name,
872
+ env: input.provider.env,
873
+ options: input.provider.options,
874
+ key: input.provider.key
875
+ } : null,
876
+ message: input?.message || null
877
+ };
878
+ }
879
+
880
+ function setJsonExpanded(expanded) {
881
+ for (const node of qs("detail").querySelectorAll("details")) node.open = expanded;
882
+ }
883
+
884
+ function jsonNode(value, key, open) {
885
+ if (value === null) return leaf(key, '<span class="json-null">null</span>');
886
+ if (Array.isArray(value)) {
887
+ const children = value.map((item, index) => jsonNode(item, String(index), false)).join("");
888
+ return '<details ' + (open ? "open" : "") + '><summary>' + label(key) + ' Array(' + value.length + ')</summary>' + children + '</details>';
889
+ }
890
+ if (typeof value === "object") {
891
+ const keys = Object.keys(value);
892
+ const children = keys.map((childKey) => jsonNode(value[childKey], childKey, false)).join("");
893
+ return '<details ' + (open ? "open" : "") + '><summary>' + label(key) + ' Object(' + keys.length + ')</summary>' + children + '</details>';
894
+ }
895
+ if (typeof value === "string") return leaf(key, '<span class="json-string">' + escapeHtml(JSON.stringify(value)) + '</span>');
896
+ if (typeof value === "number") return leaf(key, '<span class="json-number">' + value + '</span>');
897
+ if (typeof value === "boolean") return leaf(key, '<span class="json-boolean">' + value + '</span>');
898
+ return leaf(key, escapeHtml(String(value)));
899
+ }
900
+
901
+ function label(key) {
902
+ return '<span class="json-key">' + escapeHtml(key) + '</span>: ';
903
+ }
904
+
905
+ function leaf(key, value) {
906
+ return '<div class="leaf">' + label(key) + value + '</div>';
907
+ }
908
+
909
+ function escapeHtml(value) {
910
+ return String(value ?? "").replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[char]));
911
+ }
912
+
913
+ function escapeAttr(value) {
914
+ return escapeHtml(value).replace(new RegExp(String.fromCharCode(96), "g"), "&#96;");
915
+ }
916
+
917
+ qs("session-filter").oninput = render;
918
+ qs("timeline-filter").oninput = render;
919
+ qs("refresh").onclick = load;
920
+ qs("expand-json").onclick = () => setJsonExpanded(true);
921
+ qs("collapse-json").onclick = () => setJsonExpanded(false);
922
+ qs("copy").onclick = async () => {
923
+ const { message, request } = activeContext();
924
+ const value = state.tab === "request" ? { params: request?.payload || null, headers: request?.headers?.payload || null }
925
+ : state.tab === "response" ? (request?.response || message?.response || null)
926
+ : state.tab === "raw" ? { message, request }
927
+ : { messageID: message?.id, requestID: request?.id };
928
+ await navigator.clipboard.writeText(JSON.stringify(value, null, 2));
929
+ };
930
+ for (const tab of document.querySelectorAll("[data-tab]")) {
931
+ tab.onclick = () => {
932
+ state.tab = tab.dataset.tab;
933
+ for (const item of document.querySelectorAll("[data-tab]")) item.classList.toggle("active", item === tab);
934
+ renderDetail();
935
+ };
936
+ }
937
+ load();
938
+ </script>
939
+ </body>
940
+ </html>`;
941
+ }
942
+ function escapeHtml(value) {
943
+ return value.replace(/[&<>"']/g, (char) => {
944
+ if (char === "&") return "&amp;";
945
+ if (char === "<") return "&lt;";
946
+ if (char === ">") return "&gt;";
947
+ if (char === '"') return "&quot;";
948
+ return "&#39;";
949
+ });
950
+ }
951
+
952
+ // src/cli.ts
953
+ var execFileAsync2 = promisify2(execFile2);
954
+ var DEFAULT_RECENT_LIMIT = 20;
955
+ var DEFAULT_HISTORY_LIMIT = 5e3;
956
+ var SERVER_PLUGIN_SPEC = "@rejacky/opencode-insights";
957
+ var TUI_PLUGIN_SPEC = "@rejacky/opencode-insights/tui";
958
+ async function main(argv) {
959
+ const command = argv[2] ?? "recent";
960
+ const options = parseOptions(argv.slice(3));
961
+ const positionals = parsePositionals(argv.slice(3));
962
+ if (command === "help" || command === "--help" || command === "-h") {
963
+ process.stdout.write(`${usage()}
964
+ `);
965
+ return;
966
+ }
967
+ if (command === "recent") {
968
+ const records = await readRecentCaptures({ ...options, limit: options.limitProvided ? options.limit : DEFAULT_RECENT_LIMIT });
969
+ process.stdout.write(options.json ? `${JSON.stringify(records, null, 2)}
970
+ ` : `${formatCaptureSummary(records)}
971
+ `);
972
+ return;
973
+ }
974
+ if (command === "history") {
975
+ const records = await readRecentCaptures(historyReadOptions(options));
976
+ const history = buildRequestHistory(records);
977
+ process.stdout.write(`${JSON.stringify(history, null, 2)}
978
+ `);
979
+ return;
980
+ }
981
+ if (command === "sessions") {
982
+ const records = await readRecentCaptures(historyReadOptions(options));
983
+ const history = buildRequestHistory(records);
984
+ const rows = summarizeSessions(history.sessions);
985
+ process.stdout.write(options.json ? `${JSON.stringify(rows, null, 2)}
986
+ ` : `${formatSessionSummary(rows)}
987
+ `);
988
+ return;
989
+ }
990
+ if (command === "show") {
991
+ const sessionID = positionals[0];
992
+ if (!sessionID) throw new Error("Missing session id. Usage: opencode-insights show <session-id>");
993
+ const session = await readSession(sessionID, options);
994
+ process.stdout.write(`${JSON.stringify(session, null, 2)}
995
+ `);
996
+ return;
997
+ }
998
+ if (command === "export") {
999
+ const sessionID = positionals[0];
1000
+ if (!sessionID) throw new Error("Missing session id. Usage: opencode-insights export <session-id> [--output PATH]");
1001
+ const session = await readSession(sessionID, options);
1002
+ const json = `${JSON.stringify(session, null, 2)}
1003
+ `;
1004
+ if (options.output) {
1005
+ await mkdir(dirname(options.output), { recursive: true });
1006
+ await writeFile(options.output, json, "utf8");
1007
+ process.stdout.write(`Exported ${sessionID} to ${options.output}
1008
+ `);
1009
+ } else {
1010
+ process.stdout.write(json);
1011
+ }
1012
+ return;
1013
+ }
1014
+ if (command === "serve") {
1015
+ const viewer = await serveViewer({ ...options, limit: options.limitProvided ? options.limit : DEFAULT_HISTORY_LIMIT });
1016
+ process.stdout.write(`OpenCode Insights viewer listening at ${viewer.url}
1017
+ `);
1018
+ return;
1019
+ }
1020
+ if (command === "open") {
1021
+ const viewer = await serveViewer({ ...options, limit: options.limitProvided ? options.limit : DEFAULT_HISTORY_LIMIT });
1022
+ await openBrowser(viewer.url);
1023
+ process.stdout.write(`OpenCode Insights viewer listening at ${viewer.url}
1024
+ `);
1025
+ return;
1026
+ }
1027
+ if (command === "doctor") {
1028
+ process.stdout.write(`${await runDoctor(options)}
1029
+ `);
1030
+ return;
1031
+ }
1032
+ if (command === "vacuum") {
1033
+ process.stdout.write(`${await vacuumDatabase(options)}
1034
+ `);
1035
+ return;
1036
+ }
1037
+ if (command === "configure") {
1038
+ process.stdout.write(`${await configureOpenCode(options)}
1039
+ `);
1040
+ return;
1041
+ }
1042
+ {
1043
+ process.stderr.write(`Unknown command: ${command}
1044
+ `);
1045
+ process.stderr.write(`${usage()}
1046
+ `);
1047
+ process.exitCode = 1;
1048
+ }
1049
+ }
1050
+ function parseOptions(args) {
1051
+ const options = { limit: DEFAULT_RECENT_LIMIT, limitProvided: false, json: false, dryRun: false };
1052
+ for (let index = 0; index < args.length; index += 1) {
1053
+ const arg = args[index];
1054
+ if (arg === "--json") {
1055
+ options.json = true;
1056
+ } else if (arg === "--dry-run") {
1057
+ options.dryRun = true;
1058
+ } else if (arg === "--db") {
1059
+ const value = args[index + 1];
1060
+ if (value) options.dbPath = value;
1061
+ index += 1;
1062
+ } else if (arg === "--data-dir") {
1063
+ const value = args[index + 1];
1064
+ if (value) options.dataDir = value;
1065
+ index += 1;
1066
+ } else if (arg === "--limit") {
1067
+ options.limit = Number.parseInt(args[index + 1] ?? "20", 10);
1068
+ options.limitProvided = true;
1069
+ index += 1;
1070
+ } else if (arg === "--host") {
1071
+ const value = args[index + 1];
1072
+ if (value) options.host = value;
1073
+ index += 1;
1074
+ } else if (arg === "--port") {
1075
+ options.port = Number.parseInt(args[index + 1] ?? "8765", 10);
1076
+ index += 1;
1077
+ } else if (arg === "--output" || arg === "-o") {
1078
+ const value = args[index + 1];
1079
+ if (value) options.output = value;
1080
+ index += 1;
1081
+ } else if (arg === "--config-dir") {
1082
+ const value = args[index + 1];
1083
+ if (value) options.configDir = value;
1084
+ index += 1;
1085
+ }
1086
+ }
1087
+ if (!Number.isFinite(options.limit) || options.limit < 1) options.limit = DEFAULT_RECENT_LIMIT;
1088
+ if (options.port !== void 0 && (!Number.isFinite(options.port) || options.port < 1)) options.port = 8765;
1089
+ return options;
1090
+ }
1091
+ function parsePositionals(args) {
1092
+ const positionals = [];
1093
+ for (let index = 0; index < args.length; index += 1) {
1094
+ const arg = args[index];
1095
+ if (!arg) continue;
1096
+ if (arg.startsWith("--")) {
1097
+ if (["--db", "--data-dir", "--limit", "--host", "--port", "--output", "--config-dir"].includes(arg)) index += 1;
1098
+ continue;
1099
+ }
1100
+ if (arg === "-o") {
1101
+ index += 1;
1102
+ continue;
1103
+ }
1104
+ positionals.push(arg);
1105
+ }
1106
+ return positionals;
1107
+ }
1108
+ function historyReadOptions(options) {
1109
+ return { ...options, limit: options.limitProvided ? options.limit : DEFAULT_HISTORY_LIMIT };
1110
+ }
1111
+ async function readSession(sessionID, options) {
1112
+ const records = await readRecentCaptures(historyReadOptions(options));
1113
+ const session = buildRequestHistory(records).sessions.find((item) => item.id === sessionID);
1114
+ if (!session) {
1115
+ throw new Error(
1116
+ `Session not found in the latest ${historyReadOptions(options).limit} capture rows: ${sessionID}. Try --limit 20000 or check opencode-insights sessions.`
1117
+ );
1118
+ }
1119
+ return session;
1120
+ }
1121
+ function summarizeSessions(sessions) {
1122
+ return sessions.map((session) => {
1123
+ const hookCount = session.requests.length;
1124
+ const responseCount = session.messages.filter((message) => message.response).length;
1125
+ const updatedAt = session.updatedAt ?? Math.max(0, ...session.messages.map((message) => message.completedAt ?? message.createdAt ?? 0));
1126
+ return {
1127
+ id: session.id,
1128
+ title: session.title ?? "",
1129
+ updatedAt: updatedAt || void 0,
1130
+ messages: session.messages.length,
1131
+ hooks: hookCount,
1132
+ responses: responseCount
1133
+ };
1134
+ });
1135
+ }
1136
+ function formatSessionSummary(rows) {
1137
+ if (rows.length === 0) return "No sessions found.";
1138
+ const header = ["updated".padEnd(24), "messages".padStart(8), "hooks".padStart(6), "responses".padStart(9), "session".padEnd(28), "title"].join(
1139
+ " "
1140
+ );
1141
+ const body = rows.map(
1142
+ (row) => [
1143
+ (row.updatedAt ? new Date(row.updatedAt).toISOString() : "-").padEnd(24),
1144
+ String(row.messages).padStart(8),
1145
+ String(row.hooks).padStart(6),
1146
+ String(row.responses).padStart(9),
1147
+ row.id.padEnd(28),
1148
+ row.title || "-"
1149
+ ].join(" ")
1150
+ );
1151
+ return [header, ...body].join("\n");
1152
+ }
1153
+ async function openBrowser(url) {
1154
+ const platform = process.platform;
1155
+ if (platform === "darwin") {
1156
+ await execFileAsync2("open", [url]);
1157
+ return;
1158
+ }
1159
+ if (platform === "win32") {
1160
+ await execFileAsync2("cmd", ["/c", "start", "", url]);
1161
+ return;
1162
+ }
1163
+ await execFileAsync2("xdg-open", [url]);
1164
+ }
1165
+ async function runDoctor(options) {
1166
+ const dbPath = resolveCapturePath(options);
1167
+ const jsonlPath = dbPath.endsWith(".sqlite") ? `${dbPath}.jsonl` : dbPath;
1168
+ const rows = [
1169
+ `OpenCode Insights doctor`,
1170
+ `DB path: ${dbPath}`,
1171
+ `DB exists: ${existsSync2(dbPath) ? "yes" : "no"}`,
1172
+ `JSONL fallback exists: ${existsSync2(jsonlPath) ? "yes" : "no"}`
1173
+ ];
1174
+ if (existsSync2(dbPath)) {
1175
+ rows.push(...await sqliteDiagnostics(dbPath));
1176
+ } else if (existsSync2(jsonlPath)) {
1177
+ const records = await readRecentCaptures({ ...options, limit: options.limitProvided ? options.limit : DEFAULT_HISTORY_LIMIT });
1178
+ rows.push(`Readable fallback records: ${records.length}`);
1179
+ }
1180
+ return rows.join("\n");
1181
+ }
1182
+ async function sqliteDiagnostics(dbPath) {
1183
+ const diagnostics = [];
1184
+ try {
1185
+ const tableRows = await sqliteJsonQuery(dbPath, "select name from sqlite_master where type='table' order by name;");
1186
+ const tables = tableRows.filter((row) => typeof row.name === "string").map((row) => row.name);
1187
+ diagnostics.push(`SQLite CLI: yes`);
1188
+ diagnostics.push(`Tables: ${tables.join(", ") || "-"}`);
1189
+ if (tables.includes("captures")) {
1190
+ const captureRows = await sqliteJsonQuery(dbPath, "select count(*) as captures from captures;");
1191
+ const kindRows = await sqliteJsonQuery(dbPath, "select kind, count(*) as count from captures group by kind order by kind;");
1192
+ const captureRow = captureRows.find((row) => typeof row.captures === "number");
1193
+ diagnostics.push(`Capture rows: ${captureRow?.captures ?? "unknown"}`);
1194
+ diagnostics.push(`Capture kinds: ${kindRows.map((row) => `${row.kind}=${row.count}`).join(", ") || "-"}`);
1195
+ } else {
1196
+ diagnostics.push("Capture rows: unavailable (missing captures table)");
1197
+ }
1198
+ const integrityRows = await sqliteJsonQuery(dbPath, "pragma integrity_check;");
1199
+ const integrity = integrityRows.find((row) => typeof row.integrity_check === "string");
1200
+ diagnostics.push(`Integrity: ${integrity?.integrity_check ?? "unknown"}`);
1201
+ } catch (error) {
1202
+ diagnostics.push(`SQLite CLI: unavailable or failed (${error instanceof Error ? error.message : String(error)})`);
1203
+ const records = await readRecentCaptures({ dbPath, limit: DEFAULT_RECENT_LIMIT });
1204
+ diagnostics.push(`Readable records via fallback: ${records.length}`);
1205
+ }
1206
+ return diagnostics;
1207
+ }
1208
+ async function sqliteJsonQuery(dbPath, sql) {
1209
+ const { stdout } = await execFileAsync2("sqlite3", ["-json", dbPath, sql], { maxBuffer: 128 * 1024 * 1024 });
1210
+ return stdout.trim() ? JSON.parse(stdout) : [];
1211
+ }
1212
+ async function vacuumDatabase(options) {
1213
+ const dbPath = resolveCapturePath(options);
1214
+ if (!existsSync2(dbPath)) return `No SQLite DB found at ${dbPath}`;
1215
+ await execFileAsync2("sqlite3", [dbPath, "vacuum;"]);
1216
+ return `Vacuumed ${dbPath}`;
1217
+ }
1218
+ async function configureOpenCode(options) {
1219
+ const configDir = options.configDir ?? defaultOpenCodeConfigDir();
1220
+ const opencodePath = resolveOpenCodeConfigPath(configDir);
1221
+ const tuiPath = join(configDir, "tui.json");
1222
+ const opencodeConfig = await readJsonConfig(opencodePath, { plugin: [] });
1223
+ const tuiConfig = await readJsonConfig(tuiPath, { plugin: [] });
1224
+ const opencodeChanged = addUniquePlugin(opencodeConfig, SERVER_PLUGIN_SPEC);
1225
+ const tuiChanged = addUniquePlugin(tuiConfig, TUI_PLUGIN_SPEC);
1226
+ const lines = [
1227
+ `OpenCode config: ${opencodePath}`,
1228
+ `TUI config: ${tuiPath}`,
1229
+ `Server plugin: ${opencodeChanged ? "added" : "already present"} (${SERVER_PLUGIN_SPEC})`,
1230
+ `TUI plugin: ${tuiChanged ? "added" : "already present"} (${TUI_PLUGIN_SPEC})`
1231
+ ];
1232
+ if (options.dryRun) {
1233
+ lines.push("Dry run: no files written.");
1234
+ return lines.join("\n");
1235
+ }
1236
+ await mkdir(configDir, { recursive: true });
1237
+ if (opencodeChanged || !existsSync2(opencodePath)) await writeJsonConfig(opencodePath, opencodeConfig);
1238
+ if (tuiChanged || !existsSync2(tuiPath)) await writeJsonConfig(tuiPath, tuiConfig);
1239
+ lines.push("Configuration written. Restart OpenCode to load the plugin.");
1240
+ return lines.join("\n");
1241
+ }
1242
+ function defaultOpenCodeConfigDir() {
1243
+ const override = process.env.OPENCODE_CONFIG_DIR;
1244
+ if (override) return override;
1245
+ if (process.platform === "win32") return join(process.env.APPDATA ?? join(homedir(), "AppData", "Roaming"), "opencode");
1246
+ return join(homedir(), ".config", "opencode");
1247
+ }
1248
+ function resolveOpenCodeConfigPath(configDir) {
1249
+ const jsoncPath = join(configDir, "opencode.jsonc");
1250
+ if (existsSync2(jsoncPath)) return jsoncPath;
1251
+ const jsonPath = join(configDir, "opencode.json");
1252
+ if (existsSync2(jsonPath)) return jsonPath;
1253
+ return jsonPath;
1254
+ }
1255
+ async function readJsonConfig(path, fallback) {
1256
+ if (!existsSync2(path)) return { ...fallback };
1257
+ const content = await readFile2(path, "utf8");
1258
+ const trimmed = content.trim();
1259
+ if (!trimmed) return { ...fallback };
1260
+ try {
1261
+ const parsed = JSON.parse(stripJsonCommentsAndTrailingCommas(trimmed));
1262
+ return isJsonObject(parsed) ? parsed : { ...fallback };
1263
+ } catch (error) {
1264
+ throw new Error(`Could not parse ${path}: ${error instanceof Error ? error.message : String(error)}`);
1265
+ }
1266
+ }
1267
+ function stripJsonCommentsAndTrailingCommas(input) {
1268
+ let output = "";
1269
+ let inString = false;
1270
+ let quote = "";
1271
+ let escaped = false;
1272
+ for (let index = 0; index < input.length; index += 1) {
1273
+ const current = input[index] ?? "";
1274
+ const next = input[index + 1] ?? "";
1275
+ if (inString) {
1276
+ output += current;
1277
+ if (escaped) {
1278
+ escaped = false;
1279
+ } else if (current === "\\") {
1280
+ escaped = true;
1281
+ } else if (current === quote) {
1282
+ inString = false;
1283
+ }
1284
+ continue;
1285
+ }
1286
+ if (current === '"' || current === "'") {
1287
+ inString = true;
1288
+ quote = current;
1289
+ output += current;
1290
+ continue;
1291
+ }
1292
+ if (current === "/" && next === "/") {
1293
+ while (index < input.length && input[index] !== "\n") index += 1;
1294
+ output += "\n";
1295
+ continue;
1296
+ }
1297
+ if (current === "/" && next === "*") {
1298
+ index += 2;
1299
+ while (index < input.length && !(input[index] === "*" && input[index + 1] === "/")) index += 1;
1300
+ index += 1;
1301
+ continue;
1302
+ }
1303
+ output += current;
1304
+ }
1305
+ return output.replace(/,\s*([}\]])/g, "$1");
1306
+ }
1307
+ function isJsonObject(value) {
1308
+ return !!value && typeof value === "object" && !Array.isArray(value);
1309
+ }
1310
+ function addUniquePlugin(config, plugin) {
1311
+ const current = Array.isArray(config.plugin) ? config.plugin : [];
1312
+ if (current.includes(plugin)) {
1313
+ config.plugin = current;
1314
+ return false;
1315
+ }
1316
+ config.plugin = [...current, plugin];
1317
+ return true;
1318
+ }
1319
+ async function writeJsonConfig(path, config) {
1320
+ await mkdir(dirname(path), { recursive: true });
1321
+ await writeFile(path, `${JSON.stringify(config, null, 2)}
1322
+ `, "utf8");
1323
+ }
1324
+ function usage() {
1325
+ return [
1326
+ "Usage:",
1327
+ " opencode-insights configure [--config-dir DIR] [--dry-run]",
1328
+ " opencode-insights recent [--db PATH] [--data-dir DIR] [--limit N] [--json]",
1329
+ " opencode-insights sessions [--db PATH] [--data-dir DIR] [--limit N] [--json]",
1330
+ " opencode-insights history [--db PATH] [--data-dir DIR] [--limit N]",
1331
+ " opencode-insights show <session-id> [--db PATH] [--data-dir DIR] [--limit N]",
1332
+ " opencode-insights export <session-id> [--output PATH] [--db PATH] [--data-dir DIR] [--limit N]",
1333
+ " opencode-insights serve [--db PATH] [--data-dir DIR] [--limit N] [--host HOST] [--port PORT]",
1334
+ " opencode-insights open [--db PATH] [--data-dir DIR] [--limit N] [--host HOST] [--port PORT]",
1335
+ " opencode-insights doctor [--db PATH] [--data-dir DIR]",
1336
+ " opencode-insights vacuum [--db PATH] [--data-dir DIR]"
1337
+ ].join("\n");
1338
+ }
1339
+ function isDirectRun() {
1340
+ const entry = process.argv[1];
1341
+ return !!entry && pathToFileURL(entry).href === import.meta.url;
1342
+ }
1343
+ if (isDirectRun()) {
1344
+ main(process.argv).catch((error) => {
1345
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}
1346
+ `);
1347
+ process.exitCode = 1;
1348
+ });
1349
+ }
1350
+ export {
1351
+ addUniquePlugin,
1352
+ configureOpenCode,
1353
+ defaultOpenCodeConfigDir,
1354
+ formatSessionSummary,
1355
+ parseOptions,
1356
+ resolveOpenCodeConfigPath,
1357
+ stripJsonCommentsAndTrailingCommas,
1358
+ summarizeSessions
1359
+ };
1360
+ //# sourceMappingURL=cli.js.map