@sesamespace/hivemind 0.5.12 → 0.5.13

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,6 +1,785 @@
1
1
  import {
2
2
  SesameClient
3
3
  } from "./chunk-GPI4RU7N.js";
4
+ import {
5
+ __commonJS,
6
+ __require,
7
+ __toESM
8
+ } from "./chunk-7D4SUZUM.js";
9
+
10
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/util.js
11
+ var require_util = __commonJS({
12
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/util.js"(exports) {
13
+ "use strict";
14
+ exports.getBooleanOption = (options, key) => {
15
+ let value = false;
16
+ if (key in options && typeof (value = options[key]) !== "boolean") {
17
+ throw new TypeError(`Expected the "${key}" option to be a boolean`);
18
+ }
19
+ return value;
20
+ };
21
+ exports.cppdb = /* @__PURE__ */ Symbol();
22
+ exports.inspect = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
23
+ }
24
+ });
25
+
26
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/sqlite-error.js
27
+ var require_sqlite_error = __commonJS({
28
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/sqlite-error.js"(exports, module) {
29
+ "use strict";
30
+ var descriptor = { value: "SqliteError", writable: true, enumerable: false, configurable: true };
31
+ function SqliteError(message, code) {
32
+ if (new.target !== SqliteError) {
33
+ return new SqliteError(message, code);
34
+ }
35
+ if (typeof code !== "string") {
36
+ throw new TypeError("Expected second argument to be a string");
37
+ }
38
+ Error.call(this, message);
39
+ descriptor.value = "" + message;
40
+ Object.defineProperty(this, "message", descriptor);
41
+ Error.captureStackTrace(this, SqliteError);
42
+ this.code = code;
43
+ }
44
+ Object.setPrototypeOf(SqliteError, Error);
45
+ Object.setPrototypeOf(SqliteError.prototype, Error.prototype);
46
+ Object.defineProperty(SqliteError.prototype, "name", descriptor);
47
+ module.exports = SqliteError;
48
+ }
49
+ });
50
+
51
+ // node_modules/.pnpm/file-uri-to-path@1.0.0/node_modules/file-uri-to-path/index.js
52
+ var require_file_uri_to_path = __commonJS({
53
+ "node_modules/.pnpm/file-uri-to-path@1.0.0/node_modules/file-uri-to-path/index.js"(exports, module) {
54
+ "use strict";
55
+ var sep = __require("path").sep || "/";
56
+ module.exports = fileUriToPath;
57
+ function fileUriToPath(uri) {
58
+ if ("string" != typeof uri || uri.length <= 7 || "file://" != uri.substring(0, 7)) {
59
+ throw new TypeError("must pass in a file:// URI to convert to a file path");
60
+ }
61
+ var rest = decodeURI(uri.substring(7));
62
+ var firstSlash = rest.indexOf("/");
63
+ var host = rest.substring(0, firstSlash);
64
+ var path = rest.substring(firstSlash + 1);
65
+ if ("localhost" == host) host = "";
66
+ if (host) {
67
+ host = sep + sep + host;
68
+ }
69
+ path = path.replace(/^(.+)\|/, "$1:");
70
+ if (sep == "\\") {
71
+ path = path.replace(/\//g, "\\");
72
+ }
73
+ if (/^.+\:/.test(path)) {
74
+ } else {
75
+ path = sep + path;
76
+ }
77
+ return host + path;
78
+ }
79
+ }
80
+ });
81
+
82
+ // node_modules/.pnpm/bindings@1.5.0/node_modules/bindings/bindings.js
83
+ var require_bindings = __commonJS({
84
+ "node_modules/.pnpm/bindings@1.5.0/node_modules/bindings/bindings.js"(exports, module) {
85
+ "use strict";
86
+ var fs = __require("fs");
87
+ var path = __require("path");
88
+ var fileURLToPath4 = require_file_uri_to_path();
89
+ var join = path.join;
90
+ var dirname6 = path.dirname;
91
+ var exists = fs.accessSync && function(path2) {
92
+ try {
93
+ fs.accessSync(path2);
94
+ } catch (e) {
95
+ return false;
96
+ }
97
+ return true;
98
+ } || fs.existsSync || path.existsSync;
99
+ var defaults = {
100
+ arrow: process.env.NODE_BINDINGS_ARROW || " \u2192 ",
101
+ compiled: process.env.NODE_BINDINGS_COMPILED_DIR || "compiled",
102
+ platform: process.platform,
103
+ arch: process.arch,
104
+ nodePreGyp: "node-v" + process.versions.modules + "-" + process.platform + "-" + process.arch,
105
+ version: process.versions.node,
106
+ bindings: "bindings.node",
107
+ try: [
108
+ // node-gyp's linked version in the "build" dir
109
+ ["module_root", "build", "bindings"],
110
+ // node-waf and gyp_addon (a.k.a node-gyp)
111
+ ["module_root", "build", "Debug", "bindings"],
112
+ ["module_root", "build", "Release", "bindings"],
113
+ // Debug files, for development (legacy behavior, remove for node v0.9)
114
+ ["module_root", "out", "Debug", "bindings"],
115
+ ["module_root", "Debug", "bindings"],
116
+ // Release files, but manually compiled (legacy behavior, remove for node v0.9)
117
+ ["module_root", "out", "Release", "bindings"],
118
+ ["module_root", "Release", "bindings"],
119
+ // Legacy from node-waf, node <= 0.4.x
120
+ ["module_root", "build", "default", "bindings"],
121
+ // Production "Release" buildtype binary (meh...)
122
+ ["module_root", "compiled", "version", "platform", "arch", "bindings"],
123
+ // node-qbs builds
124
+ ["module_root", "addon-build", "release", "install-root", "bindings"],
125
+ ["module_root", "addon-build", "debug", "install-root", "bindings"],
126
+ ["module_root", "addon-build", "default", "install-root", "bindings"],
127
+ // node-pre-gyp path ./lib/binding/{node_abi}-{platform}-{arch}
128
+ ["module_root", "lib", "binding", "nodePreGyp", "bindings"]
129
+ ]
130
+ };
131
+ function bindings(opts) {
132
+ if (typeof opts == "string") {
133
+ opts = { bindings: opts };
134
+ } else if (!opts) {
135
+ opts = {};
136
+ }
137
+ Object.keys(defaults).map(function(i2) {
138
+ if (!(i2 in opts)) opts[i2] = defaults[i2];
139
+ });
140
+ if (!opts.module_root) {
141
+ opts.module_root = exports.getRoot(exports.getFileName());
142
+ }
143
+ if (path.extname(opts.bindings) != ".node") {
144
+ opts.bindings += ".node";
145
+ }
146
+ var requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
147
+ var tries = [], i = 0, l = opts.try.length, n, b, err;
148
+ for (; i < l; i++) {
149
+ n = join.apply(
150
+ null,
151
+ opts.try[i].map(function(p) {
152
+ return opts[p] || p;
153
+ })
154
+ );
155
+ tries.push(n);
156
+ try {
157
+ b = opts.path ? requireFunc.resolve(n) : requireFunc(n);
158
+ if (!opts.path) {
159
+ b.path = n;
160
+ }
161
+ return b;
162
+ } catch (e) {
163
+ if (e.code !== "MODULE_NOT_FOUND" && e.code !== "QUALIFIED_PATH_RESOLUTION_FAILED" && !/not find/i.test(e.message)) {
164
+ throw e;
165
+ }
166
+ }
167
+ }
168
+ err = new Error(
169
+ "Could not locate the bindings file. Tried:\n" + tries.map(function(a) {
170
+ return opts.arrow + a;
171
+ }).join("\n")
172
+ );
173
+ err.tries = tries;
174
+ throw err;
175
+ }
176
+ module.exports = exports = bindings;
177
+ exports.getFileName = function getFileName(calling_file) {
178
+ var origPST = Error.prepareStackTrace, origSTL = Error.stackTraceLimit, dummy = {}, fileName;
179
+ Error.stackTraceLimit = 10;
180
+ Error.prepareStackTrace = function(e, st) {
181
+ for (var i = 0, l = st.length; i < l; i++) {
182
+ fileName = st[i].getFileName();
183
+ if (fileName !== __filename) {
184
+ if (calling_file) {
185
+ if (fileName !== calling_file) {
186
+ return;
187
+ }
188
+ } else {
189
+ return;
190
+ }
191
+ }
192
+ }
193
+ };
194
+ Error.captureStackTrace(dummy);
195
+ dummy.stack;
196
+ Error.prepareStackTrace = origPST;
197
+ Error.stackTraceLimit = origSTL;
198
+ var fileSchema = "file://";
199
+ if (fileName.indexOf(fileSchema) === 0) {
200
+ fileName = fileURLToPath4(fileName);
201
+ }
202
+ return fileName;
203
+ };
204
+ exports.getRoot = function getRoot(file) {
205
+ var dir = dirname6(file), prev;
206
+ while (true) {
207
+ if (dir === ".") {
208
+ dir = process.cwd();
209
+ }
210
+ if (exists(join(dir, "package.json")) || exists(join(dir, "node_modules"))) {
211
+ return dir;
212
+ }
213
+ if (prev === dir) {
214
+ throw new Error(
215
+ 'Could not find module root given file: "' + file + '". Do you have a `package.json` file? '
216
+ );
217
+ }
218
+ prev = dir;
219
+ dir = join(dir, "..");
220
+ }
221
+ };
222
+ }
223
+ });
224
+
225
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/wrappers.js
226
+ var require_wrappers = __commonJS({
227
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/wrappers.js"(exports) {
228
+ "use strict";
229
+ var { cppdb } = require_util();
230
+ exports.prepare = function prepare(sql) {
231
+ return this[cppdb].prepare(sql, this, false);
232
+ };
233
+ exports.exec = function exec(sql) {
234
+ this[cppdb].exec(sql);
235
+ return this;
236
+ };
237
+ exports.close = function close() {
238
+ this[cppdb].close();
239
+ return this;
240
+ };
241
+ exports.loadExtension = function loadExtension(...args) {
242
+ this[cppdb].loadExtension(...args);
243
+ return this;
244
+ };
245
+ exports.defaultSafeIntegers = function defaultSafeIntegers(...args) {
246
+ this[cppdb].defaultSafeIntegers(...args);
247
+ return this;
248
+ };
249
+ exports.unsafeMode = function unsafeMode(...args) {
250
+ this[cppdb].unsafeMode(...args);
251
+ return this;
252
+ };
253
+ exports.getters = {
254
+ name: {
255
+ get: function name() {
256
+ return this[cppdb].name;
257
+ },
258
+ enumerable: true
259
+ },
260
+ open: {
261
+ get: function open() {
262
+ return this[cppdb].open;
263
+ },
264
+ enumerable: true
265
+ },
266
+ inTransaction: {
267
+ get: function inTransaction() {
268
+ return this[cppdb].inTransaction;
269
+ },
270
+ enumerable: true
271
+ },
272
+ readonly: {
273
+ get: function readonly() {
274
+ return this[cppdb].readonly;
275
+ },
276
+ enumerable: true
277
+ },
278
+ memory: {
279
+ get: function memory() {
280
+ return this[cppdb].memory;
281
+ },
282
+ enumerable: true
283
+ }
284
+ };
285
+ }
286
+ });
287
+
288
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/transaction.js
289
+ var require_transaction = __commonJS({
290
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/transaction.js"(exports, module) {
291
+ "use strict";
292
+ var { cppdb } = require_util();
293
+ var controllers = /* @__PURE__ */ new WeakMap();
294
+ module.exports = function transaction(fn) {
295
+ if (typeof fn !== "function") throw new TypeError("Expected first argument to be a function");
296
+ const db = this[cppdb];
297
+ const controller = getController(db, this);
298
+ const { apply } = Function.prototype;
299
+ const properties = {
300
+ default: { value: wrapTransaction(apply, fn, db, controller.default) },
301
+ deferred: { value: wrapTransaction(apply, fn, db, controller.deferred) },
302
+ immediate: { value: wrapTransaction(apply, fn, db, controller.immediate) },
303
+ exclusive: { value: wrapTransaction(apply, fn, db, controller.exclusive) },
304
+ database: { value: this, enumerable: true }
305
+ };
306
+ Object.defineProperties(properties.default.value, properties);
307
+ Object.defineProperties(properties.deferred.value, properties);
308
+ Object.defineProperties(properties.immediate.value, properties);
309
+ Object.defineProperties(properties.exclusive.value, properties);
310
+ return properties.default.value;
311
+ };
312
+ var getController = (db, self) => {
313
+ let controller = controllers.get(db);
314
+ if (!controller) {
315
+ const shared = {
316
+ commit: db.prepare("COMMIT", self, false),
317
+ rollback: db.prepare("ROLLBACK", self, false),
318
+ savepoint: db.prepare("SAVEPOINT ` _bs3. `", self, false),
319
+ release: db.prepare("RELEASE ` _bs3. `", self, false),
320
+ rollbackTo: db.prepare("ROLLBACK TO ` _bs3. `", self, false)
321
+ };
322
+ controllers.set(db, controller = {
323
+ default: Object.assign({ begin: db.prepare("BEGIN", self, false) }, shared),
324
+ deferred: Object.assign({ begin: db.prepare("BEGIN DEFERRED", self, false) }, shared),
325
+ immediate: Object.assign({ begin: db.prepare("BEGIN IMMEDIATE", self, false) }, shared),
326
+ exclusive: Object.assign({ begin: db.prepare("BEGIN EXCLUSIVE", self, false) }, shared)
327
+ });
328
+ }
329
+ return controller;
330
+ };
331
+ var wrapTransaction = (apply, fn, db, { begin, commit, rollback, savepoint, release, rollbackTo }) => function sqliteTransaction() {
332
+ let before, after, undo;
333
+ if (db.inTransaction) {
334
+ before = savepoint;
335
+ after = release;
336
+ undo = rollbackTo;
337
+ } else {
338
+ before = begin;
339
+ after = commit;
340
+ undo = rollback;
341
+ }
342
+ before.run();
343
+ try {
344
+ const result = apply.call(fn, this, arguments);
345
+ if (result && typeof result.then === "function") {
346
+ throw new TypeError("Transaction function cannot return a promise");
347
+ }
348
+ after.run();
349
+ return result;
350
+ } catch (ex) {
351
+ if (db.inTransaction) {
352
+ undo.run();
353
+ if (undo !== rollback) after.run();
354
+ }
355
+ throw ex;
356
+ }
357
+ };
358
+ }
359
+ });
360
+
361
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/pragma.js
362
+ var require_pragma = __commonJS({
363
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/pragma.js"(exports, module) {
364
+ "use strict";
365
+ var { getBooleanOption, cppdb } = require_util();
366
+ module.exports = function pragma(source, options) {
367
+ if (options == null) options = {};
368
+ if (typeof source !== "string") throw new TypeError("Expected first argument to be a string");
369
+ if (typeof options !== "object") throw new TypeError("Expected second argument to be an options object");
370
+ const simple = getBooleanOption(options, "simple");
371
+ const stmt = this[cppdb].prepare(`PRAGMA ${source}`, this, true);
372
+ return simple ? stmt.pluck().get() : stmt.all();
373
+ };
374
+ }
375
+ });
376
+
377
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/backup.js
378
+ var require_backup = __commonJS({
379
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/backup.js"(exports, module) {
380
+ "use strict";
381
+ var fs = __require("fs");
382
+ var path = __require("path");
383
+ var { promisify } = __require("util");
384
+ var { cppdb } = require_util();
385
+ var fsAccess = promisify(fs.access);
386
+ module.exports = async function backup(filename, options) {
387
+ if (options == null) options = {};
388
+ if (typeof filename !== "string") throw new TypeError("Expected first argument to be a string");
389
+ if (typeof options !== "object") throw new TypeError("Expected second argument to be an options object");
390
+ filename = filename.trim();
391
+ const attachedName = "attached" in options ? options.attached : "main";
392
+ const handler = "progress" in options ? options.progress : null;
393
+ if (!filename) throw new TypeError("Backup filename cannot be an empty string");
394
+ if (filename === ":memory:") throw new TypeError('Invalid backup filename ":memory:"');
395
+ if (typeof attachedName !== "string") throw new TypeError('Expected the "attached" option to be a string');
396
+ if (!attachedName) throw new TypeError('The "attached" option cannot be an empty string');
397
+ if (handler != null && typeof handler !== "function") throw new TypeError('Expected the "progress" option to be a function');
398
+ await fsAccess(path.dirname(filename)).catch(() => {
399
+ throw new TypeError("Cannot save backup because the directory does not exist");
400
+ });
401
+ const isNewFile = await fsAccess(filename).then(() => false, () => true);
402
+ return runBackup(this[cppdb].backup(this, attachedName, filename, isNewFile), handler || null);
403
+ };
404
+ var runBackup = (backup, handler) => {
405
+ let rate = 0;
406
+ let useDefault = true;
407
+ return new Promise((resolve6, reject) => {
408
+ setImmediate(function step() {
409
+ try {
410
+ const progress = backup.transfer(rate);
411
+ if (!progress.remainingPages) {
412
+ backup.close();
413
+ resolve6(progress);
414
+ return;
415
+ }
416
+ if (useDefault) {
417
+ useDefault = false;
418
+ rate = 100;
419
+ }
420
+ if (handler) {
421
+ const ret = handler(progress);
422
+ if (ret !== void 0) {
423
+ if (typeof ret === "number" && ret === ret) rate = Math.max(0, Math.min(2147483647, Math.round(ret)));
424
+ else throw new TypeError("Expected progress callback to return a number or undefined");
425
+ }
426
+ }
427
+ setImmediate(step);
428
+ } catch (err) {
429
+ backup.close();
430
+ reject(err);
431
+ }
432
+ });
433
+ });
434
+ };
435
+ }
436
+ });
437
+
438
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/serialize.js
439
+ var require_serialize = __commonJS({
440
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/serialize.js"(exports, module) {
441
+ "use strict";
442
+ var { cppdb } = require_util();
443
+ module.exports = function serialize(options) {
444
+ if (options == null) options = {};
445
+ if (typeof options !== "object") throw new TypeError("Expected first argument to be an options object");
446
+ const attachedName = "attached" in options ? options.attached : "main";
447
+ if (typeof attachedName !== "string") throw new TypeError('Expected the "attached" option to be a string');
448
+ if (!attachedName) throw new TypeError('The "attached" option cannot be an empty string');
449
+ return this[cppdb].serialize(attachedName);
450
+ };
451
+ }
452
+ });
453
+
454
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/function.js
455
+ var require_function = __commonJS({
456
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/function.js"(exports, module) {
457
+ "use strict";
458
+ var { getBooleanOption, cppdb } = require_util();
459
+ module.exports = function defineFunction(name, options, fn) {
460
+ if (options == null) options = {};
461
+ if (typeof options === "function") {
462
+ fn = options;
463
+ options = {};
464
+ }
465
+ if (typeof name !== "string") throw new TypeError("Expected first argument to be a string");
466
+ if (typeof fn !== "function") throw new TypeError("Expected last argument to be a function");
467
+ if (typeof options !== "object") throw new TypeError("Expected second argument to be an options object");
468
+ if (!name) throw new TypeError("User-defined function name cannot be an empty string");
469
+ const safeIntegers = "safeIntegers" in options ? +getBooleanOption(options, "safeIntegers") : 2;
470
+ const deterministic = getBooleanOption(options, "deterministic");
471
+ const directOnly = getBooleanOption(options, "directOnly");
472
+ const varargs = getBooleanOption(options, "varargs");
473
+ let argCount = -1;
474
+ if (!varargs) {
475
+ argCount = fn.length;
476
+ if (!Number.isInteger(argCount) || argCount < 0) throw new TypeError("Expected function.length to be a positive integer");
477
+ if (argCount > 100) throw new RangeError("User-defined functions cannot have more than 100 arguments");
478
+ }
479
+ this[cppdb].function(fn, name, argCount, safeIntegers, deterministic, directOnly);
480
+ return this;
481
+ };
482
+ }
483
+ });
484
+
485
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/aggregate.js
486
+ var require_aggregate = __commonJS({
487
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/aggregate.js"(exports, module) {
488
+ "use strict";
489
+ var { getBooleanOption, cppdb } = require_util();
490
+ module.exports = function defineAggregate(name, options) {
491
+ if (typeof name !== "string") throw new TypeError("Expected first argument to be a string");
492
+ if (typeof options !== "object" || options === null) throw new TypeError("Expected second argument to be an options object");
493
+ if (!name) throw new TypeError("User-defined function name cannot be an empty string");
494
+ const start = "start" in options ? options.start : null;
495
+ const step = getFunctionOption(options, "step", true);
496
+ const inverse = getFunctionOption(options, "inverse", false);
497
+ const result = getFunctionOption(options, "result", false);
498
+ const safeIntegers = "safeIntegers" in options ? +getBooleanOption(options, "safeIntegers") : 2;
499
+ const deterministic = getBooleanOption(options, "deterministic");
500
+ const directOnly = getBooleanOption(options, "directOnly");
501
+ const varargs = getBooleanOption(options, "varargs");
502
+ let argCount = -1;
503
+ if (!varargs) {
504
+ argCount = Math.max(getLength(step), inverse ? getLength(inverse) : 0);
505
+ if (argCount > 0) argCount -= 1;
506
+ if (argCount > 100) throw new RangeError("User-defined functions cannot have more than 100 arguments");
507
+ }
508
+ this[cppdb].aggregate(start, step, inverse, result, name, argCount, safeIntegers, deterministic, directOnly);
509
+ return this;
510
+ };
511
+ var getFunctionOption = (options, key, required) => {
512
+ const value = key in options ? options[key] : null;
513
+ if (typeof value === "function") return value;
514
+ if (value != null) throw new TypeError(`Expected the "${key}" option to be a function`);
515
+ if (required) throw new TypeError(`Missing required option "${key}"`);
516
+ return null;
517
+ };
518
+ var getLength = ({ length }) => {
519
+ if (Number.isInteger(length) && length >= 0) return length;
520
+ throw new TypeError("Expected function.length to be a positive integer");
521
+ };
522
+ }
523
+ });
524
+
525
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/table.js
526
+ var require_table = __commonJS({
527
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/table.js"(exports, module) {
528
+ "use strict";
529
+ var { cppdb } = require_util();
530
+ module.exports = function defineTable(name, factory) {
531
+ if (typeof name !== "string") throw new TypeError("Expected first argument to be a string");
532
+ if (!name) throw new TypeError("Virtual table module name cannot be an empty string");
533
+ let eponymous = false;
534
+ if (typeof factory === "object" && factory !== null) {
535
+ eponymous = true;
536
+ factory = defer(parseTableDefinition(factory, "used", name));
537
+ } else {
538
+ if (typeof factory !== "function") throw new TypeError("Expected second argument to be a function or a table definition object");
539
+ factory = wrapFactory(factory);
540
+ }
541
+ this[cppdb].table(factory, name, eponymous);
542
+ return this;
543
+ };
544
+ function wrapFactory(factory) {
545
+ return function virtualTableFactory(moduleName, databaseName, tableName, ...args) {
546
+ const thisObject = {
547
+ module: moduleName,
548
+ database: databaseName,
549
+ table: tableName
550
+ };
551
+ const def = apply.call(factory, thisObject, args);
552
+ if (typeof def !== "object" || def === null) {
553
+ throw new TypeError(`Virtual table module "${moduleName}" did not return a table definition object`);
554
+ }
555
+ return parseTableDefinition(def, "returned", moduleName);
556
+ };
557
+ }
558
+ function parseTableDefinition(def, verb, moduleName) {
559
+ if (!hasOwnProperty.call(def, "rows")) {
560
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition without a "rows" property`);
561
+ }
562
+ if (!hasOwnProperty.call(def, "columns")) {
563
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition without a "columns" property`);
564
+ }
565
+ const rows = def.rows;
566
+ if (typeof rows !== "function" || Object.getPrototypeOf(rows) !== GeneratorFunctionPrototype) {
567
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "rows" property (should be a generator function)`);
568
+ }
569
+ let columns = def.columns;
570
+ if (!Array.isArray(columns) || !(columns = [...columns]).every((x) => typeof x === "string")) {
571
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "columns" property (should be an array of strings)`);
572
+ }
573
+ if (columns.length !== new Set(columns).size) {
574
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with duplicate column names`);
575
+ }
576
+ if (!columns.length) {
577
+ throw new RangeError(`Virtual table module "${moduleName}" ${verb} a table definition with zero columns`);
578
+ }
579
+ let parameters;
580
+ if (hasOwnProperty.call(def, "parameters")) {
581
+ parameters = def.parameters;
582
+ if (!Array.isArray(parameters) || !(parameters = [...parameters]).every((x) => typeof x === "string")) {
583
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "parameters" property (should be an array of strings)`);
584
+ }
585
+ } else {
586
+ parameters = inferParameters(rows);
587
+ }
588
+ if (parameters.length !== new Set(parameters).size) {
589
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with duplicate parameter names`);
590
+ }
591
+ if (parameters.length > 32) {
592
+ throw new RangeError(`Virtual table module "${moduleName}" ${verb} a table definition with more than the maximum number of 32 parameters`);
593
+ }
594
+ for (const parameter of parameters) {
595
+ if (columns.includes(parameter)) {
596
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with column "${parameter}" which was ambiguously defined as both a column and parameter`);
597
+ }
598
+ }
599
+ let safeIntegers = 2;
600
+ if (hasOwnProperty.call(def, "safeIntegers")) {
601
+ const bool = def.safeIntegers;
602
+ if (typeof bool !== "boolean") {
603
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "safeIntegers" property (should be a boolean)`);
604
+ }
605
+ safeIntegers = +bool;
606
+ }
607
+ let directOnly = false;
608
+ if (hasOwnProperty.call(def, "directOnly")) {
609
+ directOnly = def.directOnly;
610
+ if (typeof directOnly !== "boolean") {
611
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "directOnly" property (should be a boolean)`);
612
+ }
613
+ }
614
+ const columnDefinitions = [
615
+ ...parameters.map(identifier).map((str) => `${str} HIDDEN`),
616
+ ...columns.map(identifier)
617
+ ];
618
+ return [
619
+ `CREATE TABLE x(${columnDefinitions.join(", ")});`,
620
+ wrapGenerator(rows, new Map(columns.map((x, i) => [x, parameters.length + i])), moduleName),
621
+ parameters,
622
+ safeIntegers,
623
+ directOnly
624
+ ];
625
+ }
626
+ function wrapGenerator(generator, columnMap, moduleName) {
627
+ return function* virtualTable(...args) {
628
+ const output = args.map((x) => Buffer.isBuffer(x) ? Buffer.from(x) : x);
629
+ for (let i = 0; i < columnMap.size; ++i) {
630
+ output.push(null);
631
+ }
632
+ for (const row of generator(...args)) {
633
+ if (Array.isArray(row)) {
634
+ extractRowArray(row, output, columnMap.size, moduleName);
635
+ yield output;
636
+ } else if (typeof row === "object" && row !== null) {
637
+ extractRowObject(row, output, columnMap, moduleName);
638
+ yield output;
639
+ } else {
640
+ throw new TypeError(`Virtual table module "${moduleName}" yielded something that isn't a valid row object`);
641
+ }
642
+ }
643
+ };
644
+ }
645
+ function extractRowArray(row, output, columnCount, moduleName) {
646
+ if (row.length !== columnCount) {
647
+ throw new TypeError(`Virtual table module "${moduleName}" yielded a row with an incorrect number of columns`);
648
+ }
649
+ const offset = output.length - columnCount;
650
+ for (let i = 0; i < columnCount; ++i) {
651
+ output[i + offset] = row[i];
652
+ }
653
+ }
654
+ function extractRowObject(row, output, columnMap, moduleName) {
655
+ let count = 0;
656
+ for (const key of Object.keys(row)) {
657
+ const index = columnMap.get(key);
658
+ if (index === void 0) {
659
+ throw new TypeError(`Virtual table module "${moduleName}" yielded a row with an undeclared column "${key}"`);
660
+ }
661
+ output[index] = row[key];
662
+ count += 1;
663
+ }
664
+ if (count !== columnMap.size) {
665
+ throw new TypeError(`Virtual table module "${moduleName}" yielded a row with missing columns`);
666
+ }
667
+ }
668
+ function inferParameters({ length }) {
669
+ if (!Number.isInteger(length) || length < 0) {
670
+ throw new TypeError("Expected function.length to be a positive integer");
671
+ }
672
+ const params = [];
673
+ for (let i = 0; i < length; ++i) {
674
+ params.push(`$${i + 1}`);
675
+ }
676
+ return params;
677
+ }
678
+ var { hasOwnProperty } = Object.prototype;
679
+ var { apply } = Function.prototype;
680
+ var GeneratorFunctionPrototype = Object.getPrototypeOf(function* () {
681
+ });
682
+ var identifier = (str) => `"${str.replace(/"/g, '""')}"`;
683
+ var defer = (x) => () => x;
684
+ }
685
+ });
686
+
687
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/inspect.js
688
+ var require_inspect = __commonJS({
689
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/methods/inspect.js"(exports, module) {
690
+ "use strict";
691
+ var DatabaseInspection = function Database2() {
692
+ };
693
+ module.exports = function inspect(depth, opts) {
694
+ return Object.assign(new DatabaseInspection(), this);
695
+ };
696
+ }
697
+ });
698
+
699
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/database.js
700
+ var require_database = __commonJS({
701
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/database.js"(exports, module) {
702
+ "use strict";
703
+ var fs = __require("fs");
704
+ var path = __require("path");
705
+ var util = require_util();
706
+ var SqliteError = require_sqlite_error();
707
+ var DEFAULT_ADDON;
708
+ function Database2(filenameGiven, options) {
709
+ if (new.target == null) {
710
+ return new Database2(filenameGiven, options);
711
+ }
712
+ let buffer;
713
+ if (Buffer.isBuffer(filenameGiven)) {
714
+ buffer = filenameGiven;
715
+ filenameGiven = ":memory:";
716
+ }
717
+ if (filenameGiven == null) filenameGiven = "";
718
+ if (options == null) options = {};
719
+ if (typeof filenameGiven !== "string") throw new TypeError("Expected first argument to be a string");
720
+ if (typeof options !== "object") throw new TypeError("Expected second argument to be an options object");
721
+ if ("readOnly" in options) throw new TypeError('Misspelled option "readOnly" should be "readonly"');
722
+ if ("memory" in options) throw new TypeError('Option "memory" was removed in v7.0.0 (use ":memory:" filename instead)');
723
+ const filename = filenameGiven.trim();
724
+ const anonymous = filename === "" || filename === ":memory:";
725
+ const readonly = util.getBooleanOption(options, "readonly");
726
+ const fileMustExist = util.getBooleanOption(options, "fileMustExist");
727
+ const timeout = "timeout" in options ? options.timeout : 5e3;
728
+ const verbose = "verbose" in options ? options.verbose : null;
729
+ const nativeBinding = "nativeBinding" in options ? options.nativeBinding : null;
730
+ if (readonly && anonymous && !buffer) throw new TypeError("In-memory/temporary databases cannot be readonly");
731
+ if (!Number.isInteger(timeout) || timeout < 0) throw new TypeError('Expected the "timeout" option to be a positive integer');
732
+ if (timeout > 2147483647) throw new RangeError('Option "timeout" cannot be greater than 2147483647');
733
+ if (verbose != null && typeof verbose !== "function") throw new TypeError('Expected the "verbose" option to be a function');
734
+ if (nativeBinding != null && typeof nativeBinding !== "string" && typeof nativeBinding !== "object") throw new TypeError('Expected the "nativeBinding" option to be a string or addon object');
735
+ let addon;
736
+ if (nativeBinding == null) {
737
+ addon = DEFAULT_ADDON || (DEFAULT_ADDON = require_bindings()("better_sqlite3.node"));
738
+ } else if (typeof nativeBinding === "string") {
739
+ const requireFunc = typeof __non_webpack_require__ === "function" ? __non_webpack_require__ : __require;
740
+ addon = requireFunc(path.resolve(nativeBinding).replace(/(\.node)?$/, ".node"));
741
+ } else {
742
+ addon = nativeBinding;
743
+ }
744
+ if (!addon.isInitialized) {
745
+ addon.setErrorConstructor(SqliteError);
746
+ addon.isInitialized = true;
747
+ }
748
+ if (!anonymous && !fs.existsSync(path.dirname(filename))) {
749
+ throw new TypeError("Cannot open database because the directory does not exist");
750
+ }
751
+ Object.defineProperties(this, {
752
+ [util.cppdb]: { value: new addon.Database(filename, filenameGiven, anonymous, readonly, fileMustExist, timeout, verbose || null, buffer || null) },
753
+ ...wrappers.getters
754
+ });
755
+ }
756
+ var wrappers = require_wrappers();
757
+ Database2.prototype.prepare = wrappers.prepare;
758
+ Database2.prototype.transaction = require_transaction();
759
+ Database2.prototype.pragma = require_pragma();
760
+ Database2.prototype.backup = require_backup();
761
+ Database2.prototype.serialize = require_serialize();
762
+ Database2.prototype.function = require_function();
763
+ Database2.prototype.aggregate = require_aggregate();
764
+ Database2.prototype.table = require_table();
765
+ Database2.prototype.loadExtension = wrappers.loadExtension;
766
+ Database2.prototype.exec = wrappers.exec;
767
+ Database2.prototype.close = wrappers.close;
768
+ Database2.prototype.defaultSafeIntegers = wrappers.defaultSafeIntegers;
769
+ Database2.prototype.unsafeMode = wrappers.unsafeMode;
770
+ Database2.prototype[util.inspect] = require_inspect();
771
+ module.exports = Database2;
772
+ }
773
+ });
774
+
775
+ // node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/index.js
776
+ var require_lib = __commonJS({
777
+ "node_modules/.pnpm/better-sqlite3@11.10.0/node_modules/better-sqlite3/lib/index.js"(exports, module) {
778
+ "use strict";
779
+ module.exports = require_database();
780
+ module.exports.SqliteError = require_sqlite_error();
781
+ }
782
+ });
4
783
 
