@codedir/mimir-code 0.1.0 → 0.1.1

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.
@@ -1,875 +1,32 @@
1
- #!/usr/bin/env node
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
10
- }) : x)(function(x) {
11
- if (typeof require !== "undefined") return require.apply(this, arguments);
12
- throw Error('Dynamic require of "' + x + '" is not supported');
13
- });
14
- var __esm = (fn, res) => function __init() {
15
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
16
- };
17
- var __commonJS = (cb, mod) => function __require2() {
18
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
- };
20
- var __export = (target, all) => {
21
- for (var name in all)
22
- __defProp(target, name, { get: all[name], enumerable: true });
23
- };
24
- var __copyProps = (to, from, except, desc) => {
25
- if (from && typeof from === "object" || typeof from === "function") {
26
- for (let key of __getOwnPropNames(from))
27
- if (!__hasOwnProp.call(to, key) && key !== except)
28
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
29
- }
30
- return to;
31
- };
32
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
33
- // If the importer is in node compatibility mode or this is not an ESM
34
- // file that has been converted to a CommonJS file using a Babel-
35
- // compatible transform (i.e. "__esModule" has not been set), then set
36
- // "default" to the CommonJS "module.exports" for node compatibility.
37
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
38
- mod
39
- ));
40
-
41
- // node_modules/tsup/assets/esm_shims.js
42
- import path from "path";
43
- import { fileURLToPath } from "url";
44
- var getFilename, __filename;
45
- var init_esm_shims = __esm({
46
- "node_modules/tsup/assets/esm_shims.js"() {
47
- "use strict";
48
- getFilename = () => fileURLToPath(import.meta.url);
49
- __filename = /* @__PURE__ */ getFilename();
50
- }
51
- });
52
-
53
- // node_modules/better-sqlite3/lib/util.js
54
- var require_util = __commonJS({
55
- "node_modules/better-sqlite3/lib/util.js"(exports) {
56
- "use strict";
57
- init_esm_shims();
58
- exports.getBooleanOption = (options, key) => {
59
- let value = false;
60
- if (key in options && typeof (value = options[key]) !== "boolean") {
61
- throw new TypeError(`Expected the "${key}" option to be a boolean`);
62
- }
63
- return value;
64
- };
65
- exports.cppdb = Symbol();
66
- exports.inspect = Symbol.for("nodejs.util.inspect.custom");
67
- }
68
- });
69
-
70
- // node_modules/better-sqlite3/lib/sqlite-error.js
71
- var require_sqlite_error = __commonJS({
72
- "node_modules/better-sqlite3/lib/sqlite-error.js"(exports, module) {
73
- "use strict";
74
- init_esm_shims();
75
- var descriptor = { value: "SqliteError", writable: true, enumerable: false, configurable: true };
76
- function SqliteError(message, code) {
77
- if (new.target !== SqliteError) {
78
- return new SqliteError(message, code);
79
- }
80
- if (typeof code !== "string") {
81
- throw new TypeError("Expected second argument to be a string");
82
- }
83
- Error.call(this, message);
84
- descriptor.value = "" + message;
85
- Object.defineProperty(this, "message", descriptor);
86
- Error.captureStackTrace(this, SqliteError);
87
- this.code = code;
88
- }
89
- Object.setPrototypeOf(SqliteError, Error);
90
- Object.setPrototypeOf(SqliteError.prototype, Error.prototype);
91
- Object.defineProperty(SqliteError.prototype, "name", descriptor);
92
- module.exports = SqliteError;
93
- }
94
- });
95
-
96
- // node_modules/file-uri-to-path/index.js
97
- var require_file_uri_to_path = __commonJS({
98
- "node_modules/file-uri-to-path/index.js"(exports, module) {
99
- "use strict";
100
- init_esm_shims();
101
- var sep = __require("path").sep || "/";
102
- module.exports = fileUriToPath;
103
- function fileUriToPath(uri) {
104
- if ("string" != typeof uri || uri.length <= 7 || "file://" != uri.substring(0, 7)) {
105
- throw new TypeError("must pass in a file:// URI to convert to a file path");
106
- }
107
- var rest = decodeURI(uri.substring(7));
108
- var firstSlash = rest.indexOf("/");
109
- var host = rest.substring(0, firstSlash);
110
- var path9 = rest.substring(firstSlash + 1);
111
- if ("localhost" == host) host = "";
112
- if (host) {
113
- host = sep + sep + host;
114
- }
115
- path9 = path9.replace(/^(.+)\|/, "$1:");
116
- if (sep == "\\") {
117
- path9 = path9.replace(/\//g, "\\");
118
- }
119
- if (/^.+\:/.test(path9)) {
120
- } else {
121
- path9 = sep + path9;
122
- }
123
- return host + path9;
124
- }
125
- }
126
- });
127
-
128
- // node_modules/bindings/bindings.js
129
- var require_bindings = __commonJS({
130
- "node_modules/bindings/bindings.js"(exports, module) {
131
- "use strict";
132
- init_esm_shims();
133
- var fs4 = __require("fs");
134
- var path9 = __require("path");
135
- var fileURLToPath3 = require_file_uri_to_path();
136
- var join = path9.join;
137
- var dirname3 = path9.dirname;
138
- var exists = fs4.accessSync && function(path10) {
139
- try {
140
- fs4.accessSync(path10);
141
- } catch (e) {
142
- return false;
143
- }
144
- return true;
145
- } || fs4.existsSync || path9.existsSync;
146
- var defaults = {
147
- arrow: process.env.NODE_BINDINGS_ARROW || " \u2192 ",
148
- compiled: process.env.NODE_BINDINGS_COMPILED_DIR || "compiled",
149
- platform: process.platform,
150
- arch: process.arch,
151
- nodePreGyp: "node-v" + process.versions.modules + "-" + process.platform + "-" + process.arch,
152
- version: process.versions.node,
153
- bindings: "bindings.node",
154
- try: [
155
- // node-gyp's linked version in the "build" dir
156
- ["module_root", "build", "bindings"],
157
- // node-waf and gyp_addon (a.k.a node-gyp)
158
- ["module_root", "build", "Debug", "bindings"],
159
- ["module_root", "build", "Release", "bindings"],
160
- // Debug files, for development (legacy behavior, remove for node v0.9)
161
- ["module_root", "out", "Debug", "bindings"],
162
- ["module_root", "Debug", "bindings"],
163
- // Release files, but manually compiled (legacy behavior, remove for node v0.9)
164
- ["module_root", "out", "Release", "bindings"],
165
- ["module_root", "Release", "bindings"],
166
- // Legacy from node-waf, node <= 0.4.x
167
- ["module_root", "build", "default", "bindings"],
168
- // Production "Release" buildtype binary (meh...)
169
- ["module_root", "compiled", "version", "platform", "arch", "bindings"],
170
- // node-qbs builds
171
- ["module_root", "addon-build", "release", "install-root", "bindings"],
172
- ["module_root", "addon-build", "debug", "install-root", "bindings"],
173
- ["module_root", "addon-build", "default", "install-root", "bindings"],
174
- // node-pre-gyp path ./lib/binding/{node_abi}-{platform}-{arch}
175
- ["module_root", "lib", "binding", "nodePreGyp", "bindings"]
176
- ]
177
- };
178
- function bindings(opts) {
179
- if (typeof opts == "string") {
180
- opts = { bindings: opts };
181
- } else if (!opts) {
182
- opts = {};
183
- }
184
- Object.keys(defaults).map(function(i2) {
185
- if (!(i2 in opts)) opts[i2] = defaults[i2];
186
- });
187
- if (!opts.module_root) {
188
- opts.module_root = exports.getRoot(exports.getFileName());
189
- }
190
- if (path9.extname(opts.bindings) != ".node") {
191
- opts.bindings += ".node";
192
- }
193
- var requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
194
- var tries = [], i = 0, l = opts.try.length, n, b, err;
195
- for (; i < l; i++) {
196
- n = join.apply(
197
- null,
198
- opts.try[i].map(function(p) {
199
- return opts[p] || p;
200
- })
201
- );
202
- tries.push(n);
203
- try {
204
- b = opts.path ? requireFunc.resolve(n) : requireFunc(n);
205
- if (!opts.path) {
206
- b.path = n;
207
- }
208
- return b;
209
- } catch (e) {
210
- if (e.code !== "MODULE_NOT_FOUND" && e.code !== "QUALIFIED_PATH_RESOLUTION_FAILED" && !/not find/i.test(e.message)) {
211
- throw e;
212
- }
213
- }
214
- }
215
- err = new Error(
216
- "Could not locate the bindings file. Tried:\n" + tries.map(function(a) {
217
- return opts.arrow + a;
218
- }).join("\n")
219
- );
220
- err.tries = tries;
221
- throw err;
222
- }
223
- module.exports = exports = bindings;
224
- exports.getFileName = function getFileName(calling_file) {
225
- var origPST = Error.prepareStackTrace, origSTL = Error.stackTraceLimit, dummy = {}, fileName;
226
- Error.stackTraceLimit = 10;
227
- Error.prepareStackTrace = function(e, st) {
228
- for (var i = 0, l = st.length; i < l; i++) {
229
- fileName = st[i].getFileName();
230
- if (fileName !== __filename) {
231
- if (calling_file) {
232
- if (fileName !== calling_file) {
233
- return;
234
- }
235
- } else {
236
- return;
237
- }
238
- }
239
- }
240
- };
241
- Error.captureStackTrace(dummy);
242
- dummy.stack;
243
- Error.prepareStackTrace = origPST;
244
- Error.stackTraceLimit = origSTL;
245
- var fileSchema = "file://";
246
- if (fileName.indexOf(fileSchema) === 0) {
247
- fileName = fileURLToPath3(fileName);
248
- }
249
- return fileName;
250
- };
251
- exports.getRoot = function getRoot(file) {
252
- var dir = dirname3(file), prev;
253
- while (true) {
254
- if (dir === ".") {
255
- dir = process.cwd();
256
- }
257
- if (exists(join(dir, "package.json")) || exists(join(dir, "node_modules"))) {
258
- return dir;
259
- }
260
- if (prev === dir) {
261
- throw new Error(
262
- 'Could not find module root given file: "' + file + '". Do you have a `package.json` file? '
263
- );
264
- }
265
- prev = dir;
266
- dir = join(dir, "..");
267
- }
268
- };
269
- }
270
- });
271
-
272
- // node_modules/better-sqlite3/lib/methods/wrappers.js
273
- var require_wrappers = __commonJS({
274
- "node_modules/better-sqlite3/lib/methods/wrappers.js"(exports) {
275
- "use strict";
276
- init_esm_shims();
277
- var { cppdb } = require_util();
278
- exports.prepare = function prepare(sql2) {
279
- return this[cppdb].prepare(sql2, this, false);
280
- };
281
- exports.exec = function exec(sql2) {
282
- this[cppdb].exec(sql2);
283
- return this;
284
- };
285
- exports.close = function close() {
286
- this[cppdb].close();
287
- return this;
288
- };
289
- exports.loadExtension = function loadExtension(...args) {
290
- this[cppdb].loadExtension(...args);
291
- return this;
292
- };
293
- exports.defaultSafeIntegers = function defaultSafeIntegers(...args) {
294
- this[cppdb].defaultSafeIntegers(...args);
295
- return this;
296
- };
297
- exports.unsafeMode = function unsafeMode(...args) {
298
- this[cppdb].unsafeMode(...args);
299
- return this;
300
- };
301
- exports.getters = {
302
- name: {
303
- get: function name() {
304
- return this[cppdb].name;
305
- },
306
- enumerable: true
307
- },
308
- open: {
309
- get: function open() {
310
- return this[cppdb].open;
311
- },
312
- enumerable: true
313
- },
314
- inTransaction: {
315
- get: function inTransaction() {
316
- return this[cppdb].inTransaction;
317
- },
318
- enumerable: true
319
- },
320
- readonly: {
321
- get: function readonly() {
322
- return this[cppdb].readonly;
323
- },
324
- enumerable: true
325
- },
326
- memory: {
327
- get: function memory() {
328
- return this[cppdb].memory;
329
- },
330
- enumerable: true
331
- }
332
- };
333
- }
334
- });
335
-
336
- // node_modules/better-sqlite3/lib/methods/transaction.js
337
- var require_transaction = __commonJS({
338
- "node_modules/better-sqlite3/lib/methods/transaction.js"(exports, module) {
339
- "use strict";
340
- init_esm_shims();
341
- var { cppdb } = require_util();
342
- var controllers = /* @__PURE__ */ new WeakMap();
343
- module.exports = function transaction(fn) {
344
- if (typeof fn !== "function") throw new TypeError("Expected first argument to be a function");
345
- const db = this[cppdb];
346
- const controller = getController(db, this);
347
- const { apply } = Function.prototype;
348
- const properties = {
349
- default: { value: wrapTransaction(apply, fn, db, controller.default) },
350
- deferred: { value: wrapTransaction(apply, fn, db, controller.deferred) },
351
- immediate: { value: wrapTransaction(apply, fn, db, controller.immediate) },
352
- exclusive: { value: wrapTransaction(apply, fn, db, controller.exclusive) },
353
- database: { value: this, enumerable: true }
354
- };
355
- Object.defineProperties(properties.default.value, properties);
356
- Object.defineProperties(properties.deferred.value, properties);
357
- Object.defineProperties(properties.immediate.value, properties);
358
- Object.defineProperties(properties.exclusive.value, properties);
359
- return properties.default.value;
360
- };
361
- var getController = (db, self) => {
362
- let controller = controllers.get(db);
363
- if (!controller) {
364
- const shared = {
365
- commit: db.prepare("COMMIT", self, false),
366
- rollback: db.prepare("ROLLBACK", self, false),
367
- savepoint: db.prepare("SAVEPOINT ` _bs3. `", self, false),
368
- release: db.prepare("RELEASE ` _bs3. `", self, false),
369
- rollbackTo: db.prepare("ROLLBACK TO ` _bs3. `", self, false)
370
- };
371
- controllers.set(db, controller = {
372
- default: Object.assign({ begin: db.prepare("BEGIN", self, false) }, shared),
373
- deferred: Object.assign({ begin: db.prepare("BEGIN DEFERRED", self, false) }, shared),
374
- immediate: Object.assign({ begin: db.prepare("BEGIN IMMEDIATE", self, false) }, shared),
375
- exclusive: Object.assign({ begin: db.prepare("BEGIN EXCLUSIVE", self, false) }, shared)
376
- });
377
- }
378
- return controller;
379
- };
380
- var wrapTransaction = (apply, fn, db, { begin, commit, rollback, savepoint, release, rollbackTo }) => function sqliteTransaction() {
381
- let before, after, undo;
382
- if (db.inTransaction) {
383
- before = savepoint;
384
- after = release;
385
- undo = rollbackTo;
386
- } else {
387
- before = begin;
388
- after = commit;
389
- undo = rollback;
390
- }
391
- before.run();
392
- try {
393
- const result = apply.call(fn, this, arguments);
394
- if (result && typeof result.then === "function") {
395
- throw new TypeError("Transaction function cannot return a promise");
396
- }
397
- after.run();
398
- return result;
399
- } catch (ex) {
400
- if (db.inTransaction) {
401
- undo.run();
402
- if (undo !== rollback) after.run();
403
- }
404
- throw ex;
405
- }
406
- };
407
- }
408
- });
409
-
410
- // node_modules/better-sqlite3/lib/methods/pragma.js
411
- var require_pragma = __commonJS({
412
- "node_modules/better-sqlite3/lib/methods/pragma.js"(exports, module) {
413
- "use strict";
414
- init_esm_shims();
415
- var { getBooleanOption, cppdb } = require_util();
416
- module.exports = function pragma(source, options) {
417
- if (options == null) options = {};
418
- if (typeof source !== "string") throw new TypeError("Expected first argument to be a string");
419
- if (typeof options !== "object") throw new TypeError("Expected second argument to be an options object");
420
- const simple = getBooleanOption(options, "simple");
421
- const stmt = this[cppdb].prepare(`PRAGMA ${source}`, this, true);
422
- return simple ? stmt.pluck().get() : stmt.all();
423
- };
424
- }
425
- });
426
-
427
- // node_modules/better-sqlite3/lib/methods/backup.js
428
- var require_backup = __commonJS({
429
- "node_modules/better-sqlite3/lib/methods/backup.js"(exports, module) {
430
- "use strict";
431
- init_esm_shims();
432
- var fs4 = __require("fs");
433
- var path9 = __require("path");
434
- var { promisify } = __require("util");
435
- var { cppdb } = require_util();
436
- var fsAccess = promisify(fs4.access);
437
- module.exports = async function backup(filename, options) {
438
- if (options == null) options = {};
439
- if (typeof filename !== "string") throw new TypeError("Expected first argument to be a string");
440
- if (typeof options !== "object") throw new TypeError("Expected second argument to be an options object");
441
- filename = filename.trim();
442
- const attachedName = "attached" in options ? options.attached : "main";
443
- const handler = "progress" in options ? options.progress : null;
444
- if (!filename) throw new TypeError("Backup filename cannot be an empty string");
445
- if (filename === ":memory:") throw new TypeError('Invalid backup filename ":memory:"');
446
- if (typeof attachedName !== "string") throw new TypeError('Expected the "attached" option to be a string');
447
- if (!attachedName) throw new TypeError('The "attached" option cannot be an empty string');
448
- if (handler != null && typeof handler !== "function") throw new TypeError('Expected the "progress" option to be a function');
449
- await fsAccess(path9.dirname(filename)).catch(() => {
450
- throw new TypeError("Cannot save backup because the directory does not exist");
451
- });
452
- const isNewFile = await fsAccess(filename).then(() => false, () => true);
453
- return runBackup(this[cppdb].backup(this, attachedName, filename, isNewFile), handler || null);
454
- };
455
- var runBackup = (backup, handler) => {
456
- let rate = 0;
457
- let useDefault = true;
458
- return new Promise((resolve, reject) => {
459
- setImmediate(function step() {
460
- try {
461
- const progress = backup.transfer(rate);
462
- if (!progress.remainingPages) {
463
- backup.close();
464
- resolve(progress);
465
- return;
466
- }
467
- if (useDefault) {
468
- useDefault = false;
469
- rate = 100;
470
- }
471
- if (handler) {
472
- const ret = handler(progress);
473
- if (ret !== void 0) {
474
- if (typeof ret === "number" && ret === ret) rate = Math.max(0, Math.min(2147483647, Math.round(ret)));
475
- else throw new TypeError("Expected progress callback to return a number or undefined");
476
- }
477
- }
478
- setImmediate(step);
479
- } catch (err) {
480
- backup.close();
481
- reject(err);
482
- }
483
- });
484
- });
485
- };
486
- }
487
- });
488
-
489
- // node_modules/better-sqlite3/lib/methods/serialize.js
490
- var require_serialize = __commonJS({
491
- "node_modules/better-sqlite3/lib/methods/serialize.js"(exports, module) {
492
- "use strict";
493
- init_esm_shims();
494
- var { cppdb } = require_util();
495
- module.exports = function serialize(options) {
496
- if (options == null) options = {};
497
- if (typeof options !== "object") throw new TypeError("Expected first argument to be an options object");
498
- const attachedName = "attached" in options ? options.attached : "main";
499
- if (typeof attachedName !== "string") throw new TypeError('Expected the "attached" option to be a string');
500
- if (!attachedName) throw new TypeError('The "attached" option cannot be an empty string');
501
- return this[cppdb].serialize(attachedName);
502
- };
503
- }
504
- });
505
-
506
- // node_modules/better-sqlite3/lib/methods/function.js
507
- var require_function = __commonJS({
508
- "node_modules/better-sqlite3/lib/methods/function.js"(exports, module) {
509
- "use strict";
510
- init_esm_shims();
511
- var { getBooleanOption, cppdb } = require_util();
512
- module.exports = function defineFunction(name, options, fn) {
513
- if (options == null) options = {};
514
- if (typeof options === "function") {
515
- fn = options;
516
- options = {};
517
- }
518
- if (typeof name !== "string") throw new TypeError("Expected first argument to be a string");
519
- if (typeof fn !== "function") throw new TypeError("Expected last argument to be a function");
520
- if (typeof options !== "object") throw new TypeError("Expected second argument to be an options object");
521
- if (!name) throw new TypeError("User-defined function name cannot be an empty string");
522
- const safeIntegers = "safeIntegers" in options ? +getBooleanOption(options, "safeIntegers") : 2;
523
- const deterministic = getBooleanOption(options, "deterministic");
524
- const directOnly = getBooleanOption(options, "directOnly");
525
- const varargs = getBooleanOption(options, "varargs");
526
- let argCount = -1;
527
- if (!varargs) {
528
- argCount = fn.length;
529
- if (!Number.isInteger(argCount) || argCount < 0) throw new TypeError("Expected function.length to be a positive integer");
530
- if (argCount > 100) throw new RangeError("User-defined functions cannot have more than 100 arguments");
531
- }
532
- this[cppdb].function(fn, name, argCount, safeIntegers, deterministic, directOnly);
533
- return this;
534
- };
535
- }
536
- });
537
-
538
- // node_modules/better-sqlite3/lib/methods/aggregate.js
539
- var require_aggregate = __commonJS({
540
- "node_modules/better-sqlite3/lib/methods/aggregate.js"(exports, module) {
541
- "use strict";
542
- init_esm_shims();
543
- var { getBooleanOption, cppdb } = require_util();
544
- module.exports = function defineAggregate(name, options) {
545
- if (typeof name !== "string") throw new TypeError("Expected first argument to be a string");
546
- if (typeof options !== "object" || options === null) throw new TypeError("Expected second argument to be an options object");
547
- if (!name) throw new TypeError("User-defined function name cannot be an empty string");
548
- const start = "start" in options ? options.start : null;
549
- const step = getFunctionOption(options, "step", true);
550
- const inverse = getFunctionOption(options, "inverse", false);
551
- const result = getFunctionOption(options, "result", false);
552
- const safeIntegers = "safeIntegers" in options ? +getBooleanOption(options, "safeIntegers") : 2;
553
- const deterministic = getBooleanOption(options, "deterministic");
554
- const directOnly = getBooleanOption(options, "directOnly");
555
- const varargs = getBooleanOption(options, "varargs");
556
- let argCount = -1;
557
- if (!varargs) {
558
- argCount = Math.max(getLength(step), inverse ? getLength(inverse) : 0);
559
- if (argCount > 0) argCount -= 1;
560
- if (argCount > 100) throw new RangeError("User-defined functions cannot have more than 100 arguments");
561
- }
562
- this[cppdb].aggregate(start, step, inverse, result, name, argCount, safeIntegers, deterministic, directOnly);
563
- return this;
564
- };
565
- var getFunctionOption = (options, key, required) => {
566
- const value = key in options ? options[key] : null;
567
- if (typeof value === "function") return value;
568
- if (value != null) throw new TypeError(`Expected the "${key}" option to be a function`);
569
- if (required) throw new TypeError(`Missing required option "${key}"`);
570
- return null;
571
- };
572
- var getLength = ({ length }) => {
573
- if (Number.isInteger(length) && length >= 0) return length;
574
- throw new TypeError("Expected function.length to be a positive integer");
575
- };
576
- }
577
- });
578
-
579
- // node_modules/better-sqlite3/lib/methods/table.js
580
- var require_table = __commonJS({
581
- "node_modules/better-sqlite3/lib/methods/table.js"(exports, module) {
582
- "use strict";
583
- init_esm_shims();
584
- var { cppdb } = require_util();
585
- module.exports = function defineTable(name, factory) {
586
- if (typeof name !== "string") throw new TypeError("Expected first argument to be a string");
587
- if (!name) throw new TypeError("Virtual table module name cannot be an empty string");
588
- let eponymous = false;
589
- if (typeof factory === "object" && factory !== null) {
590
- eponymous = true;
591
- factory = defer(parseTableDefinition(factory, "used", name));
592
- } else {
593
- if (typeof factory !== "function") throw new TypeError("Expected second argument to be a function or a table definition object");
594
- factory = wrapFactory(factory);
595
- }
596
- this[cppdb].table(factory, name, eponymous);
597
- return this;
598
- };
599
- function wrapFactory(factory) {
600
- return function virtualTableFactory(moduleName, databaseName, tableName, ...args) {
601
- const thisObject = {
602
- module: moduleName,
603
- database: databaseName,
604
- table: tableName
605
- };
606
- const def = apply.call(factory, thisObject, args);
607
- if (typeof def !== "object" || def === null) {
608
- throw new TypeError(`Virtual table module "${moduleName}" did not return a table definition object`);
609
- }
610
- return parseTableDefinition(def, "returned", moduleName);
611
- };
612
- }
613
- function parseTableDefinition(def, verb, moduleName) {
614
- if (!hasOwnProperty.call(def, "rows")) {
615
- throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition without a "rows" property`);
616
- }
617
- if (!hasOwnProperty.call(def, "columns")) {
618
- throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition without a "columns" property`);
619
- }
620
- const rows = def.rows;
621
- if (typeof rows !== "function" || Object.getPrototypeOf(rows) !== GeneratorFunctionPrototype) {
622
- throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "rows" property (should be a generator function)`);
623
- }
624
- let columns = def.columns;
625
- if (!Array.isArray(columns) || !(columns = [...columns]).every((x) => typeof x === "string")) {
626
- throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "columns" property (should be an array of strings)`);
627
- }
628
- if (columns.length !== new Set(columns).size) {
629
- throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with duplicate column names`);
630
- }
631
- if (!columns.length) {
632
- throw new RangeError(`Virtual table module "${moduleName}" ${verb} a table definition with zero columns`);
633
- }
634
- let parameters;
635
- if (hasOwnProperty.call(def, "parameters")) {
636
- parameters = def.parameters;
637
- if (!Array.isArray(parameters) || !(parameters = [...parameters]).every((x) => typeof x === "string")) {
638
- throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "parameters" property (should be an array of strings)`);
639
- }
640
- } else {
641
- parameters = inferParameters(rows);
642
- }
643
- if (parameters.length !== new Set(parameters).size) {
644
- throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with duplicate parameter names`);
645
- }
646
- if (parameters.length > 32) {
647
- throw new RangeError(`Virtual table module "${moduleName}" ${verb} a table definition with more than the maximum number of 32 parameters`);
648
- }
649
- for (const parameter of parameters) {
650
- if (columns.includes(parameter)) {
651
- throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with column "${parameter}" which was ambiguously defined as both a column and parameter`);
652
- }
653
- }
654
- let safeIntegers = 2;
655
- if (hasOwnProperty.call(def, "safeIntegers")) {
656
- const bool = def.safeIntegers;
657
- if (typeof bool !== "boolean") {
658
- throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "safeIntegers" property (should be a boolean)`);
659
- }
660
- safeIntegers = +bool;
661
- }
662
- let directOnly = false;
663
- if (hasOwnProperty.call(def, "directOnly")) {
664
- directOnly = def.directOnly;
665
- if (typeof directOnly !== "boolean") {
666
- throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "directOnly" property (should be a boolean)`);
667
- }
668
- }
669
- const columnDefinitions = [
670
- ...parameters.map(identifier).map((str) => `${str} HIDDEN`),
671
- ...columns.map(identifier)
672
- ];
673
- return [
674
- `CREATE TABLE x(${columnDefinitions.join(", ")});`,
675
- wrapGenerator(rows, new Map(columns.map((x, i) => [x, parameters.length + i])), moduleName),
676
- parameters,
677
- safeIntegers,
678
- directOnly
679
- ];
680
- }
681
- function wrapGenerator(generator, columnMap, moduleName) {
682
- return function* virtualTable(...args) {
683
- const output = args.map((x) => Buffer.isBuffer(x) ? Buffer.from(x) : x);
684
- for (let i = 0; i < columnMap.size; ++i) {
685
- output.push(null);
686
- }
687
- for (const row of generator(...args)) {
688
- if (Array.isArray(row)) {
689
- extractRowArray(row, output, columnMap.size, moduleName);
690
- yield output;
691
- } else if (typeof row === "object" && row !== null) {
692
- extractRowObject(row, output, columnMap, moduleName);
693
- yield output;
694
- } else {
695
- throw new TypeError(`Virtual table module "${moduleName}" yielded something that isn't a valid row object`);
696
- }
697
- }
698
- };
699
- }
700
- function extractRowArray(row, output, columnCount, moduleName) {
701
- if (row.length !== columnCount) {
702
- throw new TypeError(`Virtual table module "${moduleName}" yielded a row with an incorrect number of columns`);
703
- }
704
- const offset = output.length - columnCount;
705
- for (let i = 0; i < columnCount; ++i) {
706
- output[i + offset] = row[i];
707
- }
708
- }
709
- function extractRowObject(row, output, columnMap, moduleName) {
710
- let count = 0;
711
- for (const key of Object.keys(row)) {
712
- const index2 = columnMap.get(key);
713
- if (index2 === void 0) {
714
- throw new TypeError(`Virtual table module "${moduleName}" yielded a row with an undeclared column "${key}"`);
715
- }
716
- output[index2] = row[key];
717
- count += 1;
718
- }
719
- if (count !== columnMap.size) {
720
- throw new TypeError(`Virtual table module "${moduleName}" yielded a row with missing columns`);
721
- }
722
- }
723
- function inferParameters({ length }) {
724
- if (!Number.isInteger(length) || length < 0) {
725
- throw new TypeError("Expected function.length to be a positive integer");
726
- }
727
- const params = [];
728
- for (let i = 0; i < length; ++i) {
729
- params.push(`$${i + 1}`);
730
- }
731
- return params;
732
- }
733
- var { hasOwnProperty } = Object.prototype;
734
- var { apply } = Function.prototype;
735
- var GeneratorFunctionPrototype = Object.getPrototypeOf(function* () {
736
- });
737
- var identifier = (str) => `"${str.replace(/"/g, '""')}"`;
738
- var defer = (x) => () => x;
739
- }
740
- });
741
-
742
- // node_modules/better-sqlite3/lib/methods/inspect.js
743
- var require_inspect = __commonJS({
744
- "node_modules/better-sqlite3/lib/methods/inspect.js"(exports, module) {
745
- "use strict";
746
- init_esm_shims();
747
- var DatabaseInspection = function Database2() {
748
- };
749
- module.exports = function inspect(depth, opts) {
750
- return Object.assign(new DatabaseInspection(), this);
751
- };
752
- }
753
- });
754
-
755
- // node_modules/better-sqlite3/lib/database.js
756
- var require_database = __commonJS({
757
- "node_modules/better-sqlite3/lib/database.js"(exports, module) {
758
- "use strict";
759
- init_esm_shims();
760
- var fs4 = __require("fs");
761
- var path9 = __require("path");
762
- var util = require_util();
763
- var SqliteError = require_sqlite_error();
764
- var DEFAULT_ADDON;
765
- function Database2(filenameGiven, options) {
766
- if (new.target == null) {
767
- return new Database2(filenameGiven, options);
768
- }
769
- let buffer;
770
- if (Buffer.isBuffer(filenameGiven)) {
771
- buffer = filenameGiven;
772
- filenameGiven = ":memory:";
773
- }
774
- if (filenameGiven == null) filenameGiven = "";
775
- if (options == null) options = {};
776
- if (typeof filenameGiven !== "string") throw new TypeError("Expected first argument to be a string");
777
- if (typeof options !== "object") throw new TypeError("Expected second argument to be an options object");
778
- if ("readOnly" in options) throw new TypeError('Misspelled option "readOnly" should be "readonly"');
779
- if ("memory" in options) throw new TypeError('Option "memory" was removed in v7.0.0 (use ":memory:" filename instead)');
780
- const filename = filenameGiven.trim();
781
- const anonymous = filename === "" || filename === ":memory:";
782
- const readonly = util.getBooleanOption(options, "readonly");
783
- const fileMustExist = util.getBooleanOption(options, "fileMustExist");
784
- const timeout = "timeout" in options ? options.timeout : 5e3;
785
- const verbose = "verbose" in options ? options.verbose : null;
786
- const nativeBinding = "nativeBinding" in options ? options.nativeBinding : null;
787
- if (readonly && anonymous && !buffer) throw new TypeError("In-memory/temporary databases cannot be readonly");
788
- if (!Number.isInteger(timeout) || timeout < 0) throw new TypeError('Expected the "timeout" option to be a positive integer');
789
- if (timeout > 2147483647) throw new RangeError('Option "timeout" cannot be greater than 2147483647');
790
- if (verbose != null && typeof verbose !== "function") throw new TypeError('Expected the "verbose" option to be a function');
791
- if (nativeBinding != null && typeof nativeBinding !== "string" && typeof nativeBinding !== "object") throw new TypeError('Expected the "nativeBinding" option to be a string or addon object');
792
- let addon;
793
- if (nativeBinding == null) {
794
- addon = DEFAULT_ADDON || (DEFAULT_ADDON = require_bindings()("better_sqlite3.node"));
795
- } else if (typeof nativeBinding === "string") {
796
- const requireFunc = typeof __non_webpack_require__ === "function" ? __non_webpack_require__ : __require;
797
- addon = requireFunc(path9.resolve(nativeBinding).replace(/(\.node)?$/, ".node"));
798
- } else {
799
- addon = nativeBinding;
800
- }
801
- if (!addon.isInitialized) {
802
- addon.setErrorConstructor(SqliteError);
803
- addon.isInitialized = true;
804
- }
805
- if (!anonymous && !fs4.existsSync(path9.dirname(filename))) {
806
- throw new TypeError("Cannot open database because the directory does not exist");
807
- }
808
- Object.defineProperties(this, {
809
- [util.cppdb]: { value: new addon.Database(filename, filenameGiven, anonymous, readonly, fileMustExist, timeout, verbose || null, buffer || null) },
810
- ...wrappers.getters
811
- });
812
- }
813
- var wrappers = require_wrappers();
814
- Database2.prototype.prepare = wrappers.prepare;
815
- Database2.prototype.transaction = require_transaction();
816
- Database2.prototype.pragma = require_pragma();
817
- Database2.prototype.backup = require_backup();
818
- Database2.prototype.serialize = require_serialize();
819
- Database2.prototype.function = require_function();
820
- Database2.prototype.aggregate = require_aggregate();
821
- Database2.prototype.table = require_table();
822
- Database2.prototype.loadExtension = wrappers.loadExtension;
823
- Database2.prototype.exec = wrappers.exec;
824
- Database2.prototype.close = wrappers.close;
825
- Database2.prototype.defaultSafeIntegers = wrappers.defaultSafeIntegers;
826
- Database2.prototype.unsafeMode = wrappers.unsafeMode;
827
- Database2.prototype[util.inspect] = require_inspect();
828
- module.exports = Database2;
829
- }
830
- });
831
-
832
- // node_modules/better-sqlite3/lib/index.js
833
- var require_lib = __commonJS({
834
- "node_modules/better-sqlite3/lib/index.js"(exports, module) {
835
- "use strict";
836
- init_esm_shims();
837
- module.exports = require_database();
838
- module.exports.SqliteError = require_sqlite_error();
839
- }
840
- });
841
-
842
1
  // src/cli.ts
