@askexenow/exe-os 0.9.7 → 0.9.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/backfill-conversations.js +754 -79
- package/dist/bin/backfill-responses.js +752 -77
- package/dist/bin/backfill-vectors.js +752 -77
- package/dist/bin/cleanup-stale-review-tasks.js +657 -35
- package/dist/bin/cli.js +1388 -605
- package/dist/bin/exe-agent-config.js +123 -95
- package/dist/bin/exe-agent.js +41 -25
- package/dist/bin/exe-assign.js +732 -57
- package/dist/bin/exe-boot.js +784 -153
- package/dist/bin/exe-call.js +209 -138
- package/dist/bin/exe-cloud.js +35 -12
- package/dist/bin/exe-dispatch.js +692 -70
- package/dist/bin/exe-doctor.js +648 -26
- package/dist/bin/exe-export-behaviors.js +650 -20
- package/dist/bin/exe-forget.js +635 -13
- package/dist/bin/exe-gateway.js +1053 -271
- package/dist/bin/exe-heartbeat.js +665 -43
- package/dist/bin/exe-kill.js +646 -16
- package/dist/bin/exe-launch-agent.js +887 -97
- package/dist/bin/exe-link.js +658 -43
- package/dist/bin/exe-new-employee.js +378 -177
- package/dist/bin/exe-pending-messages.js +656 -34
- package/dist/bin/exe-pending-notifications.js +635 -13
- package/dist/bin/exe-pending-reviews.js +659 -37
- package/dist/bin/exe-rename.js +645 -30
- package/dist/bin/exe-review.js +635 -13
- package/dist/bin/exe-search.js +771 -88
- package/dist/bin/exe-session-cleanup.js +834 -150
- package/dist/bin/exe-settings.js +127 -91
- package/dist/bin/exe-start-codex.js +729 -94
- package/dist/bin/exe-start-opencode.js +717 -82
- package/dist/bin/exe-status.js +657 -35
- package/dist/bin/exe-team.js +635 -13
- package/dist/bin/git-sweep.js +720 -89
- package/dist/bin/graph-backfill.js +643 -13
- package/dist/bin/graph-export.js +646 -16
- package/dist/bin/install.js +596 -193
- package/dist/bin/scan-tasks.js +724 -93
- package/dist/bin/setup.js +1038 -210
- package/dist/bin/shard-migrate.js +645 -15
- package/dist/bin/wiki-sync.js +646 -16
- package/dist/gateway/index.js +1027 -245
- package/dist/hooks/bug-report-worker.js +891 -170
- package/dist/hooks/commit-complete.js +718 -87
- package/dist/hooks/error-recall.js +776 -93
- package/dist/hooks/exe-heartbeat-hook.js +85 -71
- package/dist/hooks/ingest-worker.js +840 -156
- package/dist/hooks/ingest.js +90 -73
- package/dist/hooks/instructions-loaded.js +669 -38
- package/dist/hooks/notification.js +661 -30
- package/dist/hooks/post-compact.js +674 -43
- package/dist/hooks/pre-compact.js +718 -87
- package/dist/hooks/pre-tool-use.js +872 -125
- package/dist/hooks/prompt-ingest-worker.js +758 -83
- package/dist/hooks/prompt-submit.js +1060 -319
- package/dist/hooks/response-ingest-worker.js +758 -83
- package/dist/hooks/session-end.js +721 -90
- package/dist/hooks/session-start.js +1031 -207
- package/dist/hooks/stop.js +680 -49
- package/dist/hooks/subagent-stop.js +674 -43
- package/dist/hooks/summary-worker.js +816 -132
- package/dist/index.js +1015 -232
- package/dist/lib/cloud-sync.js +663 -48
- package/dist/lib/consolidation.js +26 -3
- package/dist/lib/database.js +626 -18
- package/dist/lib/db.js +2261 -0
- package/dist/lib/device-registry.js +640 -25
- package/dist/lib/embedder.js +96 -43
- package/dist/lib/employee-templates.js +16 -0
- package/dist/lib/employees.js +259 -83
- package/dist/lib/exe-daemon-client.js +101 -63
- package/dist/lib/exe-daemon.js +894 -162
- package/dist/lib/hybrid-search.js +771 -88
- package/dist/lib/identity.js +27 -7
- package/dist/lib/messaging.js +55 -28
- package/dist/lib/reminders.js +21 -1
- package/dist/lib/schedules.js +636 -14
- package/dist/lib/skill-learning.js +21 -1
- package/dist/lib/store.js +643 -13
- package/dist/lib/task-router.js +82 -71
- package/dist/lib/tasks.js +98 -71
- package/dist/lib/tmux-routing.js +87 -60
- package/dist/lib/token-spend.js +26 -6
- package/dist/mcp/server.js +1784 -458
- package/dist/mcp/tools/complete-reminder.js +21 -1
- package/dist/mcp/tools/create-reminder.js +21 -1
- package/dist/mcp/tools/create-task.js +290 -164
- package/dist/mcp/tools/deactivate-behavior.js +24 -4
- package/dist/mcp/tools/list-reminders.js +21 -1
- package/dist/mcp/tools/list-tasks.js +195 -38
- package/dist/mcp/tools/send-message.js +58 -31
- package/dist/mcp/tools/update-task.js +75 -48
- package/dist/runtime/index.js +720 -89
- package/dist/tui/App.js +853 -123
- package/package.json +3 -2
|
@@ -344,7 +344,7 @@ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
|
|
|
344
344
|
return [];
|
|
345
345
|
}
|
|
346
346
|
}
|
|
347
|
-
var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
|
|
347
|
+
var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
|
|
348
348
|
var init_employees = __esm({
|
|
349
349
|
"src/lib/employees.ts"() {
|
|
350
350
|
"use strict";
|
|
@@ -352,12 +352,609 @@ var init_employees = __esm({
|
|
|
352
352
|
EMPLOYEES_PATH = path3.join(EXE_AI_DIR, "exe-employees.json");
|
|
353
353
|
DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
|
|
354
354
|
COORDINATOR_ROLE = "COO";
|
|
355
|
+
IDENTITY_DIR = path3.join(EXE_AI_DIR, "identity");
|
|
356
|
+
}
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
// src/lib/database-adapter.ts
|
|
360
|
+
import os3 from "os";
|
|
361
|
+
import path4 from "path";
|
|
362
|
+
import { createRequire } from "module";
|
|
363
|
+
import { pathToFileURL } from "url";
|
|
364
|
+
function quotedIdentifier(identifier) {
|
|
365
|
+
return `"${identifier.replace(/"/g, '""')}"`;
|
|
366
|
+
}
|
|
367
|
+
function unqualifiedTableName(name) {
|
|
368
|
+
const raw = name.trim().replace(/^"|"$/g, "");
|
|
369
|
+
const parts = raw.split(".");
|
|
370
|
+
return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
|
|
371
|
+
}
|
|
372
|
+
function stripTrailingSemicolon(sql) {
|
|
373
|
+
return sql.trim().replace(/;+\s*$/u, "");
|
|
374
|
+
}
|
|
375
|
+
function appendClause(sql, clause) {
|
|
376
|
+
const trimmed = stripTrailingSemicolon(sql);
|
|
377
|
+
const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
|
|
378
|
+
if (!returningMatch) {
|
|
379
|
+
return `${trimmed}${clause}`;
|
|
380
|
+
}
|
|
381
|
+
const idx = returningMatch.index;
|
|
382
|
+
return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
|
|
383
|
+
}
|
|
384
|
+
function normalizeStatement(stmt) {
|
|
385
|
+
if (typeof stmt === "string") {
|
|
386
|
+
return { kind: "positional", sql: stmt, args: [] };
|
|
387
|
+
}
|
|
388
|
+
const sql = stmt.sql;
|
|
389
|
+
if (Array.isArray(stmt.args) || stmt.args === void 0) {
|
|
390
|
+
return { kind: "positional", sql, args: stmt.args ?? [] };
|
|
391
|
+
}
|
|
392
|
+
return { kind: "named", sql, args: stmt.args };
|
|
393
|
+
}
|
|
394
|
+
function rewriteBooleanLiterals(sql) {
|
|
395
|
+
let out = sql;
|
|
396
|
+
for (const column of BOOLEAN_COLUMN_NAMES) {
|
|
397
|
+
const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
|
|
398
|
+
out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
|
|
399
|
+
out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
|
|
400
|
+
out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
|
|
401
|
+
out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
|
|
402
|
+
out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
|
|
403
|
+
out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
|
|
404
|
+
}
|
|
405
|
+
return out;
|
|
406
|
+
}
|
|
407
|
+
function rewriteInsertOrIgnore(sql) {
|
|
408
|
+
if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
|
|
409
|
+
return sql;
|
|
410
|
+
}
|
|
411
|
+
const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
|
|
412
|
+
return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
|
|
413
|
+
}
|
|
414
|
+
function rewriteInsertOrReplace(sql) {
|
|
415
|
+
const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
|
|
416
|
+
if (!match) {
|
|
417
|
+
return sql;
|
|
418
|
+
}
|
|
419
|
+
const rawTable = match[1];
|
|
420
|
+
const rawColumns = match[2];
|
|
421
|
+
const remainder = match[3];
|
|
422
|
+
const tableName = unqualifiedTableName(rawTable);
|
|
423
|
+
const conflictKeys = UPSERT_KEYS[tableName];
|
|
424
|
+
if (!conflictKeys?.length) {
|
|
425
|
+
return sql;
|
|
426
|
+
}
|
|
427
|
+
const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
|
|
428
|
+
const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
|
|
429
|
+
const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
|
|
430
|
+
const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
|
|
431
|
+
return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
|
|
432
|
+
}
|
|
433
|
+
function rewriteSql(sql) {
|
|
434
|
+
let out = sql;
|
|
435
|
+
out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
|
|
436
|
+
out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
|
|
437
|
+
out = rewriteBooleanLiterals(out);
|
|
438
|
+
out = rewriteInsertOrReplace(out);
|
|
439
|
+
out = rewriteInsertOrIgnore(out);
|
|
440
|
+
return stripTrailingSemicolon(out);
|
|
441
|
+
}
|
|
442
|
+
function toBoolean(value) {
|
|
443
|
+
if (value === null || value === void 0) return value;
|
|
444
|
+
if (typeof value === "boolean") return value;
|
|
445
|
+
if (typeof value === "number") return value !== 0;
|
|
446
|
+
if (typeof value === "bigint") return value !== 0n;
|
|
447
|
+
if (typeof value === "string") {
|
|
448
|
+
const normalized = value.trim().toLowerCase();
|
|
449
|
+
if (normalized === "0" || normalized === "false") return false;
|
|
450
|
+
if (normalized === "1" || normalized === "true") return true;
|
|
451
|
+
}
|
|
452
|
+
return Boolean(value);
|
|
453
|
+
}
|
|
454
|
+
function countQuestionMarks(sql, end) {
|
|
455
|
+
let count = 0;
|
|
456
|
+
let inSingle = false;
|
|
457
|
+
let inDouble = false;
|
|
458
|
+
let inLineComment = false;
|
|
459
|
+
let inBlockComment = false;
|
|
460
|
+
for (let i = 0; i < end; i++) {
|
|
461
|
+
const ch = sql[i];
|
|
462
|
+
const next = sql[i + 1];
|
|
463
|
+
if (inLineComment) {
|
|
464
|
+
if (ch === "\n") inLineComment = false;
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
467
|
+
if (inBlockComment) {
|
|
468
|
+
if (ch === "*" && next === "/") {
|
|
469
|
+
inBlockComment = false;
|
|
470
|
+
i += 1;
|
|
471
|
+
}
|
|
472
|
+
continue;
|
|
473
|
+
}
|
|
474
|
+
if (!inSingle && !inDouble && ch === "-" && next === "-") {
|
|
475
|
+
inLineComment = true;
|
|
476
|
+
i += 1;
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
if (!inSingle && !inDouble && ch === "/" && next === "*") {
|
|
480
|
+
inBlockComment = true;
|
|
481
|
+
i += 1;
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
484
|
+
if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
|
|
485
|
+
inSingle = !inSingle;
|
|
486
|
+
continue;
|
|
487
|
+
}
|
|
488
|
+
if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
|
|
489
|
+
inDouble = !inDouble;
|
|
490
|
+
continue;
|
|
491
|
+
}
|
|
492
|
+
if (!inSingle && !inDouble && ch === "?") {
|
|
493
|
+
count += 1;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
return count;
|
|
497
|
+
}
|
|
498
|
+
function findBooleanPlaceholderIndexes(sql) {
|
|
499
|
+
const indexes = /* @__PURE__ */ new Set();
|
|
500
|
+
for (const column of BOOLEAN_COLUMN_NAMES) {
|
|
501
|
+
const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
|
|
502
|
+
for (const match of sql.matchAll(pattern)) {
|
|
503
|
+
const matchText = match[0];
|
|
504
|
+
const qIndex = match.index + matchText.lastIndexOf("?");
|
|
505
|
+
indexes.add(countQuestionMarks(sql, qIndex + 1));
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
return indexes;
|
|
509
|
+
}
|
|
510
|
+
function coerceInsertBooleanArgs(sql, args) {
|
|
511
|
+
const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
|
|
512
|
+
if (!match) return;
|
|
513
|
+
const rawTable = match[1];
|
|
514
|
+
const rawColumns = match[2];
|
|
515
|
+
const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
|
|
516
|
+
if (!boolColumns?.size) return;
|
|
517
|
+
const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
|
|
518
|
+
for (const [index, column] of columns.entries()) {
|
|
519
|
+
if (boolColumns.has(column) && index < args.length) {
|
|
520
|
+
args[index] = toBoolean(args[index]);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
function coerceUpdateBooleanArgs(sql, args) {
|
|
525
|
+
const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
|
|
526
|
+
if (!match) return;
|
|
527
|
+
const rawTable = match[1];
|
|
528
|
+
const setClause = match[2];
|
|
529
|
+
const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
|
|
530
|
+
if (!boolColumns?.size) return;
|
|
531
|
+
const assignments = setClause.split(",");
|
|
532
|
+
let placeholderIndex = 0;
|
|
533
|
+
for (const assignment of assignments) {
|
|
534
|
+
if (!assignment.includes("?")) continue;
|
|
535
|
+
placeholderIndex += 1;
|
|
536
|
+
const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
|
|
537
|
+
if (colMatch && boolColumns.has(colMatch[1])) {
|
|
538
|
+
args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
function coerceBooleanArgs(sql, args) {
|
|
543
|
+
const nextArgs = [...args];
|
|
544
|
+
coerceInsertBooleanArgs(sql, nextArgs);
|
|
545
|
+
coerceUpdateBooleanArgs(sql, nextArgs);
|
|
546
|
+
const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
|
|
547
|
+
for (const index of placeholderIndexes) {
|
|
548
|
+
if (index > 0 && index <= nextArgs.length) {
|
|
549
|
+
nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
return nextArgs;
|
|
553
|
+
}
|
|
554
|
+
function convertQuestionMarksToDollarParams(sql) {
|
|
555
|
+
let out = "";
|
|
556
|
+
let placeholder = 0;
|
|
557
|
+
let inSingle = false;
|
|
558
|
+
let inDouble = false;
|
|
559
|
+
let inLineComment = false;
|
|
560
|
+
let inBlockComment = false;
|
|
561
|
+
for (let i = 0; i < sql.length; i++) {
|
|
562
|
+
const ch = sql[i];
|
|
563
|
+
const next = sql[i + 1];
|
|
564
|
+
if (inLineComment) {
|
|
565
|
+
out += ch;
|
|
566
|
+
if (ch === "\n") inLineComment = false;
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
if (inBlockComment) {
|
|
570
|
+
out += ch;
|
|
571
|
+
if (ch === "*" && next === "/") {
|
|
572
|
+
out += next;
|
|
573
|
+
inBlockComment = false;
|
|
574
|
+
i += 1;
|
|
575
|
+
}
|
|
576
|
+
continue;
|
|
577
|
+
}
|
|
578
|
+
if (!inSingle && !inDouble && ch === "-" && next === "-") {
|
|
579
|
+
out += ch + next;
|
|
580
|
+
inLineComment = true;
|
|
581
|
+
i += 1;
|
|
582
|
+
continue;
|
|
583
|
+
}
|
|
584
|
+
if (!inSingle && !inDouble && ch === "/" && next === "*") {
|
|
585
|
+
out += ch + next;
|
|
586
|
+
inBlockComment = true;
|
|
587
|
+
i += 1;
|
|
588
|
+
continue;
|
|
589
|
+
}
|
|
590
|
+
if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
|
|
591
|
+
inSingle = !inSingle;
|
|
592
|
+
out += ch;
|
|
593
|
+
continue;
|
|
594
|
+
}
|
|
595
|
+
if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
|
|
596
|
+
inDouble = !inDouble;
|
|
597
|
+
out += ch;
|
|
598
|
+
continue;
|
|
599
|
+
}
|
|
600
|
+
if (!inSingle && !inDouble && ch === "?") {
|
|
601
|
+
placeholder += 1;
|
|
602
|
+
out += `$${placeholder}`;
|
|
603
|
+
continue;
|
|
604
|
+
}
|
|
605
|
+
out += ch;
|
|
606
|
+
}
|
|
607
|
+
return out;
|
|
608
|
+
}
|
|
609
|
+
function translateStatementForPostgres(stmt) {
|
|
610
|
+
const normalized = normalizeStatement(stmt);
|
|
611
|
+
if (normalized.kind === "named") {
|
|
612
|
+
throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
|
|
613
|
+
}
|
|
614
|
+
const rewrittenSql = rewriteSql(normalized.sql);
|
|
615
|
+
const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
|
|
616
|
+
return {
|
|
617
|
+
sql: convertQuestionMarksToDollarParams(rewrittenSql),
|
|
618
|
+
args: coercedArgs
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
function shouldBypassPostgres(stmt) {
|
|
622
|
+
const normalized = normalizeStatement(stmt);
|
|
623
|
+
if (normalized.kind === "named") {
|
|
624
|
+
return true;
|
|
625
|
+
}
|
|
626
|
+
return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
|
|
627
|
+
}
|
|
628
|
+
function shouldFallbackOnError(error) {
|
|
629
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
630
|
+
return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
|
|
631
|
+
}
|
|
632
|
+
function isReadQuery(sql) {
|
|
633
|
+
const trimmed = sql.trimStart();
|
|
634
|
+
return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
|
|
635
|
+
}
|
|
636
|
+
function buildRow(row, columns) {
|
|
637
|
+
const values = columns.map((column) => row[column]);
|
|
638
|
+
return Object.assign(values, row);
|
|
639
|
+
}
|
|
640
|
+
function buildResultSet(rows, rowsAffected = 0) {
|
|
641
|
+
const columns = rows[0] ? Object.keys(rows[0]) : [];
|
|
642
|
+
const resultRows = rows.map((row) => buildRow(row, columns));
|
|
643
|
+
return {
|
|
644
|
+
columns,
|
|
645
|
+
columnTypes: columns.map(() => ""),
|
|
646
|
+
rows: resultRows,
|
|
647
|
+
rowsAffected,
|
|
648
|
+
lastInsertRowid: void 0,
|
|
649
|
+
toJSON() {
|
|
650
|
+
return {
|
|
651
|
+
columns,
|
|
652
|
+
columnTypes: columns.map(() => ""),
|
|
653
|
+
rows,
|
|
654
|
+
rowsAffected,
|
|
655
|
+
lastInsertRowid: void 0
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
async function loadPrismaClient() {
|
|
661
|
+
if (!prismaClientPromise) {
|
|
662
|
+
prismaClientPromise = (async () => {
|
|
663
|
+
const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
|
|
664
|
+
if (explicitPath) {
|
|
665
|
+
const module2 = await import(pathToFileURL(explicitPath).href);
|
|
666
|
+
const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
|
|
667
|
+
if (!PrismaClient2) {
|
|
668
|
+
throw new Error(`No PrismaClient export found at ${explicitPath}`);
|
|
669
|
+
}
|
|
670
|
+
return new PrismaClient2();
|
|
671
|
+
}
|
|
672
|
+
const exeDbRoot = process.env.EXE_DB_ROOT ?? path4.join(os3.homedir(), "exe-db");
|
|
673
|
+
const requireFromExeDb = createRequire(path4.join(exeDbRoot, "package.json"));
|
|
674
|
+
const prismaEntry = requireFromExeDb.resolve("@prisma/client");
|
|
675
|
+
const module = await import(pathToFileURL(prismaEntry).href);
|
|
676
|
+
const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
|
|
677
|
+
if (!PrismaClient) {
|
|
678
|
+
throw new Error(`No PrismaClient export found in ${prismaEntry}`);
|
|
679
|
+
}
|
|
680
|
+
return new PrismaClient();
|
|
681
|
+
})();
|
|
682
|
+
}
|
|
683
|
+
return prismaClientPromise;
|
|
684
|
+
}
|
|
685
|
+
async function ensureCompatibilityViews(prisma) {
|
|
686
|
+
if (!compatibilityBootstrapPromise) {
|
|
687
|
+
compatibilityBootstrapPromise = (async () => {
|
|
688
|
+
for (const mapping of VIEW_MAPPINGS) {
|
|
689
|
+
const relation = mapping.source.replace(/"/g, "");
|
|
690
|
+
const rows = await prisma.$queryRawUnsafe(
|
|
691
|
+
"SELECT to_regclass($1) AS regclass",
|
|
692
|
+
relation
|
|
693
|
+
);
|
|
694
|
+
if (!rows[0]?.regclass) {
|
|
695
|
+
continue;
|
|
696
|
+
}
|
|
697
|
+
await prisma.$executeRawUnsafe(
|
|
698
|
+
`CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
|
|
699
|
+
);
|
|
700
|
+
}
|
|
701
|
+
})();
|
|
702
|
+
}
|
|
703
|
+
return compatibilityBootstrapPromise;
|
|
704
|
+
}
|
|
705
|
+
async function executeOnPrisma(executor, stmt) {
|
|
706
|
+
const translated = translateStatementForPostgres(stmt);
|
|
707
|
+
if (isReadQuery(translated.sql)) {
|
|
708
|
+
const rows = await executor.$queryRawUnsafe(
|
|
709
|
+
translated.sql,
|
|
710
|
+
...translated.args
|
|
711
|
+
);
|
|
712
|
+
return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
|
|
713
|
+
}
|
|
714
|
+
const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
|
|
715
|
+
return buildResultSet([], rowsAffected);
|
|
716
|
+
}
|
|
717
|
+
function splitSqlStatements(sql) {
|
|
718
|
+
const parts = [];
|
|
719
|
+
let current = "";
|
|
720
|
+
let inSingle = false;
|
|
721
|
+
let inDouble = false;
|
|
722
|
+
let inLineComment = false;
|
|
723
|
+
let inBlockComment = false;
|
|
724
|
+
for (let i = 0; i < sql.length; i++) {
|
|
725
|
+
const ch = sql[i];
|
|
726
|
+
const next = sql[i + 1];
|
|
727
|
+
if (inLineComment) {
|
|
728
|
+
current += ch;
|
|
729
|
+
if (ch === "\n") inLineComment = false;
|
|
730
|
+
continue;
|
|
731
|
+
}
|
|
732
|
+
if (inBlockComment) {
|
|
733
|
+
current += ch;
|
|
734
|
+
if (ch === "*" && next === "/") {
|
|
735
|
+
current += next;
|
|
736
|
+
inBlockComment = false;
|
|
737
|
+
i += 1;
|
|
738
|
+
}
|
|
739
|
+
continue;
|
|
740
|
+
}
|
|
741
|
+
if (!inSingle && !inDouble && ch === "-" && next === "-") {
|
|
742
|
+
current += ch + next;
|
|
743
|
+
inLineComment = true;
|
|
744
|
+
i += 1;
|
|
745
|
+
continue;
|
|
746
|
+
}
|
|
747
|
+
if (!inSingle && !inDouble && ch === "/" && next === "*") {
|
|
748
|
+
current += ch + next;
|
|
749
|
+
inBlockComment = true;
|
|
750
|
+
i += 1;
|
|
751
|
+
continue;
|
|
752
|
+
}
|
|
753
|
+
if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
|
|
754
|
+
inSingle = !inSingle;
|
|
755
|
+
current += ch;
|
|
756
|
+
continue;
|
|
757
|
+
}
|
|
758
|
+
if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
|
|
759
|
+
inDouble = !inDouble;
|
|
760
|
+
current += ch;
|
|
761
|
+
continue;
|
|
762
|
+
}
|
|
763
|
+
if (!inSingle && !inDouble && ch === ";") {
|
|
764
|
+
if (current.trim()) {
|
|
765
|
+
parts.push(current.trim());
|
|
766
|
+
}
|
|
767
|
+
current = "";
|
|
768
|
+
continue;
|
|
769
|
+
}
|
|
770
|
+
current += ch;
|
|
771
|
+
}
|
|
772
|
+
if (current.trim()) {
|
|
773
|
+
parts.push(current.trim());
|
|
774
|
+
}
|
|
775
|
+
return parts;
|
|
776
|
+
}
|
|
777
|
+
async function createPrismaDbAdapter(fallbackClient) {
|
|
778
|
+
const prisma = await loadPrismaClient();
|
|
779
|
+
await ensureCompatibilityViews(prisma);
|
|
780
|
+
let closed = false;
|
|
781
|
+
let adapter;
|
|
782
|
+
const fallbackExecute = async (stmt, error) => {
|
|
783
|
+
if (!fallbackClient) {
|
|
784
|
+
if (error) throw error;
|
|
785
|
+
throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
|
|
786
|
+
}
|
|
787
|
+
if (error) {
|
|
788
|
+
process.stderr.write(
|
|
789
|
+
`[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
|
|
790
|
+
`
|
|
791
|
+
);
|
|
792
|
+
}
|
|
793
|
+
return fallbackClient.execute(stmt);
|
|
794
|
+
};
|
|
795
|
+
adapter = {
|
|
796
|
+
async execute(stmt) {
|
|
797
|
+
if (shouldBypassPostgres(stmt)) {
|
|
798
|
+
return fallbackExecute(stmt);
|
|
799
|
+
}
|
|
800
|
+
try {
|
|
801
|
+
return await executeOnPrisma(prisma, stmt);
|
|
802
|
+
} catch (error) {
|
|
803
|
+
if (shouldFallbackOnError(error)) {
|
|
804
|
+
return fallbackExecute(stmt, error);
|
|
805
|
+
}
|
|
806
|
+
throw error;
|
|
807
|
+
}
|
|
808
|
+
},
|
|
809
|
+
async batch(stmts, mode) {
|
|
810
|
+
if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
|
|
811
|
+
if (!fallbackClient) {
|
|
812
|
+
throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
|
|
813
|
+
}
|
|
814
|
+
return fallbackClient.batch(stmts, mode);
|
|
815
|
+
}
|
|
816
|
+
try {
|
|
817
|
+
if (prisma.$transaction) {
|
|
818
|
+
return await prisma.$transaction(async (tx) => {
|
|
819
|
+
const results2 = [];
|
|
820
|
+
for (const stmt of stmts) {
|
|
821
|
+
results2.push(await executeOnPrisma(tx, stmt));
|
|
822
|
+
}
|
|
823
|
+
return results2;
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
const results = [];
|
|
827
|
+
for (const stmt of stmts) {
|
|
828
|
+
results.push(await executeOnPrisma(prisma, stmt));
|
|
829
|
+
}
|
|
830
|
+
return results;
|
|
831
|
+
} catch (error) {
|
|
832
|
+
if (fallbackClient && shouldFallbackOnError(error)) {
|
|
833
|
+
process.stderr.write(
|
|
834
|
+
`[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
|
|
835
|
+
`
|
|
836
|
+
);
|
|
837
|
+
return fallbackClient.batch(stmts, mode);
|
|
838
|
+
}
|
|
839
|
+
throw error;
|
|
840
|
+
}
|
|
841
|
+
},
|
|
842
|
+
async migrate(stmts) {
|
|
843
|
+
if (fallbackClient) {
|
|
844
|
+
return fallbackClient.migrate(stmts);
|
|
845
|
+
}
|
|
846
|
+
return adapter.batch(stmts, "deferred");
|
|
847
|
+
},
|
|
848
|
+
async transaction(mode) {
|
|
849
|
+
if (!fallbackClient) {
|
|
850
|
+
throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
|
|
851
|
+
}
|
|
852
|
+
return fallbackClient.transaction(mode);
|
|
853
|
+
},
|
|
854
|
+
async executeMultiple(sql) {
|
|
855
|
+
if (fallbackClient && shouldBypassPostgres(sql)) {
|
|
856
|
+
return fallbackClient.executeMultiple(sql);
|
|
857
|
+
}
|
|
858
|
+
for (const statement of splitSqlStatements(sql)) {
|
|
859
|
+
await adapter.execute(statement);
|
|
860
|
+
}
|
|
861
|
+
},
|
|
862
|
+
async sync() {
|
|
863
|
+
if (fallbackClient) {
|
|
864
|
+
return fallbackClient.sync();
|
|
865
|
+
}
|
|
866
|
+
return { frame_no: 0, frames_synced: 0 };
|
|
867
|
+
},
|
|
868
|
+
close() {
|
|
869
|
+
closed = true;
|
|
870
|
+
prismaClientPromise = null;
|
|
871
|
+
compatibilityBootstrapPromise = null;
|
|
872
|
+
void prisma.$disconnect?.();
|
|
873
|
+
},
|
|
874
|
+
get closed() {
|
|
875
|
+
return closed;
|
|
876
|
+
},
|
|
877
|
+
get protocol() {
|
|
878
|
+
return "prisma-postgres";
|
|
879
|
+
}
|
|
880
|
+
};
|
|
881
|
+
return adapter;
|
|
882
|
+
}
|
|
883
|
+
var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
|
|
884
|
+
var init_database_adapter = __esm({
|
|
885
|
+
"src/lib/database-adapter.ts"() {
|
|
886
|
+
"use strict";
|
|
887
|
+
VIEW_MAPPINGS = [
|
|
888
|
+
{ view: "memories", source: "memory.memory_records" },
|
|
889
|
+
{ view: "tasks", source: "memory.tasks" },
|
|
890
|
+
{ view: "behaviors", source: "memory.behaviors" },
|
|
891
|
+
{ view: "entities", source: "memory.entities" },
|
|
892
|
+
{ view: "relationships", source: "memory.relationships" },
|
|
893
|
+
{ view: "entity_memories", source: "memory.entity_memories" },
|
|
894
|
+
{ view: "entity_aliases", source: "memory.entity_aliases" },
|
|
895
|
+
{ view: "notifications", source: "memory.notifications" },
|
|
896
|
+
{ view: "messages", source: "memory.messages" },
|
|
897
|
+
{ view: "users", source: "wiki.users" },
|
|
898
|
+
{ view: "workspaces", source: "wiki.workspaces" },
|
|
899
|
+
{ view: "workspace_users", source: "wiki.workspace_users" },
|
|
900
|
+
{ view: "documents", source: "wiki.workspace_documents" },
|
|
901
|
+
{ view: "chats", source: "wiki.workspace_chats" }
|
|
902
|
+
];
|
|
903
|
+
UPSERT_KEYS = {
|
|
904
|
+
memories: ["id"],
|
|
905
|
+
tasks: ["id"],
|
|
906
|
+
behaviors: ["id"],
|
|
907
|
+
entities: ["id"],
|
|
908
|
+
relationships: ["id"],
|
|
909
|
+
entity_aliases: ["alias"],
|
|
910
|
+
notifications: ["id"],
|
|
911
|
+
messages: ["id"],
|
|
912
|
+
users: ["id"],
|
|
913
|
+
workspaces: ["id"],
|
|
914
|
+
workspace_users: ["id"],
|
|
915
|
+
documents: ["id"],
|
|
916
|
+
chats: ["id"]
|
|
917
|
+
};
|
|
918
|
+
BOOLEAN_COLUMNS_BY_TABLE = {
|
|
919
|
+
memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
|
|
920
|
+
behaviors: /* @__PURE__ */ new Set(["active"]),
|
|
921
|
+
notifications: /* @__PURE__ */ new Set(["read"]),
|
|
922
|
+
users: /* @__PURE__ */ new Set(["has_personal_memory"])
|
|
923
|
+
};
|
|
924
|
+
BOOLEAN_COLUMN_NAMES = new Set(
|
|
925
|
+
Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
|
|
926
|
+
);
|
|
927
|
+
IMMEDIATE_FALLBACK_PATTERNS = [
|
|
928
|
+
/\bPRAGMA\b/i,
|
|
929
|
+
/\bsqlite_master\b/i,
|
|
930
|
+
/(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
|
|
931
|
+
/\bMATCH\b/i,
|
|
932
|
+
/\bvector_distance_cos\s*\(/i,
|
|
933
|
+
/\bjson_extract\s*\(/i,
|
|
934
|
+
/\bjulianday\s*\(/i,
|
|
935
|
+
/\bstrftime\s*\(/i,
|
|
936
|
+
/\blast_insert_rowid\s*\(/i
|
|
937
|
+
];
|
|
938
|
+
prismaClientPromise = null;
|
|
939
|
+
compatibilityBootstrapPromise = null;
|
|
355
940
|
}
|
|
356
941
|
});
|
|
357
942
|
|
|
358
943
|
// src/lib/database.ts
|
|
359
944
|
import { createClient } from "@libsql/client";
|
|
360
945
|
async function initDatabase(config) {
|
|
946
|
+
if (_walCheckpointTimer) {
|
|
947
|
+
clearInterval(_walCheckpointTimer);
|
|
948
|
+
_walCheckpointTimer = null;
|
|
949
|
+
}
|
|
950
|
+
if (_daemonClient) {
|
|
951
|
+
_daemonClient.close();
|
|
952
|
+
_daemonClient = null;
|
|
953
|
+
}
|
|
954
|
+
if (_adapterClient && _adapterClient !== _resilientClient) {
|
|
955
|
+
_adapterClient.close();
|
|
956
|
+
}
|
|
957
|
+
_adapterClient = null;
|
|
361
958
|
if (_client) {
|
|
362
959
|
_client.close();
|
|
363
960
|
_client = null;
|
|
@@ -371,6 +968,7 @@ async function initDatabase(config) {
|
|
|
371
968
|
}
|
|
372
969
|
_client = createClient(opts);
|
|
373
970
|
_resilientClient = wrapWithRetry(_client);
|
|
971
|
+
_adapterClient = _resilientClient;
|
|
374
972
|
_client.execute("PRAGMA busy_timeout = 30000").catch(() => {
|
|
375
973
|
});
|
|
376
974
|
_client.execute("PRAGMA journal_mode = WAL").catch(() => {
|
|
@@ -381,14 +979,20 @@ async function initDatabase(config) {
|
|
|
381
979
|
});
|
|
382
980
|
}, 3e4);
|
|
383
981
|
_walCheckpointTimer.unref();
|
|
982
|
+
if (process.env.DATABASE_URL) {
|
|
983
|
+
_adapterClient = await createPrismaDbAdapter(_resilientClient);
|
|
984
|
+
}
|
|
384
985
|
}
|
|
385
986
|
function isInitialized() {
|
|
386
|
-
return _client !== null;
|
|
987
|
+
return _adapterClient !== null || _client !== null;
|
|
387
988
|
}
|
|
388
989
|
function getClient() {
|
|
389
|
-
if (!
|
|
990
|
+
if (!_adapterClient) {
|
|
390
991
|
throw new Error("Database client not initialized. Call initDatabase() first.");
|
|
391
992
|
}
|
|
993
|
+
if (process.env.DATABASE_URL) {
|
|
994
|
+
return _adapterClient;
|
|
995
|
+
}
|
|
392
996
|
if (process.env.EXE_IS_DAEMON === "1") {
|
|
393
997
|
return _resilientClient;
|
|
394
998
|
}
|
|
@@ -1328,16 +1932,18 @@ async function ensureSchema() {
|
|
|
1328
1932
|
}
|
|
1329
1933
|
}
|
|
1330
1934
|
}
|
|
1331
|
-
var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso;
|
|
1935
|
+
var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
|
|
1332
1936
|
var init_database = __esm({
|
|
1333
1937
|
"src/lib/database.ts"() {
|
|
1334
1938
|
"use strict";
|
|
1335
1939
|
init_db_retry();
|
|
1336
1940
|
init_employees();
|
|
1941
|
+
init_database_adapter();
|
|
1337
1942
|
_client = null;
|
|
1338
1943
|
_resilientClient = null;
|
|
1339
1944
|
_walCheckpointTimer = null;
|
|
1340
1945
|
_daemonClient = null;
|
|
1946
|
+
_adapterClient = null;
|
|
1341
1947
|
initTurso = initDatabase;
|
|
1342
1948
|
}
|
|
1343
1949
|
});
|
|
@@ -1355,7 +1961,7 @@ __export(shard_manager_exports, {
|
|
|
1355
1961
|
listShards: () => listShards,
|
|
1356
1962
|
shardExists: () => shardExists
|
|
1357
1963
|
});
|
|
1358
|
-
import
|
|
1964
|
+
import path6 from "path";
|
|
1359
1965
|
import { existsSync as existsSync4, mkdirSync, readdirSync } from "fs";
|
|
1360
1966
|
import { createClient as createClient2 } from "@libsql/client";
|
|
1361
1967
|
function initShardManager(encryptionKey) {
|
|
@@ -1381,7 +1987,7 @@ function getShardClient(projectName) {
|
|
|
1381
1987
|
}
|
|
1382
1988
|
const cached = _shards.get(safeName);
|
|
1383
1989
|
if (cached) return cached;
|
|
1384
|
-
const dbPath =
|
|
1990
|
+
const dbPath = path6.join(SHARDS_DIR, `${safeName}.db`);
|
|
1385
1991
|
const client = createClient2({
|
|
1386
1992
|
url: `file:${dbPath}`,
|
|
1387
1993
|
encryptionKey: _encryptionKey
|
|
@@ -1391,7 +1997,7 @@ function getShardClient(projectName) {
|
|
|
1391
1997
|
}
|
|
1392
1998
|
function shardExists(projectName) {
|
|
1393
1999
|
const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
1394
|
-
return existsSync4(
|
|
2000
|
+
return existsSync4(path6.join(SHARDS_DIR, `${safeName}.db`));
|
|
1395
2001
|
}
|
|
1396
2002
|
function listShards() {
|
|
1397
2003
|
if (!existsSync4(SHARDS_DIR)) return [];
|
|
@@ -1468,7 +2074,23 @@ async function ensureShardSchema(client) {
|
|
|
1468
2074
|
// MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
|
|
1469
2075
|
"ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
|
|
1470
2076
|
"ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
|
|
1471
|
-
"ALTER TABLE memories ADD COLUMN trajectory TEXT"
|
|
2077
|
+
"ALTER TABLE memories ADD COLUMN trajectory TEXT",
|
|
2078
|
+
// Metadata enrichment columns (must match database.ts)
|
|
2079
|
+
"ALTER TABLE memories ADD COLUMN intent TEXT",
|
|
2080
|
+
"ALTER TABLE memories ADD COLUMN outcome TEXT",
|
|
2081
|
+
"ALTER TABLE memories ADD COLUMN domain TEXT",
|
|
2082
|
+
"ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
|
|
2083
|
+
"ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
|
|
2084
|
+
"ALTER TABLE memories ADD COLUMN chain_position TEXT",
|
|
2085
|
+
"ALTER TABLE memories ADD COLUMN review_status TEXT",
|
|
2086
|
+
"ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
|
|
2087
|
+
"ALTER TABLE memories ADD COLUMN file_paths TEXT",
|
|
2088
|
+
"ALTER TABLE memories ADD COLUMN commit_hash TEXT",
|
|
2089
|
+
"ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
|
|
2090
|
+
"ALTER TABLE memories ADD COLUMN token_cost REAL",
|
|
2091
|
+
"ALTER TABLE memories ADD COLUMN audience TEXT",
|
|
2092
|
+
"ALTER TABLE memories ADD COLUMN language_type TEXT",
|
|
2093
|
+
"ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
|
|
1472
2094
|
]) {
|
|
1473
2095
|
try {
|
|
1474
2096
|
await client.execute(col);
|
|
@@ -1580,7 +2202,7 @@ var init_shard_manager = __esm({
|
|
|
1580
2202
|
"src/lib/shard-manager.ts"() {
|
|
1581
2203
|
"use strict";
|
|
1582
2204
|
init_config();
|
|
1583
|
-
SHARDS_DIR =
|
|
2205
|
+
SHARDS_DIR = path6.join(EXE_AI_DIR, "shards");
|
|
1584
2206
|
_shards = /* @__PURE__ */ new Map();
|
|
1585
2207
|
_encryptionKey = null;
|
|
1586
2208
|
_shardingEnabled = false;
|
|
@@ -1776,11 +2398,11 @@ ${p.content}`).join("\n\n");
|
|
|
1776
2398
|
|
|
1777
2399
|
// src/lib/exe-daemon-client.ts
|
|
1778
2400
|
import net from "net";
|
|
1779
|
-
import
|
|
2401
|
+
import os5 from "os";
|
|
1780
2402
|
import { spawn } from "child_process";
|
|
1781
2403
|
import { randomUUID as randomUUID3 } from "crypto";
|
|
1782
2404
|
import { existsSync as existsSync7, unlinkSync as unlinkSync2, readFileSync as readFileSync5, openSync, closeSync, statSync } from "fs";
|
|
1783
|
-
import
|
|
2405
|
+
import path9 from "path";
|
|
1784
2406
|
import { fileURLToPath } from "url";
|
|
1785
2407
|
function handleData(chunk) {
|
|
1786
2408
|
_buffer += chunk.toString();
|
|
@@ -1831,17 +2453,17 @@ function cleanupStaleFiles() {
|
|
|
1831
2453
|
}
|
|
1832
2454
|
}
|
|
1833
2455
|
function findPackageRoot() {
|
|
1834
|
-
let dir =
|
|
1835
|
-
const { root } =
|
|
2456
|
+
let dir = path9.dirname(fileURLToPath(import.meta.url));
|
|
2457
|
+
const { root } = path9.parse(dir);
|
|
1836
2458
|
while (dir !== root) {
|
|
1837
|
-
if (existsSync7(
|
|
1838
|
-
dir =
|
|
2459
|
+
if (existsSync7(path9.join(dir, "package.json"))) return dir;
|
|
2460
|
+
dir = path9.dirname(dir);
|
|
1839
2461
|
}
|
|
1840
2462
|
return null;
|
|
1841
2463
|
}
|
|
1842
2464
|
function spawnDaemon() {
|
|
1843
|
-
const freeGB =
|
|
1844
|
-
const totalGB =
|
|
2465
|
+
const freeGB = os5.freemem() / (1024 * 1024 * 1024);
|
|
2466
|
+
const totalGB = os5.totalmem() / (1024 * 1024 * 1024);
|
|
1845
2467
|
if (totalGB <= 8) {
|
|
1846
2468
|
process.stderr.write(
|
|
1847
2469
|
`[exed-client] SKIP: ${totalGB.toFixed(0)}GB system \u2014 embedding daemon disabled. Using keyword search only. Minimum 16GB recommended for vector search.
|
|
@@ -1861,7 +2483,7 @@ function spawnDaemon() {
|
|
|
1861
2483
|
process.stderr.write("[exed-client] WARN: cannot find package root\n");
|
|
1862
2484
|
return;
|
|
1863
2485
|
}
|
|
1864
|
-
const daemonPath =
|
|
2486
|
+
const daemonPath = path9.join(pkgRoot, "dist", "lib", "exe-daemon.js");
|
|
1865
2487
|
if (!existsSync7(daemonPath)) {
|
|
1866
2488
|
process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
|
|
1867
2489
|
`);
|
|
@@ -1870,7 +2492,7 @@ function spawnDaemon() {
|
|
|
1870
2492
|
const resolvedPath = daemonPath;
|
|
1871
2493
|
process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
|
|
1872
2494
|
`);
|
|
1873
|
-
const logPath =
|
|
2495
|
+
const logPath = path9.join(path9.dirname(SOCKET_PATH), "exed.log");
|
|
1874
2496
|
let stderrFd = "ignore";
|
|
1875
2497
|
try {
|
|
1876
2498
|
stderrFd = openSync(logPath, "a");
|
|
@@ -2021,74 +2643,123 @@ async function pingDaemon() {
|
|
|
2021
2643
|
return null;
|
|
2022
2644
|
}
|
|
2023
2645
|
function killAndRespawnDaemon() {
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2646
|
+
if (!acquireSpawnLock()) {
|
|
2647
|
+
process.stderr.write("[exed-client] Another process is already restarting daemon \u2014 skipping\n");
|
|
2648
|
+
if (_socket) {
|
|
2649
|
+
_socket.destroy();
|
|
2650
|
+
_socket = null;
|
|
2651
|
+
}
|
|
2652
|
+
_connected = false;
|
|
2653
|
+
_buffer = "";
|
|
2654
|
+
return;
|
|
2655
|
+
}
|
|
2656
|
+
try {
|
|
2657
|
+
process.stderr.write("[exed-client] Killing daemon for restart...\n");
|
|
2658
|
+
if (existsSync7(PID_PATH)) {
|
|
2659
|
+
try {
|
|
2660
|
+
const pid = parseInt(readFileSync5(PID_PATH, "utf8").trim(), 10);
|
|
2661
|
+
if (pid > 0) {
|
|
2662
|
+
try {
|
|
2663
|
+
process.kill(pid, "SIGKILL");
|
|
2664
|
+
} catch {
|
|
2665
|
+
}
|
|
2032
2666
|
}
|
|
2667
|
+
} catch {
|
|
2033
2668
|
}
|
|
2669
|
+
}
|
|
2670
|
+
if (_socket) {
|
|
2671
|
+
_socket.destroy();
|
|
2672
|
+
_socket = null;
|
|
2673
|
+
}
|
|
2674
|
+
_connected = false;
|
|
2675
|
+
_buffer = "";
|
|
2676
|
+
try {
|
|
2677
|
+
unlinkSync2(PID_PATH);
|
|
2034
2678
|
} catch {
|
|
2035
2679
|
}
|
|
2680
|
+
try {
|
|
2681
|
+
unlinkSync2(SOCKET_PATH);
|
|
2682
|
+
} catch {
|
|
2683
|
+
}
|
|
2684
|
+
spawnDaemon();
|
|
2685
|
+
} finally {
|
|
2686
|
+
releaseSpawnLock();
|
|
2036
2687
|
}
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
_socket = null;
|
|
2040
|
-
}
|
|
2041
|
-
_connected = false;
|
|
2042
|
-
_buffer = "";
|
|
2688
|
+
}
|
|
2689
|
+
function isDaemonTooYoung() {
|
|
2043
2690
|
try {
|
|
2044
|
-
|
|
2691
|
+
const stat = statSync(PID_PATH);
|
|
2692
|
+
return Date.now() - stat.mtimeMs < MIN_DAEMON_AGE_MS;
|
|
2045
2693
|
} catch {
|
|
2694
|
+
return false;
|
|
2046
2695
|
}
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2696
|
+
}
|
|
2697
|
+
async function retryThenRestart(doRequest, label) {
|
|
2698
|
+
const result = await doRequest();
|
|
2699
|
+
if (!result.error) {
|
|
2700
|
+
_consecutiveFailures = 0;
|
|
2701
|
+
return result;
|
|
2702
|
+
}
|
|
2703
|
+
_consecutiveFailures++;
|
|
2704
|
+
for (let i = 0; i < MAX_RETRIES_BEFORE_RESTART; i++) {
|
|
2705
|
+
const delayMs = RETRY_DELAYS_MS[i] ?? 5e3;
|
|
2706
|
+
process.stderr.write(`[exed-client] ${label} failed (${result.error}), retry ${i + 1}/${MAX_RETRIES_BEFORE_RESTART} in ${delayMs}ms
|
|
2707
|
+
`);
|
|
2708
|
+
await new Promise((r) => setTimeout(r, delayMs));
|
|
2709
|
+
if (!_connected) {
|
|
2710
|
+
if (!await connectToSocket()) continue;
|
|
2711
|
+
}
|
|
2712
|
+
const retry = await doRequest();
|
|
2713
|
+
if (!retry.error) {
|
|
2714
|
+
_consecutiveFailures = 0;
|
|
2715
|
+
return retry;
|
|
2716
|
+
}
|
|
2717
|
+
_consecutiveFailures++;
|
|
2718
|
+
}
|
|
2719
|
+
if (isDaemonTooYoung()) {
|
|
2720
|
+
process.stderr.write(`[exed-client] ${label}: daemon too young (< ${MIN_DAEMON_AGE_MS / 1e3}s) \u2014 skipping restart
|
|
2721
|
+
`);
|
|
2722
|
+
return { error: result.error };
|
|
2723
|
+
}
|
|
2724
|
+
process.stderr.write(`[exed-client] ${label}: ${_consecutiveFailures} consecutive failures \u2014 restarting daemon
|
|
2725
|
+
`);
|
|
2726
|
+
killAndRespawnDaemon();
|
|
2727
|
+
const start = Date.now();
|
|
2728
|
+
let delay2 = 200;
|
|
2729
|
+
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
2730
|
+
await new Promise((r) => setTimeout(r, delay2));
|
|
2731
|
+
if (await connectToSocket()) break;
|
|
2732
|
+
delay2 = Math.min(delay2 * 2, 3e3);
|
|
2050
2733
|
}
|
|
2051
|
-
|
|
2734
|
+
if (!_connected) return { error: "Daemon restart failed" };
|
|
2735
|
+
const final = await doRequest();
|
|
2736
|
+
if (!final.error) _consecutiveFailures = 0;
|
|
2737
|
+
return final;
|
|
2052
2738
|
}
|
|
2053
2739
|
async function embedViaClient(text, priority = "high") {
|
|
2054
2740
|
if (!_connected && !await connectEmbedDaemon()) return null;
|
|
2055
2741
|
_requestCount++;
|
|
2056
2742
|
if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
|
|
2057
2743
|
const health = await pingDaemon();
|
|
2058
|
-
if (!health) {
|
|
2744
|
+
if (!health && !isDaemonTooYoung()) {
|
|
2059
2745
|
process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
|
|
2060
2746
|
`);
|
|
2061
2747
|
killAndRespawnDaemon();
|
|
2062
2748
|
const start = Date.now();
|
|
2063
|
-
let
|
|
2749
|
+
let d = 200;
|
|
2064
2750
|
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
2065
|
-
await new Promise((r) => setTimeout(r,
|
|
2751
|
+
await new Promise((r) => setTimeout(r, d));
|
|
2066
2752
|
if (await connectToSocket()) break;
|
|
2067
|
-
|
|
2753
|
+
d = Math.min(d * 2, 3e3);
|
|
2068
2754
|
}
|
|
2069
2755
|
if (!_connected) return null;
|
|
2070
2756
|
}
|
|
2071
2757
|
}
|
|
2072
|
-
const result = await
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
killAndRespawnDaemon();
|
|
2078
|
-
const start = Date.now();
|
|
2079
|
-
let delay2 = 200;
|
|
2080
|
-
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
2081
|
-
await new Promise((r) => setTimeout(r, delay2));
|
|
2082
|
-
if (await connectToSocket()) break;
|
|
2083
|
-
delay2 = Math.min(delay2 * 2, 3e3);
|
|
2084
|
-
}
|
|
2085
|
-
if (!_connected) return null;
|
|
2086
|
-
const retry = await sendRequest([text], priority);
|
|
2087
|
-
if (!retry.error && retry.vectors?.[0]) return retry.vectors[0];
|
|
2088
|
-
process.stderr.write(`[exed-client] Embed retry also failed: ${retry.error ?? "no vector"}
|
|
2089
|
-
`);
|
|
2090
|
-
}
|
|
2091
|
-
return null;
|
|
2758
|
+
const result = await retryThenRestart(
|
|
2759
|
+
() => sendRequest([text], priority),
|
|
2760
|
+
"Embed"
|
|
2761
|
+
);
|
|
2762
|
+
return !result.error && result.vectors?.[0] ? result.vectors[0] : null;
|
|
2092
2763
|
}
|
|
2093
2764
|
function disconnectClient() {
|
|
2094
2765
|
if (_socket) {
|
|
@@ -2103,14 +2774,14 @@ function disconnectClient() {
|
|
|
2103
2774
|
entry.resolve({ error: "Client disconnected" });
|
|
2104
2775
|
}
|
|
2105
2776
|
}
|
|
2106
|
-
var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, _socket, _connected, _buffer, _requestCount, HEALTH_CHECK_INTERVAL, _pending, MAX_BUFFER;
|
|
2777
|
+
var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, _socket, _connected, _buffer, _requestCount, _consecutiveFailures, HEALTH_CHECK_INTERVAL, MAX_RETRIES_BEFORE_RESTART, RETRY_DELAYS_MS, MIN_DAEMON_AGE_MS, _pending, MAX_BUFFER;
|
|
2107
2778
|
var init_exe_daemon_client = __esm({
|
|
2108
2779
|
"src/lib/exe-daemon-client.ts"() {
|
|
2109
2780
|
"use strict";
|
|
2110
2781
|
init_config();
|
|
2111
|
-
SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ??
|
|
2112
|
-
PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ??
|
|
2113
|
-
SPAWN_LOCK_PATH =
|
|
2782
|
+
SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path9.join(EXE_AI_DIR, "exed.sock");
|
|
2783
|
+
PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path9.join(EXE_AI_DIR, "exed.pid");
|
|
2784
|
+
SPAWN_LOCK_PATH = path9.join(EXE_AI_DIR, "exed-spawn.lock");
|
|
2114
2785
|
SPAWN_LOCK_STALE_MS = 3e4;
|
|
2115
2786
|
CONNECT_TIMEOUT_MS = 15e3;
|
|
2116
2787
|
REQUEST_TIMEOUT_MS = 3e4;
|
|
@@ -2118,7 +2789,11 @@ var init_exe_daemon_client = __esm({
|
|
|
2118
2789
|
_connected = false;
|
|
2119
2790
|
_buffer = "";
|
|
2120
2791
|
_requestCount = 0;
|
|
2792
|
+
_consecutiveFailures = 0;
|
|
2121
2793
|
HEALTH_CHECK_INTERVAL = 100;
|
|
2794
|
+
MAX_RETRIES_BEFORE_RESTART = 3;
|
|
2795
|
+
RETRY_DELAYS_MS = [1e3, 3e3, 5e3];
|
|
2796
|
+
MIN_DAEMON_AGE_MS = 3e4;
|
|
2122
2797
|
_pending = /* @__PURE__ */ new Map();
|
|
2123
2798
|
MAX_BUFFER = 1e7;
|
|
2124
2799
|
}
|
|
@@ -2162,8 +2837,8 @@ async function embedDirect(text) {
|
|
|
2162
2837
|
const llamaCpp = await import("node-llama-cpp");
|
|
2163
2838
|
const { MODELS_DIR: MODELS_DIR2 } = await Promise.resolve().then(() => (init_config(), config_exports));
|
|
2164
2839
|
const { existsSync: existsSync8 } = await import("fs");
|
|
2165
|
-
const
|
|
2166
|
-
const modelPath =
|
|
2840
|
+
const path11 = await import("path");
|
|
2841
|
+
const modelPath = path11.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
|
|
2167
2842
|
if (!existsSync8(modelPath)) {
|
|
2168
2843
|
throw new Error(`Embedding model not found at ${modelPath}. Run '/exe-setup' to download it.`);
|
|
2169
2844
|
}
|
|
@@ -2195,7 +2870,7 @@ var init_embedder = __esm({
|
|
|
2195
2870
|
// src/adapters/claude/hooks/prompt-ingest-worker.ts
|
|
2196
2871
|
import crypto from "crypto";
|
|
2197
2872
|
import { writeFileSync as writeFileSync3 } from "fs";
|
|
2198
|
-
import
|
|
2873
|
+
import path10 from "path";
|
|
2199
2874
|
|
|
2200
2875
|
// src/lib/project-name.ts
|
|
2201
2876
|
import { execSync } from "child_process";
|
|
@@ -2241,15 +2916,15 @@ import { createHash } from "crypto";
|
|
|
2241
2916
|
// src/lib/keychain.ts
|
|
2242
2917
|
import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
|
|
2243
2918
|
import { existsSync as existsSync3 } from "fs";
|
|
2244
|
-
import
|
|
2245
|
-
import
|
|
2919
|
+
import path5 from "path";
|
|
2920
|
+
import os4 from "os";
|
|
2246
2921
|
var SERVICE = "exe-mem";
|
|
2247
2922
|
var ACCOUNT = "master-key";
|
|
2248
2923
|
function getKeyDir() {
|
|
2249
|
-
return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ??
|
|
2924
|
+
return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path5.join(os4.homedir(), ".exe-os");
|
|
2250
2925
|
}
|
|
2251
2926
|
function getKeyPath() {
|
|
2252
|
-
return
|
|
2927
|
+
return path5.join(getKeyDir(), "master.key");
|
|
2253
2928
|
}
|
|
2254
2929
|
async function tryKeytar() {
|
|
2255
2930
|
try {
|
|
@@ -2272,7 +2947,7 @@ async function getMasterKey() {
|
|
|
2272
2947
|
const keyPath = getKeyPath();
|
|
2273
2948
|
if (!existsSync3(keyPath)) {
|
|
2274
2949
|
process.stderr.write(
|
|
2275
|
-
`[keychain] Key not found at ${keyPath} (HOME=${
|
|
2950
|
+
`[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
|
|
2276
2951
|
`
|
|
2277
2952
|
);
|
|
2278
2953
|
return null;
|
|
@@ -2697,17 +3372,17 @@ function vectorToBlob(vector) {
|
|
|
2697
3372
|
init_database();
|
|
2698
3373
|
init_employees();
|
|
2699
3374
|
import { readFileSync as readFileSync4, existsSync as existsSync6 } from "fs";
|
|
2700
|
-
import
|
|
3375
|
+
import path8 from "path";
|
|
2701
3376
|
|
|
2702
3377
|
// src/lib/license.ts
|
|
2703
3378
|
init_config();
|
|
2704
3379
|
import { readFileSync as readFileSync3, writeFileSync as writeFileSync2, existsSync as existsSync5, mkdirSync as mkdirSync2 } from "fs";
|
|
2705
3380
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
2706
|
-
import
|
|
3381
|
+
import path7 from "path";
|
|
2707
3382
|
import { jwtVerify, importSPKI } from "jose";
|
|
2708
|
-
var LICENSE_PATH =
|
|
2709
|
-
var CACHE_PATH =
|
|
2710
|
-
var DEVICE_ID_PATH =
|
|
3383
|
+
var LICENSE_PATH = path7.join(EXE_AI_DIR, "license.key");
|
|
3384
|
+
var CACHE_PATH = path7.join(EXE_AI_DIR, "license-cache.json");
|
|
3385
|
+
var DEVICE_ID_PATH = path7.join(EXE_AI_DIR, "device-id");
|
|
2711
3386
|
var API_BASE = "https://askexe.com/cloud";
|
|
2712
3387
|
var RETRY_DELAY_MS = 500;
|
|
2713
3388
|
async function fetchRetry(url, init) {
|
|
@@ -2740,7 +3415,7 @@ var FREE_LICENSE = {
|
|
|
2740
3415
|
memoryLimit: 5e3
|
|
2741
3416
|
};
|
|
2742
3417
|
function loadDeviceId() {
|
|
2743
|
-
const deviceJsonPath =
|
|
3418
|
+
const deviceJsonPath = path7.join(EXE_AI_DIR, "device.json");
|
|
2744
3419
|
try {
|
|
2745
3420
|
if (existsSync5(deviceJsonPath)) {
|
|
2746
3421
|
const data = JSON.parse(readFileSync3(deviceJsonPath, "utf8"));
|
|
@@ -2906,7 +3581,7 @@ async function checkLicense() {
|
|
|
2906
3581
|
let key = loadLicense();
|
|
2907
3582
|
if (!key) {
|
|
2908
3583
|
try {
|
|
2909
|
-
const configPath =
|
|
3584
|
+
const configPath = path7.join(EXE_AI_DIR, "config.json");
|
|
2910
3585
|
if (existsSync5(configPath)) {
|
|
2911
3586
|
const raw = JSON.parse(readFileSync3(configPath, "utf8"));
|
|
2912
3587
|
const cloud = raw.cloud;
|
|
@@ -2933,7 +3608,7 @@ var PlanLimitError = class extends Error {
|
|
|
2933
3608
|
this.name = "PlanLimitError";
|
|
2934
3609
|
}
|
|
2935
3610
|
};
|
|
2936
|
-
var CACHE_PATH2 =
|
|
3611
|
+
var CACHE_PATH2 = path8.join(EXE_AI_DIR, "license-cache.json");
|
|
2937
3612
|
async function countActiveMemories() {
|
|
2938
3613
|
if (!isInitialized()) return 0;
|
|
2939
3614
|
const client = getClient();
|
|
@@ -2996,7 +3671,7 @@ async function main() {
|
|
|
2996
3671
|
if (needsBackfill) {
|
|
2997
3672
|
try {
|
|
2998
3673
|
const { EXE_AI_DIR: exeDir } = await Promise.resolve().then(() => (init_config(), config_exports));
|
|
2999
|
-
const flagPath =
|
|
3674
|
+
const flagPath = path10.join(exeDir, "session-cache", "needs-backfill");
|
|
3000
3675
|
writeFileSync3(flagPath, "1");
|
|
3001
3676
|
} catch (err) {
|
|
3002
3677
|
process.stderr.write(`[prompt-ingest-worker] backfill flag write failed: ${err instanceof Error ? err.message : String(err)}
|