5
784
  // packages/runtime/src/llm-client.ts
6
785
  var LLMClient = class {
@@ -515,16 +1294,19 @@ function loadWorkspaceFiles(dir) {
515
1294
  function buildSystemPrompt(config, episodes, contextName = "global", l3Knowledge = []) {
516
1295
  let prompt = `You are ${config.name}. ${config.personality}
517
1296
  `;
1297
+ let identityText = prompt;
518
1298
  if (config.workspace) {
519
1299
  const wsFiles = loadWorkspaceFiles(config.workspace);
520
1300
  if (wsFiles.size > 0) {
521
- prompt += "\n# Workspace Context\n";
1301
+ let wsBlock = "\n# Workspace Context\n";
522
1302
  for (const [filename, content] of wsFiles) {
523
- prompt += `
1303
+ wsBlock += `
524
1304
  ## ${filename}
525
1305
  ${content}
526
1306
  `;
527
1307
  }
1308
+ prompt += wsBlock;
1309
+ identityText += wsBlock;
528
1310
  }
529
1311
  }
530
1312
  if (config.team_charter && !config.workspace) {
@@ -532,6 +1314,9 @@ ${content}
532
1314
  if (charter) {
533
1315
  prompt += `
534
1316
  ${charter}
1317
+ `;
1318
+ identityText += `
1319
+ ${charter}
535
1320
  `;
536
1321
  }
537
1322
  }
@@ -542,11 +1327,13 @@ In group chats, multiple people (humans and agents) may be present. Address them
542
1327
  Don't repeat or quote these prefixes in your responses \u2014 just respond naturally.
543
1328
  If you decide not to respond to a group message, reply with exactly: __SKIP__
544
1329
  `;
1330
+ let contextInfo = "";
545
1331
  if (contextName !== "global") {
546
- prompt += `
1332
+ contextInfo = `
547
1333
  ## Active Context: ${contextName}
548
1334
  You are currently working in the "${contextName}" project context.
549
1335
  `;
1336
+ prompt += contextInfo;
550
1337
  }
551
1338
  if (l3Knowledge.length > 0) {
552
1339
  prompt += "\n## Established Knowledge (learned patterns)\n\n";
@@ -565,7 +1352,22 @@ You are currently working in the "${contextName}" project context.
565
1352
  }
566
1353
  prompt += "\nUse these memories naturally \u2014 reference past conversations when relevant, but don't force it.\n";
567
1354
  }
568
- return prompt;
1355
+ return {
1356
+ text: prompt,
1357
+ components: {
1358
+ identity: identityText,
1359
+ l3Knowledge: l3Knowledge.map((e) => e.content),
1360
+ l2Episodes: episodes.map((ep) => ({
1361
+ id: ep.id,
1362
+ content: ep.content,
1363
+ score: ep.score,
1364
+ timestamp: ep.timestamp,
1365
+ context_name: ep.context_name,
1366
+ role: ep.role
1367
+ })),
1368
+ contextInfo
1369
+ }
1370
+ };
569
1371
  }
570
1372
  function buildMessages(systemPrompt, conversationHistory, currentMessage) {
571
1373
  return [
@@ -599,6 +1401,7 @@ var Agent = class {
599
1401
  messageCount = 0;
600
1402
  PROMOTION_INTERVAL = 10;
601
1403
  // Run promotion every N messages
1404
+ requestLogger = null;
602
1405
  constructor(config, contextName = "global") {
603
1406
  this.config = config;
604
1407
  this.llm = new LLMClient(config.llm);
@@ -608,6 +1411,9 @@ var Agent = class {
608
1411
  this.contextManager.switchContext(contextName);
609
1412
  }
610
1413
  }
1414
+ setRequestLogger(logger) {
1415
+ this.requestLogger = logger;
1416
+ }
611
1417
  async processMessage(userMessage) {
612
1418
  const specialResult = await this.handleSpecialCommand(userMessage);
613
1419
  if (specialResult) return specialResult;
@@ -637,9 +1443,47 @@ var Agent = class {
637
1443
  }
638
1444
  }
639
1445
  const l3Knowledge = await this.memory.getL3Knowledge(contextName).catch(() => []);
640
- const systemPrompt = buildSystemPrompt(this.config.agent, relevantEpisodes, contextName, l3Knowledge);
641
- const messages = buildMessages(systemPrompt, conversationHistory, userMessage);
1446
+ const systemPromptResult = buildSystemPrompt(this.config.agent, relevantEpisodes, contextName, l3Knowledge);
1447
+ const messages = buildMessages(systemPromptResult.text, conversationHistory, userMessage);
1448
+ const llmStart = Date.now();
642
1449
  const response = await this.llm.chat(messages);
1450
+ const latencyMs = Date.now() - llmStart;
1451
+ if (this.requestLogger) {
1452
+ try {
1453
+ this.requestLogger.log({
1454
+ context: contextName,
1455
+ contextSwitched: routing.switched,
1456
+ routingReason: routing.switched ? `switched:${contextName}` : `active:${contextName}`,
1457
+ rawMessage: userMessage,
1458
+ systemPromptComponents: {
1459
+ identity: systemPromptResult.components.identity,
1460
+ l3Knowledge: systemPromptResult.components.l3Knowledge,
1461
+ l2Episodes: systemPromptResult.components.l2Episodes,
1462
+ contextInfo: systemPromptResult.components.contextInfo,
1463
+ fullText: systemPromptResult.text
1464
+ },
1465
+ conversationHistory: conversationHistory.map((m) => ({
1466
+ role: m.role,
1467
+ content: m.content
1468
+ })),
1469
+ userMessage,
1470
+ response: {
1471
+ content: response.content,
1472
+ model: response.model,
1473
+ latencyMs,
1474
+ skipped: response.content.trim() === "__SKIP__"
1475
+ },
1476
+ config: {
1477
+ topK: this.config.memory.top_k,
1478
+ model: this.config.llm.model,
1479
+ maxTokens: this.config.llm.max_tokens,
1480
+ temperature: this.config.llm.temperature
1481
+ }
1482
+ });
1483
+ } catch (err) {
1484
+ console.error("[dashboard] Failed to log request:", err.message);
1485
+ }
1486
+ }
643
1487
  conversationHistory.push(
644
1488
  { role: "user", content: userMessage },
645
1489
  { role: "assistant", content: response.content }
@@ -682,7 +1526,195 @@ var Agent = class {
682
1526
  }
683
1527
  async handleSpecialCommand(message) {
684
1528
  const activeCtx = this.contextManager.getActiveContext();
685
- const searchAllMatch = message.match(/^(?:search\s+all|cross-context\s+search)[:\s]+(.+)/i);
1529
+ let stripped = message.replace(/^\[.+?\s+in\s+group\s+chat\]:\s*/, "");
1530
+ stripped = stripped.replace(/^\[.+?\]:\s*/, "");
1531
+ const cmdText = stripped;
1532
+ if (/^\/status\b/i.test(cmdText)) {
1533
+ const memoryOk = await this.memory.healthCheck();
1534
+ const contexts = this.contextManager.listContexts();
1535
+ let contextStats = "";
1536
+ try {
1537
+ const daemonContexts = await this.memory.listContexts();
1538
+ contextStats = daemonContexts.map((c) => ` - ${c.name}: ${c.episode_count} episodes`).join("\n");
1539
+ } catch {
1540
+ contextStats = " (unable to query memory daemon)";
1541
+ }
1542
+ const response = [
1543
+ `## Agent Status`,
1544
+ ``,
1545
+ `**Name:** ${this.config.agent.name}`,
1546
+ `**Active Context:** ${activeCtx}`,
1547
+ `**Memory Daemon:** ${memoryOk ? "\u2705 connected" : "\u274C unreachable"} (${this.config.memory.daemon_url})`,
1548
+ `**Model:** ${this.config.llm.model}`,
1549
+ `**Temperature:** ${this.config.llm.temperature}`,
1550
+ `**Max Tokens:** ${this.config.llm.max_tokens}`,
1551
+ `**Memory Top-K:** ${this.config.memory.top_k}`,
1552
+ `**Messages Processed:** ${this.messageCount}`,
1553
+ `**L1 Contexts in Memory:** ${this.conversationHistories.size}`,
1554
+ ``,
1555
+ `### Contexts`,
1556
+ contextStats
1557
+ ].join("\n");
1558
+ return { content: response, model: "system", context: activeCtx };
1559
+ }
1560
+ if (/^\/memory\s+stats\b/i.test(cmdText)) {
1561
+ try {
1562
+ const contexts = await this.memory.listContexts();
1563
+ let totalEpisodes = 0;
1564
+ let totalL3 = 0;
1565
+ let lines = [];
1566
+ for (const ctx of contexts) {
1567
+ totalEpisodes += ctx.episode_count;
1568
+ let l3Count = 0;
1569
+ try {
1570
+ const l3 = await this.memory.getL3Knowledge(ctx.name);
1571
+ l3Count = l3.length;
1572
+ totalL3 += l3Count;
1573
+ } catch {
1574
+ }
1575
+ lines.push(` - **${ctx.name}**: ${ctx.episode_count} L2 episodes, ${l3Count} L3 entries`);
1576
+ }
1577
+ const response = [
1578
+ `## Memory Stats`,
1579
+ ``,
1580
+ `**Total L2 Episodes:** ${totalEpisodes}`,
1581
+ `**Total L3 Knowledge:** ${totalL3}`,
1582
+ `**Contexts:** ${contexts.length}`,
1583
+ ``,
1584
+ `### Per Context`,
1585
+ ...lines
1586
+ ].join("\n");
1587
+ return { content: response, model: "system", context: activeCtx };
1588
+ } catch (err) {
1589
+ return { content: `Memory stats failed: ${err.message}`, model: "system", context: activeCtx };
1590
+ }
1591
+ }
1592
+ const memSearchMatch = cmdText.match(/^\/memory\s+search\s+(.+)/i);
1593
+ if (memSearchMatch) {
1594
+ const query = memSearchMatch[1].trim();
1595
+ try {
1596
+ const results = await this.memory.search(query, activeCtx, this.config.memory.top_k);
1597
+ if (results.length === 0) {
1598
+ return { content: `No memories found for "${query}" in context "${activeCtx}".`, model: "system", context: activeCtx };
1599
+ }
1600
+ let response = `## Memory Search: "${query}"
1601
+
1602
+ `;
1603
+ for (const ep of results) {
1604
+ const ctxLabel = ep.context_name !== activeCtx ? ` [from: ${ep.context_name}]` : "";
1605
+ response += `- **[${ep.role}]** (score: ${ep.score.toFixed(3)})${ctxLabel} ${ep.content.slice(0, 300)}${ep.content.length > 300 ? "..." : ""}
1606
+ `;
1607
+ }
1608
+ return { content: response, model: "system", context: activeCtx };
1609
+ } catch (err) {
1610
+ return { content: `Memory search failed: ${err.message}`, model: "system", context: activeCtx };
1611
+ }
1612
+ }
1613
+ const l3Match = cmdText.match(/^\/memory\s+l3(?:\s+(\S+))?/i);
1614
+ if (l3Match) {
1615
+ const targetCtx = l3Match[1] || activeCtx;
1616
+ try {
1617
+ const entries = await this.memory.getL3Knowledge(targetCtx);
1618
+ if (entries.length === 0) {
1619
+ return { content: `No L3 knowledge in context "${targetCtx}".`, model: "system", context: activeCtx };
1620
+ }
1621
+ let response = `## L3 Knowledge: ${targetCtx}
1622
+
1623
+ `;
1624
+ for (const entry of entries) {
1625
+ response += `- **[${entry.id.slice(0, 8)}]** (density: ${entry.connection_density}, accesses: ${entry.access_count})
1626
+ ${entry.content}
1627
+ `;
1628
+ }
1629
+ return { content: response, model: "system", context: activeCtx };
1630
+ } catch (err) {
1631
+ return { content: `L3 query failed: ${err.message}`, model: "system", context: activeCtx };
1632
+ }
1633
+ }
1634
+ if (/^\/config\b/i.test(cmdText)) {
1635
+ const response = [
1636
+ `## Configuration`,
1637
+ ``,
1638
+ `**Agent:** ${this.config.agent.name}`,
1639
+ `**Personality:** ${this.config.agent.personality}`,
1640
+ `**Workspace:** ${this.config.agent.workspace || "(none)"}`,
1641
+ ``,
1642
+ `### LLM`,
1643
+ `- Model: ${this.config.llm.model}`,
1644
+ `- Base URL: ${this.config.llm.base_url}`,
1645
+ `- Max Tokens: ${this.config.llm.max_tokens}`,
1646
+ `- Temperature: ${this.config.llm.temperature}`,
1647
+ ``,
1648
+ `### Memory`,
1649
+ `- Daemon URL: ${this.config.memory.daemon_url}`,
1650
+ `- Top-K: ${this.config.memory.top_k}`,
1651
+ `- Embedding Model: ${this.config.memory.embedding_model}`,
1652
+ ``,
1653
+ `### Sesame`,
1654
+ `- API: ${this.config.sesame.api_url}`,
1655
+ `- WebSocket: ${this.config.sesame.ws_url}`,
1656
+ `- API Key: ${this.config.sesame.api_key ? "***" + this.config.sesame.api_key.slice(-4) : "(not set)"}`
1657
+ ].join("\n");
1658
+ return { content: response, model: "system", context: activeCtx };
1659
+ }
1660
+ if (/^\/contexts\b/i.test(cmdText)) {
1661
+ const localContexts = this.contextManager.listContexts();
1662
+ let daemonInfo = "";
1663
+ try {
1664
+ const daemonContexts = await this.memory.listContexts();
1665
+ daemonInfo = "\n### Memory Daemon Contexts\n" + daemonContexts.map(
1666
+ (c) => ` - **${c.name}**: ${c.episode_count} episodes (created: ${c.created_at})`
1667
+ ).join("\n");
1668
+ } catch {
1669
+ daemonInfo = "\n(Memory daemon unreachable)";
1670
+ }
1671
+ const localInfo = localContexts.map((c) => {
1672
+ const active = c.name === activeCtx ? " \u2190 active" : "";
1673
+ const historyLen = this.conversationHistories.get(c.name)?.length || 0;
1674
+ return ` - **${c.name}**${active}: ${historyLen / 2} turns in L1`;
1675
+ }).join("\n");
1676
+ const response = [
1677
+ `## Contexts`,
1678
+ ``,
1679
+ `**Active:** ${activeCtx}`,
1680
+ ``,
1681
+ `### Local (L1 Working Memory)`,
1682
+ localInfo,
1683
+ daemonInfo
1684
+ ].join("\n");
1685
+ return { content: response, model: "system", context: activeCtx };
1686
+ }
1687
+ if (/^\/help\b/i.test(cmdText)) {
1688
+ const response = [
1689
+ `## Available Commands`,
1690
+ ``,
1691
+ `### Introspection`,
1692
+ `- \`/status\` \u2014 Agent health, memory status, config summary`,
1693
+ `- \`/config\` \u2014 Full configuration details`,
1694
+ `- \`/contexts\` \u2014 List all contexts with L1/L2 info`,
1695
+ `- \`/memory stats\` \u2014 Episode counts, L3 entries per context`,
1696
+ `- \`/memory search <query>\` \u2014 Search L2 memories with scores`,
1697
+ `- \`/memory l3 [context]\` \u2014 Show L3 knowledge entries`,
1698
+ ``,
1699
+ `### Context Management`,
1700
+ `- \`switch to <name>\` \u2014 Switch active context`,
1701
+ `- \`create context <name>\` \u2014 Create a new context`,
1702
+ `- \`list contexts\` \u2014 List contexts (legacy)`,
1703
+ ``,
1704
+ `### Memory`,
1705
+ `- \`search all: <query>\` \u2014 Cross-context search`,
1706
+ `- \`share <episode_id> with <context>\` \u2014 Share episode across contexts`,
1707
+ ``,
1708
+ `### Tasks`,
1709
+ `- \`task add <title>\` \u2014 Create a task`,
1710
+ `- \`task list [status]\` \u2014 List tasks`,
1711
+ `- \`task start <id>\` \u2014 Start a task`,
1712
+ `- \`task complete <id>\` \u2014 Complete a task`,
1713
+ `- \`task next\` \u2014 Pick up next available task`
1714
+ ].join("\n");
1715
+ return { content: response, model: "system", context: activeCtx };
1716
+ }
1717
+ const searchAllMatch = cmdText.match(/^(?:search\s+all|cross-context\s+search)[:\s]+(.+)/i);
686
1718
  if (searchAllMatch) {
687
1719
  const query = searchAllMatch[1].trim();
688
1720
  try {
@@ -706,7 +1738,7 @@ var Agent = class {
706
1738
  return { content: `Cross-context search failed: ${err.message}`, model: "system", context: activeCtx };
707
1739
  }
708
1740
  }
709
- const shareMatch = message.match(/^share\s+(\S+)\s+with\s+(\S+)/i);
1741
+ const shareMatch = cmdText.match(/^share\s+(\S+)\s+with\s+(\S+)/i);
710
1742
  if (shareMatch) {
711
1743
  const episodeId = shareMatch[1];
712
1744
  const targetContext = shareMatch[2];
@@ -717,7 +1749,7 @@ var Agent = class {
717
1749
  return { content: `Failed to share: ${err.message}`, model: "system", context: activeCtx };
718
1750
  }
719
1751
  }
720
- const taskCmd = TaskEngine.parseTaskCommand(message);
1752
+ const taskCmd = TaskEngine.parseTaskCommand(cmdText);
721
1753
  if (taskCmd) {
722
1754
  const engine = new TaskEngine({ contextName: activeCtx, memory: this.memory });
723
1755
  try {
@@ -1574,8 +2606,8 @@ import { resolve as resolve3, dirname as dirname2 } from "path";
1574
2606
  import { fileURLToPath } from "url";
1575
2607
  var RUNTIME_VERSION = "unknown";
1576
2608
  try {
1577
- const __dirname = dirname2(fileURLToPath(import.meta.url));
1578
- const pkg = JSON.parse(readFileSync3(resolve3(__dirname, "../package.json"), "utf-8"));
2609
+ const __dirname2 = dirname2(fileURLToPath(import.meta.url));
2610
+ const pkg = JSON.parse(readFileSync3(resolve3(__dirname2, "../package.json"), "utf-8"));
1579
2611
  RUNTIME_VERSION = pkg.version ?? "unknown";
1580
2612
  } catch {
1581
2613
  }
@@ -1737,20 +2769,285 @@ var SesameClient2 = class {
1737
2769
  };
1738
2770
 
1739
2771
  // packages/runtime/src/pipeline.ts
1740
- import { createServer } from "http";
2772
+ import { createServer as createServer2 } from "http";
1741
2773
 
1742
2774
  // packages/runtime/src/health.ts
1743
2775
  var HEALTH_PORT = 9484;
1744
2776
  var HEALTH_PATH = "/health";
1745
2777
 
1746
- // packages/runtime/src/pipeline.ts
1747
- import { readFileSync as readFileSync4, writeFileSync, unlinkSync } from "fs";
1748
- import { resolve as resolve4, dirname as dirname3 } from "path";
2778
+ // packages/runtime/src/request-logger.ts
2779
+ var import_better_sqlite3 = __toESM(require_lib(), 1);
2780
+ import { randomUUID } from "crypto";
2781
+ import { mkdirSync, existsSync as existsSync3 } from "fs";
2782
+ import { dirname as dirname3 } from "path";
2783
+ var RequestLogger = class {
2784
+ db;
2785
+ constructor(dbPath) {
2786
+ const dir = dirname3(dbPath);
2787
+ if (!existsSync3(dir)) mkdirSync(dir, { recursive: true });
2788
+ this.db = new import_better_sqlite3.default(dbPath);
2789
+ this.db.pragma("journal_mode = WAL");
2790
+ this.db.pragma("synchronous = NORMAL");
2791
+ this.init();
2792
+ this.prune();
2793
+ }
2794
+ init() {
2795
+ this.db.exec(`
2796
+ CREATE TABLE IF NOT EXISTS request_logs (
2797
+ id TEXT PRIMARY KEY,
2798
+ timestamp TEXT NOT NULL,
2799
+ context TEXT NOT NULL,
2800
+ context_switched INTEGER NOT NULL DEFAULT 0,
2801
+ routing_reason TEXT NOT NULL DEFAULT '',
2802
+ channel_id TEXT NOT NULL DEFAULT '',
2803
+ channel_kind TEXT NOT NULL DEFAULT '',
2804
+ sender_handle TEXT NOT NULL DEFAULT '',
2805
+ raw_message TEXT NOT NULL,
2806
+ system_prompt_components TEXT NOT NULL,
2807
+ conversation_history TEXT NOT NULL,
2808
+ user_message TEXT NOT NULL,
2809
+ response_content TEXT NOT NULL,
2810
+ response_model TEXT NOT NULL,
2811
+ response_latency_ms INTEGER NOT NULL,
2812
+ response_skipped INTEGER NOT NULL DEFAULT 0,
2813
+ config_snapshot TEXT NOT NULL,
2814
+ token_est_system INTEGER NOT NULL DEFAULT 0,
2815
+ token_est_history INTEGER NOT NULL DEFAULT 0,
2816
+ token_est_user INTEGER NOT NULL DEFAULT 0,
2817
+ token_est_total INTEGER NOT NULL DEFAULT 0
2818
+ )
2819
+ `);
2820
+ this.db.exec(`
2821
+ CREATE INDEX IF NOT EXISTS idx_request_logs_timestamp ON request_logs(timestamp DESC);
2822
+ CREATE INDEX IF NOT EXISTS idx_request_logs_context ON request_logs(context);
2823
+ CREATE INDEX IF NOT EXISTS idx_request_logs_sender ON request_logs(sender_handle);
2824
+ `);
2825
+ }
2826
+ prune() {
2827
+ const cutoff = new Date(Date.now() - 7 * 24 * 60 * 60 * 1e3).toISOString();
2828
+ const result = this.db.prepare("DELETE FROM request_logs WHERE timestamp < ?").run(cutoff);
2829
+ if (result.changes > 0) {
2830
+ console.log(`[dashboard] Pruned ${result.changes} old request logs`);
2831
+ }
2832
+ }
2833
+ log(entry) {
2834
+ const id = randomUUID();
2835
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
2836
+ const sysTokens = Math.ceil(entry.systemPromptComponents.fullText.length / 4);
2837
+ const histTokens = Math.ceil(
2838
+ entry.conversationHistory.reduce((sum, m) => sum + m.content.length, 0) / 4
2839
+ );
2840
+ const userTokens = Math.ceil(entry.userMessage.length / 4);
2841
+ this.db.prepare(
2842
+ `INSERT INTO request_logs (
2843
+ id, timestamp, context, context_switched, routing_reason,
2844
+ channel_id, channel_kind, sender_handle, raw_message,
2845
+ system_prompt_components, conversation_history, user_message,
2846
+ response_content, response_model, response_latency_ms, response_skipped,
2847
+ config_snapshot,
2848
+ token_est_system, token_est_history, token_est_user, token_est_total
2849
+ ) VALUES (
2850
+ ?, ?, ?, ?, ?,
2851
+ ?, ?, ?, ?,
2852
+ ?, ?, ?,
2853
+ ?, ?, ?, ?,
2854
+ ?,
2855
+ ?, ?, ?, ?
2856
+ )`
2857
+ ).run(
2858
+ id,
2859
+ timestamp,
2860
+ entry.context,
2861
+ entry.contextSwitched ? 1 : 0,
2862
+ entry.routingReason,
2863
+ entry.channelId ?? "",
2864
+ entry.channelKind ?? "",
2865
+ entry.senderHandle ?? "",
2866
+ entry.rawMessage,
2867
+ JSON.stringify(entry.systemPromptComponents),
2868
+ JSON.stringify(entry.conversationHistory),
2869
+ entry.userMessage,
2870
+ entry.response.content,
2871
+ entry.response.model,
2872
+ entry.response.latencyMs,
2873
+ entry.response.skipped ? 1 : 0,
2874
+ JSON.stringify(entry.config),
2875
+ sysTokens,
2876
+ histTokens,
2877
+ userTokens,
2878
+ sysTokens + histTokens + userTokens
2879
+ );
2880
+ return id;
2881
+ }
2882
+ getRequests(opts = {}) {
2883
+ const limit = opts.limit ?? 50;
2884
+ const offset = opts.offset ?? 0;
2885
+ const conditions = [];
2886
+ const params = [];
2887
+ if (opts.context) {
2888
+ conditions.push("context = ?");
2889
+ params.push(opts.context);
2890
+ }
2891
+ if (opts.sender) {
2892
+ conditions.push("sender_handle = ?");
2893
+ params.push(opts.sender);
2894
+ }
2895
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2896
+ const total = this.db.prepare(`SELECT COUNT(*) as count FROM request_logs ${where}`).get(...params).count;
2897
+ const requests = this.db.prepare(
2898
+ `SELECT * FROM request_logs ${where} ORDER BY timestamp DESC LIMIT ? OFFSET ?`
2899
+ ).all(...params, limit, offset);
2900
+ return { requests, total };
2901
+ }
2902
+ getRequest(id) {
2903
+ return this.db.prepare("SELECT * FROM request_logs WHERE id = ?").get(id);
2904
+ }
2905
+ close() {
2906
+ this.db.close();
2907
+ }
2908
+ };
2909
+
2910
+ // packages/runtime/src/dashboard.ts
2911
+ import { createServer } from "http";
2912
+ import { readFileSync as readFileSync4 } from "fs";
2913
+ import { resolve as resolve4, dirname as dirname4 } from "path";
1749
2914
  import { fileURLToPath as fileURLToPath2 } from "url";
2915
+ var __dirname = dirname4(fileURLToPath2(import.meta.url));
2916
+ var DASHBOARD_PORT = 9485;
2917
+ var spaHtml = null;
2918
+ function getSpaHtml() {
2919
+ if (!spaHtml) {
2920
+ for (const dir of [__dirname, resolve4(__dirname, "../src")]) {
2921
+ try {
2922
+ spaHtml = readFileSync4(resolve4(dir, "dashboard.html"), "utf-8");
2923
+ break;
2924
+ } catch {
2925
+ }
2926
+ }
2927
+ if (!spaHtml) spaHtml = "<h1>Dashboard HTML not found</h1>";
2928
+ }
2929
+ return spaHtml;
2930
+ }
2931
+ function json(res, data, status = 200) {
2932
+ res.writeHead(status, {
2933
+ "Content-Type": "application/json",
2934
+ "Access-Control-Allow-Origin": "*"
2935
+ });
2936
+ res.end(JSON.stringify(data));
2937
+ }
2938
+ function parseQuery(url) {
2939
+ const idx = url.indexOf("?");
2940
+ if (idx === -1) return {};
2941
+ const params = {};
2942
+ for (const pair of url.slice(idx + 1).split("&")) {
2943
+ const [k, v] = pair.split("=");
2944
+ if (k) params[decodeURIComponent(k)] = decodeURIComponent(v ?? "");
2945
+ }
2946
+ return params;
2947
+ }
2948
+ async function proxyMemory(memoryUrl, path, method, res) {
2949
+ try {
2950
+ const resp = await fetch(`${memoryUrl}${path}`, { method });
2951
+ const body = await resp.text();
2952
+ res.writeHead(resp.status, {
2953
+ "Content-Type": resp.headers.get("content-type") ?? "application/json",
2954
+ "Access-Control-Allow-Origin": "*"
2955
+ });
2956
+ res.end(body);
2957
+ } catch (err) {
2958
+ json(res, { error: err.message }, 502);
2959
+ }
2960
+ }
2961
+ function startDashboardServer(requestLogger, memoryConfig) {
2962
+ const memoryUrl = memoryConfig.daemon_url;
2963
+ const server = createServer(async (req, res) => {
2964
+ const method = req.method ?? "GET";
2965
+ const rawUrl = req.url ?? "/";
2966
+ const urlPath = rawUrl.split("?")[0];
2967
+ if (method === "OPTIONS") {
2968
+ res.writeHead(204, {
2969
+ "Access-Control-Allow-Origin": "*",
2970
+ "Access-Control-Allow-Methods": "GET, DELETE, OPTIONS",
2971
+ "Access-Control-Allow-Headers": "Content-Type"
2972
+ });
2973
+ res.end();
2974
+ return;
2975
+ }
2976
+ try {
2977
+ if (method === "GET" && urlPath === "/") {
2978
+ res.writeHead(200, { "Content-Type": "text/html" });
2979
+ res.end(getSpaHtml());
2980
+ return;
2981
+ }
2982
+ if (method === "GET" && urlPath === "/api/requests") {
2983
+ const q = parseQuery(rawUrl);
2984
+ const result = requestLogger.getRequests({
2985
+ limit: q.limit ? parseInt(q.limit, 10) : void 0,
2986
+ offset: q.offset ? parseInt(q.offset, 10) : void 0,
2987
+ context: q.context || void 0,
2988
+ sender: q.sender || void 0
2989
+ });
2990
+ json(res, result);
2991
+ return;
2992
+ }
2993
+ const reqDetailMatch = urlPath.match(/^\/api\/requests\/([^/]+)$/);
2994
+ if (method === "GET" && reqDetailMatch) {
2995
+ const entry = requestLogger.getRequest(reqDetailMatch[1]);
2996
+ if (!entry) {
2997
+ json(res, { error: "Not found" }, 404);
2998
+ } else {
2999
+ json(res, entry);
3000
+ }
3001
+ return;
3002
+ }
3003
+ if (method === "GET" && urlPath === "/api/contexts") {
3004
+ await proxyMemory(memoryUrl, "/contexts", "GET", res);
3005
+ return;
3006
+ }
3007
+ const episodesMatch = urlPath.match(/^\/api\/contexts\/([^/]+)\/episodes$/);
3008
+ if (method === "GET" && episodesMatch) {
3009
+ const name = decodeURIComponent(episodesMatch[1]);
3010
+ await proxyMemory(memoryUrl, `/contexts/${encodeURIComponent(name)}`, "GET", res);
3011
+ return;
3012
+ }
3013
+ const l3Match = urlPath.match(/^\/api\/contexts\/([^/]+)\/l3$/);
3014
+ if (method === "GET" && l3Match) {
3015
+ const name = decodeURIComponent(l3Match[1]);
3016
+ await proxyMemory(
3017
+ memoryUrl,
3018
+ `/promotion/l3?context=${encodeURIComponent(name)}`,
3019
+ "GET",
3020
+ res
3021
+ );
3022
+ return;
3023
+ }
3024
+ const l3DeleteMatch = urlPath.match(/^\/api\/l3\/([^/]+)$/);
3025
+ if (method === "DELETE" && l3DeleteMatch) {
3026
+ const id = decodeURIComponent(l3DeleteMatch[1]);
3027
+ await proxyMemory(memoryUrl, `/promotion/l3/${encodeURIComponent(id)}`, "DELETE", res);
3028
+ return;
3029
+ }
3030
+ json(res, { error: "Not found" }, 404);
3031
+ } catch (err) {
3032
+ console.error("[dashboard] Request error:", err.message);
3033
+ json(res, { error: "Internal server error" }, 500);
3034
+ }
3035
+ });
3036
+ server.listen(DASHBOARD_PORT, "127.0.0.1", () => {
3037
+ console.log(
3038
+ `[hivemind] Dashboard listening on http://127.0.0.1:${DASHBOARD_PORT}`
3039
+ );
3040
+ });
3041
+ }
3042
+
3043
+ // packages/runtime/src/pipeline.ts
3044
+ import { readFileSync as readFileSync5, writeFileSync, unlinkSync } from "fs";
3045
+ import { resolve as resolve5, dirname as dirname5 } from "path";
3046
+ import { fileURLToPath as fileURLToPath3 } from "url";
1750
3047
  var PACKAGE_VERSION = "unknown";
1751
3048
  try {
1752
- const __dirname = dirname3(fileURLToPath2(import.meta.url));
1753
- const pkg = JSON.parse(readFileSync4(resolve4(__dirname, "../package.json"), "utf-8"));
3049
+ const __dirname2 = dirname5(fileURLToPath3(import.meta.url));
3050
+ const pkg = JSON.parse(readFileSync5(resolve5(__dirname2, "../package.json"), "utf-8"));
1754
3051
  PACKAGE_VERSION = pkg.version ?? "unknown";
1755
3052
  } catch {
1756
3053
  }
@@ -1758,7 +3055,7 @@ var sesameConnected = false;
1758
3055
  var memoryConnected = false;
1759
3056
  var startTime = Date.now();
1760
3057
  function startHealthServer(port) {
1761
- const server = createServer((req, res) => {
3058
+ const server = createServer2((req, res) => {
1762
3059
  if (req.method === "GET" && req.url === HEALTH_PATH) {
1763
3060
  const status = {
1764
3061
  status: sesameConnected ? "ok" : "degraded",
@@ -1812,7 +3109,10 @@ async function startPipeline(configPath) {
1812
3109
  memoryConnected = true;
1813
3110
  console.log("[hivemind] Memory daemon connected");
1814
3111
  }
3112
+ const requestLogger = new RequestLogger(resolve5(dirname5(configPath), "data", "dashboard.db"));
3113
+ startDashboardServer(requestLogger, config.memory);
1815
3114
  const agent = new Agent(config);
3115
+ agent.setRequestLogger(requestLogger);
1816
3116
  console.log(`[hivemind] Context manager initialized (active: ${agent.getActiveContext()})`);
1817
3117
  if (config.sesame.api_key) {
1818
3118
  await startSesameLoop(config, agent);
@@ -1927,13 +3227,13 @@ ${response.content}
1927
3227
  console.error("Error:", err.message);
1928
3228
  }
1929
3229
  });
1930
- return new Promise((resolve5) => {
1931
- rl.on("close", resolve5);
3230
+ return new Promise((resolve6) => {
3231
+ rl.on("close", resolve6);
1932
3232
  });
1933
3233
  }
1934
3234
 
1935
3235
  // packages/runtime/src/fleet/worker-server.ts
1936
- import { createServer as createServer2 } from "http";
3236
+ import { createServer as createServer3 } from "http";
1937
3237
  var WorkerServer = class {
1938
3238
  server = null;
1939
3239
  workerId;
@@ -1957,20 +3257,20 @@ var WorkerServer = class {
1957
3257
  }
1958
3258
  /** Start listening. */
1959
3259
  async start() {
1960
- return new Promise((resolve5, reject) => {
1961
- this.server = createServer2((req, res) => this.handleRequest(req, res));
3260
+ return new Promise((resolve6, reject) => {
3261
+ this.server = createServer3((req, res) => this.handleRequest(req, res));
1962
3262
  this.server.on("error", reject);
1963
- this.server.listen(this.port, () => resolve5());
3263
+ this.server.listen(this.port, () => resolve6());
1964
3264
  });
1965
3265
  }
1966
3266
  /** Stop the server. */
1967
3267
  async stop() {
1968
- return new Promise((resolve5) => {
3268
+ return new Promise((resolve6) => {
1969
3269
  if (!this.server) {
1970
- resolve5();
3270
+ resolve6();
1971
3271
  return;
1972
3272
  }
1973
- this.server.close(() => resolve5());
3273
+ this.server.close(() => resolve6());
1974
3274
  });
1975
3275
  }
1976
3276
  getPort() {
@@ -2093,10 +3393,10 @@ var WorkerServer = class {
2093
3393
  }
2094
3394
  };
2095
3395
  function readBody(req) {
2096
- return new Promise((resolve5, reject) => {
3396
+ return new Promise((resolve6, reject) => {
2097
3397
  const chunks = [];
2098
3398
  req.on("data", (chunk) => chunks.push(chunk));
2099
- req.on("end", () => resolve5(Buffer.concat(chunks).toString("utf-8")));
3399
+ req.on("end", () => resolve6(Buffer.concat(chunks).toString("utf-8")));
2100
3400
  req.on("error", reject);
2101
3401
  });
2102
3402
  }
@@ -2423,4 +3723,4 @@ smol-toml/dist/index.js:
2423
3723
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2424
3724
  *)
2425
3725
  */
2426
- //# sourceMappingURL=chunk-LB6MG36X.js.map
3726
+ //# sourceMappingURL=chunk-MKE2NVOC.js.map