843
- init_esm_shims();
844
2
  import { Command } from "commander";
845
3
 
846
4
  // src/platform/FileSystemAdapter.ts
847
- init_esm_shims();
848
5
  import fs from "fs/promises";
849
- import { globby } from "globby";
6
+ import fg from "fast-glob";
850
7
  var FileSystemAdapter = class {
851
- async readFile(path9, encoding = "utf-8") {
852
- return fs.readFile(path9, encoding);
8
+ async readFile(path8, encoding = "utf-8") {
9
+ return fs.readFile(path8, encoding);
853
10
  }
854
- async writeFile(path9, content, encoding = "utf-8") {
855
- await fs.writeFile(path9, content, encoding);
11
+ async writeFile(path8, content, encoding = "utf-8") {
12
+ await fs.writeFile(path8, content, encoding);
856
13
  }
857
- async exists(path9) {
14
+ async exists(path8) {
858
15
  try {
859
- await fs.access(path9);
16
+ await fs.access(path8);
860
17
  return true;
861
18
  } catch {
862
19
  return false;
863
20
  }
864
21
  }
865
- async mkdir(path9, options) {
866
- await fs.mkdir(path9, options);
22
+ async mkdir(path8, options) {
23
+ await fs.mkdir(path8, options);
867
24
  }
868
- async readdir(path9) {
869
- return fs.readdir(path9);
25
+ async readdir(path8) {
26
+ return fs.readdir(path8);
870
27
  }
871
- async stat(path9) {
872
- const stats = await fs.stat(path9);
28
+ async stat(path8) {
29
+ const stats = await fs.stat(path8);
873
30
  return {
874
31
  isFile: () => stats.isFile(),
875
32
  isDirectory: () => stats.isDirectory(),
@@ -877,28 +34,24 @@ var FileSystemAdapter = class {
877
34
  mtime: stats.mtime
878
35
  };
879
36
  }
880
- async unlink(path9) {
881
- await fs.unlink(path9);
37
+ async unlink(path8) {
38
+ await fs.unlink(path8);
882
39
  }
883
- async rmdir(path9, options) {
884
- await fs.rmdir(path9, options);
40
+ async rmdir(path8, options) {
41
+ await fs.rmdir(path8, options);
885
42
  }
886
43
  async copyFile(src, dest) {
887
44
  await fs.copyFile(src, dest);
888
45
  }
889
46
  async glob(pattern, options) {
890
- return globby(pattern, {
47
+ return fg(pattern, {
891
48
  cwd: options?.cwd,
892
49
  ignore: options?.ignore
893
50
  });
894
51
  }
895
52
  };
896
53
 
897
- // src/config/ConfigLoader.ts
898
- init_esm_shims();
899
-
900
54
  // src/config/schemas.ts
901
- init_esm_shims();
902
55
  import { z } from "zod";
903
56
  var ThemeSchema = z.enum([
904
57
  "mimir",
@@ -994,21 +147,17 @@ var ConfigSchema = z.object({
994
147
  rateLimit: RateLimitConfigSchema
995
148
  });
996
149
 
997
- // src/config/AllowlistLoader.ts
998
- init_esm_shims();
999
-
1000
150
  // src/utils/logger.ts
1001
- init_esm_shims();
1002
151
  import winston from "winston";
1003
152
  import DailyRotateFile from "winston-daily-rotate-file";
1004
153
  import fs2 from "fs";
1005
- import path2 from "path";
154
+ import path from "path";
1006
155
  var Logger = class {
1007
156
  logger;
1008
157
  fileLoggingEnabled = false;
1009
158
  consoleTransport;
1010
159
  constructor(logDir = ".mimir/logs") {
1011
- const absoluteLogDir = path2.resolve(process.cwd(), logDir);
160
+ const absoluteLogDir = path.resolve(process.cwd(), logDir);
1012
161
  try {
1013
162
  if (!fs2.existsSync(absoluteLogDir)) {
1014
163
  fs2.mkdirSync(absoluteLogDir, { recursive: true });
@@ -1094,7 +243,7 @@ var logger = new Logger();
1094
243
 
1095
244
  // src/config/AllowlistLoader.ts
1096
245
  import yaml from "yaml";
1097
- import path3 from "path";
246
+ import path2 from "path";
1098
247
  import { z as z2 } from "zod";
1099
248
  var AllowlistSchema = z2.object({
1100
249
  // Command patterns that are always allowed
@@ -1116,7 +265,7 @@ var AllowlistLoader = class {
1116
265
  * Load allowlist from project .mimir/allowlist.yml
1117
266
  */
1118
267
  async loadProjectAllowlist(projectRoot) {
1119
- const allowlistPath = path3.join(projectRoot, ".mimir", "allowlist.yml");
268
+ const allowlistPath = path2.join(projectRoot, ".mimir", "allowlist.yml");
1120
269
  return await this.loadAllowlistFile(allowlistPath, "project");
1121
270
  }
1122
271
  /**
@@ -1124,7 +273,7 @@ var AllowlistLoader = class {
1124
273
  */
1125
274
  async loadGlobalAllowlist() {
1126
275
  const homeDir = process.env.HOME || process.env.USERPROFILE || "~";
1127
- const allowlistPath = path3.join(homeDir, ".mimir", "allowlist.yml");
276
+ const allowlistPath = path2.join(homeDir, ".mimir", "allowlist.yml");
1128
277
  return await this.loadAllowlistFile(allowlistPath, "global");
1129
278
  }
1130
279
  /**
@@ -1188,7 +337,7 @@ var AllowlistLoader = class {
1188
337
  async createExample(filePath, scope) {
1189
338
  const exampleContent = scope === "global" ? this.getGlobalExample() : this.getProjectExample();
1190
339
  try {
1191
- const dir = path3.dirname(filePath);
340
+ const dir = path2.dirname(filePath);
1192
341
  if (!await this.fs.exists(dir)) {
1193
342
  await this.fs.mkdir(dir, { recursive: true });
1194
343
  }
@@ -1294,7 +443,7 @@ envVars:
1294
443
 
1295
444
  // src/config/ConfigLoader.ts
1296
445
  import yaml2 from "yaml";
1297
- import path4 from "path";
446
+ import path3 from "path";
1298
447
  import os from "os";
1299
448
  import dotenv from "dotenv";
1300
449
  var ConfigLoader = class {
@@ -1414,7 +563,7 @@ var ConfigLoader = class {
1414
563
  }
1415
564
  async loadGlobalConfig() {
1416
565
  try {
1417
- const configPath = path4.join(os.homedir(), ".mimir", "config.yml");
566
+ const configPath = path3.join(os.homedir(), ".mimir", "config.yml");
1418
567
  if (!await this.fs.exists(configPath)) {
1419
568
  return null;
1420
569
  }
@@ -1427,7 +576,7 @@ var ConfigLoader = class {
1427
576
  }
1428
577
  async loadProjectConfig(projectRoot) {
1429
578
  try {
1430
- const configPath = path4.join(projectRoot, ".mimir", "config.yml");
579
+ const configPath = path3.join(projectRoot, ".mimir", "config.yml");
1431
580
  if (!await this.fs.exists(configPath)) {
1432
581
  return null;
1433
582
  }
@@ -1440,7 +589,7 @@ var ConfigLoader = class {
1440
589
  }
1441
590
  loadEnvConfig(projectRoot) {
1442
591
  try {
1443
- const envPath = projectRoot ? path4.join(projectRoot, ".env") : ".env";
592
+ const envPath = projectRoot ? path3.join(projectRoot, ".env") : ".env";
1444
593
  dotenv.config({ path: envPath });
1445
594
  const envConfig = {};
1446
595
  if (process.env.DEEPSEEK_API_KEY || process.env.ANTHROPIC_API_KEY || process.env.OPENAI_API_KEY) {
@@ -1483,8 +632,8 @@ var ConfigLoader = class {
1483
632
  };
1484
633
  }
1485
634
  async save(config, scope, projectRoot) {
1486
- const configPath = scope === "global" ? path4.join(os.homedir(), ".mimir", "config.yml") : path4.join(projectRoot || process.cwd(), ".mimir", "config.yml");
1487
- const configDir = path4.dirname(configPath);
635
+ const configPath = scope === "global" ? path3.join(os.homedir(), ".mimir", "config.yml") : path3.join(projectRoot || process.cwd(), ".mimir", "config.yml");
636
+ const configDir = path3.dirname(configPath);
1488
637
  if (!await this.fs.exists(configDir)) {
1489
638
  await this.fs.mkdir(configDir, { recursive: true });
1490
639
  }
@@ -1498,8 +647,7 @@ var ConfigLoader = class {
1498
647
  };
1499
648
 
1500
649
  // src/cli/utils/firstRunDetector.ts
1501
- init_esm_shims();
1502
- import path5 from "path";
650
+ import path4 from "path";
1503
651
  import os2 from "os";
1504
652
  var FirstRunDetector = class {
1505
653
  constructor(fs4) {
@@ -1512,35 +660,30 @@ var FirstRunDetector = class {
1512
660
  }
1513
661
  getGlobalConfigPath() {
1514
662
  const homeDir = os2.homedir();
1515
- return path5.join(homeDir, ".mimir", "config.yml");
663
+ return path4.join(homeDir, ".mimir", "config.yml");
1516
664
  }
1517
665
  async getGlobalConfigDir() {
1518
666
  const homeDir = os2.homedir();
1519
- return path5.join(homeDir, ".mimir");
667
+ return path4.join(homeDir, ".mimir");
1520
668
  }
1521
669
  };
1522
670
 
1523
671
  // src/cli/commands/SetupCommand.ts
1524
- init_esm_shims();
1525
672
  import React4 from "react";
1526
673
  import { render } from "ink";
1527
674
 
1528
675
  // src/cli/components/SetupWizard.tsx
1529
- init_esm_shims();
1530
676
  import { useState as useState2 } from "react";
1531
677
  import { Box as Box5 } from "ink";
1532
678
 
1533
679
  // src/cli/components/WizardLayout.tsx
1534
- init_esm_shims();
1535
680
  import { Box as Box2, Text as Text2 } from "ink";
1536
681
 
1537
682
  // src/cli/components/WizardHead.tsx
1538
- init_esm_shims();
1539
683
  import { Box, Text } from "ink";
1540
684
  import chalk from "chalk";
1541
685
 
1542
686
  // src/cli/theme-colors.ts
1543
- init_esm_shims();
1544
687
  var MimirColors = {
1545
688
  // Polar Night (dark backgrounds)
1546
689
  polarNight1: "#2E3440",
@@ -1569,14 +712,13 @@ var MimirColors = {
1569
712
  };
1570
713
 
1571
714
  // src/cli/components/logo.ts
1572
- init_esm_shims();
1573
715
  var MIMIR_LOGO = ["\u2597\u2588\u2597\u2588\u2596", "\u2588\u2588\u2588\u2588\u2588", "\u259C\u2586\u2588\u2586\u259B", " \u2586\u2585\u2586 "];
1574
716
 
1575
717
  // src/cli/components/WizardHead.tsx
1576
718
  import { jsx } from "react/jsx-runtime";
1577
719
  var WizardHead = () => {
1578
720
  const nordFrost = chalk.hex(MimirColors.frost3);
1579
- return /* @__PURE__ */ jsx(Box, { flexDirection: "column", marginBottom: 1, alignItems: "center", children: MIMIR_LOGO.map((line, index2) => /* @__PURE__ */ jsx(Text, { children: nordFrost.bold(line) }, index2)) });
721
+ return /* @__PURE__ */ jsx(Box, { flexDirection: "column", marginBottom: 1, alignItems: "center", children: MIMIR_LOGO.map((line, index) => /* @__PURE__ */ jsx(Text, { children: nordFrost.bold(line) }, index)) });
1580
722
  };
1581
723
 
1582
724
  // src/cli/components/WizardLayout.tsx
@@ -1590,14 +732,12 @@ var WizardLayout = ({ title, children }) => {
1590
732
  };
1591
733
 
1592
734
  // src/cli/components/SecurityWarning.tsx
1593
- init_esm_shims();
1594
735
  import { useMemo } from "react";
1595
736
  import { Box as Box3, Text as Text3, useInput } from "ink";
1596
737
  import figures from "figures";
1597
738
  import chalk2 from "chalk";
1598
739
 
1599
740
  // src/utils/keyboardFormatter.ts
1600
- init_esm_shims();
1601
741
  import os3 from "os";
1602
742
  var KEY_ICONS = {
1603
743
  // Arrow keys
@@ -1665,8 +805,8 @@ function formatSingleShortcut(shortcut, options) {
1665
805
  let normalized = normalizeKeyName(shortcut);
1666
806
  normalized = applyPlatformModifiers(normalized, platform);
1667
807
  const parts = normalized.split("+").map((p) => p.trim());
1668
- const formatted = parts.map((part, index2) => {
1669
- const isModifier = index2 < parts.length - 1;
808
+ const formatted = parts.map((part, index) => {
809
+ const isModifier = index < parts.length - 1;
1670
810
  const icon = KEY_ICONS[part];
1671
811
  if (useIcons && icon) {
1672
812
  if (isModifier && !useModifierIcons) {
@@ -1760,17 +900,12 @@ var SecurityWarning = ({
1760
900
  };
1761
901
 
1762
902
  // src/cli/components/ThemeSelector.tsx
1763
- init_esm_shims();
1764
903
  import { useState, useMemo as useMemo2 } from "react";
1765
904
  import { Box as Box4, Text as Text4 } from "ink";
1766
905
  import SelectInput from "ink-select-input";
1767
906
  import chalk4 from "chalk";
1768
907
 
1769
- // src/config/themes/index.ts
1770
- init_esm_shims();
1771
-
1772
908
  // src/config/themes/theme-schema.ts
1773
- init_esm_shims();
1774
909
  import chalk3 from "chalk";
1775
910
  function parseColor(color) {
1776
911
  let result = chalk3;
@@ -2147,7 +1282,6 @@ Object.entries(themeDefinitions).forEach(([key, json]) => {
2147
1282
  });
2148
1283
 
2149
1284
  // src/cli/utils/syntaxHighlight.ts
2150
- init_esm_shims();
2151
1285
  function getPreviewWithDiff() {
2152
1286
  return [
2153
1287
  { type: "remove", line: "function getRandomNumber() {" },
@@ -2178,7 +1312,7 @@ var ThemeSelector = ({
2178
1312
  const themeColors = getTheme(currentThemeKey);
2179
1313
  const preview = getPreviewWithDiff();
2180
1314
  const bg = chalk4.bgHex("#1e1e1e");
2181
- const fg = chalk4.hex("#eceff4");
1315
+ const fg2 = chalk4.hex("#eceff4");
2182
1316
  const footerText = useMemo2(() => {
2183
1317
  const navUp = keyBindings.navigateUp[0] ?? "ArrowUp";
2184
1318
  const navDown = keyBindings.navigateDown[0] ?? "ArrowDown";
@@ -2189,7 +1323,7 @@ var ThemeSelector = ({
2189
1323
  ]);
2190
1324
  }, [keyBindings]);
2191
1325
  return /* @__PURE__ */ jsxs3(Box4, { flexDirection: "column", children: [
2192
- /* @__PURE__ */ jsx4(Text4, { children: bg(fg.bold(" Select your theme: ")) }),
1326
+ /* @__PURE__ */ jsx4(Text4, { children: bg(fg2.bold(" Select your theme: ")) }),
2193
1327
  /* @__PURE__ */ jsx4(Text4, { children: bg(" ") }),
2194
1328
  /* @__PURE__ */ jsx4(Box4, { flexDirection: "column", children: /* @__PURE__ */ jsx4(
2195
1329
  SelectInput,
@@ -2197,18 +1331,18 @@ var ThemeSelector = ({
2197
1331
  items,
2198
1332
  onSelect: (item) => onSelect(item.value),
2199
1333
  onHighlight: (item) => {
2200
- const index2 = availableThemes.findIndex((t) => t === item.value);
2201
- if (index2 !== -1) setHighlightedIndex(index2);
1334
+ const index = availableThemes.findIndex((t) => t === item.value);
1335
+ if (index !== -1) setHighlightedIndex(index);
2202
1336
  }
2203
1337
  }
2204
1338
  ) }),
2205
1339
  /* @__PURE__ */ jsx4(Text4, { children: bg(" ") }),
2206
- /* @__PURE__ */ jsx4(Text4, { children: bg(fg(" Preview: ")) }),
1340
+ /* @__PURE__ */ jsx4(Text4, { children: bg(fg2(" Preview: ")) }),
2207
1341
  preview.map((item, idx) => /* @__PURE__ */ jsxs3(Text4, { children: [
2208
1342
  item.type === "remove" && bg(themeColors.colors.diffRemoveLine(`- ${item.line}`)),
2209
1343
  item.type === "add" && bg(themeColors.colors.diffAddLine(`+ ${item.line}`)),
2210
1344
  item.type === "normal" && bg(
2211
- fg(
1345
+ fg2(
2212
1346
  ` ${themeColors.colors.keyword(item.line.match(/return/)?.[0] || "")}${item.line.replace(/return/, "")}`
2213
1347
  )
2214
1348
  )
@@ -2311,22 +1445,18 @@ var SetupCommand = class {
2311
1445
  };
2312
1446
 
2313
1447
  // src/cli/commands/ChatCommand.ts
2314
- init_esm_shims();
2315
1448
  import React10 from "react";
2316
1449
  import { render as render2 } from "ink";
2317
1450
 
2318
1451
  // src/cli/components/ChatApp.tsx
2319
- init_esm_shims();
2320
1452
  import { useEffect as useEffect7 } from "react";
2321
1453
  import { useStdin } from "ink";
2322
1454
 
2323
1455
  // src/cli/components/ChatInterface.tsx
2324
- init_esm_shims();
2325
1456
  import { useState as useState7, useMemo as useMemo4, useCallback as useCallback2, useRef as useRef2, useEffect as useEffect6 } from "react";
2326
1457
  import { Box as Box11, Text as Text10 } from "ink";
2327
1458
 
2328
1459
  // src/cli/components/MimirHeader.tsx
2329
- init_esm_shims();
2330
1460
  import { Box as Box6, Text as Text5 } from "ink";
2331
1461
  import { jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
2332
1462
  var MimirHeader = ({
@@ -2349,18 +1479,17 @@ var MimirHeader = ({
2349
1479
  themeDefinition.colors.info(`Theme: ${themeDefinition.name}`)
2350
1480
  ];
2351
1481
  const LOGO_WIDTH = 7;
2352
- return /* @__PURE__ */ jsx6(Box6, { flexDirection: "column", height: MIMIR_LOGO.length, flexShrink: 0, children: MIMIR_LOGO.map((logoLine, index2) => /* @__PURE__ */ jsxs5(Box6, { children: [
1482
+ return /* @__PURE__ */ jsx6(Box6, { flexDirection: "column", height: MIMIR_LOGO.length, flexShrink: 0, children: MIMIR_LOGO.map((logoLine, index) => /* @__PURE__ */ jsxs5(Box6, { children: [
2353
1483
  /* @__PURE__ */ jsx6(Box6, { width: LOGO_WIDTH, children: /* @__PURE__ */ jsx6(Text5, { children: logoColor.bold(logoLine) }) }),
2354
- infoLines[index2] && /* @__PURE__ */ jsx6(Text5, { children: infoLines[index2] })
2355
- ] }, index2)) });
1484
+ infoLines[index] && /* @__PURE__ */ jsx6(Text5, { children: infoLines[index] })
1485
+ ] }, index)) });
2356
1486
  };
2357
1487
 
2358
1488
  // src/cli/components/MessageList.tsx
2359
- init_esm_shims();
2360
1489
  import { Box as Box7, Text as Text6, Static } from "ink";
2361
1490
  import { jsx as jsx7, jsxs as jsxs6 } from "react/jsx-runtime";
2362
1491
  var MessageList = ({
2363
- messages: messages2,
1492
+ messages,
2364
1493
  theme,
2365
1494
  syntaxHighlighting: _syntaxHighlighting
2366
1495
  }) => {
@@ -2412,25 +1541,23 @@ var MessageList = ({
2412
1541
  ")"
2413
1542
  ] }) });
2414
1543
  };
2415
- const renderMessage = (message, index2) => /* @__PURE__ */ jsxs6(Box7, { flexDirection: "column", marginBottom: 1, children: [
1544
+ const renderMessage = (message, index) => /* @__PURE__ */ jsxs6(Box7, { flexDirection: "column", marginBottom: 1, children: [
2416
1545
  /* @__PURE__ */ jsx7(Text6, { children: getRoleChalk(message.role).bold(`[${message.role.toUpperCase()}]:`) }),
2417
1546
  /* @__PURE__ */ jsx7(Text6, { children: message.content }),
2418
1547
  message.role === "assistant" && renderThinkingIndicator(message)
2419
- ] }, index2);
1548
+ ] }, index);
2420
1549
  return /* @__PURE__ */ jsxs6(Box7, { flexDirection: "column", paddingX: 1, paddingY: 1, flexGrow: 1, children: [
2421
- messages2.length === 0 && /* @__PURE__ */ jsx7(Text6, { dimColor: true, children: "No messages yet. Start typing below..." }),
2422
- messages2.length > 0 && /* @__PURE__ */ jsx7(Static, { items: messages2, children: (message, index2) => renderMessage(message, index2) })
1550
+ messages.length === 0 && /* @__PURE__ */ jsx7(Text6, { dimColor: true, children: "No messages yet. Start typing below..." }),
1551
+ messages.length > 0 && /* @__PURE__ */ jsx7(Static, { items: messages, children: (message, index) => renderMessage(message, index) })
2423
1552
  ] });
2424
1553
  };
2425
1554
 
2426
1555
  // src/cli/components/InputBox.tsx
2427
- init_esm_shims();
2428
1556
  import React6, { useState as useState4, useCallback, useEffect as useEffect2 } from "react";
2429
1557
  import { Box as Box9, Text as Text8 } from "ink";
2430
1558
  import TextInput from "ink-text-input";
2431
1559
 
2432
1560
  // src/core/SlashCommandParser.ts
2433
- init_esm_shims();
2434
1561
  var SlashCommandParser = class {
2435
1562
  static COMMAND_REGEX = /^\/(\w+)(?:\s+(.*))?$/;
2436
1563
  /**
@@ -2484,13 +1611,11 @@ var SlashCommandParser = class {
2484
1611
  };
2485
1612
 
2486
1613
  // src/cli/components/CommandAutocomplete.tsx
2487
- init_esm_shims();
2488
1614
  import React5, { useMemo as useMemo3 } from "react";
2489
1615
  import { Box as Box8, Text as Text7 } from "ink";
2490
1616
  import chalk5 from "chalk";
2491
1617
 
2492
1618
  // src/cli/hooks/useTerminalSize.ts
2493
- init_esm_shims();
2494
1619
  import { useEffect, useState as useState3 } from "react";
2495
1620
  import { useStdout } from "ink";
2496
1621
  var useTerminalSize = () => {
@@ -2559,8 +1684,8 @@ var CommandAutocomplete = ({
2559
1684
  const paramBg = chalk5.bgHex(paramBgHex);
2560
1685
  const { width: terminalWidth } = useTerminalSize();
2561
1686
  const maxAllowedWidth = Math.max(30, terminalWidth - 4);
2562
- const truncateText = (text2, maxLen) => {
2563
- const stripped = text2.replace(/\x1B\[[0-9;]*m/g, "");
1687
+ const truncateText = (text, maxLen) => {
1688
+ const stripped = text.replace(/\x1B\[[0-9;]*m/g, "");
2564
1689
  if (stripped.length <= maxLen) {
2565
1690
  return stripped;
2566
1691
  }
@@ -3085,12 +2210,10 @@ var InputBox = React6.memo(
3085
2210
  InputBox.displayName = "InputBox";
3086
2211
 
3087
2212
  // src/cli/components/Footer.tsx
3088
- init_esm_shims();
3089
2213
  import { useState as useState5, useEffect as useEffect3 } from "react";
3090
2214
  import { Box as Box10, Text as Text9 } from "ink";
3091
2215
 
3092
2216
  // src/cli/components/tips.ts
3093
- init_esm_shims();
3094
2217
  function generateTips(keyBindings) {
3095
2218
  const modeSwitchKey = formatKeyboardShortcut(keyBindings.modeSwitch, { showFirstOnly: true });
3096
2219
  const editKey = formatKeyboardShortcut(keyBindings.editCommand, { showFirstOnly: true });
@@ -3176,11 +2299,7 @@ var Footer = ({
3176
2299
  ] });
3177
2300
  };
3178
2301
 
3179
- // src/cli/keyboard/index.ts
3180
- init_esm_shims();
3181
-
3182
2302
  // src/cli/keyboard/KeyboardEventBus.ts
3183
- init_esm_shims();
3184
2303
  import { EventEmitter } from "events";
3185
2304
  var KeyboardEventBus = class extends EventEmitter {
3186
2305
  constructor(bindingsManager) {
@@ -3224,9 +2343,9 @@ var KeyboardEventBus = class extends EventEmitter {
3224
2343
  return () => {
3225
2344
  const handlers2 = this.handlers.get(action);
3226
2345
  if (handlers2) {
3227
- const index2 = handlers2.findIndex((h) => h.id === handlerObj.id);
3228
- if (index2 !== -1) {
3229
- handlers2.splice(index2, 1);
2346
+ const index = handlers2.findIndex((h) => h.id === handlerObj.id);
2347
+ if (index !== -1) {
2348
+ handlers2.splice(index, 1);
3230
2349
  }
3231
2350
  }
3232
2351
  };
@@ -3309,11 +2428,9 @@ var KeyboardEventBus = class extends EventEmitter {
3309
2428
  };
3310
2429
 
3311
2430
  // src/cli/keyboard/KeyboardContext.tsx
3312
- init_esm_shims();
3313
2431
  import { createContext, useContext, useEffect as useEffect4, useState as useState6 } from "react";
3314
2432
 
3315
2433
  // src/utils/KeyBindings.ts
3316
- init_esm_shims();
3317
2434
  import os4 from "os";
3318
2435
  var KeyBindingsManager = class _KeyBindingsManager {
3319
2436
  constructor(config) {
@@ -3523,7 +2640,6 @@ function useKeyboard() {
3523
2640
  }
3524
2641
 
3525
2642
  // src/cli/keyboard/useKeyboardAction.ts
3526
- init_esm_shims();
3527
2643
  import { useEffect as useEffect5, useRef } from "react";
3528
2644
  function useKeyboardAction(action, handler, options = {}) {
3529
2645
  const { eventBus } = useKeyboard();
@@ -3546,7 +2662,6 @@ function useKeyboardAction(action, handler, options = {}) {
3546
2662
  }
3547
2663
 
3548
2664
  // src/cli/keyboard/useKeyboardInput.ts
3549
- init_esm_shims();
3550
2665
  import { useInput as useInput2 } from "ink";
3551
2666
  var CONTROL_CHAR_MAP = {
3552
2667
  0: "Space",
@@ -3641,7 +2756,7 @@ function useKeyboardInput(options = {}) {
3641
2756
  import { jsx as jsx12, jsxs as jsxs10 } from "react/jsx-runtime";
3642
2757
  var ChatInterface = ({
3643
2758
  config,
3644
- messages: messages2,
2759
+ messages,
3645
2760
  onUserInput,
3646
2761
  onExit,
3647
2762
  currentMode,
@@ -3831,9 +2946,9 @@ var ChatInterface = ({
3831
2946
  currentMode: mode,
3832
2947
  currentProvider: config.llm.provider,
3833
2948
  currentModel: config.llm.model,
3834
- messageCount: messages2.length
2949
+ messageCount: messages.length
3835
2950
  }),
3836
- [mode, config.llm.provider, config.llm.model, messages2.length]
2951
+ [mode, config.llm.provider, config.llm.model, messages.length]
3837
2952
  );
3838
2953
  const fixedUIHeight = 8;
3839
2954
  const minMessageLines = 3;
@@ -3866,7 +2981,7 @@ var ChatInterface = ({
3866
2981
  /* @__PURE__ */ jsx12(Box11, { height: messageAreaHeight, children: /* @__PURE__ */ jsx12(
3867
2982
  MessageList,
3868
2983
  {
3869
- messages: messages2,
2984
+ messages,
3870
2985
  theme: config.ui.theme,
3871
2986
  syntaxHighlighting: config.ui.syntaxHighlighting
3872
2987
  }
@@ -3941,7 +3056,6 @@ function ChatApp({ fs: fs4, projectRoot, ...chatProps }) {
3941
3056
  }
3942
3057
 
3943
3058
  // src/core/SlashCommand.ts
3944
- init_esm_shims();
3945
3059
  var SlashCommandRegistry = class {
3946
3060
  commands = /* @__PURE__ */ new Map();
3947
3061
  aliases = /* @__PURE__ */ new Map();
@@ -4006,10 +3120,9 @@ var SlashCommandRegistry = class {
4006
3120
  };
4007
3121
 
4008
3122
  // src/core/CustomCommandLoader.ts
4009
- init_esm_shims();
4010
3123
  import { z as z3 } from "zod";
4011
3124
  import yaml3 from "yaml";
4012
- import path6 from "path";
3125
+ import path5 from "path";
4013
3126
  import os5 from "os";
4014
3127
  var CustomCommandSchema = z3.object({
4015
3128
  name: z3.string().regex(/^[a-z][a-z0-9-]*$/, "Command name must be lowercase alphanumeric with hyphens"),
@@ -4036,8 +3149,8 @@ var CustomCommand = class {
4036
3149
  }
4037
3150
  async execute(args, context) {
4038
3151
  let prompt = this.definition.prompt;
4039
- args.forEach((arg, index2) => {
4040
- const placeholder = `$${index2 + 1}`;
3152
+ args.forEach((arg, index) => {
3153
+ const placeholder = `$${index + 1}`;
4041
3154
  prompt = prompt.replace(new RegExp(`\\${placeholder}`, "g"), arg);
4042
3155
  });
4043
3156
  const allArgs = args.join(" ");
@@ -4066,12 +3179,12 @@ var CustomCommandLoader = class {
4066
3179
  async loadAll(projectRoot) {
4067
3180
  const commandMap = /* @__PURE__ */ new Map();
4068
3181
  const globalCommands = await this.loadFromDirectory(
4069
- path6.join(os5.homedir(), ".mimir", "commands")
3182
+ path5.join(os5.homedir(), ".mimir", "commands")
4070
3183
  );
4071
3184
  globalCommands.forEach((cmd) => commandMap.set(cmd.name, cmd));
4072
3185
  if (projectRoot) {
4073
3186
  const projectCommands = await this.loadFromDirectory(
4074
- path6.join(projectRoot, ".mimir", "commands")
3187
+ path5.join(projectRoot, ".mimir", "commands")
4075
3188
  );
4076
3189
  projectCommands.forEach((cmd) => {
4077
3190
  if (commandMap.has(cmd.name)) {
@@ -4093,7 +3206,7 @@ var CustomCommandLoader = class {
4093
3206
  }
4094
3207
  const files = await this.fs.glob("*.yml", { cwd: dirPath });
4095
3208
  for (const file of files) {
4096
- const fullPath = path6.join(dirPath, file);
3209
+ const fullPath = path5.join(dirPath, file);
4097
3210
  const command = await this.loadCommand(fullPath);
4098
3211
  if (command) {
4099
3212
  commands.push(command);
@@ -4147,7 +3260,6 @@ var CustomCommandLoader = class {
4147
3260
  };
4148
3261
 
4149
3262
  // src/cli/utils/signalHandler.ts
4150
- init_esm_shims();
4151
3263
  var SignalHandler = class {
4152
3264
  sigintCount = 0;
4153
3265
  cleanupTimeout = null;
@@ -4308,11 +3420,7 @@ function installSignalHandlers(options = {}) {
4308
3420
  return handler;
4309
3421
  }
4310
3422
 
4311
- // src/cli/commands/slashCommands/index.ts
4312
- init_esm_shims();
4313
-
4314
3423
  // src/cli/commands/slashCommands/NewCommand.ts
4315
- init_esm_shims();
4316
3424
  var NewCommand = class {
4317
3425
  name = "new";
4318
3426
  description = "Start a new chat conversation";
@@ -4334,7 +3442,6 @@ var NewCommand = class {
4334
3442
  };
4335
3443
 
4336
3444
  // src/cli/commands/slashCommands/ModelCommand.ts
4337
- init_esm_shims();
4338
3445
  import { z as z4 } from "zod";
4339
3446
  var ModelCommand = class {
4340
3447
  name = "model";
@@ -4405,7 +3512,6 @@ var ModelCommand = class {
4405
3512
  };
4406
3513
 
4407
3514
  // src/cli/commands/slashCommands/ModeCommand.ts
4408
- init_esm_shims();
4409
3515
  import { z as z5 } from "zod";
4410
3516
  var ModeCommand = class {
4411
3517
  name = "mode";
@@ -4450,7 +3556,6 @@ var ModeCommand = class {
4450
3556
  };
4451
3557
 
4452
3558
  // src/cli/commands/slashCommands/HelpCommand.ts
4453
- init_esm_shims();
4454
3559
  var HelpCommand = class {
4455
3560
  constructor(registry) {
4456
3561
  this.registry = registry;
@@ -4508,7 +3613,6 @@ var HelpCommand = class {
4508
3613
  };
4509
3614
 
4510
3615
  // src/cli/commands/slashCommands/ThemeCommand.ts
4511
- init_esm_shims();
4512
3616
  var ThemeCommand = class {
4513
3617
  name = "theme";
4514
3618
  description = "Show available themes or change to specified theme";
@@ -4574,250 +3678,10 @@ Use /theme <name> to switch (e.g., /theme dark)`;
4574
3678
  }
4575
3679
  };
4576
3680
 
4577
- // src/core/MimirInitializer.ts
4578
- init_esm_shims();
4579
-
4580
3681
  // src/storage/Database.ts
4581
- init_esm_shims();
4582
- var import_better_sqlite3 = __toESM(require_lib(), 1);
4583
- import { drizzle } from "drizzle-orm/better-sqlite3";
4584
- import { migrate } from "drizzle-orm/better-sqlite3/migrator";
4585
-
4586
- // src/storage/schema.ts
4587
- var schema_exports = {};
4588
- __export(schema_exports, {
4589
- checkpoints: () => checkpoints,
4590
- conversations: () => conversations,
4591
- costSummary: () => costSummary,
4592
- messages: () => messages,
4593
- metrics: () => metrics,
4594
- migrations: () => migrations,
4595
- permissions: () => permissions,
4596
- pricing: () => pricing,
4597
- sessionState: () => sessionState,
4598
- toolCalls: () => toolCalls
4599
- });
4600
- init_esm_shims();
4601
- import { sqliteTable, text, integer, real, index, uniqueIndex } from "drizzle-orm/sqlite-core";
4602
- import { sql } from "drizzle-orm";
4603
- var migrations = sqliteTable("migrations", {
4604
- id: integer("id").primaryKey({ autoIncrement: true }),
4605
- version: text("version").notNull().unique(),
4606
- appliedAt: integer("applied_at", { mode: "timestamp" }).notNull().default(sql`(strftime('%s', 'now'))`)
4607
- });
4608
- var conversations = sqliteTable(
4609
- "conversations",
4610
- {
4611
- id: text("id").primaryKey(),
4612
- title: text("title"),
4613
- createdAt: integer("created_at", { mode: "timestamp" }).notNull().default(sql`(strftime('%s', 'now'))`),
4614
- updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().default(sql`(strftime('%s', 'now'))`),
4615
- totalTokens: integer("total_tokens").default(0),
4616
- totalCost: real("total_cost").default(0),
4617
- provider: text("provider"),
4618
- model: text("model"),
4619
- status: text("status", { enum: ["active", "archived", "deleted"] }).default("active")
4620
- },
4621
- (table) => ({
4622
- createdAtIdx: index("idx_conversations_created_at").on(table.createdAt),
4623
- statusIdx: index("idx_conversations_status").on(table.status)
4624
- })
4625
- );
4626
- var messages = sqliteTable(
4627
- "messages",
4628
- {
4629
- id: text("id").primaryKey(),
4630
- conversationId: text("conversation_id").notNull().references(() => conversations.id, { onDelete: "cascade" }),
4631
- role: text("role", { enum: ["system", "user", "assistant"] }).notNull(),
4632
- content: text("content").notNull(),
4633
- timestamp: integer("timestamp", { mode: "timestamp" }).notNull().default(sql`(strftime('%s', 'now'))`),
4634
- inputTokens: integer("input_tokens").default(0),
4635
- outputTokens: integer("output_tokens").default(0),
4636
- cost: real("cost").default(0),
4637
- metadata: text("metadata")
4638
- // JSON string
4639
- },
4640
- (table) => ({
4641
- conversationIdIdx: index("idx_messages_conversation_id").on(table.conversationId),
4642
- timestampIdx: index("idx_messages_timestamp").on(table.timestamp)
4643
- })
4644
- );
4645
- var toolCalls = sqliteTable(
4646
- "tool_calls",
4647
- {
4648
- id: text("id").primaryKey(),
4649
- conversationId: text("conversation_id").notNull().references(() => conversations.id, { onDelete: "cascade" }),
4650
- messageId: text("message_id").references(() => messages.id, { onDelete: "set null" }),
4651
- toolName: text("tool_name").notNull(),
4652
- arguments: text("arguments").notNull(),
4653
- // JSON string
4654
- result: text("result"),
4655
- // JSON string
4656
- status: text("status", { enum: ["pending", "running", "success", "failed"] }).default(
4657
- "pending"
4658
- ),
4659
- error: text("error"),
4660
- startedAt: integer("started_at", { mode: "timestamp" }).notNull().default(sql`(strftime('%s', 'now'))`),
4661
- completedAt: integer("completed_at", { mode: "timestamp" }),
4662
- durationMs: integer("duration_ms")
4663
- },
4664
- (table) => ({
4665
- conversationIdIdx: index("idx_tool_calls_conversation_id").on(table.conversationId),
4666
- statusIdx: index("idx_tool_calls_status").on(table.status),
4667
- startedAtIdx: index("idx_tool_calls_started_at").on(table.startedAt)
4668
- })
4669
- );
4670
- var permissions = sqliteTable(
4671
- "permissions",
4672
- {
4673
- id: integer("id").primaryKey({ autoIncrement: true }),
4674
- conversationId: text("conversation_id").references(() => conversations.id, {
4675
- onDelete: "set null"
4676
- }),
4677
- command: text("command").notNull(),
4678
- riskLevel: text("risk_level", { enum: ["low", "medium", "high", "critical"] }).notNull(),
4679
- decision: text("decision", { enum: ["allow", "deny", "always", "never"] }).notNull(),
4680
- userConfirmed: integer("user_confirmed", { mode: "boolean" }).default(false),
4681
- timestamp: integer("timestamp", { mode: "timestamp" }).notNull().default(sql`(strftime('%s', 'now'))`),
4682
- context: text("context")
4683
- // JSON string
4684
- },
4685
- (table) => ({
4686
- conversationIdIdx: index("idx_permissions_conversation_id").on(table.conversationId),
4687
- timestampIdx: index("idx_permissions_timestamp").on(table.timestamp),
4688
- decisionIdx: index("idx_permissions_decision").on(table.decision)
4689
- })
4690
- );
4691
- var checkpoints = sqliteTable(
4692
- "checkpoints",
4693
- {
4694
- id: text("id").primaryKey(),
4695
- conversationId: text("conversation_id").notNull().references(() => conversations.id, { onDelete: "cascade" }),
4696
- description: text("description"),
4697
- filesSnapshot: text("files_snapshot").notNull(),
4698
- // JSON string
4699
- gitDiff: text("git_diff"),
4700
- createdAt: integer("created_at", { mode: "timestamp" }).notNull().default(sql`(strftime('%s', 'now'))`)
4701
- },
4702
- (table) => ({
4703
- conversationIdIdx: index("idx_checkpoints_conversation_id").on(table.conversationId),
4704
- createdAtIdx: index("idx_checkpoints_created_at").on(table.createdAt)
4705
- })
4706
- );
4707
- var costSummary = sqliteTable(
4708
- "cost_summary",
4709
- {
4710
- id: integer("id").primaryKey({ autoIncrement: true }),
4711
- date: text("date").notNull(),
4712
- // YYYY-MM-DD format
4713
- provider: text("provider").notNull(),
4714
- model: text("model").notNull(),
4715
- totalTokens: integer("total_tokens").default(0),
4716
- inputTokens: integer("input_tokens").default(0),
4717
- outputTokens: integer("output_tokens").default(0),
4718
- totalCost: real("total_cost").default(0),
4719
- requestCount: integer("request_count").default(0)
4720
- },
4721
- (table) => ({
4722
- dateIdx: index("idx_cost_summary_date").on(table.date),
4723
- providerIdx: index("idx_cost_summary_provider").on(table.provider),
4724
- uniqueIdx: uniqueIndex("unique_date_provider_model").on(
4725
- table.date,
4726
- table.provider,
4727
- table.model
4728
- )
4729
- })
4730
- );
4731
- var sessionState = sqliteTable(
4732
- "session_state",
4733
- {
4734
- id: text("id").primaryKey(),
4735
- conversationId: text("conversation_id").notNull().references(() => conversations.id, { onDelete: "cascade" }),
4736
- agentState: text("agent_state").notNull(),
4737
- // JSON string
4738
- iteration: integer("iteration").default(0),
4739
- createdAt: integer("created_at", { mode: "timestamp" }).notNull().default(sql`(strftime('%s', 'now'))`)
4740
- },
4741
- (table) => ({
4742
- conversationIdIdx: index("idx_session_state_conversation_id").on(table.conversationId)
4743
- })
4744
- );
4745
- var metrics = sqliteTable(
4746
- "metrics",
4747
- {
4748
- id: integer("id").primaryKey({ autoIncrement: true }),
4749
- timestamp: integer("timestamp", { mode: "timestamp" }).notNull().default(sql`(strftime('%s', 'now'))`),
4750
- operation: text("operation").notNull(),
4751
- // 'llm.chat', 'tool.execute', 'db.query'
4752
- durationMs: integer("duration_ms").notNull(),
4753
- // Context
4754
- conversationId: text("conversation_id"),
4755
- sessionId: text("session_id"),
4756
- // LLM specific
4757
- provider: text("provider"),
4758
- model: text("model"),
4759
- inputTokens: integer("input_tokens"),
4760
- outputTokens: integer("output_tokens"),
4761
- totalTokens: integer("total_tokens"),
4762
- cost: real("cost"),
4763
- // Tool specific
4764
- toolName: text("tool_name"),
4765
- toolArgs: text("tool_args"),
4766
- // JSON
4767
- toolResultSize: integer("tool_result_size"),
4768
- // bytes
4769
- // DB specific
4770
- queryType: text("query_type"),
4771
- // 'SELECT', 'INSERT', etc.
4772
- tableName: text("table_name"),
4773
- rowsAffected: integer("rows_affected"),
4774
- // Result
4775
- success: integer("success", { mode: "boolean" }).default(true),
4776
- error: text("error"),
4777
- // Resource usage
4778
- memoryMb: real("memory_mb"),
4779
- cpuPercent: real("cpu_percent"),
4780
- // Additional metadata
4781
- metadata: text("metadata")
4782
- // JSON for extensibility
4783
- },
4784
- (table) => ({
4785
- timestampIdx: index("idx_metrics_timestamp").on(table.timestamp),
4786
- operationIdx: index("idx_metrics_operation").on(table.operation),
4787
- conversationIdIdx: index("idx_metrics_conversation_id").on(table.conversationId),
4788
- providerIdx: index("idx_metrics_provider").on(table.provider),
4789
- successIdx: index("idx_metrics_success").on(table.success)
4790
- })
4791
- );
4792
- var pricing = sqliteTable(
4793
- "pricing",
4794
- {
4795
- id: integer("id").primaryKey({ autoIncrement: true }),
4796
- provider: text("provider").notNull(),
4797
- model: text("model").notNull(),
4798
- inputPricePer1M: real("input_price_per_1m").notNull(),
4799
- // USD per 1M input tokens
4800
- outputPricePer1M: real("output_price_per_1m").notNull(),
4801
- // USD per 1M output tokens
4802
- effectiveFrom: integer("effective_from", { mode: "timestamp" }).notNull().default(sql`(strftime('%s', 'now'))`),
4803
- effectiveUntil: integer("effective_until", { mode: "timestamp" }),
4804
- // NULL = current price
4805
- currency: text("currency").default("USD"),
4806
- notes: text("notes")
4807
- },
4808
- (table) => ({
4809
- providerModelIdx: index("idx_pricing_provider_model").on(table.provider, table.model),
4810
- effectiveIdx: index("idx_pricing_effective").on(table.effectiveFrom),
4811
- uniqueIdx: uniqueIndex("unique_provider_model_effective").on(
4812
- table.provider,
4813
- table.model,
4814
- table.effectiveFrom
4815
- )
4816
- })
4817
- );
3682
+ import initSqlJs from "sql.js";
4818
3683
 
4819
3684
  // src/storage/seed.ts
4820
- init_esm_shims();
4821
3685
  var defaultPricing = [
4822
3686
  // DeepSeek
4823
3687
  {
@@ -4947,24 +3811,67 @@ var defaultPricing = [
4947
3811
  ];
4948
3812
 
4949
3813
  // src/storage/Database.ts
4950
- import { dirname } from "path";
3814
+ import { dirname, join } from "path";
3815
+ import { fileURLToPath } from "url";
3816
+ import { readFileSync, existsSync } from "fs";
3817
+ function locateWasmFile() {
3818
+ const wasmFileName = "sql-wasm.wasm";
3819
+ const executablePath = process.argv[0] || process.execPath;
3820
+ const binaryDir = dirname(executablePath);
3821
+ const resourcesPaths = [
3822
+ // Next to the binary (same directory) - most common for our installers
3823
+ join(binaryDir, "resources", wasmFileName),
3824
+ // For development/testing
3825
+ join(process.cwd(), "resources", wasmFileName),
3826
+ // Parent directory of binary (for some install layouts)
3827
+ join(binaryDir, "..", "resources", wasmFileName)
3828
+ ];
3829
+ for (const resourcePath of resourcesPaths) {
3830
+ if (existsSync(resourcePath)) {
3831
+ const buffer = readFileSync(resourcePath);
3832
+ return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
3833
+ }
3834
+ }
3835
+ const currentDir = dirname(fileURLToPath(import.meta.url));
3836
+ const nodeModulesPaths = [
3837
+ join(currentDir, "..", "..", "node_modules", "sql.js", "dist", wasmFileName),
3838
+ join(process.cwd(), "node_modules", "sql.js", "dist", wasmFileName)
3839
+ ];
3840
+ for (const modulePath of nodeModulesPaths) {
3841
+ if (existsSync(modulePath)) {
3842
+ const buffer = readFileSync(modulePath);
3843
+ return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
3844
+ }
3845
+ }
3846
+ const diagnostics = [
3847
+ `process.argv[0]: ${process.argv[0]}`,
3848
+ `process.execPath: ${process.execPath}`,
3849
+ `executablePath: ${executablePath}`,
3850
+ `binaryDir: ${binaryDir}`,
3851
+ `currentDir: ${currentDir}`,
3852
+ `process.cwd(): ${process.cwd()}`
3853
+ ];
3854
+ throw new Error(
3855
+ `Could not locate ${wasmFileName}.
3856
+
3857
+ Diagnostics:
3858
+ ${diagnostics.join("\n")}
3859
+
3860
+ Tried:
3861
+ ` + [...resourcesPaths, ...nodeModulesPaths].map((p) => ` - ${p}`).join("\n")
3862
+ );
3863
+ }
4951
3864
  var DatabaseManager = class _DatabaseManager {
4952
- sqlite;
4953
3865
  db;
4954
3866
  config;
4955
- constructor(config) {
3867
+ SQL;
3868
+ nodeFs = null;
3869
+ constructor(config, SQL) {
4956
3870
  this.config = config;
4957
- this.sqlite = new import_better_sqlite3.default(config.path, {
4958
- verbose: config.verbose ? console.log : void 0
4959
- });
4960
- this.sqlite.pragma("journal_mode = WAL");
4961
- this.sqlite.pragma("foreign_keys = ON");
4962
- this.db = drizzle(this.sqlite, { schema: schema_exports });
4963
- this.initialize();
3871
+ this.SQL = SQL;
4964
3872
  }
4965
3873
  /**
4966
3874
  * Create DatabaseManager instance with proper directory setup
4967
- * Use this factory method instead of constructor for proper async initialization
4968
3875
  */
4969
3876
  static async create(config) {
4970
3877
  const dbDir = dirname(config.path);
@@ -4974,72 +3881,103 @@ var DatabaseManager = class _DatabaseManager {
4974
3881
  await config.fileSystem.mkdir(dbDir, { recursive: true });
4975
3882
  }
4976
3883
  } else {
4977
- const { existsSync, mkdirSync } = await import("fs");
4978
- if (!existsSync(dbDir)) {
3884
+ const { existsSync: existsSync2, mkdirSync } = await import("fs");
3885
+ if (!existsSync2(dbDir)) {
4979
3886
  mkdirSync(dbDir, { recursive: true });
4980
3887
  }
4981
3888
  }
4982
- return new _DatabaseManager(config);
4983
- }
4984
- /**
4985
- * Initialize database with migrations and seed data
4986
- */
4987
- initialize() {
4988
- try {
4989
- this.runMigrations();
4990
- this.seedDatabase();
4991
- } catch (error) {
4992
- console.error("Database initialization failed:", error);
4993
- throw error;
4994
- }
3889
+ const wasmBinary = locateWasmFile();
3890
+ const SQL = await initSqlJs({
3891
+ wasmBinary
3892
+ });
3893
+ const manager = new _DatabaseManager(config, SQL);
3894
+ manager.nodeFs = await import("fs");
3895
+ await manager.loadDatabase();
3896
+ manager.initialize();
3897
+ await manager.save();
3898
+ return manager;
4995
3899
  }
4996
3900
  /**
4997
- * Run Drizzle migrations
3901
+ * Load database from file or create new
4998
3902
  */
4999
- runMigrations() {
3903
+ async loadDatabase() {
5000
3904
  try {
5001
- const migrationsFolder = "./drizzle";
5002
- const { existsSync } = __require("fs");
5003
- if (existsSync(migrationsFolder)) {
5004
- migrate(this.db, { migrationsFolder });
3905
+ if (this.config.fileSystem) {
3906
+ const exists = await this.config.fileSystem.exists(this.config.path);
3907
+ if (exists) {
3908
+ const buffer = await this.config.fileSystem.readFile(
3909
+ this.config.path,
3910
+ "binary"
3911
+ );
3912
+ const uint8Array = new Uint8Array(Buffer.from(buffer, "binary"));
3913
+ this.db = new this.SQL.Database(uint8Array);
3914
+ if (this.config.verbose) {
3915
+ console.log("Loaded existing database from", this.config.path);
3916
+ }
3917
+ } else {
3918
+ this.db = new this.SQL.Database();
3919
+ if (this.config.verbose) {
3920
+ console.log("Created new database");
3921
+ }
3922
+ }
5005
3923
  } else {
3924
+ const { existsSync: existsSync2, readFileSync: readFileSync2 } = await import("fs");
3925
+ if (existsSync2(this.config.path)) {
3926
+ const buffer = readFileSync2(this.config.path);
3927
+ this.db = new this.SQL.Database(buffer);
3928
+ } else {
3929
+ this.db = new this.SQL.Database();
3930
+ }
5006
3931
  }
5007
3932
  } catch (error) {
3933
+ this.db = new this.SQL.Database();
5008
3934
  if (this.config.verbose) {
5009
- console.log("No migrations to run, will use manual initialization");
3935
+ console.log("Created new database after error:", error);
5010
3936
  }
5011
3937
  }
5012
3938
  }
5013
3939
  /**
5014
- * Seed database with initial data
3940
+ * Save database to disk (async version)
5015
3941
  */
5016
- seedDatabase() {
5017
- const pricingCount = this.sqlite.prepare("SELECT COUNT(*) as count FROM sqlite_master WHERE type='table' AND name='pricing'").get();
5018
- if (pricingCount.count === 0) {
5019
- this.createTablesManually();
3942
+ async save() {
3943
+ const data = this.db.export();
3944
+ const buffer = Buffer.from(data);
3945
+ if (this.config.fileSystem) {
3946
+ await this.config.fileSystem.writeFile(
3947
+ this.config.path,
3948
+ buffer.toString("binary"),
3949
+ "binary"
3950
+ );
3951
+ } else {
3952
+ const { writeFileSync } = await import("fs");
3953
+ writeFileSync(this.config.path, buffer);
5020
3954
  }
5021
- const existingPricing = this.sqlite.prepare("SELECT COUNT(*) as count FROM pricing").get();
5022
- if (existingPricing.count === 0) {
5023
- this.db.transaction((tx) => {
5024
- for (const price of defaultPricing) {
5025
- tx.insert(pricing).values(price).run();
5026
- }
5027
- });
5028
- if (this.config.verbose) {
5029
- console.log(`Seeded ${defaultPricing.length} pricing entries`);
5030
- }
3955
+ }
3956
+ /**
3957
+ * Save database to disk (sync version for auto-save)
3958
+ * Uses sync fs operations to avoid async in execute/transaction
3959
+ */
3960
+ saveSync() {
3961
+ const data = this.db.export();
3962
+ const buffer = Buffer.from(data);
3963
+ if (this.nodeFs) {
3964
+ this.nodeFs.writeFileSync(this.config.path, buffer);
5031
3965
  }
3966
+ }
3967
+ /**
3968
+ * Initialize database with migrations and seed data
3969
+ */
3970
+ initialize() {
5032
3971
  try {
5033
- const migrationExists = this.sqlite.prepare("SELECT COUNT(*) as count FROM migrations WHERE version = ?").get("1.0.0");
5034
- if (migrationExists.count === 0) {
5035
- this.db.insert(migrations).values({ version: "1.0.0" }).run();
5036
- }
3972
+ this.createTablesManually();
3973
+ this.seedDatabase();
5037
3974
  } catch (error) {
3975
+ console.error("Database initialization failed:", error);
3976
+ throw error;
5038
3977
  }
5039
3978
  }
5040
3979
  /**
5041
- * Manually create tables from Drizzle schema
5042
- * This is a fallback for when migrations don't exist yet
3980
+ * Manually create tables from schema
5043
3981
  */
5044
3982
  createTablesManually() {
5045
3983
  const createTablesSQL = `
@@ -5207,7 +4145,7 @@ var DatabaseManager = class _DatabaseManager {
5207
4145
  const statements = createTablesSQL.split(";").filter((s) => s.trim());
5208
4146
  for (const statement of statements) {
5209
4147
  try {
5210
- this.sqlite.exec(statement);
4148
+ this.db.run(statement);
5211
4149
  } catch (error) {
5212
4150
  if (this.config.verbose) {
5213
4151
  console.log("Table creation warning:", error);
@@ -5219,83 +4157,149 @@ var DatabaseManager = class _DatabaseManager {
5219
4157
  }
5220
4158
  }
5221
4159
  /**
5222
- * Get Drizzle database instance
4160
+ * Seed database with initial data
5223
4161
  */
5224
- getDb() {
5225
- return this.db;
4162
+ seedDatabase() {
4163
+ const pricingCount = this.db.exec(
4164
+ "SELECT COUNT(*) as count FROM sqlite_master WHERE type='table' AND name='pricing'"
4165
+ );
4166
+ if (pricingCount.length === 0 || pricingCount[0]?.values[0]?.[0] === 0) {
4167
+ this.createTablesManually();
4168
+ }
4169
+ const existingPricing = this.db.exec("SELECT COUNT(*) as count FROM pricing");
4170
+ const count = existingPricing.length > 0 ? existingPricing[0]?.values[0]?.[0] : 0;
4171
+ if (count === 0) {
4172
+ for (const price of defaultPricing) {
4173
+ const stmt = this.db.prepare(
4174
+ `INSERT INTO pricing (provider, model, input_price_per_1m, output_price_per_1m, effective_from, currency)
4175
+ VALUES (?, ?, ?, ?, ?, ?)`
4176
+ );
4177
+ const effectiveFrom = price.effectiveFrom ? typeof price.effectiveFrom === "number" ? price.effectiveFrom : Math.floor(price.effectiveFrom.getTime() / 1e3) : Math.floor(Date.now() / 1e3);
4178
+ stmt.run([
4179
+ price.provider,
4180
+ price.model,
4181
+ price.inputPricePer1M,
4182
+ price.outputPricePer1M,
4183
+ effectiveFrom,
4184
+ price.currency ?? "USD"
4185
+ ]);
4186
+ stmt.free();
4187
+ }
4188
+ if (this.config.verbose) {
4189
+ console.log(`Seeded ${defaultPricing.length} pricing entries`);
4190
+ }
4191
+ }
4192
+ try {
4193
+ const migrationExists = this.db.exec(
4194
+ "SELECT COUNT(*) as count FROM migrations WHERE version = '1.0.0'"
4195
+ );
4196
+ const migCount = migrationExists.length > 0 ? migrationExists[0]?.values[0]?.[0] : 0;
4197
+ if (migCount === 0) {
4198
+ this.db.run("INSERT INTO migrations (version) VALUES ('1.0.0')");
4199
+ }
4200
+ } catch (error) {
4201
+ }
5226
4202
  }
5227
4203
  /**
5228
- * Get raw SQLite database instance (for legacy code)
4204
+ * Execute a raw SQL query (auto-saves for write operations)
5229
4205
  */
5230
- getSqlite() {
5231
- return this.sqlite;
4206
+ execute(sql, params) {
4207
+ const stmt = this.db.prepare(sql);
4208
+ stmt.bind(params || []);
4209
+ stmt.step();
4210
+ const info = this.db.getRowsModified();
4211
+ stmt.free();
4212
+ const isWrite = /^\s*(INSERT|UPDATE|DELETE|CREATE|DROP|ALTER)/i.test(sql);
4213
+ if (isWrite && info > 0) {
4214
+ this.saveSync();
4215
+ }
4216
+ return {
4217
+ changes: info,
4218
+ lastInsertRowid: 0
4219
+ // sql.js doesn't provide this easily
4220
+ };
5232
4221
  }
5233
4222
  /**
5234
- * Execute a raw SQL query (for backward compatibility)
4223
+ * Query a raw SQL statement
5235
4224
  */
5236
- execute(sql2, params) {
5237
- const stmt = this.sqlite.prepare(sql2);
5238
- return stmt.run(...params || []);
4225
+ query(sql, params) {
4226
+ const stmt = this.db.prepare(sql);
4227
+ stmt.bind(params || []);
4228
+ const results = [];
4229
+ while (stmt.step()) {
4230
+ const row = stmt.getAsObject();
4231
+ results.push(row);
4232
+ }
4233
+ stmt.free();
4234
+ return results;
5239
4235
  }
5240
4236
  /**
5241
- * Query a raw SQL statement (for backward compatibility)
4237
+ * Execute a query and return a single row
5242
4238
  */
5243
- query(sql2, params) {
5244
- const stmt = this.sqlite.prepare(sql2);
5245
- return stmt.all(...params || []);
4239
+ queryOne(sql, params) {
4240
+ try {
4241
+ const stmt = this.db.prepare(sql);
4242
+ stmt.bind(params || []);
4243
+ if (stmt.step()) {
4244
+ const row = stmt.getAsObject();
4245
+ stmt.free();
4246
+ return row;
4247
+ }
4248
+ stmt.free();
4249
+ return null;
4250
+ } catch (error) {
4251
+ console.error("Query failed:", error);
4252
+ return null;
4253
+ }
5246
4254
  }
5247
4255
  /**
5248
- * Run a transaction
4256
+ * Run a transaction (auto-saves after commit)
5249
4257
  */
5250
4258
  transaction(fn) {
5251
- return this.db.transaction((tx) => fn(tx));
4259
+ this.db.run("BEGIN TRANSACTION");
4260
+ try {
4261
+ const result = fn(this);
4262
+ this.db.run("COMMIT");
4263
+ this.saveSync();
4264
+ return result;
4265
+ } catch (error) {
4266
+ this.db.run("ROLLBACK");
4267
+ throw error;
4268
+ }
5252
4269
  }
5253
4270
  /**
5254
4271
  * Close database connection
5255
4272
  */
5256
4273
  close() {
5257
- this.sqlite.close();
4274
+ this.db.close();
5258
4275
  }
5259
4276
  /**
5260
4277
  * Vacuum database to optimize storage
5261
4278
  */
5262
4279
  vacuum() {
5263
- this.sqlite.exec("VACUUM");
4280
+ this.db.run("VACUUM");
5264
4281
  }
5265
4282
  /**
5266
4283
  * Get database statistics
5267
4284
  */
5268
4285
  getStats() {
5269
- const pageCount = this.sqlite.pragma("page_count", { simple: true });
5270
- const pageSize = this.sqlite.pragma("page_size", { simple: true });
5271
- const journalMode = this.sqlite.pragma("journal_mode", { simple: true });
4286
+ const pageCount = this.queryOne("PRAGMA page_count");
4287
+ const pageSize = this.queryOne("PRAGMA page_size");
5272
4288
  return {
5273
- pageCount,
5274
- pageSize,
5275
- sizeBytes: pageCount * pageSize,
5276
- walMode: journalMode.toLowerCase() === "wal"
4289
+ pageCount: pageCount?.page_count || 0,
4290
+ pageSize: pageSize?.page_size || 0,
4291
+ sizeBytes: (pageCount?.page_count || 0) * (pageSize?.page_size || 0),
4292
+ walMode: false
4293
+ // sql.js doesn't support WAL mode
5277
4294
  };
5278
4295
  }
5279
- /**
5280
- * Execute a query and return a single row
5281
- */
5282
- queryOne(sql2, params) {
5283
- try {
5284
- const stmt = this.sqlite.prepare(sql2);
5285
- const result = params ? stmt.get(...params) : stmt.get();
5286
- return result || null;
5287
- } catch (error) {
5288
- console.error("Query failed:", error);
5289
- return null;
5290
- }
5291
- }
5292
4296
  /**
5293
4297
  * Perform a database health check
5294
4298
  */
5295
4299
  async healthCheck() {
5296
4300
  try {
5297
- const result = this.sqlite.pragma("integrity_check", { simple: true });
5298
- return result === "ok";
4301
+ const result = this.queryOne("PRAGMA integrity_check");
4302
+ return result?.integrity_check === "ok";
5299
4303
  } catch (error) {
5300
4304
  console.error("Health check failed:", error);
5301
4305
  return false;
@@ -5320,9 +4324,7 @@ function closeDatabaseManager() {
5320
4324
  }
5321
4325
 
5322
4326
  // src/core/MimirInitializer.ts
5323
- import path7 from "path";
5324
- import { fileURLToPath as fileURLToPath2 } from "url";
5325
- import { dirname as dirname2 } from "path";
4327
+ import path6, { dirname as dirname2 } from "path";
5326
4328
  var MimirInitializer = class {
5327
4329
  constructor(fs4, configLoader2) {
5328
4330
  this.fs = fs4;
@@ -5341,7 +4343,7 @@ var MimirInitializer = class {
5341
4343
  configCreated: false
5342
4344
  };
5343
4345
  try {
5344
- const mimirDir = path7.join(workspaceRoot, ".mimir");
4346
+ const mimirDir = path6.join(workspaceRoot, ".mimir");
5345
4347
  if (!await this.fs.exists(mimirDir)) {
5346
4348
  await this.fs.mkdir(mimirDir, { recursive: true });
5347
4349
  result.created.push(".mimir/");
@@ -5354,7 +4356,7 @@ var MimirInitializer = class {
5354
4356
  { name: "themes", purpose: "UI theme definitions" }
5355
4357
  ];
5356
4358
  for (const { name, purpose } of subdirs) {
5357
- const subdir = path7.join(mimirDir, name);
4359
+ const subdir = path6.join(mimirDir, name);
5358
4360
  if (!await this.fs.exists(subdir)) {
5359
4361
  await this.fs.mkdir(subdir, { recursive: true });
5360
4362
  result.created.push(`.mimir/${name}/`);
@@ -5380,15 +4382,15 @@ var MimirInitializer = class {
5380
4382
  * Check if workspace is initialized
5381
4383
  */
5382
4384
  async isWorkspaceInitialized(workspaceRoot) {
5383
- const mimirDir = path7.join(workspaceRoot, ".mimir");
5384
- const dbPath = path7.join(mimirDir, "mimir.db");
4385
+ const mimirDir = path6.join(workspaceRoot, ".mimir");
4386
+ const dbPath = path6.join(mimirDir, "mimir.db");
5385
4387
  return await this.fs.exists(mimirDir) && await this.fs.exists(dbPath);
5386
4388
  }
5387
4389
  /**
5388
4390
  * Create .gitignore inside .mimir directory
5389
4391
  */
5390
4392
  async createMimirGitignore(mimirDir, result) {
5391
- const gitignorePath = path7.join(mimirDir, ".gitignore");
4393
+ const gitignorePath = path6.join(mimirDir, ".gitignore");
5392
4394
  if (await this.fs.exists(gitignorePath)) {
5393
4395
  return;
5394
4396
  }
@@ -5433,7 +4435,7 @@ checkpoints/
5433
4435
  * Copy default theme files to .mimir/themes/ directory
5434
4436
  */
5435
4437
  async copyDefaultThemes(mimirDir, result) {
5436
- const themesDir = path7.join(mimirDir, "themes");
4438
+ const themesDir = path6.join(mimirDir, "themes");
5437
4439
  const defaultThemes = [
5438
4440
  "mimir.json",
5439
4441
  "dark.json",
@@ -5442,22 +4444,39 @@ checkpoints/
5442
4444
  "light-colorblind.json"
5443
4445
  ];
5444
4446
  try {
5445
- const __filename2 = fileURLToPath2(import.meta.url);
5446
- const __dirname2 = dirname2(__filename2);
5447
- const sourceThemesDir = path7.join(__dirname2, "../cli/themes");
4447
+ const executablePath = process.argv[0] || process.execPath;
4448
+ const binaryDir = dirname2(executablePath);
4449
+ const possibleSourceDirs = [
4450
+ path6.join(binaryDir, "resources", "themes"),
4451
+ // Compiled binary: ~/.local/bin/resources/themes/
4452
+ path6.join(binaryDir, "../cli/themes"),
4453
+ // Development: dist/core/../cli/themes
4454
+ path6.join(binaryDir, "../../src/cli/themes")
4455
+ // Development: dist/core/../../src/cli/themes
4456
+ ];
5448
4457
  for (const themeFile of defaultThemes) {
5449
- const destPath = path7.join(themesDir, themeFile);
4458
+ const destPath = path6.join(themesDir, themeFile);
5450
4459
  if (await this.fs.exists(destPath)) {
5451
4460
  continue;
5452
4461
  }
5453
- try {
5454
- const sourcePath = path7.join(sourceThemesDir, themeFile);
5455
- const themeContent = await this.fs.readFile(sourcePath, "utf-8");
5456
- await this.fs.writeFile(destPath, themeContent);
5457
- result.created.push(`.mimir/themes/${themeFile}`);
5458
- logger.info("Copied default theme", { theme: themeFile });
5459
- } catch (error) {
5460
- logger.warn(`Failed to copy theme ${themeFile}, will use built-in fallback`, { error });
4462
+ let copied = false;
4463
+ for (const sourceDir of possibleSourceDirs) {
4464
+ try {
4465
+ const sourcePath = path6.join(sourceDir, themeFile);
4466
+ const themeContent = await this.fs.readFile(sourcePath, "utf-8");
4467
+ await this.fs.writeFile(destPath, themeContent);
4468
+ result.created.push(`.mimir/themes/${themeFile}`);
4469
+ logger.info("Copied default theme", { theme: themeFile, from: sourceDir });
4470
+ copied = true;
4471
+ break;
4472
+ } catch (error) {
4473
+ continue;
4474
+ }
4475
+ }
4476
+ if (!copied) {
4477
+ logger.warn(`Failed to copy theme ${themeFile}, will use built-in fallback`, {
4478
+ triedLocations: possibleSourceDirs
4479
+ });
5461
4480
  }
5462
4481
  }
5463
4482
  } catch (error) {
@@ -5471,32 +4490,42 @@ checkpoints/
5471
4490
  * Copy example command files to .mimir/commands/ directory
5472
4491
  */
5473
4492
  async copyExampleCommands(mimirDir, result) {
5474
- const commandsDir = path7.join(mimirDir, "commands");
5475
- const exampleCommands = [
5476
- "security.yml",
5477
- "refactor.yml",
5478
- "test.yml",
5479
- "docs.yml",
5480
- "review.yml",
5481
- "perf.yml"
5482
- ];
4493
+ const commandsDir = path6.join(mimirDir, "commands");
4494
+ const exampleCommands = ["update-docs.yml"];
5483
4495
  try {
5484
- const __filename2 = fileURLToPath2(import.meta.url);
5485
- const __dirname2 = dirname2(__filename2);
5486
- const sourceCommandsDir = path7.join(__dirname2, "../../scripts/templates/commands");
4496
+ const executablePath = process.argv[0] || process.execPath;
4497
+ const binaryDir = dirname2(executablePath);
4498
+ const possibleSourceDirs = [
4499
+ path6.join(binaryDir, "resources", "commands"),
4500
+ // Compiled binary: ~/.local/bin/resources/commands/
4501
+ path6.join(binaryDir, "../../scripts/templates/commands"),
4502
+ // Development: dist/core/../../scripts/templates/commands
4503
+ path6.join(binaryDir, "../../../scripts/templates/commands")
4504
+ // Alternative dev path
4505
+ ];
5487
4506
  for (const commandFile of exampleCommands) {
5488
- const destPath = path7.join(commandsDir, commandFile);
4507
+ const destPath = path6.join(commandsDir, commandFile);
5489
4508
  if (await this.fs.exists(destPath)) {
5490
4509
  continue;
5491
4510
  }
5492
- try {
5493
- const sourcePath = path7.join(sourceCommandsDir, commandFile);
5494
- const commandContent = await this.fs.readFile(sourcePath, "utf-8");
5495
- await this.fs.writeFile(destPath, commandContent);
5496
- result.created.push(`.mimir/commands/${commandFile}`);
5497
- logger.info("Copied example command", { command: commandFile });
5498
- } catch (error) {
5499
- logger.warn(`Failed to copy command ${commandFile}, continuing`, { error });
4511
+ let copied = false;
4512
+ for (const sourceDir of possibleSourceDirs) {
4513
+ try {
4514
+ const sourcePath = path6.join(sourceDir, commandFile);
4515
+ const commandContent = await this.fs.readFile(sourcePath, "utf-8");
4516
+ await this.fs.writeFile(destPath, commandContent);
4517
+ result.created.push(`.mimir/commands/${commandFile}`);
4518
+ logger.info("Copied example command", { command: commandFile, from: sourceDir });
4519
+ copied = true;
4520
+ break;
4521
+ } catch (error) {
4522
+ continue;
4523
+ }
4524
+ }
4525
+ if (!copied) {
4526
+ logger.warn(`Failed to copy command ${commandFile}, continuing`, {
4527
+ triedLocations: possibleSourceDirs
4528
+ });
5500
4529
  }
5501
4530
  }
5502
4531
  } catch (error) {
@@ -5510,7 +4539,7 @@ checkpoints/
5510
4539
  * Initialize SQLite database with Drizzle ORM
5511
4540
  */
5512
4541
  async initializeDatabase(mimirDir, result) {
5513
- const dbPath = path7.join(mimirDir, "mimir.db");
4542
+ const dbPath = path6.join(mimirDir, "mimir.db");
5514
4543
  if (await this.fs.exists(dbPath)) {
5515
4544
  logger.info("Database already exists, skipping initialization", { path: dbPath });
5516
4545
  return;
@@ -5562,7 +4591,7 @@ checkpoints/
5562
4591
  * Create config.yml if it doesn't exist
5563
4592
  */
5564
4593
  async createConfigIfNeeded(mimirDir, result) {
5565
- const configPath = path7.join(mimirDir, "config.yml");
4594
+ const configPath = path6.join(mimirDir, "config.yml");
5566
4595
  if (await this.fs.exists(configPath)) {
5567
4596
  return;
5568
4597
  }
@@ -5660,7 +4689,7 @@ rateLimit:
5660
4689
  * Create README in .mimir directory
5661
4690
  */
5662
4691
  async createReadme(mimirDir, result) {
5663
- const readmePath = path7.join(mimirDir, "README.md");
4692
+ const readmePath = path6.join(mimirDir, "README.md");
5664
4693
  if (await this.fs.exists(readmePath)) {
5665
4694
  return;
5666
4695
  }
@@ -5825,7 +4854,7 @@ See the theme documentation for creating custom themes.
5825
4854
  result.errors.forEach((error) => console.log(` ! ${error}`));
5826
4855
  }
5827
4856
  console.log("\n\u{1F4C1} Workspace structure:");
5828
- console.log(` ${path7.join(workspaceRoot, ".mimir")}`);
4857
+ console.log(` ${path6.join(workspaceRoot, ".mimir")}`);
5829
4858
  console.log(" \u251C\u2500\u2500 config.yml (tracked in git)");
5830
4859
  console.log(" \u251C\u2500\u2500 mimir.db (ignored)");
5831
4860
  console.log(" \u251C\u2500\u2500 logs/ (ignored)");
@@ -5845,18 +4874,10 @@ See the theme documentation for creating custom themes.
5845
4874
  }
5846
4875
  };
5847
4876
 
5848
- // src/providers/ProviderFactory.ts
5849
- init_esm_shims();
5850
-
5851
4877
  // src/providers/DeepSeekProvider.ts
5852
- init_esm_shims();
5853
- import { encoding_for_model } from "tiktoken";
5854
-
5855
- // src/providers/BaseLLMProvider.ts
5856
- init_esm_shims();
4878
+ import { encode } from "gpt-tokenizer";
5857
4879
 
5858
4880
  // src/utils/errors.ts
5859
- init_esm_shims();
5860
4881
  var MimirError = class extends Error {
5861
4882
  constructor(message) {
5862
4883
  super(message);
@@ -5939,7 +4960,6 @@ var BaseLLMProvider = class {
5939
4960
  };
5940
4961
 
5941
4962
  // src/providers/utils/apiClient.ts
5942
- init_esm_shims();
5943
4963
  import axios from "axios";
5944
4964
  var APIClient = class {
5945
4965
  axiosInstance;
@@ -6047,7 +5067,6 @@ var APIClient = class {
6047
5067
  };
6048
5068
 
6049
5069
  // src/providers/pricing/pricingData.ts
6050
- init_esm_shims();
6051
5070
  var STATIC_PRICING_TABLE = {
6052
5071
  deepseek: {
6053
5072
  "deepseek-chat": {
@@ -6100,7 +5119,6 @@ function getStaticPricing(provider, model) {
6100
5119
  }
6101
5120
 
6102
5121
  // src/providers/utils/toolFormatters.ts
6103
- init_esm_shims();
6104
5122
  function toOpenAITools(tools) {
6105
5123
  return tools.map((tool) => ({
6106
5124
  type: "function",
@@ -6124,8 +5142,8 @@ function toAnthropicTools(tools) {
6124
5142
  }));
6125
5143
  }
6126
5144
  function parseOpenAIToolCalls(response) {
6127
- const toolCalls2 = response.choices?.[0]?.message?.tool_calls || [];
6128
- return toolCalls2.map((tc) => {
5145
+ const toolCalls = response.choices?.[0]?.message?.tool_calls || [];
5146
+ return toolCalls.map((tc) => {
6129
5147
  let parsedArgs;
6130
5148
  try {
6131
5149
  parsedArgs = JSON.parse(tc.function.arguments);
@@ -6180,7 +5198,6 @@ function mapAnthropicFinishReason(reason) {
6180
5198
  }
6181
5199
 
6182
5200
  // src/providers/utils/streamParsers.ts
6183
- init_esm_shims();
6184
5201
  async function* parseOpenAIStream(stream) {
6185
5202
  let buffer = "";
6186
5203
  for await (const chunk of stream) {
@@ -6275,7 +5292,6 @@ async function* parseAnthropicStream(stream) {
6275
5292
  // src/providers/DeepSeekProvider.ts
6276
5293
  var DeepSeekProvider = class extends BaseLLMProvider {
6277
5294
  apiClient;
6278
- encoder;
6279
5295
  constructor(config) {
6280
5296
  super(config);
6281
5297
  const apiKey = config.apiKey || process.env.DEEPSEEK_API_KEY;
@@ -6293,13 +5309,12 @@ var DeepSeekProvider = class extends BaseLLMProvider {
6293
5309
  },
6294
5310
  timeout: 6e4
6295
5311
  });
6296
- this.encoder = encoding_for_model("gpt-4");
6297
5312
  }
6298
- async chat(messages2, tools) {
5313
+ async chat(messages, tools) {
6299
5314
  return this.withRetry(async () => {
6300
5315
  const requestBody = {
6301
5316
  model: this.config.model,
6302
- messages: this.formatMessages(messages2),
5317
+ messages: this.formatMessages(messages),
6303
5318
  tools: tools ? toOpenAITools(tools) : void 0,
6304
5319
  temperature: this.config.temperature,
6305
5320
  max_tokens: this.config.maxTokens
@@ -6311,10 +5326,10 @@ var DeepSeekProvider = class extends BaseLLMProvider {
6311
5326
  return this.parseResponse(response);
6312
5327
  });
6313
5328
  }
6314
- async *streamChat(messages2, tools) {
5329
+ async *streamChat(messages, tools) {
6315
5330
  const requestBody = {
6316
5331
  model: this.config.model,
6317
- messages: this.formatMessages(messages2),
5332
+ messages: this.formatMessages(messages),
6318
5333
  tools: tools ? toOpenAITools(tools) : void 0,
6319
5334
  temperature: this.config.temperature,
6320
5335
  max_tokens: this.config.maxTokens,
@@ -6325,21 +5340,21 @@ var DeepSeekProvider = class extends BaseLLMProvider {
6325
5340
  yield chunk;
6326
5341
  }
6327
5342
  }
6328
- countTokens(text2) {
6329
- return this.encoder.encode(text2).length;
5343
+ countTokens(text) {
5344
+ return encode(text).length;
6330
5345
  }
6331
5346
  calculateCost(inputTokens, outputTokens) {
6332
- const pricing2 = getStaticPricing("deepseek", this.config.model);
6333
- if (!pricing2) {
5347
+ const pricing = getStaticPricing("deepseek", this.config.model);
5348
+ if (!pricing) {
6334
5349
  return 0;
6335
5350
  }
6336
- return inputTokens / 1e6 * pricing2.inputPerMillionTokens + outputTokens / 1e6 * pricing2.outputPerMillionTokens;
5351
+ return inputTokens / 1e6 * pricing.inputPerMillionTokens + outputTokens / 1e6 * pricing.outputPerMillionTokens;
6337
5352
  }
6338
5353
  /**
6339
5354
  * Format messages for OpenAI-compatible API
6340
5355
  */
6341
- formatMessages(messages2) {
6342
- return messages2.map((msg) => ({
5356
+ formatMessages(messages) {
5357
+ return messages.map((msg) => ({
6343
5358
  role: msg.role,
6344
5359
  content: msg.content,
6345
5360
  name: msg.name
@@ -6369,11 +5384,9 @@ var DeepSeekProvider = class extends BaseLLMProvider {
6369
5384
  };
6370
5385
 
6371
5386
  // src/providers/AnthropicProvider.ts
6372
- init_esm_shims();
6373
- import { encoding_for_model as encoding_for_model2 } from "tiktoken";
5387
+ import { encode as encode2 } from "gpt-tokenizer";
6374
5388
  var AnthropicProvider = class extends BaseLLMProvider {
6375
5389
  apiClient;
6376
- encoder;
6377
5390
  constructor(config) {
6378
5391
  super(config);
6379
5392
  const apiKey = config.apiKey || process.env.ANTHROPIC_API_KEY;
@@ -6392,11 +5405,10 @@ var AnthropicProvider = class extends BaseLLMProvider {
6392
5405
  },
6393
5406
  timeout: 6e4
6394
5407
  });
6395
- this.encoder = encoding_for_model2("gpt-4");
6396
5408
  }
6397
- async chat(messages2, tools) {
5409
+ async chat(messages, tools) {
6398
5410
  return this.withRetry(async () => {
6399
- const { system, messages: userMessages } = this.formatAnthropicMessages(messages2);
5411
+ const { system, messages: userMessages } = this.formatAnthropicMessages(messages);
6400
5412
  const requestBody = {
6401
5413
  model: this.config.model,
6402
5414
  messages: userMessages,
@@ -6416,8 +5428,8 @@ var AnthropicProvider = class extends BaseLLMProvider {
6416
5428
  return this.parseResponse(response);
6417
5429
  });
6418
5430
  }
6419
- async *streamChat(messages2, tools) {
6420
- const { system, messages: userMessages } = this.formatAnthropicMessages(messages2);
5431
+ async *streamChat(messages, tools) {
5432
+ const { system, messages: userMessages } = this.formatAnthropicMessages(messages);
6421
5433
  const requestBody = {
6422
5434
  model: this.config.model,
6423
5435
  messages: userMessages,
@@ -6436,23 +5448,23 @@ var AnthropicProvider = class extends BaseLLMProvider {
6436
5448
  yield chunk;
6437
5449
  }
6438
5450
  }
6439
- countTokens(text2) {
6440
- return this.encoder.encode(text2).length;
5451
+ countTokens(text) {
5452
+ return encode2(text).length;
6441
5453
  }
6442
5454
  calculateCost(inputTokens, outputTokens) {
6443
- const pricing2 = getStaticPricing("anthropic", this.config.model);
6444
- if (!pricing2) {
5455
+ const pricing = getStaticPricing("anthropic", this.config.model);
5456
+ if (!pricing) {
6445
5457
  return 0;
6446
5458
  }
6447
- return inputTokens / 1e6 * pricing2.inputPerMillionTokens + outputTokens / 1e6 * pricing2.outputPerMillionTokens;
5459
+ return inputTokens / 1e6 * pricing.inputPerMillionTokens + outputTokens / 1e6 * pricing.outputPerMillionTokens;
6448
5460
  }
6449
5461
  /**
6450
5462
  * Format messages for Anthropic API
6451
5463
  * Extracts system messages into separate parameter
6452
5464
  */
6453
- formatAnthropicMessages(messages2) {
6454
- const systemMessages = messages2.filter((m) => m.role === "system");
6455
- const userMessages = messages2.filter((m) => m.role !== "system");
5465
+ formatAnthropicMessages(messages) {
5466
+ const systemMessages = messages.filter((m) => m.role === "system");
5467
+ const userMessages = messages.filter((m) => m.role !== "system");
6456
5468
  const system = systemMessages.length > 0 ? systemMessages.map((m) => m.content).join("\n\n") : void 0;
6457
5469
  return {
6458
5470
  system,
@@ -6510,7 +5522,7 @@ var ProviderFactory = class {
6510
5522
  };
6511
5523
 
6512
5524
  // src/cli/commands/ChatCommand.ts
6513
- import path8 from "path";
5525
+ import path7 from "path";
6514
5526
  import yaml4 from "yaml";
6515
5527
  var ChatCommand = class {
6516
5528
  constructor(configLoader2, firstRunDetector2, setupCommand2, fs4) {
@@ -6562,7 +5574,7 @@ var ChatCommand = class {
6562
5574
  */
6563
5575
  async saveConfig(projectRoot, config) {
6564
5576
  try {
6565
- const configPath = path8.join(projectRoot, ".mimir", "config.yml");
5577
+ const configPath = path7.join(projectRoot, ".mimir", "config.yml");
6566
5578
  const yamlContent = yaml4.stringify(config);
6567
5579
  await this.fs.writeFile(configPath, yamlContent);
6568
5580
  logger.info("Config saved", { path: configPath });
@@ -6574,15 +5586,15 @@ var ChatCommand = class {
6574
5586
  /**
6575
5587
  * Process user message through LLM provider
6576
5588
  */
6577
- async processMessage(provider, messages2, userInput) {
5589
+ async processMessage(provider, messages, userInput) {
6578
5590
  const startTime = Date.now();
6579
5591
  try {
6580
5592
  const userMessage = {
6581
5593
  role: "user",
6582
5594
  content: userInput
6583
5595
  };
6584
- messages2.push(userMessage);
6585
- const response = await provider.chat(messages2);
5596
+ messages.push(userMessage);
5597
+ const response = await provider.chat(messages);
6586
5598
  const duration = Date.now() - startTime;
6587
5599
  const assistantMessage = {
6588
5600
  role: "assistant",
@@ -6596,7 +5608,7 @@ var ChatCommand = class {
6596
5608
  provider: provider.getProviderName()
6597
5609
  }
6598
5610
  };
6599
- messages2.push(assistantMessage);
5611
+ messages.push(assistantMessage);
6600
5612
  return assistantMessage;
6601
5613
  } catch (error) {
6602
5614
  const duration = Date.now() - startTime;
@@ -6611,7 +5623,7 @@ var ChatCommand = class {
6611
5623
  provider: provider.getProviderName()
6612
5624
  }
6613
5625
  };
6614
- messages2.push(errorMessage);
5626
+ messages.push(errorMessage);
6615
5627
  return errorMessage;
6616
5628
  }
6617
5629
  }
@@ -7019,22 +6031,27 @@ Available providers: deepseek, anthropic`
7019
6031
  };
7020
6032
 
7021
6033
  // src/cli/commands/InitCommand.ts
7022
- init_esm_shims();
7023
6034
  var InitCommand = class {
7024
6035
  initializer;
7025
6036
  constructor(_fs, _configLoader) {
7026
6037
  this.initializer = new MimirInitializer(_fs, _configLoader);
7027
6038
  }
7028
- async execute(projectRoot) {
6039
+ async execute(projectRoot, options = {}) {
7029
6040
  const root = projectRoot || process.cwd();
7030
- logger.info("Initializing Mimir workspace", { projectRoot: root });
6041
+ if (!options.quiet) {
6042
+ logger.info("Initializing Mimir workspace", { projectRoot: root });
6043
+ }
7031
6044
  if (await this.initializer.isWorkspaceInitialized(root)) {
7032
- logger.info("Mimir workspace is already initialized in this directory.");
7033
- logger.info('Run "mimir" to start an interactive chat session.');
6045
+ if (!options.quiet) {
6046
+ logger.info("Mimir workspace is already initialized in this directory.");
6047
+ logger.info('Run "mimir" to start an interactive chat session.');
6048
+ }
7034
6049
  return;
7035
6050
  }
7036
6051
  const result = await this.initializer.initializeWorkspace(root);
7037
- this.initializer.printSummary(result, root);
6052
+ if (!options.quiet) {
6053
+ this.initializer.printSummary(result, root);
6054
+ }
7038
6055
  if (!result.success) {
7039
6056
  process.exit(1);
7040
6057
  }
@@ -7058,8 +6075,8 @@ program.command("chat", { isDefault: true }).description("Start interactive chat
7058
6075
  await chatCommand.execute();
7059
6076
  process.exit(0);
7060
6077
  });
7061
- program.command("init").description("Initialize Mimir in current project").action(async () => {
7062
- await initCommand.execute();
6078
+ program.command("init").description("Initialize Mimir in current project").option("--no-interactive", "Run without interactive prompts (for automated setup)").option("-q, --quiet", "Suppress output").action(async (options) => {
6079
+ await initCommand.execute(void 0, options);
7063
6080
  process.exit(0);
7064
6081
  });
7065
6082
  var history = program.command("history").description("Manage conversation history");
@@ -7091,15 +6108,15 @@ cost.command("compare").description("Compare provider costs").action(() => {
7091
6108
  program.command("doctor").description("Run diagnostics").action(() => {
7092
6109
  logger.warn("Running diagnostics... (not implemented yet)");
7093
6110
  });
7094
- var permissions2 = program.command("permissions").description("Manage command permissions");
7095
- permissions2.command("list").description("List allowed commands").action(() => {
6111
+ var permissions = program.command("permissions").description("Manage command permissions");
6112
+ permissions.command("list").description("List allowed commands").action(() => {
7096
6113
  logger.warn("Listing permissions... (not implemented yet)");
7097
6114
  });
7098
- permissions2.command("add <pattern>").description("Add command to allowlist").action((pattern) => {
6115
+ permissions.command("add <pattern>").description("Add command to allowlist").action((pattern) => {
7099
6116
  logger.warn(`Adding ${pattern} to allowlist... (not implemented yet)`);
7100
6117
  });
7101
- permissions2.command("remove <pattern>").description("Remove command from allowlist").action((pattern) => {
6118
+ permissions.command("remove <pattern>").description("Remove command from allowlist").action((pattern) => {
7102
6119
  logger.warn(`Removing ${pattern} from allowlist... (not implemented yet)`);
7103
6120
  });
7104
6121
  program.parse();
7105
- //# sourceMappingURL=cli.js.map
6122
+ //# sourceMappingURL=cli.mjs.map