crispy-recall 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.
@@ -0,0 +1,2785 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __commonJS = (cb, mod) => function __require() {
13
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
14
+ };
15
+ var __export = (target, all) => {
16
+ for (var name in all)
17
+ __defProp(target, name, { get: all[name], enumerable: true });
18
+ };
19
+ var __copyProps = (to, from, except, desc) => {
20
+ if (from && typeof from === "object" || typeof from === "function") {
21
+ for (let key of __getOwnPropNames(from))
22
+ if (!__hasOwnProp.call(to, key) && key !== except)
23
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
24
+ }
25
+ return to;
26
+ };
27
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
28
+ // If the importer is in node compatibility mode or this is not an ESM
29
+ // file that has been converted to a CommonJS file using a Babel-
30
+ // compatible transform (i.e. "__esModule" has not been set), then set
31
+ // "default" to the CommonJS "module.exports" for node compatibility.
32
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
33
+ mod
34
+ ));
35
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
+
37
+ // src/log.ts
38
+ function log(entry) {
39
+ if (LEVEL_ORDER[entry.level] < _threshold)
40
+ return;
41
+ const line = `[${entry.level}] ${entry.source}: ${entry.summary}`;
42
+ if (entry.data !== void 0) {
43
+ try {
44
+ process.stderr.write(`${line} ${JSON.stringify(entry.data)}
45
+ `);
46
+ } catch {
47
+ process.stderr.write(`${line}
48
+ `);
49
+ }
50
+ } else {
51
+ process.stderr.write(`${line}
52
+ `);
53
+ }
54
+ }
55
+ var LEVEL_ORDER, _rawEnvLevel, _thresholdLevel, _threshold;
56
+ var init_log = __esm({
57
+ "src/log.ts"() {
58
+ "use strict";
59
+ LEVEL_ORDER = {
60
+ debug: 0,
61
+ info: 1,
62
+ warn: 2,
63
+ error: 3
64
+ };
65
+ _rawEnvLevel = process.env["RECALL_LOG_LEVEL"]?.toLowerCase();
66
+ _thresholdLevel = _rawEnvLevel === "debug" || _rawEnvLevel === "info" || _rawEnvLevel === "warn" || _rawEnvLevel === "error" ? _rawEnvLevel : "info";
67
+ _threshold = LEVEL_ORDER[_thresholdLevel];
68
+ }
69
+ });
70
+
71
+ // node_modules/node-sqlite3-wasm/dist/node-sqlite3-wasm.js
72
+ var require_node_sqlite3_wasm = __commonJS({
73
+ "node_modules/node-sqlite3-wasm/dist/node-sqlite3-wasm.js"(exports2, module2) {
74
+ var Module = typeof Module != "undefined" ? Module : {};
75
+ var ENVIRONMENT_IS_NODE = true;
76
+ var INT32_MIN = -2147483648;
77
+ var INT32_MAX = 2147483647;
78
+ var NULL = 0;
79
+ var SQLITE_OK = 0;
80
+ var SQLITE_ROW = 100;
81
+ var SQLITE_DONE = 101;
82
+ var SQLITE_INTEGER = 1;
83
+ var SQLITE_FLOAT = 2;
84
+ var SQLITE_TEXT = 3;
85
+ var SQLITE_BLOB = 4;
86
+ var SQLITE_NULL = 5;
87
+ var SQLITE_UTF8 = 1;
88
+ var SQLITE_TRANSIENT = -1;
89
+ var SQLITE_DETERMINISTIC = 2048;
90
+ var temp;
91
+ var sqlite3 = {};
92
+ Module.onRuntimeInitialized = () => {
93
+ temp = stackAlloc(4);
94
+ const v = null;
95
+ const n = "number";
96
+ const s = "string";
97
+ const n1 = [n];
98
+ const n2 = [n, ...n1];
99
+ const n3 = [n, ...n2];
100
+ const n4 = [n, ...n3];
101
+ const n5 = [n, ...n4];
102
+ const signatures = { open_v2: [n, [s, n, n, s]], exec: [n, n5], errmsg: [s, n1], prepare_v2: [n, n5], close_v2: [n, n1], finalize: [n, n1], reset: [n, n1], clear_bindings: [n, n1], bind_int: [n, n3], bind_int64: [n, n3], bind_double: [n, n3], bind_text: [n, n5], bind_blob: [n, n5], bind_blob64: [n, n5], bind_null: [n, n2], bind_parameter_index: [n, [n, s]], step: [n, n1], column_int64: [n, n2], column_double: [n, n2], column_text: [s, n2], column_blob: [n, n2], column_type: [n, n2], column_name: [s, n2], column_count: [n, n1], column_bytes: [n, n2], last_insert_rowid: [n, n1], changes: [n, n1], create_function_v2: [n, [n, s, n, n, n, n, n, n, n]], value_type: [n, n1], value_text: [s, n1], value_blob: [n, n1], value_int64: [n, n1], value_double: [n, n1], value_bytes: [n, n1], result_double: [v, n2], result_null: [v, n1], result_text: [v, n4], result_blob: [v, n4], result_blob64: [v, n4], result_int: [v, n2], result_int64: [v, n2], result_error: [v, n3], column_table_name: [s, n2], get_autocommit: [n, n1] };
103
+ for (const [name, sig] of Object.entries(signatures)) {
104
+ sqlite3[name] = cwrap(`sqlite3_${name}`, sig[0], sig[1]);
105
+ }
106
+ };
107
+ var SQLite3Error = class extends Error {
108
+ constructor(message) {
109
+ super(message);
110
+ this.name = "SQLite3Error";
111
+ }
112
+ };
113
+ function arrayToHeap(array) {
114
+ const ptr = _malloc(array.byteLength);
115
+ HEAPU8.set(array, ptr);
116
+ return ptr;
117
+ }
118
+ function stringToHeap(str) {
119
+ const size = lengthBytesUTF8(str) + 1;
120
+ const ptr = _malloc(size);
121
+ stringToUTF8(str, ptr, size);
122
+ return ptr;
123
+ }
124
+ function toNumberOrNot(bigInt) {
125
+ if (bigInt >= Number.MIN_SAFE_INTEGER && bigInt <= Number.MAX_SAFE_INTEGER) {
126
+ return Number(bigInt);
127
+ }
128
+ return bigInt;
129
+ }
130
+ function parseFunctionArguments(argc, argv) {
131
+ const args = [];
132
+ for (let i = 0; i < argc; i++) {
133
+ const ptr = getValue(argv + 4 * i, "i32");
134
+ const type = sqlite3.value_type(ptr);
135
+ let arg;
136
+ switch (type) {
137
+ case SQLITE_INTEGER:
138
+ arg = toNumberOrNot(sqlite3.value_int64(ptr));
139
+ break;
140
+ case SQLITE_FLOAT:
141
+ arg = sqlite3.value_double(ptr);
142
+ break;
143
+ case SQLITE_TEXT:
144
+ arg = sqlite3.value_text(ptr);
145
+ break;
146
+ case SQLITE_BLOB:
147
+ const p = sqlite3.value_blob(ptr);
148
+ if (p != NULL) {
149
+ arg = HEAPU8.slice(p, p + sqlite3.value_bytes(ptr));
150
+ } else {
151
+ arg = new Uint8Array();
152
+ }
153
+ break;
154
+ case SQLITE_NULL:
155
+ arg = null;
156
+ break;
157
+ }
158
+ args.push(arg);
159
+ }
160
+ return args;
161
+ }
162
+ function setFunctionResult(cx, result) {
163
+ switch (typeof result) {
164
+ case "boolean":
165
+ sqlite3.result_int(cx, result ? 1 : 0);
166
+ break;
167
+ case "number":
168
+ if (Number.isSafeInteger(result)) {
169
+ if (result >= INT32_MIN && result <= INT32_MAX) {
170
+ sqlite3.result_int(cx, result);
171
+ } else {
172
+ sqlite3.result_int64(cx, BigInt(result));
173
+ }
174
+ } else {
175
+ sqlite3.result_double(cx, result);
176
+ }
177
+ break;
178
+ case "bigint":
179
+ sqlite3.result_int64(cx, result);
180
+ break;
181
+ case "string":
182
+ const tempPtr = stringToHeap(result);
183
+ sqlite3.result_text(cx, tempPtr, -1, SQLITE_TRANSIENT);
184
+ _free(tempPtr);
185
+ break;
186
+ case "object":
187
+ if (result === null) {
188
+ sqlite3.result_null(cx);
189
+ } else if (result instanceof Uint8Array) {
190
+ const tempPtr2 = arrayToHeap(result);
191
+ if (result.byteLength <= INT32_MAX) {
192
+ sqlite3.result_blob(cx, tempPtr2, result.byteLength, SQLITE_TRANSIENT);
193
+ } else {
194
+ sqlite3.result_blob64(cx, tempPtr2, BigInt(result.byteLength), SQLITE_TRANSIENT);
195
+ }
196
+ _free(tempPtr2);
197
+ } else {
198
+ throw new SQLite3Error(`Unsupported type for function result: "${typeof result}"`);
199
+ }
200
+ break;
201
+ default:
202
+ throw new SQLite3Error(`Unsupported type for function result: "${typeof result}"`);
203
+ }
204
+ }
205
+ var Database = class {
206
+ constructor(filename, { fileMustExist = false, readOnly = false } = {}) {
207
+ let flags;
208
+ if (readOnly) {
209
+ flags = SQLITE_OPEN_READONLY;
210
+ } else {
211
+ flags = SQLITE_OPEN_READWRITE;
212
+ if (!fileMustExist)
213
+ flags |= SQLITE_OPEN_CREATE;
214
+ }
215
+ const rc = sqlite3.open_v2(filename, temp, flags, NULL);
216
+ this._ptr = getValue(temp, "i32");
217
+ if (rc !== SQLITE_OK) {
218
+ if (this._ptr !== NULL)
219
+ sqlite3.close_v2(this._ptr);
220
+ throw new SQLite3Error(`Could not open the database "${filename}"`);
221
+ }
222
+ this._functions = /* @__PURE__ */ new Map();
223
+ }
224
+ get isOpen() {
225
+ return this._ptr !== null;
226
+ }
227
+ get inTransaction() {
228
+ this._assertOpen();
229
+ return sqlite3.get_autocommit(this._ptr) === 0;
230
+ }
231
+ close() {
232
+ this._assertOpen();
233
+ for (const func of this._functions.values())
234
+ removeFunction(func);
235
+ this._functions.clear();
236
+ this._handleError(sqlite3.close_v2(this._ptr));
237
+ this._ptr = null;
238
+ }
239
+ function(name, func, { deterministic = false } = {}) {
240
+ this._assertOpen();
241
+ function wrappedFunc(cx, argc, argv) {
242
+ const args = parseFunctionArguments(argc, argv);
243
+ let result;
244
+ try {
245
+ result = func.apply(null, args);
246
+ } catch (err2) {
247
+ const tempPtr = stringToHeap(err2.toString());
248
+ sqlite3.result_error(cx, tempPtr, -1);
249
+ _free(tempPtr);
250
+ return;
251
+ }
252
+ setFunctionResult(cx, result);
253
+ }
254
+ if (this._functions.has(name)) {
255
+ removeFunction(this._functions.get(name));
256
+ this._functions.delete(name);
257
+ }
258
+ const funcPtr = addFunction(wrappedFunc, "viii");
259
+ this._functions.set(name, funcPtr);
260
+ let eTextRep = SQLITE_UTF8;
261
+ if (deterministic)
262
+ eTextRep |= SQLITE_DETERMINISTIC;
263
+ this._handleError(sqlite3.create_function_v2(this._ptr, name, func.length, eTextRep, NULL, funcPtr, NULL, NULL, NULL));
264
+ return this;
265
+ }
266
+ exec(sql) {
267
+ this._assertOpen();
268
+ const tempPtr = stringToHeap(sql);
269
+ try {
270
+ this._handleError(sqlite3.exec(this._ptr, tempPtr, NULL, NULL, NULL));
271
+ } finally {
272
+ _free(tempPtr);
273
+ }
274
+ }
275
+ prepare(sql) {
276
+ this._assertOpen();
277
+ return new Statement(this, sql);
278
+ }
279
+ run(sql, values) {
280
+ const stmt = this.prepare(sql);
281
+ try {
282
+ return stmt.run(values);
283
+ } finally {
284
+ stmt.finalize();
285
+ }
286
+ }
287
+ all(sql, values, { expand = false } = {}) {
288
+ return this._query(sql, values, false, expand);
289
+ }
290
+ get(sql, values, { expand = false } = {}) {
291
+ return this._query(sql, values, true, expand);
292
+ }
293
+ _query(sql, values, single, expand) {
294
+ const stmt = this.prepare(sql);
295
+ try {
296
+ if (single) {
297
+ return stmt.get(values, { expand });
298
+ } else {
299
+ return stmt.all(values, { expand });
300
+ }
301
+ } finally {
302
+ stmt.finalize();
303
+ }
304
+ }
305
+ _assertOpen() {
306
+ if (!this.isOpen)
307
+ throw new SQLite3Error("Database already closed");
308
+ }
309
+ _handleError(returnCode) {
310
+ if (returnCode !== SQLITE_OK)
311
+ throw new SQLite3Error(sqlite3.errmsg(this._ptr));
312
+ }
313
+ };
314
+ var Statement = class {
315
+ constructor(db3, sql) {
316
+ const tempPtr = stringToHeap(sql);
317
+ try {
318
+ db3._handleError(sqlite3.prepare_v2(db3._ptr, tempPtr, -1, temp, NULL));
319
+ } finally {
320
+ _free(tempPtr);
321
+ }
322
+ this._ptr = getValue(temp, "i32");
323
+ if (this._ptr === NULL)
324
+ throw new SQLite3Error("Nothing to prepare");
325
+ this._db = db3;
326
+ }
327
+ get database() {
328
+ return this._db;
329
+ }
330
+ get isFinalized() {
331
+ return this._ptr === null;
332
+ }
333
+ run(values) {
334
+ this._assertReady();
335
+ this._bind(values);
336
+ this._step();
337
+ return { changes: sqlite3.changes(this._db._ptr), lastInsertRowid: toNumberOrNot(sqlite3.last_insert_rowid(this._db._ptr)) };
338
+ }
339
+ iterate(values, { expand = false } = {}) {
340
+ return this._queryRows(values, expand);
341
+ }
342
+ all(values, { expand = false } = {}) {
343
+ return Array.from(this.iterate(values, { expand }));
344
+ }
345
+ get(values, { expand = false } = {}) {
346
+ const result = this._queryRows(values, expand).next();
347
+ return result.done ? null : result.value;
348
+ }
349
+ finalize() {
350
+ if (this.isFinalized)
351
+ throw new SQLite3Error("Statement already finalized");
352
+ try {
353
+ this._db._handleError(sqlite3.finalize(this._ptr));
354
+ } finally {
355
+ this._ptr = null;
356
+ }
357
+ }
358
+ _reset() {
359
+ return sqlite3.clear_bindings(this._ptr) === SQLITE_OK && sqlite3.reset(this._ptr) === SQLITE_OK;
360
+ }
361
+ *_queryRows(values, expand) {
362
+ this._assertReady();
363
+ this._bind(values);
364
+ const columns = this._getColumnNames();
365
+ while (this._step())
366
+ yield this._getRow(columns, expand);
367
+ }
368
+ _bind(values) {
369
+ if (!this._reset()) {
370
+ throw new SQLite3Error("Could not reset statement prior to binding new values");
371
+ }
372
+ if (Array.isArray(values)) {
373
+ this._bindArray(values);
374
+ } else if (values != null && typeof values === "object") {
375
+ this._bindObject(values);
376
+ } else if (typeof values !== "undefined") {
377
+ this._bindValue(values, 1);
378
+ }
379
+ }
380
+ _step() {
381
+ const ret = sqlite3.step(this._ptr);
382
+ switch (ret) {
383
+ case SQLITE_ROW:
384
+ return true;
385
+ case SQLITE_DONE:
386
+ return false;
387
+ default:
388
+ this._db._handleError(ret);
389
+ }
390
+ }
391
+ _getRow(columns, expand) {
392
+ const row = {};
393
+ for (let i = 0; i < columns.length; i++) {
394
+ let v;
395
+ const colType = sqlite3.column_type(this._ptr, i);
396
+ switch (colType) {
397
+ case SQLITE_INTEGER:
398
+ v = toNumberOrNot(sqlite3.column_int64(this._ptr, i));
399
+ break;
400
+ case SQLITE_FLOAT:
401
+ v = sqlite3.column_double(this._ptr, i);
402
+ break;
403
+ case SQLITE_TEXT:
404
+ v = sqlite3.column_text(this._ptr, i);
405
+ break;
406
+ case SQLITE_BLOB:
407
+ const p = sqlite3.column_blob(this._ptr, i);
408
+ if (p != NULL) {
409
+ v = HEAPU8.slice(p, p + sqlite3.column_bytes(this._ptr, i));
410
+ } else {
411
+ v = new Uint8Array();
412
+ }
413
+ break;
414
+ case SQLITE_NULL:
415
+ v = null;
416
+ break;
417
+ }
418
+ const column = columns[i];
419
+ if (expand) {
420
+ let table = sqlite3.column_table_name(this._ptr, i);
421
+ table = table === "" ? "$" : table;
422
+ if (Object.hasOwn(row, table)) {
423
+ row[table][column] = v;
424
+ } else {
425
+ row[table] = { [column]: v };
426
+ }
427
+ } else {
428
+ row[column] = v;
429
+ }
430
+ }
431
+ return row;
432
+ }
433
+ _getColumnNames() {
434
+ const names = [];
435
+ const columns = sqlite3.column_count(this._ptr);
436
+ for (let i = 0; i < columns; i++)
437
+ names.push(sqlite3.column_name(this._ptr, i));
438
+ return names;
439
+ }
440
+ _bindArray(values) {
441
+ for (let i = 0; i < values.length; i++)
442
+ this._bindValue(values[i], i + 1);
443
+ }
444
+ _bindObject(values) {
445
+ for (const [param, value] of Object.entries(values)) {
446
+ const i = sqlite3.bind_parameter_index(this._ptr, param);
447
+ if (i === 0)
448
+ throw new SQLite3Error(`Unknown binding parameter: "${param}"`);
449
+ this._bindValue(value, i);
450
+ }
451
+ }
452
+ _bindValue(value, position) {
453
+ let ret;
454
+ switch (typeof value) {
455
+ case "string":
456
+ const tempPtr = stringToHeap(value);
457
+ ret = sqlite3.bind_text(this._ptr, position, tempPtr, -1, SQLITE_TRANSIENT);
458
+ _free(tempPtr);
459
+ break;
460
+ case "number":
461
+ if (Number.isSafeInteger(value)) {
462
+ if (value >= INT32_MIN && value <= INT32_MAX) {
463
+ ret = sqlite3.bind_int(this._ptr, position, value);
464
+ } else {
465
+ ret = sqlite3.bind_int64(this._ptr, position, BigInt(value));
466
+ }
467
+ } else {
468
+ ret = sqlite3.bind_double(this._ptr, position, value);
469
+ }
470
+ break;
471
+ case "bigint":
472
+ ret = sqlite3.bind_int64(this._ptr, position, value);
473
+ break;
474
+ case "boolean":
475
+ ret = sqlite3.bind_int(this._ptr, position, value ? 1 : 0);
476
+ break;
477
+ case "object":
478
+ if (value === null) {
479
+ ret = sqlite3.bind_null(this._ptr, position);
480
+ } else if (value instanceof Uint8Array) {
481
+ const tempPtr2 = arrayToHeap(value);
482
+ if (value.byteLength <= INT32_MAX) {
483
+ ret = sqlite3.bind_blob(this._ptr, position, tempPtr2, value.byteLength, SQLITE_TRANSIENT);
484
+ } else {
485
+ ret = sqlite3.bind_blob64(this._ptr, position, tempPtr2, BigInt(value.byteLength), SQLITE_TRANSIENT);
486
+ }
487
+ _free(tempPtr2);
488
+ } else {
489
+ throw new SQLite3Error(`Unsupported type for binding: "${typeof value}"`);
490
+ }
491
+ break;
492
+ default:
493
+ throw new SQLite3Error(`Unsupported type for binding: "${typeof value}"`);
494
+ }
495
+ if (ret !== SQLITE_OK)
496
+ this._db._handleError(ret);
497
+ }
498
+ _assertReady() {
499
+ if (this.isFinalized)
500
+ throw new SQLite3Error("Statement already finalized");
501
+ if (!this._db.isOpen)
502
+ throw new SQLite3Error("Database is closed");
503
+ }
504
+ };
505
+ Module.Database = Database;
506
+ Module.SQLite3Error = SQLite3Error;
507
+ var path2 = require("node:path");
508
+ var crypto = require("node:crypto");
509
+ var SQLITE_CANTOPEN = 14;
510
+ var SQLITE_IOERR_READ = 266;
511
+ var SQLITE_IOERR_SHORT_READ = 522;
512
+ var SQLITE_IOERR_FSYNC = 1034;
513
+ var SQLITE_IOERR_WRITE = 778;
514
+ var SQLITE_IOERR_DELETE = 2570;
515
+ var SQLITE_IOERR_CLOSE = 4106;
516
+ var SQLITE_IOERR_TRUNCATE = 1546;
517
+ var SQLITE_IOERR_FSTAT = 1802;
518
+ var SQLITE_IOERR_LOCK = 3850;
519
+ var SQLITE_IOERR_UNLOCK = 2058;
520
+ var SQLITE_OPEN_READONLY = 1;
521
+ var SQLITE_OPEN_READWRITE = 2;
522
+ var SQLITE_OPEN_CREATE = 4;
523
+ var SQLITE_OPEN_EXCLUSIVE = 16;
524
+ var SQLITE_ACCESS_READWRITE = 1;
525
+ var SQLITE_ACCESS_READ = 2;
526
+ var SQLITE_LOCK_NONE = 0;
527
+ var SQLITE_BUSY = 5;
528
+ function _fd(fileInfo) {
529
+ return getValue(fileInfo + 4, "i32");
530
+ }
531
+ function _isLocked(fileInfo) {
532
+ return getValue(fileInfo + 8, "i32") != 0;
533
+ }
534
+ function _setLocked(fileInfo, locked) {
535
+ setValue(fileInfo + 8, locked ? 1 : 0, "i32");
536
+ }
537
+ function _path(fileInfo) {
538
+ return UTF8ToString(getValue(fileInfo + 12, "i32"));
539
+ }
540
+ function _safeInt(bigInt) {
541
+ if (bigInt < Number.MIN_SAFE_INTEGER || bigInt > Number.MAX_SAFE_INTEGER)
542
+ throw 0;
543
+ return Number(bigInt);
544
+ }
545
+ var arguments_ = [];
546
+ var thisProgram = "./this.program";
547
+ var quit_ = (status, toThrow) => {
548
+ throw toThrow;
549
+ };
550
+ var _scriptName;
551
+ if (typeof __filename != "undefined") {
552
+ _scriptName = __filename;
553
+ } else {
554
+ }
555
+ var scriptDirectory = "";
556
+ function locateFile(path3) {
557
+ if (Module["locateFile"]) {
558
+ return Module["locateFile"](path3, scriptDirectory);
559
+ }
560
+ return scriptDirectory + path3;
561
+ }
562
+ var readAsync;
563
+ var readBinary;
564
+ if (ENVIRONMENT_IS_NODE) {
565
+ fs3 = require("node:fs");
566
+ scriptDirectory = __dirname + "/";
567
+ readBinary = (filename) => {
568
+ filename = isFileURI(filename) ? new URL(filename) : filename;
569
+ var ret = fs3.readFileSync(filename);
570
+ return ret;
571
+ };
572
+ readAsync = async (filename, binary = true) => {
573
+ filename = isFileURI(filename) ? new URL(filename) : filename;
574
+ var ret = fs3.readFileSync(filename, binary ? void 0 : "utf8");
575
+ return ret;
576
+ };
577
+ if (process.argv.length > 1) {
578
+ thisProgram = process.argv[1].replace(/\\/g, "/");
579
+ }
580
+ arguments_ = process.argv.slice(2);
581
+ if (typeof module2 != "undefined") {
582
+ module2["exports"] = Module;
583
+ }
584
+ quit_ = (status, toThrow) => {
585
+ process.exitCode = status;
586
+ throw toThrow;
587
+ };
588
+ } else {
589
+ }
590
+ var fs3;
591
+ var out = console.log.bind(console);
592
+ var err = console.error.bind(console);
593
+ var wasmBinary;
594
+ var ABORT = false;
595
+ var EXITSTATUS;
596
+ var isFileURI = (filename) => filename.startsWith("file://");
597
+ var runtimeInitialized = false;
598
+ function updateMemoryViews() {
599
+ var b = wasmMemory.buffer;
600
+ HEAP8 = new Int8Array(b);
601
+ HEAP16 = new Int16Array(b);
602
+ HEAPU8 = new Uint8Array(b);
603
+ HEAPU16 = new Uint16Array(b);
604
+ HEAP32 = new Int32Array(b);
605
+ HEAPU32 = new Uint32Array(b);
606
+ HEAPF32 = new Float32Array(b);
607
+ HEAPF64 = new Float64Array(b);
608
+ HEAP64 = new BigInt64Array(b);
609
+ HEAPU64 = new BigUint64Array(b);
610
+ }
611
+ function preRun() {
612
+ if (Module["preRun"]) {
613
+ if (typeof Module["preRun"] == "function")
614
+ Module["preRun"] = [Module["preRun"]];
615
+ while (Module["preRun"].length) {
616
+ addOnPreRun(Module["preRun"].shift());
617
+ }
618
+ }
619
+ callRuntimeCallbacks(onPreRuns);
620
+ }
621
+ function initRuntime() {
622
+ runtimeInitialized = true;
623
+ wasmExports["z"]();
624
+ }
625
+ function postRun() {
626
+ if (Module["postRun"]) {
627
+ if (typeof Module["postRun"] == "function")
628
+ Module["postRun"] = [Module["postRun"]];
629
+ while (Module["postRun"].length) {
630
+ addOnPostRun(Module["postRun"].shift());
631
+ }
632
+ }
633
+ callRuntimeCallbacks(onPostRuns);
634
+ }
635
+ function abort(what) {
636
+ Module["onAbort"]?.(what);
637
+ what = `Aborted(${what})`;
638
+ err(what);
639
+ ABORT = true;
640
+ what += ". Build with -sASSERTIONS for more info.";
641
+ var e = new WebAssembly.RuntimeError(what);
642
+ throw e;
643
+ }
644
+ var wasmBinaryFile;
645
+ function findWasmBinary() {
646
+ return locateFile("node-sqlite3-wasm.wasm");
647
+ }
648
+ function getBinarySync(file) {
649
+ if (file == wasmBinaryFile && wasmBinary) {
650
+ return new Uint8Array(wasmBinary);
651
+ }
652
+ if (readBinary) {
653
+ return readBinary(file);
654
+ }
655
+ throw 'sync fetching of the wasm failed: you can preload it to Module["wasmBinary"] manually, or emcc.py will do that for you when generating HTML (but not JS)';
656
+ }
657
+ function instantiateSync(file, info) {
658
+ var module3;
659
+ var binary = getBinarySync(file);
660
+ module3 = new WebAssembly.Module(binary);
661
+ var instance = new WebAssembly.Instance(module3, info);
662
+ return [instance, module3];
663
+ }
664
+ function getWasmImports() {
665
+ var imports = { a: wasmImports };
666
+ return imports;
667
+ }
668
+ function createWasm() {
669
+ function receiveInstance(instance, module3) {
670
+ wasmExports = instance.exports;
671
+ assignWasmExports(wasmExports);
672
+ updateMemoryViews();
673
+ return wasmExports;
674
+ }
675
+ var info = getWasmImports();
676
+ if (Module["instantiateWasm"]) {
677
+ return new Promise((resolve, reject) => {
678
+ Module["instantiateWasm"](info, (inst, mod) => {
679
+ resolve(receiveInstance(inst, mod));
680
+ });
681
+ });
682
+ }
683
+ wasmBinaryFile ??= findWasmBinary();
684
+ var result = instantiateSync(wasmBinaryFile, info);
685
+ return receiveInstance(result[0]);
686
+ }
687
+ var ExitStatus = class {
688
+ name = "ExitStatus";
689
+ constructor(status) {
690
+ this.message = `Program terminated with exit(${status})`;
691
+ this.status = status;
692
+ }
693
+ };
694
+ var HEAP16;
695
+ var HEAP32;
696
+ var HEAP64;
697
+ var HEAP8;
698
+ var HEAPF32;
699
+ var HEAPF64;
700
+ var HEAPU16;
701
+ var HEAPU32;
702
+ var HEAPU64;
703
+ var HEAPU8;
704
+ var callRuntimeCallbacks = (callbacks) => {
705
+ while (callbacks.length > 0) {
706
+ callbacks.shift()(Module);
707
+ }
708
+ };
709
+ var onPostRuns = [];
710
+ var addOnPostRun = (cb) => onPostRuns.push(cb);
711
+ var onPreRuns = [];
712
+ var addOnPreRun = (cb) => onPreRuns.push(cb);
713
+ function getValue(ptr, type = "i8") {
714
+ if (type.endsWith("*"))
715
+ type = "*";
716
+ switch (type) {
717
+ case "i1":
718
+ return HEAP8[ptr];
719
+ case "i8":
720
+ return HEAP8[ptr];
721
+ case "i16":
722
+ return HEAP16[ptr >> 1];
723
+ case "i32":
724
+ return HEAP32[ptr >> 2];
725
+ case "i64":
726
+ return HEAP64[ptr >> 3];
727
+ case "float":
728
+ return HEAPF32[ptr >> 2];
729
+ case "double":
730
+ return HEAPF64[ptr >> 3];
731
+ case "*":
732
+ return HEAPU32[ptr >> 2];
733
+ default:
734
+ abort(`invalid type for getValue: ${type}`);
735
+ }
736
+ }
737
+ var noExitRuntime = true;
738
+ function setValue(ptr, value, type = "i8") {
739
+ if (type.endsWith("*"))
740
+ type = "*";
741
+ switch (type) {
742
+ case "i1":
743
+ HEAP8[ptr] = value;
744
+ break;
745
+ case "i8":
746
+ HEAP8[ptr] = value;
747
+ break;
748
+ case "i16":
749
+ HEAP16[ptr >> 1] = value;
750
+ break;
751
+ case "i32":
752
+ HEAP32[ptr >> 2] = value;
753
+ break;
754
+ case "i64":
755
+ HEAP64[ptr >> 3] = BigInt(value);
756
+ break;
757
+ case "float":
758
+ HEAPF32[ptr >> 2] = value;
759
+ break;
760
+ case "double":
761
+ HEAPF64[ptr >> 3] = value;
762
+ break;
763
+ case "*":
764
+ HEAPU32[ptr >> 2] = value;
765
+ break;
766
+ default:
767
+ abort(`invalid type for setValue: ${type}`);
768
+ }
769
+ }
770
+ var stackRestore = (val) => __emscripten_stack_restore(val);
771
+ var stackSave = () => _emscripten_stack_get_current();
772
+ var __abort_js = () => abort("");
773
+ var runtimeKeepaliveCounter = 0;
774
+ var __emscripten_runtime_keepalive_clear = () => {
775
+ noExitRuntime = false;
776
+ runtimeKeepaliveCounter = 0;
777
+ };
778
+ var isLeapYear = (year) => year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
779
+ var MONTH_DAYS_LEAP_CUMULATIVE = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];
780
+ var MONTH_DAYS_REGULAR_CUMULATIVE = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
781
+ var ydayFromDate = (date) => {
782
+ var leap = isLeapYear(date.getFullYear());
783
+ var monthDaysCumulative = leap ? MONTH_DAYS_LEAP_CUMULATIVE : MONTH_DAYS_REGULAR_CUMULATIVE;
784
+ var yday = monthDaysCumulative[date.getMonth()] + date.getDate() - 1;
785
+ return yday;
786
+ };
787
+ var INT53_MAX = 9007199254740992;
788
+ var INT53_MIN = -9007199254740992;
789
+ var bigintToI53Checked = (num) => num < INT53_MIN || num > INT53_MAX ? NaN : Number(num);
790
+ function __localtime_js(time, tmPtr) {
791
+ time = bigintToI53Checked(time);
792
+ var date = new Date(time * 1e3);
793
+ HEAP32[tmPtr >> 2] = date.getSeconds();
794
+ HEAP32[tmPtr + 4 >> 2] = date.getMinutes();
795
+ HEAP32[tmPtr + 8 >> 2] = date.getHours();
796
+ HEAP32[tmPtr + 12 >> 2] = date.getDate();
797
+ HEAP32[tmPtr + 16 >> 2] = date.getMonth();
798
+ HEAP32[tmPtr + 20 >> 2] = date.getFullYear() - 1900;
799
+ HEAP32[tmPtr + 24 >> 2] = date.getDay();
800
+ var yday = ydayFromDate(date) | 0;
801
+ HEAP32[tmPtr + 28 >> 2] = yday;
802
+ HEAP32[tmPtr + 36 >> 2] = -(date.getTimezoneOffset() * 60);
803
+ var start = new Date(date.getFullYear(), 0, 1);
804
+ var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();
805
+ var winterOffset = start.getTimezoneOffset();
806
+ var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset)) | 0;
807
+ HEAP32[tmPtr + 32 >> 2] = dst;
808
+ }
809
+ var timers = {};
810
+ var handleException = (e) => {
811
+ if (e instanceof ExitStatus || e == "unwind") {
812
+ return EXITSTATUS;
813
+ }
814
+ quit_(1, e);
815
+ };
816
+ var keepRuntimeAlive = () => noExitRuntime || runtimeKeepaliveCounter > 0;
817
+ var _proc_exit = (code) => {
818
+ EXITSTATUS = code;
819
+ if (!keepRuntimeAlive()) {
820
+ Module["onExit"]?.(code);
821
+ ABORT = true;
822
+ }
823
+ quit_(code, new ExitStatus(code));
824
+ };
825
+ var exitJS = (status, implicit) => {
826
+ EXITSTATUS = status;
827
+ _proc_exit(status);
828
+ };
829
+ var _exit = exitJS;
830
+ var maybeExit = () => {
831
+ if (!keepRuntimeAlive()) {
832
+ try {
833
+ _exit(EXITSTATUS);
834
+ } catch (e) {
835
+ handleException(e);
836
+ }
837
+ }
838
+ };
839
+ var callUserCallback = (func) => {
840
+ if (ABORT) {
841
+ return;
842
+ }
843
+ try {
844
+ return func();
845
+ } catch (e) {
846
+ handleException(e);
847
+ } finally {
848
+ maybeExit();
849
+ }
850
+ };
851
+ var _emscripten_get_now = () => performance.now();
852
+ var __setitimer_js = (which, timeout_ms) => {
853
+ if (timers[which]) {
854
+ clearTimeout(timers[which].id);
855
+ delete timers[which];
856
+ }
857
+ if (!timeout_ms)
858
+ return 0;
859
+ var id = setTimeout(() => {
860
+ delete timers[which];
861
+ callUserCallback(() => __emscripten_timeout(which, _emscripten_get_now()));
862
+ }, timeout_ms);
863
+ timers[which] = { id, timeout_ms };
864
+ return 0;
865
+ };
866
+ var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {
867
+ if (!(maxBytesToWrite > 0))
868
+ return 0;
869
+ var startIdx = outIdx;
870
+ var endIdx = outIdx + maxBytesToWrite - 1;
871
+ for (var i = 0; i < str.length; ++i) {
872
+ var u = str.codePointAt(i);
873
+ if (u <= 127) {
874
+ if (outIdx >= endIdx)
875
+ break;
876
+ heap[outIdx++] = u;
877
+ } else if (u <= 2047) {
878
+ if (outIdx + 1 >= endIdx)
879
+ break;
880
+ heap[outIdx++] = 192 | u >> 6;
881
+ heap[outIdx++] = 128 | u & 63;
882
+ } else if (u <= 65535) {
883
+ if (outIdx + 2 >= endIdx)
884
+ break;
885
+ heap[outIdx++] = 224 | u >> 12;
886
+ heap[outIdx++] = 128 | u >> 6 & 63;
887
+ heap[outIdx++] = 128 | u & 63;
888
+ } else {
889
+ if (outIdx + 3 >= endIdx)
890
+ break;
891
+ heap[outIdx++] = 240 | u >> 18;
892
+ heap[outIdx++] = 128 | u >> 12 & 63;
893
+ heap[outIdx++] = 128 | u >> 6 & 63;
894
+ heap[outIdx++] = 128 | u & 63;
895
+ i++;
896
+ }
897
+ }
898
+ heap[outIdx] = 0;
899
+ return outIdx - startIdx;
900
+ };
901
+ var stringToUTF8 = (str, outPtr, maxBytesToWrite) => stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);
902
+ var __tzset_js = (timezone, daylight, std_name, dst_name) => {
903
+ var currentYear = (/* @__PURE__ */ new Date()).getFullYear();
904
+ var winter = new Date(currentYear, 0, 1);
905
+ var summer = new Date(currentYear, 6, 1);
906
+ var winterOffset = winter.getTimezoneOffset();
907
+ var summerOffset = summer.getTimezoneOffset();
908
+ var stdTimezoneOffset = Math.max(winterOffset, summerOffset);
909
+ HEAPU32[timezone >> 2] = stdTimezoneOffset * 60;
910
+ HEAP32[daylight >> 2] = Number(winterOffset != summerOffset);
911
+ var extractZone = (timezoneOffset) => {
912
+ var sign = timezoneOffset >= 0 ? "-" : "+";
913
+ var absOffset = Math.abs(timezoneOffset);
914
+ var hours = String(Math.floor(absOffset / 60)).padStart(2, "0");
915
+ var minutes = String(absOffset % 60).padStart(2, "0");
916
+ return `UTC${sign}${hours}${minutes}`;
917
+ };
918
+ var winterName = extractZone(winterOffset);
919
+ var summerName = extractZone(summerOffset);
920
+ if (summerOffset < winterOffset) {
921
+ stringToUTF8(winterName, std_name, 17);
922
+ stringToUTF8(summerName, dst_name, 17);
923
+ } else {
924
+ stringToUTF8(winterName, dst_name, 17);
925
+ stringToUTF8(summerName, std_name, 17);
926
+ }
927
+ };
928
+ var _emscripten_date_now = () => Date.now();
929
+ var getHeapMax = () => 2147483648;
930
+ var alignMemory = (size, alignment) => Math.ceil(size / alignment) * alignment;
931
+ var growMemory = (size) => {
932
+ var oldHeapSize = wasmMemory.buffer.byteLength;
933
+ var pages = (size - oldHeapSize + 65535) / 65536 | 0;
934
+ try {
935
+ wasmMemory.grow(pages);
936
+ updateMemoryViews();
937
+ return 1;
938
+ } catch (e) {
939
+ }
940
+ };
941
+ var _emscripten_resize_heap = (requestedSize) => {
942
+ var oldSize = HEAPU8.length;
943
+ requestedSize >>>= 0;
944
+ var maxHeapSize = getHeapMax();
945
+ if (requestedSize > maxHeapSize) {
946
+ return false;
947
+ }
948
+ for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
949
+ var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);
950
+ overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);
951
+ var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536));
952
+ var replacement = growMemory(newSize);
953
+ if (replacement) {
954
+ return true;
955
+ }
956
+ }
957
+ return false;
958
+ };
959
+ var UTF8Decoder = globalThis.TextDecoder && new TextDecoder();
960
+ var findStringEnd = (heapOrArray, idx, maxBytesToRead, ignoreNul) => {
961
+ var maxIdx = idx + maxBytesToRead;
962
+ if (ignoreNul)
963
+ return maxIdx;
964
+ while (heapOrArray[idx] && !(idx >= maxIdx))
965
+ ++idx;
966
+ return idx;
967
+ };
968
+ var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead, ignoreNul) => {
969
+ var endPtr = findStringEnd(heapOrArray, idx, maxBytesToRead, ignoreNul);
970
+ if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
971
+ return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
972
+ }
973
+ var str = "";
974
+ while (idx < endPtr) {
975
+ var u0 = heapOrArray[idx++];
976
+ if (!(u0 & 128)) {
977
+ str += String.fromCharCode(u0);
978
+ continue;
979
+ }
980
+ var u1 = heapOrArray[idx++] & 63;
981
+ if ((u0 & 224) == 192) {
982
+ str += String.fromCharCode((u0 & 31) << 6 | u1);
983
+ continue;
984
+ }
985
+ var u2 = heapOrArray[idx++] & 63;
986
+ if ((u0 & 240) == 224) {
987
+ u0 = (u0 & 15) << 12 | u1 << 6 | u2;
988
+ } else {
989
+ u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heapOrArray[idx++] & 63;
990
+ }
991
+ if (u0 < 65536) {
992
+ str += String.fromCharCode(u0);
993
+ } else {
994
+ var ch = u0 - 65536;
995
+ str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
996
+ }
997
+ }
998
+ return str;
999
+ };
1000
+ var UTF8ToString = (ptr, maxBytesToRead, ignoreNul) => ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead, ignoreNul) : "";
1001
+ function _nodejsAccess(vfs, filePath, flags, outResult) {
1002
+ let aflags = fs3.constants.F_OK;
1003
+ if (flags == SQLITE_ACCESS_READWRITE)
1004
+ aflags = fs3.constants.R_OK | fs3.constants.W_OK;
1005
+ if (flags == SQLITE_ACCESS_READ)
1006
+ aflags = fs3.constants.R_OK;
1007
+ try {
1008
+ fs3.accessSync(UTF8ToString(filePath), aflags);
1009
+ setValue(outResult, 1, "i32");
1010
+ } catch {
1011
+ setValue(outResult, 0, "i32");
1012
+ }
1013
+ return SQLITE_OK;
1014
+ }
1015
+ function _nodejsCheckReservedLock(fi, outResult) {
1016
+ try {
1017
+ fs3.accessSync(`${_path(fi)}.lock`, fs3.constants.F_OK);
1018
+ setValue(outResult, 1, "i32");
1019
+ } catch {
1020
+ setValue(outResult, 0, "i32");
1021
+ }
1022
+ return SQLITE_OK;
1023
+ }
1024
+ function _nodejsClose(fi) {
1025
+ _nodejsUnlock(fi, SQLITE_LOCK_NONE);
1026
+ try {
1027
+ fs3.closeSync(_fd(fi));
1028
+ } catch {
1029
+ return SQLITE_IOERR_CLOSE;
1030
+ }
1031
+ return SQLITE_OK;
1032
+ }
1033
+ function _nodejsDelete(vfs, filePath, dirSync) {
1034
+ const pathStr = UTF8ToString(filePath);
1035
+ try {
1036
+ fs3.unlinkSync(pathStr);
1037
+ } catch (err2) {
1038
+ if (err2.code != "ENOENT")
1039
+ return SQLITE_IOERR_DELETE;
1040
+ }
1041
+ if (dirSync) {
1042
+ let fd = -1;
1043
+ try {
1044
+ fd = fs3.openSync(path2.dirname(pathStr), "r");
1045
+ fs3.fsyncSync(fd);
1046
+ } catch {
1047
+ return SQLITE_IOERR_FSYNC;
1048
+ } finally {
1049
+ try {
1050
+ fs3.closeSync(fd);
1051
+ } catch {
1052
+ return SQLITE_IOERR_FSYNC;
1053
+ }
1054
+ }
1055
+ }
1056
+ return SQLITE_OK;
1057
+ }
1058
+ function _nodejsFileSize(fi, outSize) {
1059
+ try {
1060
+ setValue(outSize, fs3.fstatSync(_fd(fi)).size, "i64");
1061
+ } catch {
1062
+ return SQLITE_IOERR_FSTAT;
1063
+ }
1064
+ return SQLITE_OK;
1065
+ }
1066
+ function _nodejsFullPathname(vfs, relPath, sizeFullPath, outFullPath) {
1067
+ const full = path2.resolve(UTF8ToString(relPath));
1068
+ stringToUTF8(full, outFullPath, sizeFullPath);
1069
+ return full.length < sizeFullPath ? SQLITE_OK : SQLITE_CANTOPEN;
1070
+ }
1071
+ function _nodejsLock(fi, level) {
1072
+ if (!_isLocked(fi)) {
1073
+ try {
1074
+ fs3.mkdirSync(`${_path(fi)}.lock`);
1075
+ } catch (err2) {
1076
+ return err2.code == "EEXIST" ? SQLITE_BUSY : SQLITE_IOERR_LOCK;
1077
+ }
1078
+ _setLocked(fi, true);
1079
+ }
1080
+ return SQLITE_OK;
1081
+ }
1082
+ function _nodejsRandomness(vfs, bytes, outBuffer) {
1083
+ const buf = HEAPU8.subarray(outBuffer, outBuffer + bytes);
1084
+ crypto.randomFillSync(buf);
1085
+ return bytes;
1086
+ }
1087
+ function _nodejsRead(fi, outBuffer, bytes, offset) {
1088
+ const buf = HEAPU8.subarray(outBuffer, outBuffer + bytes);
1089
+ let bytesRead;
1090
+ try {
1091
+ bytesRead = fs3.readSync(_fd(fi), buf, 0, bytes, offset);
1092
+ } catch {
1093
+ return SQLITE_IOERR_READ;
1094
+ }
1095
+ if (bytesRead == bytes) {
1096
+ return SQLITE_OK;
1097
+ } else if (bytesRead >= 0) {
1098
+ if (bytesRead < bytes) {
1099
+ try {
1100
+ buf.fill(0, bytesRead);
1101
+ } catch {
1102
+ return SQLITE_IOERR_READ;
1103
+ }
1104
+ }
1105
+ return SQLITE_IOERR_SHORT_READ;
1106
+ }
1107
+ return SQLITE_IOERR_READ;
1108
+ }
1109
+ function _nodejsSync(fi, flags) {
1110
+ try {
1111
+ fs3.fsyncSync(_fd(fi));
1112
+ } catch {
1113
+ return SQLITE_IOERR_FSYNC;
1114
+ }
1115
+ return SQLITE_OK;
1116
+ }
1117
+ function _nodejsTruncate(fi, size) {
1118
+ try {
1119
+ fs3.ftruncateSync(_fd(fi), _safeInt(size));
1120
+ } catch {
1121
+ return SQLITE_IOERR_TRUNCATE;
1122
+ }
1123
+ return SQLITE_OK;
1124
+ }
1125
+ function _nodejsUnlock(fi, level) {
1126
+ if (level == SQLITE_LOCK_NONE && _isLocked(fi)) {
1127
+ try {
1128
+ fs3.rmdirSync(`${_path(fi)}.lock`);
1129
+ } catch (err2) {
1130
+ if (err2.code != "ENOENT")
1131
+ return SQLITE_IOERR_UNLOCK;
1132
+ }
1133
+ _setLocked(fi, false);
1134
+ }
1135
+ return SQLITE_OK;
1136
+ }
1137
+ function _nodejsWrite(fi, buffer, bytes, offset) {
1138
+ try {
1139
+ const bytesWritten = fs3.writeSync(_fd(fi), HEAPU8.subarray(buffer, buffer + bytes), 0, bytes, _safeInt(offset));
1140
+ return bytesWritten != bytes ? SQLITE_IOERR_WRITE : SQLITE_OK;
1141
+ } catch {
1142
+ return SQLITE_IOERR_WRITE;
1143
+ }
1144
+ }
1145
+ function _nodejs_max_path_length() {
1146
+ return process.platform == "win32" ? 260 : 4096;
1147
+ }
1148
+ function _nodejs_open(filePath, flags, mode) {
1149
+ let oflags = 0;
1150
+ if (flags & SQLITE_OPEN_EXCLUSIVE)
1151
+ oflags |= fs3.constants.O_EXCL;
1152
+ if (flags & SQLITE_OPEN_CREATE)
1153
+ oflags |= fs3.constants.O_CREAT;
1154
+ if (flags & SQLITE_OPEN_READONLY)
1155
+ oflags |= fs3.constants.O_RDONLY;
1156
+ if (flags & SQLITE_OPEN_READWRITE)
1157
+ oflags |= fs3.constants.O_RDWR;
1158
+ try {
1159
+ return fs3.openSync(UTF8ToString(filePath), oflags, mode);
1160
+ } catch {
1161
+ return -1;
1162
+ }
1163
+ }
1164
+ var getCFunc = (ident) => {
1165
+ var func = Module["_" + ident];
1166
+ return func;
1167
+ };
1168
+ var writeArrayToMemory = (array, buffer) => {
1169
+ HEAP8.set(array, buffer);
1170
+ };
1171
+ var lengthBytesUTF8 = (str) => {
1172
+ var len = 0;
1173
+ for (var i = 0; i < str.length; ++i) {
1174
+ var c = str.charCodeAt(i);
1175
+ if (c <= 127) {
1176
+ len++;
1177
+ } else if (c <= 2047) {
1178
+ len += 2;
1179
+ } else if (c >= 55296 && c <= 57343) {
1180
+ len += 4;
1181
+ ++i;
1182
+ } else {
1183
+ len += 3;
1184
+ }
1185
+ }
1186
+ return len;
1187
+ };
1188
+ var stackAlloc = (sz) => __emscripten_stack_alloc(sz);
1189
+ var stringToUTF8OnStack = (str) => {
1190
+ var size = lengthBytesUTF8(str) + 1;
1191
+ var ret = stackAlloc(size);
1192
+ stringToUTF8(str, ret, size);
1193
+ return ret;
1194
+ };
1195
+ var ccall = (ident, returnType, argTypes, args, opts) => {
1196
+ var toC = { string: (str) => {
1197
+ var ret2 = 0;
1198
+ if (str !== null && str !== void 0 && str !== 0) {
1199
+ ret2 = stringToUTF8OnStack(str);
1200
+ }
1201
+ return ret2;
1202
+ }, array: (arr) => {
1203
+ var ret2 = stackAlloc(arr.length);
1204
+ writeArrayToMemory(arr, ret2);
1205
+ return ret2;
1206
+ } };
1207
+ function convertReturnValue(ret2) {
1208
+ if (returnType === "string") {
1209
+ return UTF8ToString(ret2);
1210
+ }
1211
+ if (returnType === "boolean")
1212
+ return Boolean(ret2);
1213
+ return ret2;
1214
+ }
1215
+ var func = getCFunc(ident);
1216
+ var cArgs = [];
1217
+ var stack = 0;
1218
+ if (args) {
1219
+ for (var i = 0; i < args.length; i++) {
1220
+ var converter = toC[argTypes[i]];
1221
+ if (converter) {
1222
+ if (stack === 0)
1223
+ stack = stackSave();
1224
+ cArgs[i] = converter(args[i]);
1225
+ } else {
1226
+ cArgs[i] = args[i];
1227
+ }
1228
+ }
1229
+ }
1230
+ var ret = func(...cArgs);
1231
+ function onDone(ret2) {
1232
+ if (stack !== 0)
1233
+ stackRestore(stack);
1234
+ return convertReturnValue(ret2);
1235
+ }
1236
+ ret = onDone(ret);
1237
+ return ret;
1238
+ };
1239
+ var cwrap = (ident, returnType, argTypes, opts) => {
1240
+ var numericArgs = !argTypes || argTypes.every((type) => type === "number" || type === "boolean");
1241
+ var numericRet = returnType !== "string";
1242
+ if (numericRet && numericArgs && !opts) {
1243
+ return getCFunc(ident);
1244
+ }
1245
+ return (...args) => ccall(ident, returnType, argTypes, args, opts);
1246
+ };
1247
+ var wasmTableMirror = [];
1248
+ var getWasmTableEntry = (funcPtr) => {
1249
+ var func = wasmTableMirror[funcPtr];
1250
+ if (!func) {
1251
+ wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr);
1252
+ }
1253
+ return func;
1254
+ };
1255
+ var updateTableMap = (offset, count) => {
1256
+ if (functionsInTableMap) {
1257
+ for (var i = offset; i < offset + count; i++) {
1258
+ var item = getWasmTableEntry(i);
1259
+ if (item) {
1260
+ functionsInTableMap.set(item, i);
1261
+ }
1262
+ }
1263
+ }
1264
+ };
1265
+ var functionsInTableMap;
1266
+ var getFunctionAddress = (func) => {
1267
+ if (!functionsInTableMap) {
1268
+ functionsInTableMap = /* @__PURE__ */ new WeakMap();
1269
+ updateTableMap(0, wasmTable.length);
1270
+ }
1271
+ return functionsInTableMap.get(func) || 0;
1272
+ };
1273
+ var freeTableIndexes = [];
1274
+ var getEmptyTableSlot = () => {
1275
+ if (freeTableIndexes.length) {
1276
+ return freeTableIndexes.pop();
1277
+ }
1278
+ return wasmTable["grow"](1);
1279
+ };
1280
+ var setWasmTableEntry = (idx, func) => {
1281
+ wasmTable.set(idx, func);
1282
+ wasmTableMirror[idx] = wasmTable.get(idx);
1283
+ };
1284
+ var uleb128EncodeWithLen = (arr) => {
1285
+ const n = arr.length;
1286
+ return [n % 128 | 128, n >> 7, ...arr];
1287
+ };
1288
+ var wasmTypeCodes = { i: 127, p: 127, j: 126, f: 125, d: 124, e: 111 };
1289
+ var generateTypePack = (types) => uleb128EncodeWithLen(Array.from(types, (type) => {
1290
+ var code = wasmTypeCodes[type];
1291
+ return code;
1292
+ }));
1293
+ var convertJsFunctionToWasm = (func, sig) => {
1294
+ var bytes = Uint8Array.of(0, 97, 115, 109, 1, 0, 0, 0, 1, ...uleb128EncodeWithLen([1, 96, ...generateTypePack(sig.slice(1)), ...generateTypePack(sig[0] === "v" ? "" : sig[0])]), 2, 7, 1, 1, 101, 1, 102, 0, 0, 7, 5, 1, 1, 102, 0, 0);
1295
+ var module3 = new WebAssembly.Module(bytes);
1296
+ var instance = new WebAssembly.Instance(module3, { e: { f: func } });
1297
+ var wrappedFunc = instance.exports["f"];
1298
+ return wrappedFunc;
1299
+ };
1300
+ var addFunction = (func, sig) => {
1301
+ var rtn = getFunctionAddress(func);
1302
+ if (rtn) {
1303
+ return rtn;
1304
+ }
1305
+ var ret = getEmptyTableSlot();
1306
+ try {
1307
+ setWasmTableEntry(ret, func);
1308
+ } catch (err2) {
1309
+ if (!(err2 instanceof TypeError)) {
1310
+ throw err2;
1311
+ }
1312
+ var wrapped = convertJsFunctionToWasm(func, sig);
1313
+ setWasmTableEntry(ret, wrapped);
1314
+ }
1315
+ functionsInTableMap.set(func, ret);
1316
+ return ret;
1317
+ };
1318
+ var removeFunction = (index) => {
1319
+ functionsInTableMap.delete(getWasmTableEntry(index));
1320
+ setWasmTableEntry(index, null);
1321
+ freeTableIndexes.push(index);
1322
+ };
1323
+ {
1324
+ if (Module["noExitRuntime"])
1325
+ noExitRuntime = Module["noExitRuntime"];
1326
+ if (Module["print"])
1327
+ out = Module["print"];
1328
+ if (Module["printErr"])
1329
+ err = Module["printErr"];
1330
+ if (Module["wasmBinary"])
1331
+ wasmBinary = Module["wasmBinary"];
1332
+ if (Module["arguments"])
1333
+ arguments_ = Module["arguments"];
1334
+ if (Module["thisProgram"])
1335
+ thisProgram = Module["thisProgram"];
1336
+ if (Module["preInit"]) {
1337
+ if (typeof Module["preInit"] == "function")
1338
+ Module["preInit"] = [Module["preInit"]];
1339
+ while (Module["preInit"].length > 0) {
1340
+ Module["preInit"].shift()();
1341
+ }
1342
+ }
1343
+ }
1344
+ Module["cwrap"] = cwrap;
1345
+ Module["addFunction"] = addFunction;
1346
+ Module["removeFunction"] = removeFunction;
1347
+ var _sqlite3_finalize;
1348
+ var _sqlite3_reset;
1349
+ var _sqlite3_clear_bindings;
1350
+ var _sqlite3_value_blob;
1351
+ var _sqlite3_value_text;
1352
+ var _sqlite3_value_bytes;
1353
+ var _sqlite3_value_double;
1354
+ var _sqlite3_value_int64;
1355
+ var _sqlite3_value_type;
1356
+ var _sqlite3_result_blob;
1357
+ var _sqlite3_result_blob64;
1358
+ var _sqlite3_result_double;
1359
+ var _sqlite3_result_error;
1360
+ var _sqlite3_result_int;
1361
+ var _sqlite3_result_int64;
1362
+ var _sqlite3_result_null;
1363
+ var _sqlite3_result_text;
1364
+ var _sqlite3_step;
1365
+ var _sqlite3_column_count;
1366
+ var _sqlite3_column_blob;
1367
+ var _sqlite3_column_bytes;
1368
+ var _sqlite3_column_double;
1369
+ var _sqlite3_column_int64;
1370
+ var _sqlite3_column_text;
1371
+ var _sqlite3_column_type;
1372
+ var _sqlite3_column_name;
1373
+ var _sqlite3_column_table_name;
1374
+ var _sqlite3_bind_blob;
1375
+ var _sqlite3_bind_blob64;
1376
+ var _sqlite3_bind_double;
1377
+ var _sqlite3_bind_int;
1378
+ var _sqlite3_bind_int64;
1379
+ var _sqlite3_bind_null;
1380
+ var _sqlite3_bind_text;
1381
+ var _sqlite3_bind_parameter_index;
1382
+ var _sqlite3_exec;
1383
+ var _sqlite3_prepare_v2;
1384
+ var _sqlite3_errmsg;
1385
+ var _sqlite3_last_insert_rowid;
1386
+ var _sqlite3_changes;
1387
+ var _sqlite3_close_v2;
1388
+ var _sqlite3_create_function_v2;
1389
+ var _sqlite3_open_v2;
1390
+ var _sqlite3_get_autocommit;
1391
+ var _malloc;
1392
+ var _free;
1393
+ var __emscripten_timeout;
1394
+ var __emscripten_stack_restore;
1395
+ var __emscripten_stack_alloc;
1396
+ var _emscripten_stack_get_current;
1397
+ var memory;
1398
+ var __indirect_function_table;
1399
+ var wasmMemory;
1400
+ var wasmTable;
1401
+ function assignWasmExports(wasmExports2) {
1402
+ _sqlite3_finalize = Module["_sqlite3_finalize"] = wasmExports2["A"];
1403
+ _sqlite3_reset = Module["_sqlite3_reset"] = wasmExports2["B"];
1404
+ _sqlite3_clear_bindings = Module["_sqlite3_clear_bindings"] = wasmExports2["C"];
1405
+ _sqlite3_value_blob = Module["_sqlite3_value_blob"] = wasmExports2["D"];
1406
+ _sqlite3_value_text = Module["_sqlite3_value_text"] = wasmExports2["E"];
1407
+ _sqlite3_value_bytes = Module["_sqlite3_value_bytes"] = wasmExports2["F"];
1408
+ _sqlite3_value_double = Module["_sqlite3_value_double"] = wasmExports2["G"];
1409
+ _sqlite3_value_int64 = Module["_sqlite3_value_int64"] = wasmExports2["H"];
1410
+ _sqlite3_value_type = Module["_sqlite3_value_type"] = wasmExports2["I"];
1411
+ _sqlite3_result_blob = Module["_sqlite3_result_blob"] = wasmExports2["J"];
1412
+ _sqlite3_result_blob64 = Module["_sqlite3_result_blob64"] = wasmExports2["K"];
1413
+ _sqlite3_result_double = Module["_sqlite3_result_double"] = wasmExports2["L"];
1414
+ _sqlite3_result_error = Module["_sqlite3_result_error"] = wasmExports2["M"];
1415
+ _sqlite3_result_int = Module["_sqlite3_result_int"] = wasmExports2["N"];
1416
+ _sqlite3_result_int64 = Module["_sqlite3_result_int64"] = wasmExports2["O"];
1417
+ _sqlite3_result_null = Module["_sqlite3_result_null"] = wasmExports2["P"];
1418
+ _sqlite3_result_text = Module["_sqlite3_result_text"] = wasmExports2["Q"];
1419
+ _sqlite3_step = Module["_sqlite3_step"] = wasmExports2["R"];
1420
+ _sqlite3_column_count = Module["_sqlite3_column_count"] = wasmExports2["S"];
1421
+ _sqlite3_column_blob = Module["_sqlite3_column_blob"] = wasmExports2["T"];
1422
+ _sqlite3_column_bytes = Module["_sqlite3_column_bytes"] = wasmExports2["U"];
1423
+ _sqlite3_column_double = Module["_sqlite3_column_double"] = wasmExports2["V"];
1424
+ _sqlite3_column_int64 = Module["_sqlite3_column_int64"] = wasmExports2["W"];
1425
+ _sqlite3_column_text = Module["_sqlite3_column_text"] = wasmExports2["X"];
1426
+ _sqlite3_column_type = Module["_sqlite3_column_type"] = wasmExports2["Y"];
1427
+ _sqlite3_column_name = Module["_sqlite3_column_name"] = wasmExports2["Z"];
1428
+ _sqlite3_column_table_name = Module["_sqlite3_column_table_name"] = wasmExports2["_"];
1429
+ _sqlite3_bind_blob = Module["_sqlite3_bind_blob"] = wasmExports2["$"];
1430
+ _sqlite3_bind_blob64 = Module["_sqlite3_bind_blob64"] = wasmExports2["aa"];
1431
+ _sqlite3_bind_double = Module["_sqlite3_bind_double"] = wasmExports2["ba"];
1432
+ _sqlite3_bind_int = Module["_sqlite3_bind_int"] = wasmExports2["ca"];
1433
+ _sqlite3_bind_int64 = Module["_sqlite3_bind_int64"] = wasmExports2["da"];
1434
+ _sqlite3_bind_null = Module["_sqlite3_bind_null"] = wasmExports2["ea"];
1435
+ _sqlite3_bind_text = Module["_sqlite3_bind_text"] = wasmExports2["fa"];
1436
+ _sqlite3_bind_parameter_index = Module["_sqlite3_bind_parameter_index"] = wasmExports2["ga"];
1437
+ _sqlite3_exec = Module["_sqlite3_exec"] = wasmExports2["ha"];
1438
+ _sqlite3_prepare_v2 = Module["_sqlite3_prepare_v2"] = wasmExports2["ia"];
1439
+ _sqlite3_errmsg = Module["_sqlite3_errmsg"] = wasmExports2["ja"];
1440
+ _sqlite3_last_insert_rowid = Module["_sqlite3_last_insert_rowid"] = wasmExports2["ka"];
1441
+ _sqlite3_changes = Module["_sqlite3_changes"] = wasmExports2["la"];
1442
+ _sqlite3_close_v2 = Module["_sqlite3_close_v2"] = wasmExports2["ma"];
1443
+ _sqlite3_create_function_v2 = Module["_sqlite3_create_function_v2"] = wasmExports2["na"];
1444
+ _sqlite3_open_v2 = Module["_sqlite3_open_v2"] = wasmExports2["oa"];
1445
+ _sqlite3_get_autocommit = Module["_sqlite3_get_autocommit"] = wasmExports2["pa"];
1446
+ _malloc = Module["_malloc"] = wasmExports2["qa"];
1447
+ _free = Module["_free"] = wasmExports2["ra"];
1448
+ __emscripten_timeout = wasmExports2["ta"];
1449
+ __emscripten_stack_restore = wasmExports2["ua"];
1450
+ __emscripten_stack_alloc = wasmExports2["va"];
1451
+ _emscripten_stack_get_current = wasmExports2["wa"];
1452
+ memory = wasmMemory = wasmExports2["y"];
1453
+ __indirect_function_table = wasmTable = wasmExports2["sa"];
1454
+ }
1455
+ var wasmImports = { n: __abort_js, l: __emscripten_runtime_keepalive_clear, o: __localtime_js, i: __setitimer_js, p: __tzset_js, q: _emscripten_date_now, a: _emscripten_get_now, j: _emscripten_resize_heap, w: _nodejsAccess, s: _nodejsCheckReservedLock, f: _nodejsClose, x: _nodejsDelete, v: _nodejsFileSize, m: _nodejsFullPathname, u: _nodejsLock, h: _nodejsRandomness, e: _nodejsRead, b: _nodejsSync, c: _nodejsTruncate, t: _nodejsUnlock, d: _nodejsWrite, g: _nodejs_max_path_length, r: _nodejs_open, k: _proc_exit };
1456
+ function run() {
1457
+ preRun();
1458
+ function doRun() {
1459
+ Module["calledRun"] = true;
1460
+ if (ABORT)
1461
+ return;
1462
+ initRuntime();
1463
+ Module["onRuntimeInitialized"]?.();
1464
+ postRun();
1465
+ }
1466
+ if (Module["setStatus"]) {
1467
+ Module["setStatus"]("Running...");
1468
+ setTimeout(() => {
1469
+ setTimeout(() => Module["setStatus"](""), 1);
1470
+ doRun();
1471
+ }, 1);
1472
+ } else {
1473
+ doRun();
1474
+ }
1475
+ }
1476
+ var wasmExports;
1477
+ wasmExports = createWasm();
1478
+ run();
1479
+ }
1480
+ });
1481
+
1482
+ // src/paths.ts
1483
+ function recallRoot() {
1484
+ if (rootOverride)
1485
+ return rootOverride;
1486
+ const envRoot = process.env["RECALL_HOME"];
1487
+ if (envRoot && envRoot.length > 0)
1488
+ return envRoot;
1489
+ return (0, import_node_path2.join)((0, import_node_os.homedir)(), ".recall");
1490
+ }
1491
+ function dbPath() {
1492
+ return (0, import_node_path2.join)(recallRoot(), "recall.db");
1493
+ }
1494
+ function binDir() {
1495
+ return (0, import_node_path2.join)(recallRoot(), "bin");
1496
+ }
1497
+ function logsDir() {
1498
+ return (0, import_node_path2.join)(recallRoot(), "logs");
1499
+ }
1500
+ function ensureDir() {
1501
+ (0, import_node_fs2.mkdirSync)(recallRoot(), { recursive: true });
1502
+ }
1503
+ var import_node_fs2, import_node_os, import_node_path2, rootOverride;
1504
+ var init_paths = __esm({
1505
+ "src/paths.ts"() {
1506
+ "use strict";
1507
+ import_node_fs2 = require("node:fs");
1508
+ import_node_os = require("node:os");
1509
+ import_node_path2 = require("node:path");
1510
+ rootOverride = null;
1511
+ }
1512
+ });
1513
+
1514
+ // src/recall/quantize.ts
1515
+ var init_quantize = __esm({
1516
+ "src/recall/quantize.ts"() {
1517
+ "use strict";
1518
+ }
1519
+ });
1520
+
1521
+ // src/hooks/stop-hook.ts
1522
+ var stop_hook_exports = {};
1523
+ __export(stop_hook_exports, {
1524
+ vendorForTranscript: () => vendorForTranscript
1525
+ });
1526
+ module.exports = __toCommonJS(stop_hook_exports);
1527
+
1528
+ // src/recall/transcript-utils.ts
1529
+ function stripToolContent(entries) {
1530
+ const out = [];
1531
+ for (const entry of entries) {
1532
+ if (entry.type !== "user" && entry.type !== "assistant")
1533
+ continue;
1534
+ const msg = entry.message;
1535
+ if (!msg)
1536
+ continue;
1537
+ if (typeof msg.content === "string") {
1538
+ if (msg.content.trim())
1539
+ out.push(entry);
1540
+ continue;
1541
+ }
1542
+ if (!Array.isArray(msg.content)) {
1543
+ out.push(entry);
1544
+ continue;
1545
+ }
1546
+ const textBlocks = msg.content.filter(
1547
+ (b) => b.type === "text" && b.text?.trim()
1548
+ );
1549
+ if (textBlocks.length === 0)
1550
+ continue;
1551
+ out.push({ ...entry, message: { ...msg, content: textBlocks } });
1552
+ }
1553
+ return out;
1554
+ }
1555
+
1556
+ // src/db.ts
1557
+ var import_node_fs = require("node:fs");
1558
+ var import_node_path = require("node:path");
1559
+ init_log();
1560
+ var import_node_sqlite3_wasm = __toESM(require_node_sqlite3_wasm());
1561
+ var db = null;
1562
+ var currentDbPath = null;
1563
+ function getDb(dbPath2) {
1564
+ if (db && currentDbPath === dbPath2)
1565
+ return db;
1566
+ if (db) {
1567
+ closeDb();
1568
+ }
1569
+ (0, import_node_fs.mkdirSync)((0, import_node_path.dirname)(dbPath2), { recursive: true });
1570
+ clearStaleLock(dbPath2);
1571
+ writeOwnerFile(dbPath2);
1572
+ db = new import_node_sqlite3_wasm.Database(dbPath2);
1573
+ currentDbPath = dbPath2;
1574
+ db.exec("PRAGMA busy_timeout = 5000");
1575
+ db.exec("PRAGMA journal_mode = WAL");
1576
+ db.exec("PRAGMA synchronous = NORMAL");
1577
+ db.exec("PRAGMA wal_autocheckpoint = 1000");
1578
+ db.exec("PRAGMA foreign_keys = ON");
1579
+ ensureSchema(db);
1580
+ log({ source: "db", level: "info", summary: `DB: initialized at ${dbPath2}` });
1581
+ return db;
1582
+ }
1583
+ function closeDb() {
1584
+ if (db) {
1585
+ db.close();
1586
+ if (currentDbPath)
1587
+ removeOwnerFile(currentDbPath);
1588
+ db = null;
1589
+ currentDbPath = null;
1590
+ }
1591
+ }
1592
+ function ownerFilePath(dbPath2) {
1593
+ return `${dbPath2}.owner`;
1594
+ }
1595
+ function processStartToken(pid) {
1596
+ if (process.platform !== "linux")
1597
+ return "";
1598
+ try {
1599
+ const stat = (0, import_node_fs.readFileSync)(`/proc/${pid}/stat`, "utf-8");
1600
+ const close = stat.lastIndexOf(")");
1601
+ if (close === -1)
1602
+ return "";
1603
+ const rest = stat.slice(close + 2).trim().split(/\s+/);
1604
+ const starttime = rest[19];
1605
+ return starttime ?? "";
1606
+ } catch {
1607
+ return "";
1608
+ }
1609
+ }
1610
+ function writeOwnerFile(dbPath2) {
1611
+ try {
1612
+ const token = processStartToken(process.pid);
1613
+ (0, import_node_fs.writeFileSync)(ownerFilePath(dbPath2), `${process.pid}:${token}`, "utf-8");
1614
+ } catch {
1615
+ }
1616
+ }
1617
+ function removeOwnerFile(dbPath2) {
1618
+ try {
1619
+ (0, import_node_fs.unlinkSync)(ownerFilePath(dbPath2));
1620
+ } catch {
1621
+ }
1622
+ }
1623
+ function isProcessAlive(pid) {
1624
+ try {
1625
+ process.kill(pid, 0);
1626
+ return true;
1627
+ } catch {
1628
+ return false;
1629
+ }
1630
+ }
1631
+ function clearStaleLock(dbPath2) {
1632
+ const lockDir = `${dbPath2}.lock`;
1633
+ if (!(0, import_node_fs.existsSync)(lockDir))
1634
+ return;
1635
+ const ownerFile = ownerFilePath(dbPath2);
1636
+ if ((0, import_node_fs.existsSync)(ownerFile)) {
1637
+ try {
1638
+ const raw = (0, import_node_fs.readFileSync)(ownerFile, "utf-8").trim();
1639
+ const sep = raw.indexOf(":");
1640
+ const pidStr = sep === -1 ? raw : raw.slice(0, sep);
1641
+ const storedToken = sep === -1 ? "" : raw.slice(sep + 1);
1642
+ const pid = parseInt(pidStr, 10);
1643
+ if (!isNaN(pid) && isProcessAlive(pid)) {
1644
+ if (storedToken === "" || storedToken === processStartToken(pid)) {
1645
+ return;
1646
+ }
1647
+ }
1648
+ } catch {
1649
+ }
1650
+ }
1651
+ try {
1652
+ (0, import_node_fs.rmSync)(lockDir, { recursive: true, force: true });
1653
+ log({
1654
+ source: "db",
1655
+ level: "warn",
1656
+ summary: `DB: removed stale lock directory (${lockDir}) \u2014 owning process is dead`
1657
+ });
1658
+ } catch (err) {
1659
+ log({
1660
+ source: "db",
1661
+ level: "error",
1662
+ summary: `DB: failed to remove stale lock directory: ${err}`
1663
+ });
1664
+ }
1665
+ }
1666
+ function ensureSchema(db3) {
1667
+ db3.exec(`
1668
+ CREATE TABLE IF NOT EXISTS messages (
1669
+ message_id TEXT PRIMARY KEY,
1670
+ session_id TEXT NOT NULL,
1671
+ message_seq INTEGER NOT NULL,
1672
+ message_text TEXT NOT NULL,
1673
+ project_id TEXT,
1674
+ created_at INTEGER NOT NULL,
1675
+ message_role TEXT,
1676
+ UNIQUE(session_id, message_id)
1677
+ );
1678
+
1679
+ CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id, created_at);
1680
+ CREATE INDEX IF NOT EXISTS idx_messages_project ON messages(project_id);
1681
+ `);
1682
+ db3.exec(`
1683
+ CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
1684
+ message_text,
1685
+ content=messages,
1686
+ content_rowid=rowid,
1687
+ tokenize='porter unicode61'
1688
+ );
1689
+
1690
+ CREATE TRIGGER IF NOT EXISTS messages_fts_ai AFTER INSERT ON messages BEGIN
1691
+ INSERT INTO messages_fts(rowid, message_text) VALUES (new.rowid, new.message_text);
1692
+ END;
1693
+
1694
+ CREATE TRIGGER IF NOT EXISTS messages_fts_ad AFTER DELETE ON messages BEGIN
1695
+ INSERT INTO messages_fts(messages_fts, rowid, message_text)
1696
+ VALUES ('delete', old.rowid, old.message_text);
1697
+ END;
1698
+
1699
+ CREATE TRIGGER IF NOT EXISTS messages_fts_au AFTER UPDATE ON messages BEGIN
1700
+ INSERT INTO messages_fts(messages_fts, rowid, message_text)
1701
+ VALUES ('delete', old.rowid, old.message_text);
1702
+ INSERT INTO messages_fts(rowid, message_text) VALUES (new.rowid, new.message_text);
1703
+ END;
1704
+ `);
1705
+ db3.exec(`
1706
+ CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts_vocab
1707
+ USING fts5vocab(messages_fts, 'row');
1708
+ `);
1709
+ db3.exec(`
1710
+ CREATE VIRTUAL TABLE IF NOT EXISTS _stem USING fts5(
1711
+ t, tokenize='porter unicode61'
1712
+ );
1713
+ CREATE VIRTUAL TABLE IF NOT EXISTS _stem_vocab
1714
+ USING fts5vocab(_stem, 'row');
1715
+ `);
1716
+ db3.exec(`
1717
+ CREATE TABLE IF NOT EXISTS message_vectors (
1718
+ message_id TEXT PRIMARY KEY REFERENCES messages(message_id) ON DELETE CASCADE,
1719
+ embedding_q8 BLOB NOT NULL,
1720
+ norm REAL NOT NULL,
1721
+ quant_scale REAL NOT NULL
1722
+ );
1723
+ `);
1724
+ db3.exec(`
1725
+ CREATE TABLE IF NOT EXISTS ingest_watermark (
1726
+ transcript_path TEXT PRIMARY KEY,
1727
+ last_mtime INTEGER NOT NULL,
1728
+ last_size INTEGER NOT NULL,
1729
+ vendor TEXT NOT NULL
1730
+ );
1731
+ CREATE INDEX IF NOT EXISTS idx_watermark_vendor ON ingest_watermark(vendor);
1732
+ `);
1733
+ }
1734
+
1735
+ // src/recall/message-store.ts
1736
+ init_paths();
1737
+
1738
+ // src/recall/query-sanitizer.ts
1739
+ init_paths();
1740
+ init_log();
1741
+
1742
+ // src/recall/message-store.ts
1743
+ init_quantize();
1744
+ var dirEnsured = false;
1745
+ function db2() {
1746
+ return getDb(dbPath());
1747
+ }
1748
+ function ensureDir2() {
1749
+ if (!dirEnsured) {
1750
+ ensureDir();
1751
+ dirEnsured = true;
1752
+ }
1753
+ }
1754
+ function insertMessages(messages, opts) {
1755
+ if (messages.length === 0 && !opts?.replaceSessionId)
1756
+ return;
1757
+ ensureDir2();
1758
+ const d = db2();
1759
+ d.exec("BEGIN");
1760
+ try {
1761
+ if (opts?.replaceSessionId) {
1762
+ d.run(
1763
+ `DELETE FROM message_vectors WHERE message_id IN
1764
+ (SELECT message_id FROM messages WHERE session_id = ?)`,
1765
+ [opts.replaceSessionId]
1766
+ );
1767
+ d.run("DELETE FROM messages WHERE session_id = ?", [opts.replaceSessionId]);
1768
+ }
1769
+ const stmt = d.prepare(
1770
+ `INSERT OR IGNORE INTO messages
1771
+ (message_id, session_id, message_seq, message_text, project_id, created_at, message_role)
1772
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
1773
+ );
1774
+ try {
1775
+ for (const m of messages) {
1776
+ stmt.run([
1777
+ m.message_id,
1778
+ m.session_id,
1779
+ m.message_seq,
1780
+ m.message_text,
1781
+ m.project_id,
1782
+ m.created_at,
1783
+ m.message_role
1784
+ ]);
1785
+ }
1786
+ } finally {
1787
+ stmt.finalize();
1788
+ }
1789
+ d.exec("COMMIT");
1790
+ } catch (e) {
1791
+ d.exec("ROLLBACK");
1792
+ throw e;
1793
+ }
1794
+ }
1795
+
1796
+ // src/recall/message-ingest.ts
1797
+ init_paths();
1798
+
1799
+ // src/url-path-resolver.ts
1800
+ function normalizePath(p) {
1801
+ let normalized = p.startsWith("\\\\?\\") ? p.slice(4) : p;
1802
+ normalized = normalized.replace(/\\/g, "/");
1803
+ normalized = normalized.replace(/^([A-Za-z]):/, (_, d) => d.toLowerCase() + ":");
1804
+ if (normalized.length > 1 && normalized.endsWith("/")) {
1805
+ normalized = normalized.slice(0, -1);
1806
+ }
1807
+ return normalized;
1808
+ }
1809
+
1810
+ // src/adapters/claude/jsonl-reader.ts
1811
+ var fs = __toESM(require("fs"));
1812
+ init_log();
1813
+ var READ_BUFFER_SIZE = 64 * 1024;
1814
+ var TURN_CONTENT_CAP = 8 * 1024;
1815
+ function parseJsonlFile(filepath) {
1816
+ try {
1817
+ const content = fs.readFileSync(filepath, "utf-8");
1818
+ const lines = content.split("\n");
1819
+ const entries = [];
1820
+ for (const line of lines) {
1821
+ const trimmed = line.trim();
1822
+ if (!trimmed) {
1823
+ continue;
1824
+ }
1825
+ try {
1826
+ const entry = JSON.parse(trimmed);
1827
+ entries.push(entry);
1828
+ } catch (err) {
1829
+ log({ level: "warn", source: "claude:jsonl-reader", summary: `Skipping unparseable line: ${err.message}` });
1830
+ continue;
1831
+ }
1832
+ }
1833
+ return entries;
1834
+ } catch (error) {
1835
+ log({ level: "error", source: "jsonl-reader", summary: `Failed to read JSONL file ${filepath}: ${error instanceof Error ? error.message : String(error)}`, data: { filepath, error: String(error) } });
1836
+ return [];
1837
+ }
1838
+ }
1839
+
1840
+ // src/adapters/claude/claude-entry-adapter.ts
1841
+ function isSystemContextContent(message) {
1842
+ if (!message || message.role !== "user")
1843
+ return false;
1844
+ const content = message.content;
1845
+ let text;
1846
+ if (typeof content === "string") {
1847
+ text = content;
1848
+ } else if (Array.isArray(content)) {
1849
+ const firstText = content.find(
1850
+ (b) => typeof b === "object" && b !== null && b.type === "text"
1851
+ );
1852
+ if (firstText && "text" in firstText) {
1853
+ text = firstText.text;
1854
+ }
1855
+ }
1856
+ if (!text)
1857
+ return false;
1858
+ if (text.startsWith("<system-reminder>"))
1859
+ return true;
1860
+ if (text.startsWith("<environment_context>"))
1861
+ return true;
1862
+ if (text.startsWith("<INSTRUCTIONS>"))
1863
+ return true;
1864
+ if (text.startsWith("# AGENTS.md instructions for"))
1865
+ return true;
1866
+ if (text.startsWith("<context>"))
1867
+ return true;
1868
+ if (text.startsWith("<task-notification>"))
1869
+ return true;
1870
+ if (text.startsWith("<command-name>"))
1871
+ return true;
1872
+ if (text.startsWith("<local-command-stdout>"))
1873
+ return true;
1874
+ if (text.startsWith("<local-command-caveat>"))
1875
+ return true;
1876
+ return false;
1877
+ }
1878
+ function sanitizeContentBlocks(content) {
1879
+ if (typeof content === "string")
1880
+ return content;
1881
+ if (!Array.isArray(content))
1882
+ return content;
1883
+ return content.map((block) => {
1884
+ if (typeof block !== "object" || block === null)
1885
+ return block;
1886
+ const b = block;
1887
+ if (b.type === "tool_use" && typeof b.name !== "string") {
1888
+ return { ...b, name: "<unknown>" };
1889
+ }
1890
+ return block;
1891
+ });
1892
+ }
1893
+ function sanitizeMessage(message) {
1894
+ if (!message)
1895
+ return message;
1896
+ if (Array.isArray(message.content)) {
1897
+ return { ...message, content: sanitizeContentBlocks(message.content) };
1898
+ }
1899
+ return message;
1900
+ }
1901
+ function adaptClaudeEntry(raw) {
1902
+ if (raw.type === "queue-operation")
1903
+ return null;
1904
+ if (typeof raw.type !== "string")
1905
+ return null;
1906
+ if (raw.type === "progress") {
1907
+ const data = raw.data;
1908
+ const innerMessage = data?.message;
1909
+ const actualMessage = innerMessage?.message;
1910
+ if (actualMessage?.content) {
1911
+ const {
1912
+ type: _type,
1913
+ uuid: _uuid,
1914
+ parentUuid: _parentUuid,
1915
+ sessionId: _sessionId,
1916
+ timestamp: _timestamp,
1917
+ parentToolUseID: _parentToolUseID,
1918
+ parent_tool_use_id: _parent_tool_use_id,
1919
+ ...progressOverflow
1920
+ } = raw;
1921
+ return {
1922
+ type: innerMessage?.type ?? "assistant",
1923
+ uuid: raw.uuid,
1924
+ parentUuid: raw.parentUuid,
1925
+ sessionId: raw.sessionId,
1926
+ timestamp: raw.timestamp,
1927
+ message: sanitizeMessage(actualMessage),
1928
+ agentId: data?.agentId,
1929
+ parentToolUseID: raw.parentToolUseID ?? raw.parent_tool_use_id,
1930
+ vendor: "claude",
1931
+ ...Object.keys(progressOverflow).length > 0 && { metadata: progressOverflow }
1932
+ };
1933
+ }
1934
+ return null;
1935
+ }
1936
+ const {
1937
+ type,
1938
+ uuid,
1939
+ parentUuid,
1940
+ sessionId,
1941
+ session_id,
1942
+ // SDK snake_case variant
1943
+ timestamp,
1944
+ isSidechain,
1945
+ isMeta,
1946
+ agentId,
1947
+ cwd,
1948
+ message,
1949
+ toolUseResult,
1950
+ tool_use_result,
1951
+ // SDK snake_case variant
1952
+ summary,
1953
+ leafUuid,
1954
+ customTitle,
1955
+ sourceToolAssistantUUID,
1956
+ // Claude's casing → our camelCase
1957
+ parent_tool_use_id,
1958
+ // SDK snake_case
1959
+ parentToolUseID,
1960
+ // JSONL camelCase
1961
+ ...overflow
1962
+ } = raw;
1963
+ const mergedMetadata = {
1964
+ ...overflow
1965
+ };
1966
+ let sanitizedMessage = sanitizeMessage(message);
1967
+ if (!sanitizedMessage && typeof mergedMetadata.content === "string") {
1968
+ sanitizedMessage = { role: "assistant", content: mergedMetadata.content };
1969
+ delete mergedMetadata.content;
1970
+ }
1971
+ const detectedMeta = isMeta || type === "user" && isSystemContextContent(sanitizedMessage) || void 0;
1972
+ return {
1973
+ type,
1974
+ uuid,
1975
+ parentUuid,
1976
+ // Prefer camelCase, fall back to snake_case (SDK format)
1977
+ sessionId: sessionId ?? session_id,
1978
+ timestamp,
1979
+ vendor: "claude",
1980
+ // Message content (sanitized — coerces malformed blocks to safe defaults)
1981
+ message: sanitizedMessage,
1982
+ // Sub-agent
1983
+ isSidechain,
1984
+ agentId,
1985
+ parentToolUseID: parentToolUseID ?? parent_tool_use_id,
1986
+ // Working directory
1987
+ cwd,
1988
+ // Structured tool result (prefer camelCase, fall back to SDK snake_case)
1989
+ toolUseResult: toolUseResult ?? tool_use_result,
1990
+ // Session display
1991
+ isMeta: detectedMeta,
1992
+ customTitle,
1993
+ // Summary entries
1994
+ summary,
1995
+ leafUuid,
1996
+ // Tool result linking
1997
+ sourceToolAssistantUuid: sourceToolAssistantUUID,
1998
+ // Vendor-specific overflow
1999
+ ...Object.keys(mergedMetadata).length > 0 && { metadata: mergedMetadata }
2000
+ };
2001
+ }
2002
+ function adaptClaudeEntries(rawEntries) {
2003
+ return rawEntries.map(adaptClaudeEntry).filter((entry) => entry !== null);
2004
+ }
2005
+
2006
+ // src/adapters/codex/codex-jsonl-reader.ts
2007
+ var fs2 = __toESM(require("fs"));
2008
+ init_log();
2009
+ var path = __toESM(require("path"));
2010
+ var os = __toESM(require("os"));
2011
+ var CODEX_SESSIONS_DIR = path.join(os.homedir(), ".codex", "sessions");
2012
+ function parseCodexJsonlFile(filepath) {
2013
+ try {
2014
+ const content = fs2.readFileSync(filepath, "utf-8");
2015
+ const lines = content.split("\n");
2016
+ const records = [];
2017
+ for (const line of lines) {
2018
+ const trimmed = line.trim();
2019
+ if (!trimmed)
2020
+ continue;
2021
+ try {
2022
+ const record = JSON.parse(trimmed);
2023
+ records.push(record);
2024
+ } catch (err) {
2025
+ log({ level: "warn", source: "codex-jsonl-reader", summary: `Skipping unparseable line: ${err.message}` });
2026
+ }
2027
+ }
2028
+ return records;
2029
+ } catch (error) {
2030
+ log({ level: "error", source: "codex-jsonl-reader", summary: `Failed to read ${filepath}: ${error instanceof Error ? error.message : String(error)}`, data: { filepath, error: String(error) } });
2031
+ return [];
2032
+ }
2033
+ }
2034
+ var READ_BUFFER_SIZE2 = 64 * 1024;
2035
+ var TURN_CONTENT_CAP2 = 8 * 1024;
2036
+
2037
+ // src/adapters/codex/codex-jsonl-adapter.ts
2038
+ function adaptCodexJsonlRecords(records, sessionId) {
2039
+ const outputIndex = /* @__PURE__ */ new Map();
2040
+ for (const record of records) {
2041
+ if (record.type !== "response_item")
2042
+ continue;
2043
+ const subtype = record.payload.type;
2044
+ if (subtype === "function_call_output" || subtype === "custom_tool_call_output") {
2045
+ const callId = record.payload.call_id;
2046
+ if (callId)
2047
+ outputIndex.set(callId, record);
2048
+ }
2049
+ }
2050
+ const entries = [];
2051
+ let currentCwd;
2052
+ let currentModel;
2053
+ let entryCounter = 0;
2054
+ for (const record of records) {
2055
+ switch (record.type) {
2056
+ case "session_meta": {
2057
+ currentCwd = record.payload.cwd;
2058
+ break;
2059
+ }
2060
+ case "turn_context": {
2061
+ const payload = record.payload;
2062
+ if (payload.cwd)
2063
+ currentCwd = payload.cwd;
2064
+ if (payload.model)
2065
+ currentModel = payload.model;
2066
+ break;
2067
+ }
2068
+ case "event_msg":
2069
+ break;
2070
+ case "response_item": {
2071
+ const emitted = emitResponseItem(
2072
+ record,
2073
+ sessionId,
2074
+ outputIndex,
2075
+ currentCwd,
2076
+ currentModel,
2077
+ entryCounter
2078
+ );
2079
+ for (const entry of emitted) {
2080
+ entries.push(entry);
2081
+ }
2082
+ entryCounter += emitted.length;
2083
+ break;
2084
+ }
2085
+ }
2086
+ }
2087
+ return entries;
2088
+ }
2089
+ function emitResponseItem(record, sessionId, outputIndex, cwd, model, counter) {
2090
+ const payload = record.payload;
2091
+ const subtype = payload.type;
2092
+ const timestamp = record.timestamp;
2093
+ const base = {
2094
+ sessionId,
2095
+ vendor: "codex",
2096
+ timestamp,
2097
+ cwd
2098
+ };
2099
+ switch (subtype) {
2100
+ case "message":
2101
+ return emitMessage(payload, base, model, counter);
2102
+ case "reasoning":
2103
+ return emitReasoning(payload, base, counter);
2104
+ case "function_call":
2105
+ return emitFunctionCall(payload, base, outputIndex, counter);
2106
+ case "custom_tool_call":
2107
+ return emitCustomToolCall(payload, base, outputIndex, counter);
2108
+ case "web_search_call":
2109
+ return emitWebSearchCall(payload, base, counter);
2110
+ case "function_call_output":
2111
+ case "custom_tool_call_output":
2112
+ return emitOrphanedOutput(payload, subtype, base, outputIndex, counter);
2113
+ case "ghost_snapshot":
2114
+ case "compaction":
2115
+ case "other":
2116
+ return [];
2117
+ default:
2118
+ return [];
2119
+ }
2120
+ }
2121
+ function emitMessage(payload, base, model, counter) {
2122
+ const role = payload.role;
2123
+ const contentItems = payload.content;
2124
+ const phase = payload.phase;
2125
+ if (role === "developer")
2126
+ return [];
2127
+ if (role === "user") {
2128
+ return [
2129
+ {
2130
+ type: "user",
2131
+ uuid: generateId(base.sessionId, counter),
2132
+ ...base,
2133
+ message: {
2134
+ role: "user",
2135
+ content: adaptContentItems(contentItems)
2136
+ }
2137
+ }
2138
+ ];
2139
+ }
2140
+ if (role === "assistant") {
2141
+ return [
2142
+ {
2143
+ type: "assistant",
2144
+ uuid: generateId(base.sessionId, counter),
2145
+ ...base,
2146
+ message: {
2147
+ role: "assistant",
2148
+ content: adaptContentItems(contentItems),
2149
+ model
2150
+ },
2151
+ metadata: phase ? { phase } : void 0
2152
+ }
2153
+ ];
2154
+ }
2155
+ return [];
2156
+ }
2157
+ function emitReasoning(payload, base, counter) {
2158
+ const summaryItems = payload.summary;
2159
+ const thinkingBlocks = [];
2160
+ if (Array.isArray(summaryItems)) {
2161
+ for (const item of summaryItems) {
2162
+ if (item.type === "summary_text" && item.text) {
2163
+ thinkingBlocks.push({
2164
+ type: "thinking",
2165
+ thinking: item.text,
2166
+ isSummary: true
2167
+ });
2168
+ }
2169
+ }
2170
+ }
2171
+ if (thinkingBlocks.length === 0)
2172
+ return [];
2173
+ return [
2174
+ {
2175
+ type: "assistant",
2176
+ uuid: generateId(base.sessionId, counter),
2177
+ ...base,
2178
+ message: {
2179
+ role: "assistant",
2180
+ content: thinkingBlocks
2181
+ }
2182
+ }
2183
+ ];
2184
+ }
2185
+ function emitFunctionCall(payload, base, outputIndex, _counter) {
2186
+ const callId = payload.call_id;
2187
+ const name = payload.name;
2188
+ const rawArgs = payload.arguments;
2189
+ let args = {};
2190
+ if (typeof rawArgs === "string") {
2191
+ try {
2192
+ args = JSON.parse(rawArgs);
2193
+ } catch {
2194
+ args = { raw: rawArgs };
2195
+ }
2196
+ } else if (typeof rawArgs === "object" && rawArgs !== null) {
2197
+ args = rawArgs;
2198
+ }
2199
+ const { toolName, toolInput, metadata } = mapFunctionCall(name, args);
2200
+ const toolUse = {
2201
+ type: "tool_use",
2202
+ id: callId,
2203
+ name: toolName,
2204
+ input: toolInput
2205
+ };
2206
+ const assistantEntry = {
2207
+ type: "assistant",
2208
+ uuid: callId,
2209
+ ...base,
2210
+ message: {
2211
+ role: "assistant",
2212
+ content: [toolUse]
2213
+ },
2214
+ metadata
2215
+ };
2216
+ const entries = [assistantEntry];
2217
+ const outputRecord = outputIndex.get(callId);
2218
+ if (outputRecord) {
2219
+ const outputPayload = outputRecord.payload;
2220
+ const rawOutput = outputPayload.output;
2221
+ const { exitCode, body } = parseExecOutputHeader(rawOutput);
2222
+ const isError = exitCode !== 0;
2223
+ const toolResult = {
2224
+ type: "tool_result",
2225
+ tool_use_id: callId,
2226
+ content: body,
2227
+ is_error: isError
2228
+ };
2229
+ const resultEntry = {
2230
+ type: "result",
2231
+ uuid: `${callId}-result`,
2232
+ parentUuid: callId,
2233
+ sessionId: base.sessionId,
2234
+ vendor: base.vendor,
2235
+ timestamp: outputRecord.timestamp,
2236
+ cwd: base.cwd,
2237
+ message: {
2238
+ role: "tool",
2239
+ content: [toolResult]
2240
+ },
2241
+ toolUseResult: {
2242
+ output: body,
2243
+ exitCode
2244
+ }
2245
+ };
2246
+ entries.push(resultEntry);
2247
+ outputIndex.delete(callId);
2248
+ }
2249
+ return entries;
2250
+ }
2251
+ function emitCustomToolCall(payload, base, outputIndex, _counter) {
2252
+ const callId = payload.call_id;
2253
+ const name = payload.name;
2254
+ const input = payload.input;
2255
+ if (name === "apply_patch") {
2256
+ return emitApplyPatch(callId, input, base, outputIndex);
2257
+ }
2258
+ const toolUse = {
2259
+ type: "tool_use",
2260
+ id: callId,
2261
+ name,
2262
+ input: { raw: input }
2263
+ };
2264
+ const assistantEntry = {
2265
+ type: "assistant",
2266
+ uuid: callId,
2267
+ ...base,
2268
+ message: {
2269
+ role: "assistant",
2270
+ content: [toolUse]
2271
+ }
2272
+ };
2273
+ const entries = [assistantEntry];
2274
+ const outputRecord = outputIndex.get(callId);
2275
+ if (outputRecord) {
2276
+ entries.push(
2277
+ buildCustomToolResult(callId, callId, outputRecord, base)
2278
+ );
2279
+ outputIndex.delete(callId);
2280
+ }
2281
+ return entries;
2282
+ }
2283
+ function emitApplyPatch(callId, input, base, outputIndex) {
2284
+ const changes = parseCodexPatch(input);
2285
+ if (changes.length === 0) {
2286
+ const toolUse = {
2287
+ type: "tool_use",
2288
+ id: callId,
2289
+ name: "Edit",
2290
+ input: { patch: input }
2291
+ };
2292
+ const entries2 = [
2293
+ {
2294
+ type: "assistant",
2295
+ uuid: callId,
2296
+ ...base,
2297
+ message: { role: "assistant", content: [toolUse] }
2298
+ }
2299
+ ];
2300
+ const outputRecord2 = outputIndex.get(callId);
2301
+ if (outputRecord2) {
2302
+ entries2.push(buildCustomToolResult(callId, callId, outputRecord2, base));
2303
+ outputIndex.delete(callId);
2304
+ }
2305
+ return entries2;
2306
+ }
2307
+ const entries = [];
2308
+ for (let i = 0; i < changes.length; i++) {
2309
+ const change = changes[i];
2310
+ const entryId = i === 0 ? callId : `${callId}-file-${i}`;
2311
+ let toolName;
2312
+ let toolInput;
2313
+ let metadata;
2314
+ switch (change.kind) {
2315
+ case "add":
2316
+ toolName = "Write";
2317
+ toolInput = { file_path: change.path, content: change.newString };
2318
+ break;
2319
+ case "delete":
2320
+ toolName = "Edit";
2321
+ toolInput = { file_path: change.path };
2322
+ metadata = { isDelete: true };
2323
+ break;
2324
+ case "update":
2325
+ default:
2326
+ toolName = "Edit";
2327
+ toolInput = {
2328
+ file_path: change.path,
2329
+ old_string: change.oldString,
2330
+ new_string: change.newString
2331
+ };
2332
+ break;
2333
+ }
2334
+ const toolUse = {
2335
+ type: "tool_use",
2336
+ id: entryId,
2337
+ name: toolName,
2338
+ input: toolInput
2339
+ };
2340
+ entries.push({
2341
+ type: "assistant",
2342
+ uuid: entryId,
2343
+ ...base,
2344
+ message: { role: "assistant", content: [toolUse] },
2345
+ metadata
2346
+ });
2347
+ }
2348
+ const outputRecord = outputIndex.get(callId);
2349
+ if (outputRecord) {
2350
+ const lastEntry = entries[entries.length - 1];
2351
+ entries.push(
2352
+ buildCustomToolResult(lastEntry.uuid ?? callId, callId, outputRecord, base)
2353
+ );
2354
+ outputIndex.delete(callId);
2355
+ }
2356
+ return entries;
2357
+ }
2358
+ function buildCustomToolResult(parentUuid, callId, outputRecord, base) {
2359
+ const rawOutput = outputRecord.payload.output;
2360
+ let content;
2361
+ let isError = false;
2362
+ try {
2363
+ const parsed = JSON.parse(rawOutput);
2364
+ content = parsed.output ?? rawOutput;
2365
+ if (parsed.success === false || parsed.error) {
2366
+ isError = true;
2367
+ }
2368
+ } catch {
2369
+ content = rawOutput;
2370
+ }
2371
+ const toolResult = {
2372
+ type: "tool_result",
2373
+ tool_use_id: callId,
2374
+ content,
2375
+ is_error: isError
2376
+ };
2377
+ return {
2378
+ type: "result",
2379
+ uuid: `${parentUuid}-result`,
2380
+ parentUuid,
2381
+ sessionId: base.sessionId,
2382
+ vendor: base.vendor,
2383
+ timestamp: outputRecord.timestamp,
2384
+ cwd: base.cwd,
2385
+ message: {
2386
+ role: "tool",
2387
+ content: [toolResult]
2388
+ }
2389
+ };
2390
+ }
2391
+ function emitWebSearchCall(payload, base, counter) {
2392
+ const action = payload.action;
2393
+ const query = action?.query;
2394
+ const status = payload.status;
2395
+ const id = generateId(base.sessionId, counter);
2396
+ const toolUse = {
2397
+ type: "tool_use",
2398
+ id,
2399
+ name: "WebSearch",
2400
+ input: { query: query ?? "" }
2401
+ };
2402
+ const entries = [
2403
+ {
2404
+ type: "assistant",
2405
+ uuid: id,
2406
+ ...base,
2407
+ message: {
2408
+ role: "assistant",
2409
+ content: [toolUse]
2410
+ },
2411
+ metadata: { action }
2412
+ }
2413
+ ];
2414
+ if (status === "completed") {
2415
+ const toolResult = {
2416
+ type: "tool_result",
2417
+ tool_use_id: id,
2418
+ content: "",
2419
+ is_error: false
2420
+ };
2421
+ entries.push({
2422
+ type: "result",
2423
+ uuid: `${id}-result`,
2424
+ parentUuid: id,
2425
+ ...base,
2426
+ message: {
2427
+ role: "tool",
2428
+ content: [toolResult]
2429
+ }
2430
+ });
2431
+ }
2432
+ return entries;
2433
+ }
2434
+ function emitOrphanedOutput(payload, subtype, base, outputIndex, _counter) {
2435
+ const callId = payload.call_id;
2436
+ if (!callId)
2437
+ return [];
2438
+ if (!outputIndex.has(callId))
2439
+ return [];
2440
+ const rawOutput = payload.output;
2441
+ let content;
2442
+ let isError = false;
2443
+ if (subtype === "function_call_output") {
2444
+ const parsed = parseExecOutputHeader(rawOutput);
2445
+ content = parsed.body;
2446
+ isError = parsed.exitCode !== 0;
2447
+ } else {
2448
+ content = rawOutput;
2449
+ }
2450
+ const toolResult = {
2451
+ type: "tool_result",
2452
+ tool_use_id: callId,
2453
+ content,
2454
+ is_error: isError
2455
+ };
2456
+ outputIndex.delete(callId);
2457
+ return [
2458
+ {
2459
+ type: "result",
2460
+ uuid: `${callId}-result`,
2461
+ parentUuid: callId,
2462
+ ...base,
2463
+ message: {
2464
+ role: "tool",
2465
+ content: [toolResult]
2466
+ }
2467
+ }
2468
+ ];
2469
+ }
2470
+ function adaptContentItems(items) {
2471
+ if (!Array.isArray(items))
2472
+ return [];
2473
+ const blocks = [];
2474
+ for (const item of items) {
2475
+ switch (item.type) {
2476
+ case "input_text":
2477
+ case "output_text":
2478
+ if (item.text) {
2479
+ blocks.push({ type: "text", text: item.text });
2480
+ }
2481
+ break;
2482
+ case "input_image":
2483
+ if (item.image_url) {
2484
+ const dataUriMatch = item.image_url.match(
2485
+ /^data:(image\/[^;]+);base64,(.+)$/s
2486
+ );
2487
+ if (dataUriMatch) {
2488
+ blocks.push({
2489
+ type: "image",
2490
+ source: {
2491
+ type: "base64",
2492
+ media_type: dataUriMatch[1],
2493
+ data: dataUriMatch[2]
2494
+ }
2495
+ });
2496
+ } else {
2497
+ blocks.push({
2498
+ type: "image",
2499
+ source: {
2500
+ type: "base64",
2501
+ data: item.image_url
2502
+ }
2503
+ });
2504
+ }
2505
+ }
2506
+ break;
2507
+ }
2508
+ }
2509
+ return blocks;
2510
+ }
2511
+ function mapFunctionCall(name, args) {
2512
+ switch (name) {
2513
+ case "exec_command":
2514
+ return {
2515
+ toolName: "Bash",
2516
+ toolInput: { command: args.cmd ?? "" }
2517
+ };
2518
+ case "shell_command":
2519
+ return {
2520
+ toolName: "Bash",
2521
+ toolInput: { command: args.command ?? "" }
2522
+ };
2523
+ case "view_image":
2524
+ return {
2525
+ toolName: "Read",
2526
+ toolInput: { file_path: args.path ?? "" },
2527
+ metadata: { isImageView: true }
2528
+ };
2529
+ case "update_plan": {
2530
+ const plan = args.plan ?? [];
2531
+ return {
2532
+ toolName: "TodoWrite",
2533
+ toolInput: {
2534
+ todos: plan.map((item) => ({
2535
+ content: item.step,
2536
+ status: item.status,
2537
+ activeForm: item.step
2538
+ }))
2539
+ }
2540
+ };
2541
+ }
2542
+ case "write_stdin":
2543
+ return {
2544
+ toolName: "Bash",
2545
+ toolInput: {
2546
+ command: `(write_stdin to session ${args.session_id ?? "unknown"})`
2547
+ }
2548
+ };
2549
+ default:
2550
+ return { toolName: name, toolInput: args };
2551
+ }
2552
+ }
2553
+ function parseExecOutputHeader(output) {
2554
+ if (!output)
2555
+ return { exitCode: 0, body: "" };
2556
+ const currentMatch = output.match(/Process exited with code (\d+)/);
2557
+ if (currentMatch) {
2558
+ const exitCode = parseInt(currentMatch[1], 10);
2559
+ const outputIdx = output.indexOf("Output:\n");
2560
+ const body = outputIdx >= 0 ? output.slice(outputIdx + "Output:\n".length) : "";
2561
+ return { exitCode, body };
2562
+ }
2563
+ const legacyMatch = output.match(/Exit code: (\d+)/);
2564
+ if (legacyMatch) {
2565
+ const exitCode = parseInt(legacyMatch[1], 10);
2566
+ const outputIdx = output.indexOf("Output:\n");
2567
+ const body = outputIdx >= 0 ? output.slice(outputIdx + "Output:\n".length) : "";
2568
+ return { exitCode, body };
2569
+ }
2570
+ return { exitCode: 0, body: output };
2571
+ }
2572
+ function parseCodexPatch(input) {
2573
+ if (!input)
2574
+ return [];
2575
+ const lines = input.split("\n");
2576
+ const changes = [];
2577
+ let currentPath;
2578
+ let currentKind;
2579
+ let oldLines = [];
2580
+ let newLines = [];
2581
+ function flushCurrent() {
2582
+ if (currentPath && currentKind) {
2583
+ changes.push({
2584
+ path: currentPath,
2585
+ kind: currentKind,
2586
+ oldString: oldLines.join("\n"),
2587
+ newString: newLines.join("\n")
2588
+ });
2589
+ }
2590
+ currentPath = void 0;
2591
+ currentKind = void 0;
2592
+ oldLines = [];
2593
+ newLines = [];
2594
+ }
2595
+ for (const line of lines) {
2596
+ const updateMatch = line.match(/^\*\*\* Update File:\s*(.+)$/);
2597
+ if (updateMatch) {
2598
+ flushCurrent();
2599
+ currentPath = updateMatch[1].trim();
2600
+ currentKind = "update";
2601
+ continue;
2602
+ }
2603
+ const addMatch = line.match(/^\*\*\* Add File:\s*(.+)$/);
2604
+ if (addMatch) {
2605
+ flushCurrent();
2606
+ currentPath = addMatch[1].trim();
2607
+ currentKind = "add";
2608
+ continue;
2609
+ }
2610
+ const deleteMatch = line.match(/^\*\*\* Delete File:\s*(.+)$/);
2611
+ if (deleteMatch) {
2612
+ flushCurrent();
2613
+ currentPath = deleteMatch[1].trim();
2614
+ currentKind = "delete";
2615
+ continue;
2616
+ }
2617
+ if (line.startsWith("*** Begin Patch") || line.startsWith("*** End Patch")) {
2618
+ continue;
2619
+ }
2620
+ if (line.startsWith("@@")) {
2621
+ continue;
2622
+ }
2623
+ if (!currentPath)
2624
+ continue;
2625
+ if (line.startsWith("-")) {
2626
+ oldLines.push(line.slice(1));
2627
+ } else if (line.startsWith("+")) {
2628
+ newLines.push(line.slice(1));
2629
+ } else if (line.startsWith(" ")) {
2630
+ oldLines.push(line.slice(1));
2631
+ newLines.push(line.slice(1));
2632
+ }
2633
+ }
2634
+ flushCurrent();
2635
+ return changes;
2636
+ }
2637
+ function generateId(sessionId, counter) {
2638
+ return `codex-jsonl-${sessionId.slice(0, 8)}-${counter}`;
2639
+ }
2640
+
2641
+ // src/recall/message-ingest.ts
2642
+ function extractEntryText(entry) {
2643
+ const msg = entry.message;
2644
+ if (!msg)
2645
+ return "";
2646
+ if (typeof msg.content === "string")
2647
+ return msg.content.trim();
2648
+ if (Array.isArray(msg.content)) {
2649
+ return msg.content.filter((b) => b.type === "text").map((b) => b.text?.trim()).filter(Boolean).join("\n\n");
2650
+ }
2651
+ return "";
2652
+ }
2653
+ async function ingestSessionMessages(sessionId, transcriptPath, vendor, options) {
2654
+ const rawProjectId = options?.projectId ?? null;
2655
+ const projectId = rawProjectId ? normalizePath(rawProjectId) : null;
2656
+ let rawEntries;
2657
+ try {
2658
+ if (vendor === "claude") {
2659
+ const raw = parseJsonlFile(transcriptPath);
2660
+ rawEntries = adaptClaudeEntries(raw);
2661
+ } else {
2662
+ const envelopes = parseCodexJsonlFile(transcriptPath);
2663
+ rawEntries = adaptCodexJsonlRecords(envelopes, sessionId);
2664
+ }
2665
+ } catch (err) {
2666
+ return {
2667
+ sessionId,
2668
+ chunksCreated: 0,
2669
+ skipped: false,
2670
+ error: `Failed to load session: ${err instanceof Error ? err.message : String(err)}`
2671
+ };
2672
+ }
2673
+ if (rawEntries.length === 0) {
2674
+ return { sessionId, chunksCreated: 0, skipped: true };
2675
+ }
2676
+ const filtered = stripToolContent(rawEntries);
2677
+ const topLevel = filtered.filter((e) => !e.parentToolUseID);
2678
+ const records = [];
2679
+ for (let i = 0; i < topLevel.length; i++) {
2680
+ const entry = topLevel[i];
2681
+ if (!entry.uuid)
2682
+ continue;
2683
+ const text = extractEntryText(entry);
2684
+ if (!text)
2685
+ continue;
2686
+ const createdAt = entry.timestamp ? new Date(entry.timestamp).getTime() : Date.now();
2687
+ records.push({
2688
+ message_id: entry.uuid,
2689
+ session_id: sessionId,
2690
+ message_seq: i,
2691
+ message_text: text,
2692
+ project_id: projectId,
2693
+ created_at: createdAt,
2694
+ message_role: entry.message?.role ?? entry.type ?? null
2695
+ });
2696
+ }
2697
+ if (records.length === 0) {
2698
+ return { sessionId, chunksCreated: 0, skipped: true };
2699
+ }
2700
+ try {
2701
+ insertMessages(records, options?.force ? { replaceSessionId: sessionId } : void 0);
2702
+ } catch (err) {
2703
+ return {
2704
+ sessionId,
2705
+ chunksCreated: 0,
2706
+ skipped: false,
2707
+ error: `DB insert failed: ${err instanceof Error ? err.message : String(err)}`
2708
+ };
2709
+ }
2710
+ return {
2711
+ sessionId,
2712
+ chunksCreated: records.length,
2713
+ skipped: false
2714
+ };
2715
+ }
2716
+
2717
+ // src/hooks/stop-hook.ts
2718
+ init_paths();
2719
+ var import_fs = require("fs");
2720
+ var import_child_process = require("child_process");
2721
+ var import_path = require("path");
2722
+ function vendorForTranscript(transcriptPath) {
2723
+ const p = transcriptPath.replace(/\\/g, "/");
2724
+ return p.includes("/.codex/") ? "codex" : "claude";
2725
+ }
2726
+ function logStopHook(line) {
2727
+ try {
2728
+ (0, import_fs.mkdirSync)(logsDir(), { recursive: true });
2729
+ (0, import_fs.appendFileSync)((0, import_path.join)(logsDir(), "stop-hook.log"), line);
2730
+ } catch {
2731
+ }
2732
+ }
2733
+ async function runStopHook() {
2734
+ let data = "";
2735
+ for await (const chunk of process.stdin)
2736
+ data += chunk;
2737
+ let payload;
2738
+ try {
2739
+ payload = JSON.parse(data);
2740
+ } catch {
2741
+ process.exit(0);
2742
+ }
2743
+ if (!payload?.session_id || !payload?.transcript_path)
2744
+ process.exit(0);
2745
+ if (payload.stop_hook_active)
2746
+ process.exit(0);
2747
+ try {
2748
+ getDb(dbPath()).exec("PRAGMA busy_timeout = 500;");
2749
+ const vendor = vendorForTranscript(payload.transcript_path);
2750
+ const result = await ingestSessionMessages(
2751
+ payload.session_id,
2752
+ payload.transcript_path,
2753
+ vendor,
2754
+ { projectId: payload.cwd ?? void 0 }
2755
+ );
2756
+ if (result?.error) {
2757
+ logStopHook(
2758
+ `${(/* @__PURE__ */ new Date()).toISOString()} ingest-failed sid=${payload.session_id} err=${result.error}
2759
+ `
2760
+ );
2761
+ }
2762
+ } catch (e) {
2763
+ logStopHook(
2764
+ `${(/* @__PURE__ */ new Date()).toISOString()} ingest-failed sid=${payload.session_id} err=${e.message}
2765
+ `
2766
+ );
2767
+ }
2768
+ (0, import_child_process.spawn)(
2769
+ process.execPath,
2770
+ [(0, import_path.join)(binDir(), "embed-pending.js"), payload.session_id],
2771
+ {
2772
+ detached: true,
2773
+ stdio: "ignore",
2774
+ windowsHide: true
2775
+ }
2776
+ ).unref();
2777
+ process.exit(0);
2778
+ }
2779
+ if (typeof require !== "undefined" && typeof module !== "undefined" && require.main === module) {
2780
+ void runStopHook();
2781
+ }
2782
+ // Annotate the CommonJS export names for ESM import in node:
2783
+ 0 && (module.exports = {
2784
+ vendorForTranscript
2785
+ });