agent-inspect 4.0.0 → 4.2.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,1157 @@
1
+ import { __commonJS, __require, __toESM, resolveTraceDir, TraceDirectory, parseTraceJsonl, validateEvent } from './chunk-5VSPJEZ7.mjs';
2
+ import { readFile, mkdir, rm } from 'fs/promises';
3
+ import path from 'path';
4
+ import { existsSync } from 'fs';
5
+
6
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/util.js
7
+ var require_util = __commonJS({
8
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/util.js"(exports$1) {
9
+ exports$1.getBooleanOption = (options, key) => {
10
+ let value = false;
11
+ if (key in options && typeof (value = options[key]) !== "boolean") {
12
+ throw new TypeError(`Expected the "${key}" option to be a boolean`);
13
+ }
14
+ return value;
15
+ };
16
+ exports$1.cppdb = /* @__PURE__ */ Symbol();
17
+ exports$1.inspect = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
18
+ }
19
+ });
20
+
21
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/sqlite-error.js
22
+ var require_sqlite_error = __commonJS({
23
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/sqlite-error.js"(exports$1, module) {
24
+ var descriptor = { value: "SqliteError", writable: true, enumerable: false, configurable: true };
25
+ function SqliteError(message, code) {
26
+ if (new.target !== SqliteError) {
27
+ return new SqliteError(message, code);
28
+ }
29
+ if (typeof code !== "string") {
30
+ throw new TypeError("Expected second argument to be a string");
31
+ }
32
+ Error.call(this, message);
33
+ descriptor.value = "" + message;
34
+ Object.defineProperty(this, "message", descriptor);
35
+ Error.captureStackTrace(this, SqliteError);
36
+ this.code = code;
37
+ }
38
+ Object.setPrototypeOf(SqliteError, Error);
39
+ Object.setPrototypeOf(SqliteError.prototype, Error.prototype);
40
+ Object.defineProperty(SqliteError.prototype, "name", descriptor);
41
+ module.exports = SqliteError;
42
+ }
43
+ });
44
+
45
+ // node_modules/.pnpm/file-uri-to-path@1.0.0/node_modules/file-uri-to-path/index.js
46
+ var require_file_uri_to_path = __commonJS({
47
+ "node_modules/.pnpm/file-uri-to-path@1.0.0/node_modules/file-uri-to-path/index.js"(exports$1, module) {
48
+ var sep = __require("path").sep || "/";
49
+ module.exports = fileUriToPath;
50
+ function fileUriToPath(uri) {
51
+ if ("string" != typeof uri || uri.length <= 7 || "file://" != uri.substring(0, 7)) {
52
+ throw new TypeError("must pass in a file:// URI to convert to a file path");
53
+ }
54
+ var rest = decodeURI(uri.substring(7));
55
+ var firstSlash = rest.indexOf("/");
56
+ var host = rest.substring(0, firstSlash);
57
+ var path2 = rest.substring(firstSlash + 1);
58
+ if ("localhost" == host) host = "";
59
+ if (host) {
60
+ host = sep + sep + host;
61
+ }
62
+ path2 = path2.replace(/^(.+)\|/, "$1:");
63
+ if (sep == "\\") {
64
+ path2 = path2.replace(/\//g, "\\");
65
+ }
66
+ if (/^.+\:/.test(path2)) ; else {
67
+ path2 = sep + path2;
68
+ }
69
+ return host + path2;
70
+ }
71
+ }
72
+ });
73
+
74
+ // node_modules/.pnpm/bindings@1.5.0/node_modules/bindings/bindings.js
75
+ var require_bindings = __commonJS({
76
+ "node_modules/.pnpm/bindings@1.5.0/node_modules/bindings/bindings.js"(exports$1, module) {
77
+ var fs = __require("fs");
78
+ var path2 = __require("path");
79
+ var fileURLToPath = require_file_uri_to_path();
80
+ var join = path2.join;
81
+ var dirname = path2.dirname;
82
+ var exists = fs.accessSync && function(path3) {
83
+ try {
84
+ fs.accessSync(path3);
85
+ } catch (e) {
86
+ return false;
87
+ }
88
+ return true;
89
+ } || fs.existsSync || path2.existsSync;
90
+ var defaults = {
91
+ arrow: process.env.NODE_BINDINGS_ARROW || " \u2192 ",
92
+ compiled: process.env.NODE_BINDINGS_COMPILED_DIR || "compiled",
93
+ platform: process.platform,
94
+ arch: process.arch,
95
+ nodePreGyp: "node-v" + process.versions.modules + "-" + process.platform + "-" + process.arch,
96
+ version: process.versions.node,
97
+ bindings: "bindings.node",
98
+ try: [
99
+ // node-gyp's linked version in the "build" dir
100
+ ["module_root", "build", "bindings"],
101
+ // node-waf and gyp_addon (a.k.a node-gyp)
102
+ ["module_root", "build", "Debug", "bindings"],
103
+ ["module_root", "build", "Release", "bindings"],
104
+ // Debug files, for development (legacy behavior, remove for node v0.9)
105
+ ["module_root", "out", "Debug", "bindings"],
106
+ ["module_root", "Debug", "bindings"],
107
+ // Release files, but manually compiled (legacy behavior, remove for node v0.9)
108
+ ["module_root", "out", "Release", "bindings"],
109
+ ["module_root", "Release", "bindings"],
110
+ // Legacy from node-waf, node <= 0.4.x
111
+ ["module_root", "build", "default", "bindings"],
112
+ // Production "Release" buildtype binary (meh...)
113
+ ["module_root", "compiled", "version", "platform", "arch", "bindings"],
114
+ // node-qbs builds
115
+ ["module_root", "addon-build", "release", "install-root", "bindings"],
116
+ ["module_root", "addon-build", "debug", "install-root", "bindings"],
117
+ ["module_root", "addon-build", "default", "install-root", "bindings"],
118
+ // node-pre-gyp path ./lib/binding/{node_abi}-{platform}-{arch}
119
+ ["module_root", "lib", "binding", "nodePreGyp", "bindings"]
120
+ ]
121
+ };
122
+ function bindings(opts) {
123
+ if (typeof opts == "string") {
124
+ opts = { bindings: opts };
125
+ } else if (!opts) {
126
+ opts = {};
127
+ }
128
+ Object.keys(defaults).map(function(i2) {
129
+ if (!(i2 in opts)) opts[i2] = defaults[i2];
130
+ });
131
+ if (!opts.module_root) {
132
+ opts.module_root = exports$1.getRoot(exports$1.getFileName());
133
+ }
134
+ if (path2.extname(opts.bindings) != ".node") {
135
+ opts.bindings += ".node";
136
+ }
137
+ var requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
138
+ var tries = [], i = 0, l = opts.try.length, n, b, err;
139
+ for (; i < l; i++) {
140
+ n = join.apply(
141
+ null,
142
+ opts.try[i].map(function(p) {
143
+ return opts[p] || p;
144
+ })
145
+ );
146
+ tries.push(n);
147
+ try {
148
+ b = opts.path ? requireFunc.resolve(n) : requireFunc(n);
149
+ if (!opts.path) {
150
+ b.path = n;
151
+ }
152
+ return b;
153
+ } catch (e) {
154
+ if (e.code !== "MODULE_NOT_FOUND" && e.code !== "QUALIFIED_PATH_RESOLUTION_FAILED" && !/not find/i.test(e.message)) {
155
+ throw e;
156
+ }
157
+ }
158
+ }
159
+ err = new Error(
160
+ "Could not locate the bindings file. Tried:\n" + tries.map(function(a) {
161
+ return opts.arrow + a;
162
+ }).join("\n")
163
+ );
164
+ err.tries = tries;
165
+ throw err;
166
+ }
167
+ module.exports = exports$1 = bindings;
168
+ exports$1.getFileName = function getFileName(calling_file) {
169
+ var origPST = Error.prepareStackTrace, origSTL = Error.stackTraceLimit, dummy = {}, fileName;
170
+ Error.stackTraceLimit = 10;
171
+ Error.prepareStackTrace = function(e, st) {
172
+ for (var i = 0, l = st.length; i < l; i++) {
173
+ fileName = st[i].getFileName();
174
+ if (fileName !== __filename) {
175
+ if (calling_file) {
176
+ if (fileName !== calling_file) {
177
+ return;
178
+ }
179
+ } else {
180
+ return;
181
+ }
182
+ }
183
+ }
184
+ };
185
+ Error.captureStackTrace(dummy);
186
+ dummy.stack;
187
+ Error.prepareStackTrace = origPST;
188
+ Error.stackTraceLimit = origSTL;
189
+ var fileSchema = "file://";
190
+ if (fileName.indexOf(fileSchema) === 0) {
191
+ fileName = fileURLToPath(fileName);
192
+ }
193
+ return fileName;
194
+ };
195
+ exports$1.getRoot = function getRoot(file) {
196
+ var dir = dirname(file), prev;
197
+ while (true) {
198
+ if (dir === ".") {
199
+ dir = process.cwd();
200
+ }
201
+ if (exists(join(dir, "package.json")) || exists(join(dir, "node_modules"))) {
202
+ return dir;
203
+ }
204
+ if (prev === dir) {
205
+ throw new Error(
206
+ 'Could not find module root given file: "' + file + '". Do you have a `package.json` file? '
207
+ );
208
+ }
209
+ prev = dir;
210
+ dir = join(dir, "..");
211
+ }
212
+ };
213
+ }
214
+ });
215
+
216
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/wrappers.js
217
+ var require_wrappers = __commonJS({
218
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/wrappers.js"(exports$1) {
219
+ var { cppdb } = require_util();
220
+ exports$1.prepare = function prepare(sql) {
221
+ return this[cppdb].prepare(sql, this, false);
222
+ };
223
+ exports$1.exec = function exec(sql) {
224
+ this[cppdb].exec(sql);
225
+ return this;
226
+ };
227
+ exports$1.close = function close() {
228
+ this[cppdb].close();
229
+ return this;
230
+ };
231
+ exports$1.loadExtension = function loadExtension(...args) {
232
+ this[cppdb].loadExtension(...args);
233
+ return this;
234
+ };
235
+ exports$1.defaultSafeIntegers = function defaultSafeIntegers(...args) {
236
+ this[cppdb].defaultSafeIntegers(...args);
237
+ return this;
238
+ };
239
+ exports$1.unsafeMode = function unsafeMode(...args) {
240
+ this[cppdb].unsafeMode(...args);
241
+ return this;
242
+ };
243
+ exports$1.getters = {
244
+ name: {
245
+ get: function name() {
246
+ return this[cppdb].name;
247
+ },
248
+ enumerable: true
249
+ },
250
+ open: {
251
+ get: function open() {
252
+ return this[cppdb].open;
253
+ },
254
+ enumerable: true
255
+ },
256
+ inTransaction: {
257
+ get: function inTransaction() {
258
+ return this[cppdb].inTransaction;
259
+ },
260
+ enumerable: true
261
+ },
262
+ readonly: {
263
+ get: function readonly() {
264
+ return this[cppdb].readonly;
265
+ },
266
+ enumerable: true
267
+ },
268
+ memory: {
269
+ get: function memory() {
270
+ return this[cppdb].memory;
271
+ },
272
+ enumerable: true
273
+ }
274
+ };
275
+ }
276
+ });
277
+
278
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/transaction.js
279
+ var require_transaction = __commonJS({
280
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/transaction.js"(exports$1, module) {
281
+ var { cppdb } = require_util();
282
+ var controllers = /* @__PURE__ */ new WeakMap();
283
+ module.exports = function transaction(fn) {
284
+ if (typeof fn !== "function") throw new TypeError("Expected first argument to be a function");
285
+ const db = this[cppdb];
286
+ const controller = getController(db, this);
287
+ const { apply } = Function.prototype;
288
+ const properties = {
289
+ default: { value: wrapTransaction(apply, fn, db, controller.default) },
290
+ deferred: { value: wrapTransaction(apply, fn, db, controller.deferred) },
291
+ immediate: { value: wrapTransaction(apply, fn, db, controller.immediate) },
292
+ exclusive: { value: wrapTransaction(apply, fn, db, controller.exclusive) },
293
+ database: { value: this, enumerable: true }
294
+ };
295
+ Object.defineProperties(properties.default.value, properties);
296
+ Object.defineProperties(properties.deferred.value, properties);
297
+ Object.defineProperties(properties.immediate.value, properties);
298
+ Object.defineProperties(properties.exclusive.value, properties);
299
+ return properties.default.value;
300
+ };
301
+ var getController = (db, self) => {
302
+ let controller = controllers.get(db);
303
+ if (!controller) {
304
+ const shared = {
305
+ commit: db.prepare("COMMIT", self, false),
306
+ rollback: db.prepare("ROLLBACK", self, false),
307
+ savepoint: db.prepare("SAVEPOINT ` _bs3. `", self, false),
308
+ release: db.prepare("RELEASE ` _bs3. `", self, false),
309
+ rollbackTo: db.prepare("ROLLBACK TO ` _bs3. `", self, false)
310
+ };
311
+ controllers.set(db, controller = {
312
+ default: Object.assign({ begin: db.prepare("BEGIN", self, false) }, shared),
313
+ deferred: Object.assign({ begin: db.prepare("BEGIN DEFERRED", self, false) }, shared),
314
+ immediate: Object.assign({ begin: db.prepare("BEGIN IMMEDIATE", self, false) }, shared),
315
+ exclusive: Object.assign({ begin: db.prepare("BEGIN EXCLUSIVE", self, false) }, shared)
316
+ });
317
+ }
318
+ return controller;
319
+ };
320
+ var wrapTransaction = (apply, fn, db, { begin, commit, rollback, savepoint, release, rollbackTo }) => function sqliteTransaction() {
321
+ let before, after, undo;
322
+ if (db.inTransaction) {
323
+ before = savepoint;
324
+ after = release;
325
+ undo = rollbackTo;
326
+ } else {
327
+ before = begin;
328
+ after = commit;
329
+ undo = rollback;
330
+ }
331
+ before.run();
332
+ try {
333
+ const result = apply.call(fn, this, arguments);
334
+ if (result && typeof result.then === "function") {
335
+ throw new TypeError("Transaction function cannot return a promise");
336
+ }
337
+ after.run();
338
+ return result;
339
+ } catch (ex) {
340
+ if (db.inTransaction) {
341
+ undo.run();
342
+ if (undo !== rollback) after.run();
343
+ }
344
+ throw ex;
345
+ }
346
+ };
347
+ }
348
+ });
349
+
350
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/pragma.js
351
+ var require_pragma = __commonJS({
352
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/pragma.js"(exports$1, module) {
353
+ var { getBooleanOption, cppdb } = require_util();
354
+ module.exports = function pragma(source, options) {
355
+ if (options == null) options = {};
356
+ if (typeof source !== "string") throw new TypeError("Expected first argument to be a string");
357
+ if (typeof options !== "object") throw new TypeError("Expected second argument to be an options object");
358
+ const simple = getBooleanOption(options, "simple");
359
+ const stmt = this[cppdb].prepare(`PRAGMA ${source}`, this, true);
360
+ return simple ? stmt.pluck().get() : stmt.all();
361
+ };
362
+ }
363
+ });
364
+
365
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/backup.js
366
+ var require_backup = __commonJS({
367
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/backup.js"(exports$1, module) {
368
+ var fs = __require("fs");
369
+ var path2 = __require("path");
370
+ var { promisify } = __require("util");
371
+ var { cppdb } = require_util();
372
+ var fsAccess = promisify(fs.access);
373
+ module.exports = async function backup(filename, options) {
374
+ if (options == null) options = {};
375
+ if (typeof filename !== "string") throw new TypeError("Expected first argument to be a string");
376
+ if (typeof options !== "object") throw new TypeError("Expected second argument to be an options object");
377
+ filename = filename.trim();
378
+ const attachedName = "attached" in options ? options.attached : "main";
379
+ const handler = "progress" in options ? options.progress : null;
380
+ if (!filename) throw new TypeError("Backup filename cannot be an empty string");
381
+ if (filename === ":memory:") throw new TypeError('Invalid backup filename ":memory:"');
382
+ if (typeof attachedName !== "string") throw new TypeError('Expected the "attached" option to be a string');
383
+ if (!attachedName) throw new TypeError('The "attached" option cannot be an empty string');
384
+ if (handler != null && typeof handler !== "function") throw new TypeError('Expected the "progress" option to be a function');
385
+ await fsAccess(path2.dirname(filename)).catch(() => {
386
+ throw new TypeError("Cannot save backup because the directory does not exist");
387
+ });
388
+ const isNewFile = await fsAccess(filename).then(() => false, () => true);
389
+ return runBackup(this[cppdb].backup(this, attachedName, filename, isNewFile), handler || null);
390
+ };
391
+ var runBackup = (backup, handler) => {
392
+ let rate = 0;
393
+ let useDefault = true;
394
+ return new Promise((resolve, reject) => {
395
+ setImmediate(function step() {
396
+ try {
397
+ const progress = backup.transfer(rate);
398
+ if (!progress.remainingPages) {
399
+ backup.close();
400
+ resolve(progress);
401
+ return;
402
+ }
403
+ if (useDefault) {
404
+ useDefault = false;
405
+ rate = 100;
406
+ }
407
+ if (handler) {
408
+ const ret = handler(progress);
409
+ if (ret !== void 0) {
410
+ if (typeof ret === "number" && ret === ret) rate = Math.max(0, Math.min(2147483647, Math.round(ret)));
411
+ else throw new TypeError("Expected progress callback to return a number or undefined");
412
+ }
413
+ }
414
+ setImmediate(step);
415
+ } catch (err) {
416
+ backup.close();
417
+ reject(err);
418
+ }
419
+ });
420
+ });
421
+ };
422
+ }
423
+ });
424
+
425
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/serialize.js
426
+ var require_serialize = __commonJS({
427
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/serialize.js"(exports$1, module) {
428
+ var { cppdb } = require_util();
429
+ module.exports = function serialize(options) {
430
+ if (options == null) options = {};
431
+ if (typeof options !== "object") throw new TypeError("Expected first argument to be an options object");
432
+ const attachedName = "attached" in options ? options.attached : "main";
433
+ if (typeof attachedName !== "string") throw new TypeError('Expected the "attached" option to be a string');
434
+ if (!attachedName) throw new TypeError('The "attached" option cannot be an empty string');
435
+ return this[cppdb].serialize(attachedName);
436
+ };
437
+ }
438
+ });
439
+
440
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/function.js
441
+ var require_function = __commonJS({
442
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/function.js"(exports$1, module) {
443
+ var { getBooleanOption, cppdb } = require_util();
444
+ module.exports = function defineFunction(name, options, fn) {
445
+ if (options == null) options = {};
446
+ if (typeof options === "function") {
447
+ fn = options;
448
+ options = {};
449
+ }
450
+ if (typeof name !== "string") throw new TypeError("Expected first argument to be a string");
451
+ if (typeof fn !== "function") throw new TypeError("Expected last argument to be a function");
452
+ if (typeof options !== "object") throw new TypeError("Expected second argument to be an options object");
453
+ if (!name) throw new TypeError("User-defined function name cannot be an empty string");
454
+ const safeIntegers = "safeIntegers" in options ? +getBooleanOption(options, "safeIntegers") : 2;
455
+ const deterministic = getBooleanOption(options, "deterministic");
456
+ const directOnly = getBooleanOption(options, "directOnly");
457
+ const varargs = getBooleanOption(options, "varargs");
458
+ let argCount = -1;
459
+ if (!varargs) {
460
+ argCount = fn.length;
461
+ if (!Number.isInteger(argCount) || argCount < 0) throw new TypeError("Expected function.length to be a positive integer");
462
+ if (argCount > 100) throw new RangeError("User-defined functions cannot have more than 100 arguments");
463
+ }
464
+ this[cppdb].function(fn, name, argCount, safeIntegers, deterministic, directOnly);
465
+ return this;
466
+ };
467
+ }
468
+ });
469
+
470
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/aggregate.js
471
+ var require_aggregate = __commonJS({
472
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/aggregate.js"(exports$1, module) {
473
+ var { getBooleanOption, cppdb } = require_util();
474
+ module.exports = function defineAggregate(name, options) {
475
+ if (typeof name !== "string") throw new TypeError("Expected first argument to be a string");
476
+ if (typeof options !== "object" || options === null) throw new TypeError("Expected second argument to be an options object");
477
+ if (!name) throw new TypeError("User-defined function name cannot be an empty string");
478
+ const start = "start" in options ? options.start : null;
479
+ const step = getFunctionOption(options, "step", true);
480
+ const inverse = getFunctionOption(options, "inverse", false);
481
+ const result = getFunctionOption(options, "result", false);
482
+ const safeIntegers = "safeIntegers" in options ? +getBooleanOption(options, "safeIntegers") : 2;
483
+ const deterministic = getBooleanOption(options, "deterministic");
484
+ const directOnly = getBooleanOption(options, "directOnly");
485
+ const varargs = getBooleanOption(options, "varargs");
486
+ let argCount = -1;
487
+ if (!varargs) {
488
+ argCount = Math.max(getLength(step), inverse ? getLength(inverse) : 0);
489
+ if (argCount > 0) argCount -= 1;
490
+ if (argCount > 100) throw new RangeError("User-defined functions cannot have more than 100 arguments");
491
+ }
492
+ this[cppdb].aggregate(start, step, inverse, result, name, argCount, safeIntegers, deterministic, directOnly);
493
+ return this;
494
+ };
495
+ var getFunctionOption = (options, key, required) => {
496
+ const value = key in options ? options[key] : null;
497
+ if (typeof value === "function") return value;
498
+ if (value != null) throw new TypeError(`Expected the "${key}" option to be a function`);
499
+ if (required) throw new TypeError(`Missing required option "${key}"`);
500
+ return null;
501
+ };
502
+ var getLength = ({ length }) => {
503
+ if (Number.isInteger(length) && length >= 0) return length;
504
+ throw new TypeError("Expected function.length to be a positive integer");
505
+ };
506
+ }
507
+ });
508
+
509
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/table.js
510
+ var require_table = __commonJS({
511
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/table.js"(exports$1, module) {
512
+ var { cppdb } = require_util();
513
+ module.exports = function defineTable(name, factory) {
514
+ if (typeof name !== "string") throw new TypeError("Expected first argument to be a string");
515
+ if (!name) throw new TypeError("Virtual table module name cannot be an empty string");
516
+ let eponymous = false;
517
+ if (typeof factory === "object" && factory !== null) {
518
+ eponymous = true;
519
+ factory = defer(parseTableDefinition(factory, "used", name));
520
+ } else {
521
+ if (typeof factory !== "function") throw new TypeError("Expected second argument to be a function or a table definition object");
522
+ factory = wrapFactory(factory);
523
+ }
524
+ this[cppdb].table(factory, name, eponymous);
525
+ return this;
526
+ };
527
+ function wrapFactory(factory) {
528
+ return function virtualTableFactory(moduleName, databaseName, tableName, ...args) {
529
+ const thisObject = {
530
+ module: moduleName,
531
+ database: databaseName,
532
+ table: tableName
533
+ };
534
+ const def = apply.call(factory, thisObject, args);
535
+ if (typeof def !== "object" || def === null) {
536
+ throw new TypeError(`Virtual table module "${moduleName}" did not return a table definition object`);
537
+ }
538
+ return parseTableDefinition(def, "returned", moduleName);
539
+ };
540
+ }
541
+ function parseTableDefinition(def, verb, moduleName) {
542
+ if (!hasOwnProperty.call(def, "rows")) {
543
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition without a "rows" property`);
544
+ }
545
+ if (!hasOwnProperty.call(def, "columns")) {
546
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition without a "columns" property`);
547
+ }
548
+ const rows = def.rows;
549
+ if (typeof rows !== "function" || Object.getPrototypeOf(rows) !== GeneratorFunctionPrototype) {
550
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "rows" property (should be a generator function)`);
551
+ }
552
+ let columns = def.columns;
553
+ if (!Array.isArray(columns) || !(columns = [...columns]).every((x) => typeof x === "string")) {
554
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "columns" property (should be an array of strings)`);
555
+ }
556
+ if (columns.length !== new Set(columns).size) {
557
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with duplicate column names`);
558
+ }
559
+ if (!columns.length) {
560
+ throw new RangeError(`Virtual table module "${moduleName}" ${verb} a table definition with zero columns`);
561
+ }
562
+ let parameters;
563
+ if (hasOwnProperty.call(def, "parameters")) {
564
+ parameters = def.parameters;
565
+ if (!Array.isArray(parameters) || !(parameters = [...parameters]).every((x) => typeof x === "string")) {
566
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "parameters" property (should be an array of strings)`);
567
+ }
568
+ } else {
569
+ parameters = inferParameters(rows);
570
+ }
571
+ if (parameters.length !== new Set(parameters).size) {
572
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with duplicate parameter names`);
573
+ }
574
+ if (parameters.length > 32) {
575
+ throw new RangeError(`Virtual table module "${moduleName}" ${verb} a table definition with more than the maximum number of 32 parameters`);
576
+ }
577
+ for (const parameter of parameters) {
578
+ if (columns.includes(parameter)) {
579
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with column "${parameter}" which was ambiguously defined as both a column and parameter`);
580
+ }
581
+ }
582
+ let safeIntegers = 2;
583
+ if (hasOwnProperty.call(def, "safeIntegers")) {
584
+ const bool = def.safeIntegers;
585
+ if (typeof bool !== "boolean") {
586
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "safeIntegers" property (should be a boolean)`);
587
+ }
588
+ safeIntegers = +bool;
589
+ }
590
+ let directOnly = false;
591
+ if (hasOwnProperty.call(def, "directOnly")) {
592
+ directOnly = def.directOnly;
593
+ if (typeof directOnly !== "boolean") {
594
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "directOnly" property (should be a boolean)`);
595
+ }
596
+ }
597
+ const columnDefinitions = [
598
+ ...parameters.map(identifier).map((str2) => `${str2} HIDDEN`),
599
+ ...columns.map(identifier)
600
+ ];
601
+ return [
602
+ `CREATE TABLE x(${columnDefinitions.join(", ")});`,
603
+ wrapGenerator(rows, new Map(columns.map((x, i) => [x, parameters.length + i])), moduleName),
604
+ parameters,
605
+ safeIntegers,
606
+ directOnly
607
+ ];
608
+ }
609
+ function wrapGenerator(generator, columnMap, moduleName) {
610
+ return function* virtualTable(...args) {
611
+ const output = args.map((x) => Buffer.isBuffer(x) ? Buffer.from(x) : x);
612
+ for (let i = 0; i < columnMap.size; ++i) {
613
+ output.push(null);
614
+ }
615
+ for (const row of generator(...args)) {
616
+ if (Array.isArray(row)) {
617
+ extractRowArray(row, output, columnMap.size, moduleName);
618
+ yield output;
619
+ } else if (typeof row === "object" && row !== null) {
620
+ extractRowObject(row, output, columnMap, moduleName);
621
+ yield output;
622
+ } else {
623
+ throw new TypeError(`Virtual table module "${moduleName}" yielded something that isn't a valid row object`);
624
+ }
625
+ }
626
+ };
627
+ }
628
+ function extractRowArray(row, output, columnCount, moduleName) {
629
+ if (row.length !== columnCount) {
630
+ throw new TypeError(`Virtual table module "${moduleName}" yielded a row with an incorrect number of columns`);
631
+ }
632
+ const offset = output.length - columnCount;
633
+ for (let i = 0; i < columnCount; ++i) {
634
+ output[i + offset] = row[i];
635
+ }
636
+ }
637
+ function extractRowObject(row, output, columnMap, moduleName) {
638
+ let count = 0;
639
+ for (const key of Object.keys(row)) {
640
+ const index = columnMap.get(key);
641
+ if (index === void 0) {
642
+ throw new TypeError(`Virtual table module "${moduleName}" yielded a row with an undeclared column "${key}"`);
643
+ }
644
+ output[index] = row[key];
645
+ count += 1;
646
+ }
647
+ if (count !== columnMap.size) {
648
+ throw new TypeError(`Virtual table module "${moduleName}" yielded a row with missing columns`);
649
+ }
650
+ }
651
+ function inferParameters({ length }) {
652
+ if (!Number.isInteger(length) || length < 0) {
653
+ throw new TypeError("Expected function.length to be a positive integer");
654
+ }
655
+ const params = [];
656
+ for (let i = 0; i < length; ++i) {
657
+ params.push(`$${i + 1}`);
658
+ }
659
+ return params;
660
+ }
661
+ var { hasOwnProperty } = Object.prototype;
662
+ var { apply } = Function.prototype;
663
+ var GeneratorFunctionPrototype = Object.getPrototypeOf(function* () {
664
+ });
665
+ var identifier = (str2) => `"${str2.replace(/"/g, '""')}"`;
666
+ var defer = (x) => () => x;
667
+ }
668
+ });
669
+
670
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/inspect.js
671
+ var require_inspect = __commonJS({
672
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/inspect.js"(exports$1, module) {
673
+ var DatabaseInspection = function Database3() {
674
+ };
675
+ module.exports = function inspect(depth, opts) {
676
+ return Object.assign(new DatabaseInspection(), this);
677
+ };
678
+ }
679
+ });
680
+
681
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/database.js
682
+ var require_database = __commonJS({
683
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/database.js"(exports$1, module) {
684
+ var fs = __require("fs");
685
+ var path2 = __require("path");
686
+ var util = require_util();
687
+ var SqliteError = require_sqlite_error();
688
+ var DEFAULT_ADDON;
689
+ function Database3(filenameGiven, options) {
690
+ if (new.target == null) {
691
+ return new Database3(filenameGiven, options);
692
+ }
693
+ let buffer;
694
+ if (Buffer.isBuffer(filenameGiven)) {
695
+ buffer = filenameGiven;
696
+ filenameGiven = ":memory:";
697
+ }
698
+ if (filenameGiven == null) filenameGiven = "";
699
+ if (options == null) options = {};
700
+ if (typeof filenameGiven !== "string") throw new TypeError("Expected first argument to be a string");
701
+ if (typeof options !== "object") throw new TypeError("Expected second argument to be an options object");
702
+ if ("readOnly" in options) throw new TypeError('Misspelled option "readOnly" should be "readonly"');
703
+ if ("memory" in options) throw new TypeError('Option "memory" was removed in v7.0.0 (use ":memory:" filename instead)');
704
+ const filename = filenameGiven.trim();
705
+ const anonymous = filename === "" || filename === ":memory:";
706
+ const readonly = util.getBooleanOption(options, "readonly");
707
+ const fileMustExist = util.getBooleanOption(options, "fileMustExist");
708
+ const timeout = "timeout" in options ? options.timeout : 5e3;
709
+ const verbose = "verbose" in options ? options.verbose : null;
710
+ const nativeBinding = "nativeBinding" in options ? options.nativeBinding : null;
711
+ if (readonly && anonymous && !buffer) throw new TypeError("In-memory/temporary databases cannot be readonly");
712
+ if (!Number.isInteger(timeout) || timeout < 0) throw new TypeError('Expected the "timeout" option to be a positive integer');
713
+ if (timeout > 2147483647) throw new RangeError('Option "timeout" cannot be greater than 2147483647');
714
+ if (verbose != null && typeof verbose !== "function") throw new TypeError('Expected the "verbose" option to be a function');
715
+ if (nativeBinding != null && typeof nativeBinding !== "string" && typeof nativeBinding !== "object") throw new TypeError('Expected the "nativeBinding" option to be a string or addon object');
716
+ let addon;
717
+ if (nativeBinding == null) {
718
+ addon = DEFAULT_ADDON || (DEFAULT_ADDON = require_bindings()("better_sqlite3.node"));
719
+ } else if (typeof nativeBinding === "string") {
720
+ const requireFunc = typeof __non_webpack_require__ === "function" ? __non_webpack_require__ : __require;
721
+ addon = requireFunc(path2.resolve(nativeBinding).replace(/(\.node)?$/, ".node"));
722
+ } else {
723
+ addon = nativeBinding;
724
+ }
725
+ if (!addon.isInitialized) {
726
+ addon.setErrorConstructor(SqliteError);
727
+ addon.isInitialized = true;
728
+ }
729
+ if (!anonymous && !fs.existsSync(path2.dirname(filename))) {
730
+ throw new TypeError("Cannot open database because the directory does not exist");
731
+ }
732
+ Object.defineProperties(this, {
733
+ [util.cppdb]: { value: new addon.Database(filename, filenameGiven, anonymous, readonly, fileMustExist, timeout, verbose || null, buffer || null) },
734
+ ...wrappers.getters
735
+ });
736
+ }
737
+ var wrappers = require_wrappers();
738
+ Database3.prototype.prepare = wrappers.prepare;
739
+ Database3.prototype.transaction = require_transaction();
740
+ Database3.prototype.pragma = require_pragma();
741
+ Database3.prototype.backup = require_backup();
742
+ Database3.prototype.serialize = require_serialize();
743
+ Database3.prototype.function = require_function();
744
+ Database3.prototype.aggregate = require_aggregate();
745
+ Database3.prototype.table = require_table();
746
+ Database3.prototype.loadExtension = wrappers.loadExtension;
747
+ Database3.prototype.exec = wrappers.exec;
748
+ Database3.prototype.close = wrappers.close;
749
+ Database3.prototype.defaultSafeIntegers = wrappers.defaultSafeIntegers;
750
+ Database3.prototype.unsafeMode = wrappers.unsafeMode;
751
+ Database3.prototype[util.inspect] = require_inspect();
752
+ module.exports = Database3;
753
+ }
754
+ });
755
+
756
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/index.js
757
+ var require_lib = __commonJS({
758
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/index.js"(exports$1, module) {
759
+ module.exports = require_database();
760
+ module.exports.SqliteError = require_sqlite_error();
761
+ }
762
+ });
763
+
764
+ // packages/index-sqlite/src/types.ts
765
+ var INDEX_SCHEMA_VERSION = "1";
766
+ var INDEX_DB_FILENAME = "trace-index.sqlite";
767
+
768
+ // packages/index-sqlite/src/builder.ts
769
+ var import_better_sqlite3 = __toESM(require_lib(), 1);
770
+
771
+ // packages/index-sqlite/src/schema.ts
772
+ var INDEX_SCHEMA_SQL = `
773
+ DROP TABLE IF EXISTS meta;
774
+ DROP TABLE IF EXISTS errors;
775
+ DROP TABLE IF EXISTS steps;
776
+ DROP TABLE IF EXISTS sessions;
777
+ DROP TABLE IF EXISTS runs;
778
+
779
+ CREATE TABLE meta (
780
+ key TEXT PRIMARY KEY,
781
+ value TEXT
782
+ );
783
+
784
+ CREATE TABLE runs (
785
+ run_id TEXT PRIMARY KEY,
786
+ file TEXT NOT NULL,
787
+ mtime_ms REAL NOT NULL,
788
+ name TEXT,
789
+ status TEXT,
790
+ started_at REAL,
791
+ ended_at REAL,
792
+ duration_ms REAL,
793
+ session_id TEXT,
794
+ group_id TEXT,
795
+ correlation_id TEXT
796
+ );
797
+
798
+ CREATE TABLE steps (
799
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
800
+ run_id TEXT NOT NULL,
801
+ step_id TEXT NOT NULL,
802
+ kind TEXT,
803
+ name TEXT,
804
+ status TEXT,
805
+ duration_ms REAL,
806
+ tool_name TEXT,
807
+ model TEXT,
808
+ parent_id TEXT
809
+ );
810
+
811
+ CREATE TABLE errors (
812
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
813
+ run_id TEXT NOT NULL,
814
+ step_id TEXT,
815
+ message TEXT,
816
+ code TEXT
817
+ );
818
+
819
+ CREATE TABLE sessions (
820
+ session_id TEXT PRIMARY KEY,
821
+ run_count INTEGER NOT NULL,
822
+ first_started_at REAL,
823
+ last_ended_at REAL
824
+ );
825
+
826
+ CREATE INDEX idx_runs_status ON runs(status);
827
+ CREATE INDEX idx_runs_session ON runs(session_id);
828
+ CREATE INDEX idx_runs_started ON runs(started_at);
829
+ CREATE INDEX idx_steps_run ON steps(run_id);
830
+ CREATE INDEX idx_steps_kind ON steps(kind);
831
+ CREATE INDEX idx_steps_tool ON steps(tool_name);
832
+ `;
833
+ var DERIVE_SESSIONS_SQL = `
834
+ INSERT INTO sessions (session_id, run_count, first_started_at, last_ended_at)
835
+ SELECT session_id, COUNT(*), MIN(started_at), MAX(ended_at)
836
+ FROM runs
837
+ WHERE session_id IS NOT NULL
838
+ GROUP BY session_id;
839
+ `;
840
+ var META_KEYS = {
841
+ schemaVersion: "schemaVersion",
842
+ builtAt: "builtAt",
843
+ sourceDir: "sourceDir",
844
+ fileCount: "fileCount",
845
+ driver: "driver"
846
+ };
847
+ function metaDefaults(sourceDir, fileCount) {
848
+ return {
849
+ [META_KEYS.schemaVersion]: INDEX_SCHEMA_VERSION,
850
+ [META_KEYS.builtAt]: (/* @__PURE__ */ new Date()).toISOString(),
851
+ [META_KEYS.sourceDir]: sourceDir,
852
+ [META_KEYS.fileCount]: String(fileCount),
853
+ [META_KEYS.driver]: "better-sqlite3"
854
+ };
855
+ }
856
+
857
+ // packages/index-sqlite/src/builder.ts
858
+ var DEFAULT_MAX_RUNS = 1e4;
859
+ function resolveIndexDbPath(traceDir, dbPath) {
860
+ if (dbPath && dbPath.trim() !== "") return path.resolve(dbPath);
861
+ return path.join(path.resolve(traceDir), INDEX_DB_FILENAME);
862
+ }
863
+ function str(value) {
864
+ return typeof value === "string" && value !== "" ? value : null;
865
+ }
866
+ function num(value) {
867
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
868
+ }
869
+ function deriveRun(file, mtimeMs, events) {
870
+ const started = events.find((e) => e.event === "run_started");
871
+ if (!started || started.event !== "run_started") return null;
872
+ const completed = events.find((e) => e.event === "run_completed");
873
+ const metadata = started.metadata ?? {};
874
+ const run = {
875
+ runId: started.runId,
876
+ file,
877
+ mtimeMs,
878
+ name: str(started.name),
879
+ status: completed && completed.event === "run_completed" ? completed.status : null,
880
+ startedAt: num(started.startTime),
881
+ endedAt: completed && completed.event === "run_completed" ? num(completed.endTime) : null,
882
+ durationMs: completed && completed.event === "run_completed" ? num(completed.durationMs) : null,
883
+ sessionId: str(metadata.sessionId),
884
+ groupId: str(metadata.groupId),
885
+ correlationId: str(metadata.correlationId)
886
+ };
887
+ const stepStarts = /* @__PURE__ */ new Map();
888
+ const steps = [];
889
+ const errors = [];
890
+ if (completed && completed.event === "run_completed" && completed.error) {
891
+ errors.push({
892
+ stepId: null,
893
+ message: str(completed.error.message),
894
+ code: str(completed.error.code)
895
+ });
896
+ }
897
+ for (const event of events) {
898
+ if (event.event === "step_started") {
899
+ stepStarts.set(event.stepId, event);
900
+ }
901
+ }
902
+ for (const event of events) {
903
+ if (event.event !== "step_completed") continue;
904
+ const start = stepStarts.get(event.stepId);
905
+ const meta2 = start?.metadata ?? {};
906
+ steps.push({
907
+ runId: run.runId,
908
+ stepId: event.stepId,
909
+ kind: start ? str(start.type) : null,
910
+ name: start ? str(start.name) : null,
911
+ status: event.status,
912
+ durationMs: num(event.durationMs),
913
+ toolName: str(meta2.toolName),
914
+ model: str(meta2.model),
915
+ parentId: start ? str(start.parentId) : null
916
+ });
917
+ if (event.error) {
918
+ errors.push({
919
+ stepId: event.stepId,
920
+ message: str(event.error.message),
921
+ code: str(event.error.code)
922
+ });
923
+ }
924
+ }
925
+ return { run, steps, errors };
926
+ }
927
+ async function buildIndex(options = {}) {
928
+ const traceDir = resolveTraceDir({ dir: options.traceDir });
929
+ const dbPath = resolveIndexDbPath(traceDir, options.dbPath);
930
+ const maxRuns = options.maxRuns ?? DEFAULT_MAX_RUNS;
931
+ const warnings = [];
932
+ const td = new TraceDirectory({ dir: traceDir });
933
+ const files = await td.list();
934
+ if (files.length > maxRuns) {
935
+ warnings.push(
936
+ `index.truncated: ${files.length} trace files present; indexing first ${maxRuns}`
937
+ );
938
+ }
939
+ const slice = files.slice(0, maxRuns);
940
+ const derived = [];
941
+ for (const file of slice) {
942
+ try {
943
+ const raw = await readFile(td.getPath(file), "utf-8");
944
+ const parsed = parseTraceJsonl(raw, { validate: validateEvent });
945
+ const stats = await td.getFileStats(file);
946
+ const one = deriveRun(file, stats.mtimeMs, parsed.events);
947
+ if (one) derived.push(one);
948
+ else warnings.push(`index.skipped: ${file} has no run_started event`);
949
+ } catch {
950
+ warnings.push(`index.unreadable: ${file}`);
951
+ }
952
+ }
953
+ await mkdir(path.dirname(dbPath), { recursive: true });
954
+ await rm(dbPath, { force: true });
955
+ const db = new import_better_sqlite3.default(dbPath);
956
+ let runCount = 0;
957
+ let stepCount = 0;
958
+ let errorCount = 0;
959
+ try {
960
+ db.pragma("journal_mode = WAL");
961
+ db.exec(INDEX_SCHEMA_SQL);
962
+ const insertRun = db.prepare(
963
+ `INSERT INTO runs (run_id, file, mtime_ms, name, status, started_at, ended_at, duration_ms, session_id, group_id, correlation_id)
964
+ VALUES (@runId, @file, @mtimeMs, @name, @status, @startedAt, @endedAt, @durationMs, @sessionId, @groupId, @correlationId)`
965
+ );
966
+ const insertStep = db.prepare(
967
+ `INSERT INTO steps (run_id, step_id, kind, name, status, duration_ms, tool_name, model, parent_id)
968
+ VALUES (@runId, @stepId, @kind, @name, @status, @durationMs, @toolName, @model, @parentId)`
969
+ );
970
+ const insertError = db.prepare(
971
+ `INSERT INTO errors (run_id, step_id, message, code) VALUES (@runId, @stepId, @message, @code)`
972
+ );
973
+ const insertMeta = db.prepare(`INSERT INTO meta (key, value) VALUES (?, ?)`);
974
+ const write = db.transaction((items) => {
975
+ const seen = /* @__PURE__ */ new Set();
976
+ for (const item of items) {
977
+ if (seen.has(item.run.runId)) continue;
978
+ seen.add(item.run.runId);
979
+ insertRun.run(item.run);
980
+ runCount += 1;
981
+ for (const step of item.steps) {
982
+ insertStep.run(step);
983
+ stepCount += 1;
984
+ }
985
+ for (const err of item.errors) {
986
+ insertError.run({ runId: item.run.runId, ...err });
987
+ errorCount += 1;
988
+ }
989
+ }
990
+ db.exec(DERIVE_SESSIONS_SQL);
991
+ for (const [key, value] of Object.entries(metaDefaults(traceDir, slice.length))) {
992
+ insertMeta.run(key, value);
993
+ }
994
+ });
995
+ write(derived);
996
+ } finally {
997
+ db.close();
998
+ }
999
+ const builtAtRow = readMetaValue(dbPath, META_KEYS.builtAt);
1000
+ return {
1001
+ dbPath,
1002
+ traceDir,
1003
+ runs: runCount,
1004
+ steps: stepCount,
1005
+ errors: errorCount,
1006
+ builtAt: builtAtRow ?? (/* @__PURE__ */ new Date()).toISOString(),
1007
+ warnings
1008
+ };
1009
+ }
1010
+ var rebuildIndex = buildIndex;
1011
+ function readMetaValue(dbPath, key) {
1012
+ try {
1013
+ const db = new import_better_sqlite3.default(dbPath, { readonly: true, fileMustExist: true });
1014
+ try {
1015
+ const row = db.prepare(`SELECT value FROM meta WHERE key = ?`).get(key);
1016
+ return row?.value ?? null;
1017
+ } finally {
1018
+ db.close();
1019
+ }
1020
+ } catch {
1021
+ return null;
1022
+ }
1023
+ }
1024
+ async function cleanIndex(dbPath) {
1025
+ await rm(dbPath, { force: true });
1026
+ await rm(`${dbPath}-wal`, { force: true });
1027
+ await rm(`${dbPath}-shm`, { force: true });
1028
+ }
1029
+
1030
+ // packages/index-sqlite/src/query.ts
1031
+ var import_better_sqlite32 = __toESM(require_lib(), 1);
1032
+ function openHealthy(dbPath) {
1033
+ if (!existsSync(dbPath)) return null;
1034
+ try {
1035
+ const db = new import_better_sqlite32.default(dbPath, { readonly: true, fileMustExist: true });
1036
+ try {
1037
+ const result = db.pragma("integrity_check", { simple: true });
1038
+ if (result !== "ok") {
1039
+ db.close();
1040
+ return null;
1041
+ }
1042
+ db.prepare(`SELECT 1 FROM meta LIMIT 1`).get();
1043
+ db.prepare(`SELECT 1 FROM runs LIMIT 1`).get();
1044
+ return { db, healthy: true };
1045
+ } catch {
1046
+ db.close();
1047
+ return null;
1048
+ }
1049
+ } catch {
1050
+ return null;
1051
+ }
1052
+ }
1053
+ function meta(db, key) {
1054
+ const row = db.prepare(`SELECT value FROM meta WHERE key = ?`).get(key);
1055
+ return row?.value ?? null;
1056
+ }
1057
+ function indexStatus(dbPath) {
1058
+ const opened = openHealthy(dbPath);
1059
+ if (!opened) {
1060
+ return {
1061
+ dbPath,
1062
+ exists: existsSync(dbPath),
1063
+ healthy: false,
1064
+ builtAt: null,
1065
+ sourceDir: null,
1066
+ schemaVersion: null,
1067
+ runs: 0,
1068
+ steps: 0
1069
+ };
1070
+ }
1071
+ const { db } = opened;
1072
+ try {
1073
+ const runs = db.prepare(`SELECT COUNT(*) AS c FROM runs`).get().c;
1074
+ const steps = db.prepare(`SELECT COUNT(*) AS c FROM steps`).get().c;
1075
+ return {
1076
+ dbPath,
1077
+ exists: true,
1078
+ healthy: true,
1079
+ builtAt: meta(db, META_KEYS.builtAt),
1080
+ sourceDir: meta(db, META_KEYS.sourceDir),
1081
+ schemaVersion: meta(db, META_KEYS.schemaVersion),
1082
+ runs,
1083
+ steps
1084
+ };
1085
+ } finally {
1086
+ db.close();
1087
+ }
1088
+ }
1089
+ function isIndexStale(dbPath, newestTraceMtimeMs) {
1090
+ const opened = openHealthy(dbPath);
1091
+ if (!opened) return true;
1092
+ try {
1093
+ const builtAt = meta(opened.db, META_KEYS.builtAt);
1094
+ if (!builtAt) return true;
1095
+ const builtMs = Date.parse(builtAt);
1096
+ if (Number.isNaN(builtMs)) return true;
1097
+ return newestTraceMtimeMs > builtMs;
1098
+ } finally {
1099
+ opened.db.close();
1100
+ }
1101
+ }
1102
+ function mapRow(row) {
1103
+ return {
1104
+ runId: row.run_id,
1105
+ file: row.file,
1106
+ mtimeMs: row.mtime_ms,
1107
+ name: row.name ?? null,
1108
+ status: row.status ?? null,
1109
+ startedAt: row.started_at ?? null,
1110
+ endedAt: row.ended_at ?? null,
1111
+ durationMs: row.duration_ms ?? null,
1112
+ sessionId: row.session_id ?? null,
1113
+ groupId: row.group_id ?? null,
1114
+ correlationId: row.correlation_id ?? null
1115
+ };
1116
+ }
1117
+ function queryRuns(dbPath, query = {}) {
1118
+ const opened = openHealthy(dbPath);
1119
+ if (!opened) return [];
1120
+ const { db } = opened;
1121
+ try {
1122
+ const where = [];
1123
+ const params = {};
1124
+ if (query.status) {
1125
+ where.push(`r.status = @status`);
1126
+ params.status = query.status;
1127
+ }
1128
+ if (query.sessionId) {
1129
+ where.push(`r.session_id = @sessionId`);
1130
+ params.sessionId = query.sessionId;
1131
+ }
1132
+ if (query.name) {
1133
+ where.push(`LOWER(r.name) LIKE @name`);
1134
+ params.name = `%${query.name.toLowerCase()}%`;
1135
+ }
1136
+ if (query.kind) {
1137
+ where.push(`EXISTS (SELECT 1 FROM steps s WHERE s.run_id = r.run_id AND s.kind = @kind)`);
1138
+ params.kind = query.kind;
1139
+ }
1140
+ if (query.tool) {
1141
+ where.push(
1142
+ `EXISTS (SELECT 1 FROM steps s WHERE s.run_id = r.run_id AND LOWER(s.tool_name) LIKE @tool)`
1143
+ );
1144
+ params.tool = `%${query.tool.toLowerCase()}%`;
1145
+ }
1146
+ const limit = Number.isInteger(query.limit) && query.limit > 0 ? query.limit : 100;
1147
+ const sql = `SELECT r.* FROM runs r ${where.length ? `WHERE ${where.join(" AND ")}` : ""} ORDER BY r.started_at DESC LIMIT ${limit}`;
1148
+ const rows = db.prepare(sql).all(params);
1149
+ return rows.map(mapRow);
1150
+ } finally {
1151
+ db.close();
1152
+ }
1153
+ }
1154
+
1155
+ export { INDEX_DB_FILENAME, INDEX_SCHEMA_VERSION, buildIndex, cleanIndex, indexStatus, isIndexStale, queryRuns, rebuildIndex, resolveIndexDbPath };
1156
+ //# sourceMappingURL=src-VQT7QLGV.mjs.map
1157
+ //# sourceMappingURL=src-VQT7QLGV.mjs.map