@askexenow/exe-os 0.8.0 → 0.8.2

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.
Files changed (107) hide show
  1. package/README.md +178 -79
  2. package/package.json +1 -1
  3. package/dist/bin/backfill-responses.js +0 -1912
  4. package/dist/bin/backfill-vectors.js +0 -1642
  5. package/dist/bin/cleanup-stale-review-tasks.js +0 -1339
  6. package/dist/bin/cli.js +0 -18800
  7. package/dist/bin/exe-agent.js +0 -1858
  8. package/dist/bin/exe-assign.js +0 -1957
  9. package/dist/bin/exe-boot.js +0 -6460
  10. package/dist/bin/exe-call.js +0 -197
  11. package/dist/bin/exe-cloud.js +0 -850
  12. package/dist/bin/exe-dispatch.js +0 -1146
  13. package/dist/bin/exe-doctor.js +0 -1657
  14. package/dist/bin/exe-export-behaviors.js +0 -1494
  15. package/dist/bin/exe-forget.js +0 -1627
  16. package/dist/bin/exe-gateway.js +0 -7732
  17. package/dist/bin/exe-healthcheck.js +0 -207
  18. package/dist/bin/exe-heartbeat.js +0 -1647
  19. package/dist/bin/exe-kill.js +0 -1479
  20. package/dist/bin/exe-launch-agent.js +0 -1704
  21. package/dist/bin/exe-link.js +0 -192
  22. package/dist/bin/exe-new-employee.js +0 -852
  23. package/dist/bin/exe-pending-messages.js +0 -1446
  24. package/dist/bin/exe-pending-notifications.js +0 -1321
  25. package/dist/bin/exe-pending-reviews.js +0 -1468
  26. package/dist/bin/exe-repo-drift.js +0 -95
  27. package/dist/bin/exe-review.js +0 -1590
  28. package/dist/bin/exe-search.js +0 -2651
  29. package/dist/bin/exe-session-cleanup.js +0 -3173
  30. package/dist/bin/exe-settings.js +0 -354
  31. package/dist/bin/exe-status.js +0 -1532
  32. package/dist/bin/exe-team.js +0 -1324
  33. package/dist/bin/git-sweep.js +0 -2185
  34. package/dist/bin/graph-backfill.js +0 -1968
  35. package/dist/bin/graph-export.js +0 -1604
  36. package/dist/bin/install.js +0 -656
  37. package/dist/bin/list-providers.js +0 -140
  38. package/dist/bin/scan-tasks.js +0 -1820
  39. package/dist/bin/setup.js +0 -951
  40. package/dist/bin/shard-migrate.js +0 -1494
  41. package/dist/bin/update.js +0 -95
  42. package/dist/bin/wiki-sync.js +0 -1514
  43. package/dist/gateway/index.js +0 -8848
  44. package/dist/hooks/bug-report-worker.js +0 -2743
  45. package/dist/hooks/commit-complete.js +0 -2108
  46. package/dist/hooks/error-recall.js +0 -2861
  47. package/dist/hooks/exe-heartbeat-hook.js +0 -232
  48. package/dist/hooks/ingest-worker.js +0 -4793
  49. package/dist/hooks/ingest.js +0 -684
  50. package/dist/hooks/instructions-loaded.js +0 -1880
  51. package/dist/hooks/notification.js +0 -1726
  52. package/dist/hooks/post-compact.js +0 -1751
  53. package/dist/hooks/pre-compact.js +0 -1746
  54. package/dist/hooks/pre-tool-use.js +0 -2191
  55. package/dist/hooks/prompt-ingest-worker.js +0 -2126
  56. package/dist/hooks/prompt-submit.js +0 -4693
  57. package/dist/hooks/response-ingest-worker.js +0 -1936
  58. package/dist/hooks/session-end.js +0 -1752
  59. package/dist/hooks/session-start.js +0 -2795
  60. package/dist/hooks/stop.js +0 -1835
  61. package/dist/hooks/subagent-stop.js +0 -1726
  62. package/dist/hooks/summary-worker.js +0 -2661
  63. package/dist/index.js +0 -11834
  64. package/dist/lib/cloud-sync.js +0 -495
  65. package/dist/lib/config.js +0 -222
  66. package/dist/lib/consolidation.js +0 -476
  67. package/dist/lib/crypto.js +0 -51
  68. package/dist/lib/database.js +0 -730
  69. package/dist/lib/device-registry.js +0 -900
  70. package/dist/lib/embedder.js +0 -632
  71. package/dist/lib/employee-templates.js +0 -543
  72. package/dist/lib/employees.js +0 -177
  73. package/dist/lib/error-detector.js +0 -156
  74. package/dist/lib/exe-daemon-client.js +0 -451
  75. package/dist/lib/exe-daemon.js +0 -8285
  76. package/dist/lib/file-grep.js +0 -199
  77. package/dist/lib/hybrid-search.js +0 -1819
  78. package/dist/lib/identity-templates.js +0 -320
  79. package/dist/lib/identity.js +0 -223
  80. package/dist/lib/keychain.js +0 -145
  81. package/dist/lib/license.js +0 -377
  82. package/dist/lib/messaging.js +0 -1376
  83. package/dist/lib/reminders.js +0 -63
  84. package/dist/lib/schedules.js +0 -1396
  85. package/dist/lib/session-registry.js +0 -52
  86. package/dist/lib/skill-learning.js +0 -477
  87. package/dist/lib/status-brief.js +0 -235
  88. package/dist/lib/store.js +0 -1551
  89. package/dist/lib/task-router.js +0 -62
  90. package/dist/lib/tasks.js +0 -2456
  91. package/dist/lib/tmux-routing.js +0 -2836
  92. package/dist/lib/tmux-status.js +0 -261
  93. package/dist/lib/tmux-transport.js +0 -83
  94. package/dist/lib/transport.js +0 -128
  95. package/dist/lib/ws-auth.js +0 -19
  96. package/dist/lib/ws-client.js +0 -160
  97. package/dist/mcp/server.js +0 -10538
  98. package/dist/mcp/tools/complete-reminder.js +0 -67
  99. package/dist/mcp/tools/create-reminder.js +0 -52
  100. package/dist/mcp/tools/create-task.js +0 -1853
  101. package/dist/mcp/tools/deactivate-behavior.js +0 -263
  102. package/dist/mcp/tools/list-reminders.js +0 -62
  103. package/dist/mcp/tools/list-tasks.js +0 -463
  104. package/dist/mcp/tools/send-message.js +0 -1382
  105. package/dist/mcp/tools/update-task.js +0 -1692
  106. package/dist/runtime/index.js +0 -6809
  107. package/dist/tui/App.js +0 -17479
@@ -1,4693 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
6
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
7
- }) : x)(function(x) {
8
- if (typeof require !== "undefined") return require.apply(this, arguments);
9
- throw Error('Dynamic require of "' + x + '" is not supported');
10
- });
11
- var __esm = (fn, res) => function __init() {
12
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
13
- };
14
- var __export = (target, all) => {
15
- for (var name in all)
16
- __defProp(target, name, { get: all[name], enumerable: true });
17
- };
18
- var __copyProps = (to, from, except, desc) => {
19
- if (from && typeof from === "object" || typeof from === "function") {
20
- for (let key of __getOwnPropNames(from))
21
- if (!__hasOwnProp.call(to, key) && key !== except)
22
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
- }
24
- return to;
25
- };
26
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
-
28
- // src/lib/config.ts
29
- var config_exports = {};
30
- __export(config_exports, {
31
- CONFIG_MIGRATIONS: () => CONFIG_MIGRATIONS,
32
- CONFIG_PATH: () => CONFIG_PATH,
33
- CURRENT_CONFIG_VERSION: () => CURRENT_CONFIG_VERSION,
34
- DB_PATH: () => DB_PATH,
35
- EXE_AI_DIR: () => EXE_AI_DIR,
36
- LEGACY_LANCE_PATH: () => LEGACY_LANCE_PATH,
37
- MODELS_DIR: () => MODELS_DIR,
38
- loadConfig: () => loadConfig,
39
- loadConfigFrom: () => loadConfigFrom,
40
- loadConfigSync: () => loadConfigSync,
41
- migrateConfig: () => migrateConfig,
42
- saveConfig: () => saveConfig
43
- });
44
- import { readFile, writeFile, mkdir } from "fs/promises";
45
- import { readFileSync, existsSync, renameSync } from "fs";
46
- import path from "path";
47
- import os from "os";
48
- function resolveDataDir() {
49
- if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
50
- if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
51
- const newDir = path.join(os.homedir(), ".exe-os");
52
- const legacyDir = path.join(os.homedir(), ".exe-mem");
53
- if (!existsSync(newDir) && existsSync(legacyDir)) {
54
- try {
55
- renameSync(legacyDir, newDir);
56
- process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
57
- `);
58
- } catch {
59
- return legacyDir;
60
- }
61
- }
62
- return newDir;
63
- }
64
- function migrateLegacyConfig(raw) {
65
- if ("r2" in raw) {
66
- process.stderr.write(
67
- "[exe-os] Warning: config.json contains deprecated 'r2' field from v1.0. R2 sync has been replaced in v1.1. The 'r2' field will be ignored.\n"
68
- );
69
- delete raw.r2;
70
- }
71
- if ("syncIntervalMs" in raw) {
72
- delete raw.syncIntervalMs;
73
- }
74
- return raw;
75
- }
76
- function migrateConfig(raw) {
77
- const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
78
- let currentVersion = fromVersion;
79
- let migrated = false;
80
- if (currentVersion > CURRENT_CONFIG_VERSION) {
81
- return { config: raw, migrated: false, fromVersion };
82
- }
83
- for (const migration of CONFIG_MIGRATIONS) {
84
- if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
85
- raw = migration.migrate(raw);
86
- currentVersion = migration.to;
87
- migrated = true;
88
- }
89
- }
90
- return { config: raw, migrated, fromVersion };
91
- }
92
- function normalizeScalingRoadmap(raw) {
93
- const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
94
- const userRoadmap = raw.scalingRoadmap ?? {};
95
- const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
96
- if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
97
- userAuto.enabled = raw.rerankerEnabled;
98
- }
99
- raw.scalingRoadmap = {
100
- ...userRoadmap,
101
- rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
102
- };
103
- }
104
- function normalizeSessionLifecycle(raw) {
105
- const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
106
- const userSL = raw.sessionLifecycle ?? {};
107
- raw.sessionLifecycle = { ...defaultSL, ...userSL };
108
- }
109
- async function loadConfig() {
110
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
111
- await mkdir(dir, { recursive: true });
112
- const configPath = path.join(dir, "config.json");
113
- if (!existsSync(configPath)) {
114
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
115
- }
116
- const raw = await readFile(configPath, "utf-8");
117
- try {
118
- let parsed = JSON.parse(raw);
119
- parsed = migrateLegacyConfig(parsed);
120
- const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
121
- if (migrated) {
122
- process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
123
- `);
124
- try {
125
- await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
126
- } catch {
127
- }
128
- }
129
- normalizeScalingRoadmap(migratedCfg);
130
- normalizeSessionLifecycle(migratedCfg);
131
- const config = { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
132
- if (config.dbPath.startsWith("~")) {
133
- config.dbPath = config.dbPath.replace(/^~/, os.homedir());
134
- }
135
- return config;
136
- } catch {
137
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
138
- }
139
- }
140
- function loadConfigSync() {
141
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
142
- const configPath = path.join(dir, "config.json");
143
- if (!existsSync(configPath)) {
144
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
145
- }
146
- try {
147
- const raw = readFileSync(configPath, "utf-8");
148
- let parsed = JSON.parse(raw);
149
- parsed = migrateLegacyConfig(parsed);
150
- const { config: migratedCfg } = migrateConfig(parsed);
151
- normalizeScalingRoadmap(migratedCfg);
152
- normalizeSessionLifecycle(migratedCfg);
153
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
154
- } catch {
155
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
156
- }
157
- }
158
- async function saveConfig(config) {
159
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
160
- await mkdir(dir, { recursive: true });
161
- const configPath = path.join(dir, "config.json");
162
- await writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
163
- }
164
- async function loadConfigFrom(configPath) {
165
- const raw = await readFile(configPath, "utf-8");
166
- try {
167
- let parsed = JSON.parse(raw);
168
- parsed = migrateLegacyConfig(parsed);
169
- const { config: migratedCfg } = migrateConfig(parsed);
170
- normalizeScalingRoadmap(migratedCfg);
171
- normalizeSessionLifecycle(migratedCfg);
172
- return { ...DEFAULT_CONFIG, ...migratedCfg };
173
- } catch {
174
- return { ...DEFAULT_CONFIG };
175
- }
176
- }
177
- var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
178
- var init_config = __esm({
179
- "src/lib/config.ts"() {
180
- "use strict";
181
- EXE_AI_DIR = resolveDataDir();
182
- DB_PATH = path.join(EXE_AI_DIR, "memories.db");
183
- MODELS_DIR = path.join(EXE_AI_DIR, "models");
184
- CONFIG_PATH = path.join(EXE_AI_DIR, "config.json");
185
- LEGACY_LANCE_PATH = path.join(EXE_AI_DIR, "local.lance");
186
- CURRENT_CONFIG_VERSION = 1;
187
- DEFAULT_CONFIG = {
188
- config_version: CURRENT_CONFIG_VERSION,
189
- dbPath: DB_PATH,
190
- modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
191
- embeddingDim: 1024,
192
- batchSize: 20,
193
- flushIntervalMs: 1e4,
194
- autoIngestion: true,
195
- autoRetrieval: true,
196
- searchMode: "hybrid",
197
- hookSearchMode: "hybrid",
198
- fileGrepEnabled: true,
199
- splashEffect: true,
200
- consolidationEnabled: true,
201
- consolidationIntervalMs: 6 * 60 * 60 * 1e3,
202
- consolidationModel: "claude-haiku-4-5-20251001",
203
- consolidationMaxCallsPerRun: 20,
204
- selfQueryRouter: true,
205
- selfQueryModel: "claude-haiku-4-5-20251001",
206
- rerankerEnabled: true,
207
- scalingRoadmap: {
208
- rerankerAutoTrigger: {
209
- enabled: true,
210
- broadQueryMinCardinality: 5e4,
211
- fetchTopK: 150,
212
- returnTopK: 5
213
- }
214
- },
215
- graphRagEnabled: true,
216
- wikiEnabled: false,
217
- wikiUrl: "",
218
- wikiApiKey: "",
219
- wikiSyncIntervalMs: 30 * 60 * 1e3,
220
- wikiWorkspaceMapping: {
221
- exe: "Executive",
222
- yoshi: "Engineering",
223
- mari: "Marketing",
224
- tom: "Engineering",
225
- sasha: "Production"
226
- },
227
- wikiAutoUpdate: true,
228
- wikiAutoUpdateThreshold: 0.5,
229
- wikiAutoUpdateCreateNew: true,
230
- skillLearning: true,
231
- skillThreshold: 3,
232
- skillModel: "claude-haiku-4-5-20251001",
233
- exeHeartbeat: {
234
- enabled: true,
235
- intervalSeconds: 60,
236
- staleInProgressThresholdHours: 2
237
- },
238
- sessionLifecycle: {
239
- idleKillEnabled: true,
240
- idleKillTicksRequired: 3,
241
- idleKillIntercomAckWindowMs: 1e4,
242
- maxAutoInstances: 10
243
- }
244
- };
245
- CONFIG_MIGRATIONS = [
246
- {
247
- from: 0,
248
- to: 1,
249
- migrate: (cfg) => {
250
- cfg.config_version = 1;
251
- return cfg;
252
- }
253
- }
254
- ];
255
- }
256
- });
257
-
258
- // src/types/memory.ts
259
- var EMBEDDING_DIM;
260
- var init_memory = __esm({
261
- "src/types/memory.ts"() {
262
- "use strict";
263
- EMBEDDING_DIM = 1024;
264
- }
265
- });
266
-
267
- // src/lib/database.ts
268
- import { createClient } from "@libsql/client";
269
- async function initDatabase(config) {
270
- if (_client) {
271
- _client.close();
272
- _client = null;
273
- }
274
- const opts = {
275
- url: `file:${config.dbPath}`
276
- };
277
- if (config.encryptionKey) {
278
- opts.encryptionKey = config.encryptionKey;
279
- }
280
- _client = createClient(opts);
281
- }
282
- function getClient() {
283
- if (!_client) {
284
- throw new Error("Database client not initialized. Call initDatabase() first.");
285
- }
286
- return _client;
287
- }
288
- async function ensureSchema() {
289
- const client = getClient();
290
- await client.execute("PRAGMA journal_mode = WAL");
291
- await client.execute("PRAGMA busy_timeout = 5000");
292
- try {
293
- await client.execute("PRAGMA libsql_vector_search_ef = 128");
294
- } catch {
295
- }
296
- await client.executeMultiple(`
297
- CREATE TABLE IF NOT EXISTS memories (
298
- id TEXT PRIMARY KEY,
299
- agent_id TEXT NOT NULL,
300
- agent_role TEXT NOT NULL,
301
- session_id TEXT NOT NULL,
302
- timestamp TEXT NOT NULL,
303
- tool_name TEXT NOT NULL,
304
- project_name TEXT NOT NULL,
305
- has_error INTEGER NOT NULL DEFAULT 0,
306
- raw_text TEXT NOT NULL,
307
- vector F32_BLOB(1024),
308
- version INTEGER NOT NULL DEFAULT 0
309
- );
310
-
311
- CREATE INDEX IF NOT EXISTS idx_memories_agent
312
- ON memories(agent_id);
313
-
314
- CREATE INDEX IF NOT EXISTS idx_memories_timestamp
315
- ON memories(timestamp);
316
-
317
- CREATE INDEX IF NOT EXISTS idx_memories_session
318
- ON memories(session_id);
319
-
320
- CREATE INDEX IF NOT EXISTS idx_memories_project
321
- ON memories(project_name);
322
-
323
- CREATE INDEX IF NOT EXISTS idx_memories_tool
324
- ON memories(tool_name);
325
-
326
- CREATE INDEX IF NOT EXISTS idx_memories_version
327
- ON memories(version);
328
-
329
- CREATE INDEX IF NOT EXISTS idx_memories_agent_project
330
- ON memories(agent_id, project_name);
331
- `);
332
- await client.executeMultiple(`
333
- CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
334
- raw_text,
335
- content='memories',
336
- content_rowid='rowid'
337
- );
338
-
339
- CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
340
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
341
- END;
342
-
343
- CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
344
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
345
- END;
346
-
347
- CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
348
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
349
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
350
- END;
351
- `);
352
- await client.executeMultiple(`
353
- CREATE TABLE IF NOT EXISTS sync_meta (
354
- key TEXT PRIMARY KEY,
355
- value TEXT NOT NULL
356
- );
357
- `);
358
- await client.executeMultiple(`
359
- CREATE TABLE IF NOT EXISTS tasks (
360
- id TEXT PRIMARY KEY,
361
- title TEXT NOT NULL,
362
- assigned_to TEXT NOT NULL,
363
- assigned_by TEXT NOT NULL,
364
- project_name TEXT NOT NULL,
365
- priority TEXT NOT NULL DEFAULT 'p1',
366
- status TEXT NOT NULL DEFAULT 'open',
367
- task_file TEXT,
368
- created_at TEXT NOT NULL,
369
- updated_at TEXT NOT NULL
370
- );
371
-
372
- CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
373
- ON tasks(assigned_to, status);
374
- `);
375
- await client.executeMultiple(`
376
- CREATE TABLE IF NOT EXISTS behaviors (
377
- id TEXT PRIMARY KEY,
378
- agent_id TEXT NOT NULL,
379
- project_name TEXT,
380
- domain TEXT,
381
- content TEXT NOT NULL,
382
- active INTEGER NOT NULL DEFAULT 1,
383
- created_at TEXT NOT NULL,
384
- updated_at TEXT NOT NULL
385
- );
386
-
387
- CREATE INDEX IF NOT EXISTS idx_behaviors_agent
388
- ON behaviors(agent_id, active);
389
- `);
390
- try {
391
- const existing = await client.execute({
392
- sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = 'exe'",
393
- args: []
394
- });
395
- if (Number(existing.rows[0]?.cnt) === 0) {
396
- await client.executeMultiple(`
397
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
398
- VALUES
399
- (hex(randomblob(16)), 'exe', NULL, 'workflow', 'Don''t ask "keep going?" \u2014 just keep executing phases/plans autonomously', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
400
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
401
- VALUES
402
- (hex(randomblob(16)), 'exe', NULL, 'tool-use', 'Always use create_task MCP tool, never write .md files directly for task creation', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
403
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
404
- VALUES
405
- (hex(randomblob(16)), 'exe', NULL, 'workflow', 'Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
406
- `);
407
- }
408
- } catch {
409
- }
410
- try {
411
- await client.execute({
412
- sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
413
- args: []
414
- });
415
- } catch {
416
- }
417
- try {
418
- await client.execute({
419
- sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
420
- args: []
421
- });
422
- } catch {
423
- }
424
- try {
425
- await client.execute({
426
- sql: `ALTER TABLE tasks ADD COLUMN parent_task_id TEXT`,
427
- args: []
428
- });
429
- } catch {
430
- }
431
- try {
432
- await client.execute({
433
- sql: `CREATE INDEX IF NOT EXISTS idx_tasks_parent_task_id
434
- ON tasks(parent_task_id)
435
- WHERE parent_task_id IS NOT NULL`,
436
- args: []
437
- });
438
- } catch {
439
- }
440
- try {
441
- await client.execute({
442
- sql: `UPDATE tasks SET status = 'done' WHERE status = 'completed'`,
443
- args: []
444
- });
445
- } catch {
446
- }
447
- try {
448
- await client.execute({
449
- sql: `ALTER TABLE tasks ADD COLUMN reviewer TEXT`,
450
- args: []
451
- });
452
- } catch {
453
- }
454
- try {
455
- await client.execute({
456
- sql: `ALTER TABLE tasks ADD COLUMN context TEXT`,
457
- args: []
458
- });
459
- } catch {
460
- }
461
- try {
462
- await client.execute({
463
- sql: `ALTER TABLE tasks ADD COLUMN result TEXT`,
464
- args: []
465
- });
466
- } catch {
467
- }
468
- try {
469
- await client.execute({
470
- sql: `ALTER TABLE tasks ADD COLUMN assigned_tmux TEXT`,
471
- args: []
472
- });
473
- } catch {
474
- }
475
- try {
476
- await client.execute({
477
- sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
478
- args: []
479
- });
480
- } catch {
481
- }
482
- try {
483
- await client.execute({
484
- sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
485
- args: []
486
- });
487
- } catch {
488
- }
489
- try {
490
- await client.execute({
491
- sql: `ALTER TABLE memories ADD COLUMN author_device_id TEXT`,
492
- args: []
493
- });
494
- } catch {
495
- }
496
- try {
497
- await client.execute({
498
- sql: `ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'`,
499
- args: []
500
- });
501
- } catch {
502
- }
503
- await client.executeMultiple(`
504
- CREATE TABLE IF NOT EXISTS consolidations (
505
- id TEXT PRIMARY KEY,
506
- consolidated_memory_id TEXT NOT NULL,
507
- source_memory_id TEXT NOT NULL,
508
- created_at TEXT NOT NULL
509
- );
510
-
511
- CREATE INDEX IF NOT EXISTS idx_consolidations_source
512
- ON consolidations(source_memory_id);
513
-
514
- CREATE INDEX IF NOT EXISTS idx_consolidations_consolidated
515
- ON consolidations(consolidated_memory_id);
516
- `);
517
- await client.executeMultiple(`
518
- CREATE TABLE IF NOT EXISTS reminders (
519
- id TEXT PRIMARY KEY,
520
- text TEXT NOT NULL,
521
- created_at TEXT NOT NULL,
522
- due_date TEXT,
523
- completed_at TEXT
524
- );
525
- `);
526
- await client.executeMultiple(`
527
- CREATE TABLE IF NOT EXISTS notifications (
528
- id TEXT PRIMARY KEY,
529
- agent_id TEXT NOT NULL,
530
- agent_role TEXT NOT NULL,
531
- event TEXT NOT NULL,
532
- project TEXT NOT NULL,
533
- summary TEXT NOT NULL,
534
- task_file TEXT,
535
- read INTEGER NOT NULL DEFAULT 0,
536
- created_at TEXT NOT NULL
537
- );
538
-
539
- CREATE INDEX IF NOT EXISTS idx_notifications_read
540
- ON notifications(read);
541
-
542
- CREATE INDEX IF NOT EXISTS idx_notifications_agent
543
- ON notifications(agent_id);
544
-
545
- CREATE INDEX IF NOT EXISTS idx_notifications_task_file
546
- ON notifications(task_file);
547
- `);
548
- await client.executeMultiple(`
549
- CREATE TABLE IF NOT EXISTS schedules (
550
- id TEXT PRIMARY KEY,
551
- cron TEXT NOT NULL,
552
- description TEXT NOT NULL,
553
- job_type TEXT NOT NULL DEFAULT 'report',
554
- prompt TEXT,
555
- assigned_to TEXT,
556
- project_name TEXT,
557
- active INTEGER NOT NULL DEFAULT 1,
558
- use_crontab INTEGER NOT NULL DEFAULT 0,
559
- created_at TEXT NOT NULL
560
- );
561
- `);
562
- await client.executeMultiple(`
563
- CREATE TABLE IF NOT EXISTS device_registry (
564
- device_id TEXT PRIMARY KEY,
565
- friendly_name TEXT NOT NULL,
566
- hostname TEXT NOT NULL,
567
- projects TEXT NOT NULL DEFAULT '[]',
568
- agents TEXT NOT NULL DEFAULT '[]',
569
- connected INTEGER DEFAULT 0,
570
- last_seen TEXT NOT NULL
571
- );
572
- `);
573
- await client.executeMultiple(`
574
- CREATE TABLE IF NOT EXISTS messages (
575
- id TEXT PRIMARY KEY,
576
- from_agent TEXT NOT NULL,
577
- from_device TEXT NOT NULL DEFAULT 'local',
578
- target_agent TEXT NOT NULL,
579
- target_project TEXT,
580
- target_device TEXT NOT NULL DEFAULT 'local',
581
- content TEXT NOT NULL,
582
- priority TEXT DEFAULT 'normal',
583
- status TEXT DEFAULT 'pending',
584
- server_seq INTEGER,
585
- retry_count INTEGER DEFAULT 0,
586
- created_at TEXT NOT NULL,
587
- delivered_at TEXT,
588
- processed_at TEXT,
589
- failed_at TEXT,
590
- failure_reason TEXT
591
- );
592
-
593
- CREATE INDEX IF NOT EXISTS idx_messages_target
594
- ON messages(target_agent, status);
595
-
596
- CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
597
- ON messages(target_agent, from_agent, server_seq);
598
- `);
599
- try {
600
- await client.execute({
601
- sql: `UPDATE memories SET project_name = 'exe-create' WHERE project_name = 'web'`,
602
- args: []
603
- });
604
- await client.execute({
605
- sql: `UPDATE memories SET project_name = 'exe-os' WHERE project_name = 'worker'`,
606
- args: []
607
- });
608
- await client.execute({
609
- sql: `UPDATE tasks SET project_name = 'exe-create' WHERE project_name = 'web'`,
610
- args: []
611
- });
612
- await client.execute({
613
- sql: `UPDATE tasks SET project_name = 'exe-os' WHERE project_name = 'worker'`,
614
- args: []
615
- });
616
- } catch {
617
- }
618
- await client.executeMultiple(`
619
- CREATE TABLE IF NOT EXISTS trajectories (
620
- id TEXT PRIMARY KEY,
621
- task_id TEXT NOT NULL,
622
- agent_id TEXT NOT NULL,
623
- project_name TEXT NOT NULL,
624
- task_title TEXT NOT NULL,
625
- signature TEXT NOT NULL,
626
- signature_hash TEXT NOT NULL,
627
- tool_count INTEGER NOT NULL,
628
- skill_id TEXT,
629
- created_at TEXT NOT NULL
630
- );
631
-
632
- CREATE INDEX IF NOT EXISTS idx_trajectories_hash
633
- ON trajectories(signature_hash);
634
-
635
- CREATE INDEX IF NOT EXISTS idx_trajectories_agent
636
- ON trajectories(agent_id);
637
- `);
638
- try {
639
- await client.execute("ALTER TABLE trajectories ADD COLUMN skill_id TEXT");
640
- } catch {
641
- }
642
- await client.executeMultiple(`
643
- CREATE TABLE IF NOT EXISTS consolidations (
644
- id TEXT PRIMARY KEY,
645
- consolidated_memory_id TEXT NOT NULL,
646
- source_memory_id TEXT NOT NULL,
647
- created_at TEXT NOT NULL
648
- );
649
-
650
- CREATE INDEX IF NOT EXISTS idx_consolidations_source
651
- ON consolidations(source_memory_id);
652
- `);
653
- await client.executeMultiple(`
654
- CREATE TABLE IF NOT EXISTS audit_trail (
655
- id INTEGER PRIMARY KEY AUTOINCREMENT,
656
- timestamp TEXT NOT NULL,
657
- session_id TEXT NOT NULL,
658
- agent_id TEXT NOT NULL,
659
- tool TEXT NOT NULL,
660
- input TEXT,
661
- decision TEXT NOT NULL,
662
- reason TEXT,
663
- is_customer_facing INTEGER NOT NULL DEFAULT 0
664
- );
665
-
666
- CREATE INDEX IF NOT EXISTS idx_audit_trail_agent
667
- ON audit_trail(agent_id, timestamp);
668
-
669
- CREATE INDEX IF NOT EXISTS idx_audit_trail_session
670
- ON audit_trail(session_id);
671
- `);
672
- try {
673
- await client.execute({
674
- sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
675
- args: []
676
- });
677
- } catch {
678
- }
679
- try {
680
- await client.execute({
681
- sql: `ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5`,
682
- args: []
683
- });
684
- } catch {
685
- }
686
- try {
687
- await client.execute({
688
- sql: `ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'`,
689
- args: []
690
- });
691
- } catch {
692
- }
693
- try {
694
- await client.execute({
695
- sql: `ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7`,
696
- args: []
697
- });
698
- } catch {
699
- }
700
- try {
701
- await client.execute({
702
- sql: `ALTER TABLE memories ADD COLUMN last_accessed TEXT`,
703
- args: []
704
- });
705
- } catch {
706
- }
707
- try {
708
- await client.execute({
709
- sql: `UPDATE memories SET last_accessed = timestamp WHERE last_accessed IS NULL`,
710
- args: []
711
- });
712
- } catch {
713
- }
714
- try {
715
- await client.execute({
716
- sql: `ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0`,
717
- args: []
718
- });
719
- } catch {
720
- }
721
- try {
722
- await client.execute({
723
- sql: `ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0`,
724
- args: []
725
- });
726
- } catch {
727
- }
728
- for (const col of [
729
- "ALTER TABLE memories ADD COLUMN content_hash TEXT",
730
- "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT"
731
- ]) {
732
- try {
733
- await client.execute(col);
734
- } catch {
735
- }
736
- }
737
- await client.executeMultiple(`
738
- CREATE TABLE IF NOT EXISTS entities (
739
- id TEXT PRIMARY KEY,
740
- name TEXT NOT NULL,
741
- type TEXT NOT NULL,
742
- first_seen TEXT NOT NULL,
743
- last_seen TEXT NOT NULL,
744
- properties TEXT DEFAULT '{}',
745
- UNIQUE(name, type)
746
- );
747
-
748
- CREATE TABLE IF NOT EXISTS relationships (
749
- id TEXT PRIMARY KEY,
750
- source_entity_id TEXT NOT NULL,
751
- target_entity_id TEXT NOT NULL,
752
- type TEXT NOT NULL,
753
- weight REAL DEFAULT 1.0,
754
- timestamp TEXT NOT NULL,
755
- properties TEXT DEFAULT '{}',
756
- UNIQUE(source_entity_id, target_entity_id, type)
757
- );
758
-
759
- CREATE TABLE IF NOT EXISTS entity_memories (
760
- entity_id TEXT NOT NULL,
761
- memory_id TEXT NOT NULL,
762
- PRIMARY KEY (entity_id, memory_id)
763
- );
764
-
765
- CREATE TABLE IF NOT EXISTS relationship_memories (
766
- relationship_id TEXT NOT NULL,
767
- memory_id TEXT NOT NULL,
768
- PRIMARY KEY (relationship_id, memory_id)
769
- );
770
-
771
- CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
772
- CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
773
- CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
774
- CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
775
-
776
- CREATE TABLE IF NOT EXISTS hyperedges (
777
- id TEXT PRIMARY KEY,
778
- label TEXT NOT NULL,
779
- relation TEXT NOT NULL,
780
- confidence REAL DEFAULT 1.0,
781
- timestamp TEXT NOT NULL
782
- );
783
-
784
- CREATE TABLE IF NOT EXISTS hyperedge_nodes (
785
- hyperedge_id TEXT NOT NULL,
786
- entity_id TEXT NOT NULL,
787
- PRIMARY KEY (hyperedge_id, entity_id)
788
- );
789
- `);
790
- await client.executeMultiple(`
791
- CREATE TABLE IF NOT EXISTS entity_aliases (
792
- alias TEXT NOT NULL PRIMARY KEY,
793
- canonical_entity_id TEXT NOT NULL
794
- );
795
- CREATE INDEX IF NOT EXISTS idx_entity_aliases_canonical ON entity_aliases(canonical_entity_id);
796
- `);
797
- for (const col of [
798
- "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
799
- "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
800
- ]) {
801
- try {
802
- await client.execute(col);
803
- } catch {
804
- }
805
- }
806
- try {
807
- await client.execute(
808
- `CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)`
809
- );
810
- } catch {
811
- }
812
- await client.executeMultiple(`
813
- CREATE TABLE IF NOT EXISTS identity (
814
- id INTEGER PRIMARY KEY AUTOINCREMENT,
815
- agent_id TEXT NOT NULL UNIQUE,
816
- content_hash TEXT NOT NULL,
817
- updated_at TEXT NOT NULL,
818
- updated_by TEXT NOT NULL
819
- );
820
-
821
- CREATE INDEX IF NOT EXISTS idx_identity_agent ON identity(agent_id);
822
- `);
823
- await client.executeMultiple(`
824
- CREATE TABLE IF NOT EXISTS chat_history (
825
- id INTEGER PRIMARY KEY AUTOINCREMENT,
826
- session_id TEXT NOT NULL,
827
- role TEXT NOT NULL,
828
- content TEXT NOT NULL,
829
- tool_name TEXT,
830
- tool_id TEXT,
831
- is_error INTEGER NOT NULL DEFAULT 0,
832
- timestamp INTEGER NOT NULL
833
- );
834
-
835
- CREATE INDEX IF NOT EXISTS idx_chat_history_session
836
- ON chat_history(session_id, id);
837
- `);
838
- await client.executeMultiple(`
839
- CREATE TABLE IF NOT EXISTS workspaces (
840
- id TEXT PRIMARY KEY,
841
- slug TEXT NOT NULL UNIQUE,
842
- name TEXT NOT NULL,
843
- owner_agent_id TEXT,
844
- created_at TEXT NOT NULL,
845
- metadata TEXT
846
- );
847
-
848
- CREATE INDEX IF NOT EXISTS idx_workspaces_slug
849
- ON workspaces(slug);
850
- `);
851
- await client.executeMultiple(`
852
- CREATE TABLE IF NOT EXISTS documents (
853
- id TEXT PRIMARY KEY,
854
- workspace_id TEXT NOT NULL,
855
- filename TEXT NOT NULL,
856
- mime TEXT,
857
- source_type TEXT,
858
- user_id TEXT,
859
- uploaded_at TEXT NOT NULL,
860
- metadata TEXT,
861
- FOREIGN KEY (workspace_id) REFERENCES workspaces(id)
862
- );
863
-
864
- CREATE INDEX IF NOT EXISTS idx_documents_workspace
865
- ON documents(workspace_id);
866
-
867
- CREATE INDEX IF NOT EXISTS idx_documents_user
868
- ON documents(user_id);
869
- `);
870
- for (const column of [
871
- "workspace_id TEXT",
872
- "document_id TEXT",
873
- "user_id TEXT",
874
- "char_offset INTEGER",
875
- "page_number INTEGER"
876
- ]) {
877
- try {
878
- await client.execute({
879
- sql: `ALTER TABLE memories ADD COLUMN ${column}`,
880
- args: []
881
- });
882
- } catch {
883
- }
884
- }
885
- await client.executeMultiple(`
886
- CREATE INDEX IF NOT EXISTS idx_memories_workspace
887
- ON memories(workspace_id);
888
-
889
- CREATE INDEX IF NOT EXISTS idx_memories_document
890
- ON memories(document_id);
891
-
892
- CREATE INDEX IF NOT EXISTS idx_memories_user
893
- ON memories(user_id);
894
- `);
895
- await client.executeMultiple(`
896
- CREATE TABLE IF NOT EXISTS session_kills (
897
- id TEXT PRIMARY KEY,
898
- session_name TEXT NOT NULL,
899
- agent_id TEXT NOT NULL,
900
- killed_at TIMESTAMP NOT NULL,
901
- reason TEXT NOT NULL,
902
- ticks_idle INTEGER,
903
- estimated_tokens_saved INTEGER
904
- );
905
-
906
- CREATE INDEX IF NOT EXISTS idx_session_kills_killed_at
907
- ON session_kills(killed_at);
908
-
909
- CREATE INDEX IF NOT EXISTS idx_session_kills_agent
910
- ON session_kills(agent_id);
911
- `);
912
- await client.executeMultiple(`
913
- CREATE TABLE IF NOT EXISTS conversations (
914
- id TEXT PRIMARY KEY,
915
- platform TEXT NOT NULL,
916
- external_id TEXT,
917
- sender_id TEXT NOT NULL,
918
- sender_name TEXT,
919
- sender_phone TEXT,
920
- sender_email TEXT,
921
- recipient_id TEXT,
922
- channel_id TEXT NOT NULL,
923
- thread_id TEXT,
924
- reply_to_id TEXT,
925
- content_text TEXT,
926
- content_media TEXT,
927
- content_metadata TEXT,
928
- agent_response TEXT,
929
- agent_name TEXT,
930
- timestamp TEXT NOT NULL,
931
- ingested_at TEXT NOT NULL
932
- );
933
-
934
- CREATE INDEX IF NOT EXISTS idx_conversations_platform
935
- ON conversations(platform);
936
-
937
- CREATE INDEX IF NOT EXISTS idx_conversations_sender
938
- ON conversations(sender_id);
939
-
940
- CREATE INDEX IF NOT EXISTS idx_conversations_timestamp
941
- ON conversations(timestamp);
942
-
943
- CREATE INDEX IF NOT EXISTS idx_conversations_thread
944
- ON conversations(thread_id);
945
-
946
- CREATE INDEX IF NOT EXISTS idx_conversations_channel
947
- ON conversations(channel_id);
948
- `);
949
- await client.executeMultiple(`
950
- CREATE VIRTUAL TABLE IF NOT EXISTS conversations_fts USING fts5(
951
- content_text,
952
- sender_name,
953
- agent_response,
954
- content='conversations',
955
- content_rowid='rowid'
956
- );
957
-
958
- CREATE TRIGGER IF NOT EXISTS conversations_fts_ai AFTER INSERT ON conversations BEGIN
959
- INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
960
- VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
961
- END;
962
-
963
- CREATE TRIGGER IF NOT EXISTS conversations_fts_ad AFTER DELETE ON conversations BEGIN
964
- INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
965
- VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
966
- END;
967
-
968
- CREATE TRIGGER IF NOT EXISTS conversations_fts_au AFTER UPDATE ON conversations BEGIN
969
- INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
970
- VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
971
- INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
972
- VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
973
- END;
974
- `);
975
- }
976
- var _client, initTurso;
977
- var init_database = __esm({
978
- "src/lib/database.ts"() {
979
- "use strict";
980
- _client = null;
981
- initTurso = initDatabase;
982
- }
983
- });
984
-
985
- // src/lib/shard-manager.ts
986
- var shard_manager_exports = {};
987
- __export(shard_manager_exports, {
988
- disposeShards: () => disposeShards,
989
- ensureShardSchema: () => ensureShardSchema,
990
- getReadyShardClient: () => getReadyShardClient,
991
- getShardClient: () => getShardClient,
992
- getShardsDir: () => getShardsDir,
993
- initShardManager: () => initShardManager,
994
- isShardingEnabled: () => isShardingEnabled,
995
- listShards: () => listShards,
996
- shardExists: () => shardExists
997
- });
998
- import path3 from "path";
999
- import { existsSync as existsSync3, mkdirSync } from "fs";
1000
- import { createClient as createClient2 } from "@libsql/client";
1001
- function initShardManager(encryptionKey) {
1002
- _encryptionKey = encryptionKey;
1003
- if (!existsSync3(SHARDS_DIR)) {
1004
- mkdirSync(SHARDS_DIR, { recursive: true });
1005
- }
1006
- _shardingEnabled = true;
1007
- }
1008
- function isShardingEnabled() {
1009
- return _shardingEnabled;
1010
- }
1011
- function getShardsDir() {
1012
- return SHARDS_DIR;
1013
- }
1014
- function getShardClient(projectName) {
1015
- if (!_encryptionKey) {
1016
- throw new Error("Shard manager not initialized. Call initShardManager() first.");
1017
- }
1018
- const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1019
- if (!safeName) {
1020
- throw new Error(`Invalid project name for shard: "${projectName}"`);
1021
- }
1022
- const cached = _shards.get(safeName);
1023
- if (cached) return cached;
1024
- const dbPath = path3.join(SHARDS_DIR, `${safeName}.db`);
1025
- const client = createClient2({
1026
- url: `file:${dbPath}`,
1027
- encryptionKey: _encryptionKey
1028
- });
1029
- _shards.set(safeName, client);
1030
- return client;
1031
- }
1032
- function shardExists(projectName) {
1033
- const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1034
- return existsSync3(path3.join(SHARDS_DIR, `${safeName}.db`));
1035
- }
1036
- function listShards() {
1037
- if (!existsSync3(SHARDS_DIR)) return [];
1038
- const { readdirSync: readdirSync5 } = __require("fs");
1039
- return readdirSync5(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
1040
- }
1041
- async function ensureShardSchema(client) {
1042
- await client.execute("PRAGMA journal_mode = WAL");
1043
- await client.execute("PRAGMA busy_timeout = 5000");
1044
- try {
1045
- await client.execute("PRAGMA libsql_vector_search_ef = 128");
1046
- } catch {
1047
- }
1048
- await client.executeMultiple(`
1049
- CREATE TABLE IF NOT EXISTS memories (
1050
- id TEXT PRIMARY KEY,
1051
- agent_id TEXT NOT NULL,
1052
- agent_role TEXT NOT NULL,
1053
- session_id TEXT NOT NULL,
1054
- timestamp TEXT NOT NULL,
1055
- tool_name TEXT NOT NULL,
1056
- project_name TEXT NOT NULL,
1057
- has_error INTEGER NOT NULL DEFAULT 0,
1058
- raw_text TEXT NOT NULL,
1059
- vector F32_BLOB(1024),
1060
- version INTEGER NOT NULL DEFAULT 0
1061
- );
1062
-
1063
- CREATE INDEX IF NOT EXISTS idx_memories_agent ON memories(agent_id);
1064
- CREATE INDEX IF NOT EXISTS idx_memories_timestamp ON memories(timestamp);
1065
- CREATE INDEX IF NOT EXISTS idx_memories_agent_project ON memories(agent_id, project_name);
1066
- `);
1067
- await client.executeMultiple(`
1068
- CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
1069
- raw_text,
1070
- content='memories',
1071
- content_rowid='rowid'
1072
- );
1073
-
1074
- CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
1075
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1076
- END;
1077
-
1078
- CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
1079
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1080
- END;
1081
-
1082
- CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
1083
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1084
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1085
- END;
1086
- `);
1087
- for (const col of [
1088
- "ALTER TABLE memories ADD COLUMN task_id TEXT",
1089
- "ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
1090
- "ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
1091
- "ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
1092
- "ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
1093
- "ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0",
1094
- "ALTER TABLE memories ADD COLUMN content_hash TEXT",
1095
- "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT",
1096
- "ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7",
1097
- "ALTER TABLE memories ADD COLUMN last_accessed TEXT",
1098
- // Wiki linkage columns (must match database.ts)
1099
- "ALTER TABLE memories ADD COLUMN workspace_id TEXT",
1100
- "ALTER TABLE memories ADD COLUMN document_id TEXT",
1101
- "ALTER TABLE memories ADD COLUMN user_id TEXT",
1102
- "ALTER TABLE memories ADD COLUMN char_offset INTEGER",
1103
- "ALTER TABLE memories ADD COLUMN page_number INTEGER"
1104
- ]) {
1105
- try {
1106
- await client.execute(col);
1107
- } catch {
1108
- }
1109
- }
1110
- try {
1111
- await client.execute("CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)");
1112
- } catch {
1113
- }
1114
- for (const idx of [
1115
- "CREATE INDEX IF NOT EXISTS idx_memories_workspace ON memories(workspace_id)",
1116
- "CREATE INDEX IF NOT EXISTS idx_memories_document ON memories(document_id)",
1117
- "CREATE INDEX IF NOT EXISTS idx_memories_user ON memories(user_id)"
1118
- ]) {
1119
- try {
1120
- await client.execute(idx);
1121
- } catch {
1122
- }
1123
- }
1124
- await client.executeMultiple(`
1125
- CREATE TABLE IF NOT EXISTS entities (
1126
- id TEXT PRIMARY KEY,
1127
- name TEXT NOT NULL,
1128
- type TEXT NOT NULL,
1129
- first_seen TEXT NOT NULL,
1130
- last_seen TEXT NOT NULL,
1131
- properties TEXT DEFAULT '{}',
1132
- UNIQUE(name, type)
1133
- );
1134
-
1135
- CREATE TABLE IF NOT EXISTS relationships (
1136
- id TEXT PRIMARY KEY,
1137
- source_entity_id TEXT NOT NULL,
1138
- target_entity_id TEXT NOT NULL,
1139
- type TEXT NOT NULL,
1140
- weight REAL DEFAULT 1.0,
1141
- timestamp TEXT NOT NULL,
1142
- properties TEXT DEFAULT '{}',
1143
- UNIQUE(source_entity_id, target_entity_id, type)
1144
- );
1145
-
1146
- CREATE TABLE IF NOT EXISTS entity_memories (
1147
- entity_id TEXT NOT NULL,
1148
- memory_id TEXT NOT NULL,
1149
- PRIMARY KEY (entity_id, memory_id)
1150
- );
1151
-
1152
- CREATE TABLE IF NOT EXISTS relationship_memories (
1153
- relationship_id TEXT NOT NULL,
1154
- memory_id TEXT NOT NULL,
1155
- PRIMARY KEY (relationship_id, memory_id)
1156
- );
1157
-
1158
- CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
1159
- CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
1160
- CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
1161
- CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
1162
- CREATE INDEX IF NOT EXISTS idx_relationships_type ON relationships(type);
1163
-
1164
- CREATE TABLE IF NOT EXISTS hyperedges (
1165
- id TEXT PRIMARY KEY,
1166
- label TEXT NOT NULL,
1167
- relation TEXT NOT NULL,
1168
- confidence REAL DEFAULT 1.0,
1169
- timestamp TEXT NOT NULL
1170
- );
1171
-
1172
- CREATE TABLE IF NOT EXISTS hyperedge_nodes (
1173
- hyperedge_id TEXT NOT NULL,
1174
- entity_id TEXT NOT NULL,
1175
- PRIMARY KEY (hyperedge_id, entity_id)
1176
- );
1177
- `);
1178
- for (const col of [
1179
- "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
1180
- "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
1181
- ]) {
1182
- try {
1183
- await client.execute(col);
1184
- } catch {
1185
- }
1186
- }
1187
- }
1188
- async function getReadyShardClient(projectName) {
1189
- const client = getShardClient(projectName);
1190
- await ensureShardSchema(client);
1191
- return client;
1192
- }
1193
- function disposeShards() {
1194
- for (const [, client] of _shards) {
1195
- client.close();
1196
- }
1197
- _shards.clear();
1198
- _shardingEnabled = false;
1199
- _encryptionKey = null;
1200
- }
1201
- var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
1202
- var init_shard_manager = __esm({
1203
- "src/lib/shard-manager.ts"() {
1204
- "use strict";
1205
- init_config();
1206
- SHARDS_DIR = path3.join(EXE_AI_DIR, "shards");
1207
- _shards = /* @__PURE__ */ new Map();
1208
- _encryptionKey = null;
1209
- _shardingEnabled = false;
1210
- }
1211
- });
1212
-
1213
- // src/lib/self-query-router.ts
1214
- var self_query_router_exports = {};
1215
- __export(self_query_router_exports, {
1216
- routeQuery: () => routeQuery
1217
- });
1218
- async function routeQuery(query, model = "claude-haiku-4-5-20251001") {
1219
- if (query.length < 10) {
1220
- return {
1221
- semanticQuery: query,
1222
- projectFilter: null,
1223
- roleFilter: null,
1224
- timeFilter: null,
1225
- isBroadQuery: false
1226
- };
1227
- }
1228
- try {
1229
- const Anthropic = (await import("@anthropic-ai/sdk")).default;
1230
- const client = new Anthropic();
1231
- const now = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
1232
- const response = await client.messages.create({
1233
- model,
1234
- max_tokens: 256,
1235
- system: `You are a search query router. Extract metadata filters from the user's memory search query. Today is ${now}. Convert relative time references (yesterday, last week) to ISO timestamps.`,
1236
- messages: [{ role: "user", content: query }],
1237
- tools: [EXTRACT_TOOL],
1238
- tool_choice: { type: "tool", name: "extract_search_filters" }
1239
- });
1240
- const toolBlock = response.content.find((b) => b.type === "tool_use");
1241
- if (toolBlock && toolBlock.type === "tool_use") {
1242
- const input2 = toolBlock.input;
1243
- return {
1244
- semanticQuery: input2.semantic_query || query,
1245
- projectFilter: input2.project_filter || null,
1246
- roleFilter: input2.role_filter || null,
1247
- timeFilter: input2.time_filter || null,
1248
- isBroadQuery: Boolean(input2.is_broad_query)
1249
- };
1250
- }
1251
- } catch (err) {
1252
- process.stderr.write(
1253
- `[self-query-router] LLM extraction failed, using passthrough: ${err instanceof Error ? err.message : String(err)}
1254
- `
1255
- );
1256
- }
1257
- return {
1258
- semanticQuery: query,
1259
- projectFilter: null,
1260
- roleFilter: null,
1261
- timeFilter: null,
1262
- isBroadQuery: false
1263
- };
1264
- }
1265
- var EXTRACT_TOOL;
1266
- var init_self_query_router = __esm({
1267
- "src/lib/self-query-router.ts"() {
1268
- "use strict";
1269
- EXTRACT_TOOL = {
1270
- name: "extract_search_filters",
1271
- description: "Extract metadata filters from a memory search query to improve retrieval precision.",
1272
- input_schema: {
1273
- type: "object",
1274
- properties: {
1275
- semantic_query: {
1276
- type: "string",
1277
- description: "The core semantic meaning of the query, stripped of metadata references. This is used for embedding search."
1278
- },
1279
- project_filter: {
1280
- type: ["string", "null"],
1281
- description: "Project name if the query references a specific project (e.g., 'exe-os', 'exe-create'). Null if no project specified."
1282
- },
1283
- role_filter: {
1284
- type: ["string", "null"],
1285
- description: "Agent role if the query targets a specific role (e.g., 'CTO', 'CMO'). Null if no role specified."
1286
- },
1287
- time_filter: {
1288
- type: ["string", "null"],
1289
- description: "ISO 8601 timestamp lower bound if the query references a time period (e.g., 'last week', 'yesterday'). Null if no time reference."
1290
- },
1291
- is_broad_query: {
1292
- type: "boolean",
1293
- description: "True if the query is exploratory/broad (e.g., 'what has yoshi been working on', 'summarize recent activity'). False if targeted (e.g., 'how did we fix the auth bug')."
1294
- }
1295
- },
1296
- required: ["semantic_query", "project_filter", "role_filter", "time_filter", "is_broad_query"]
1297
- }
1298
- };
1299
- }
1300
- });
1301
-
1302
- // src/lib/exe-daemon-client.ts
1303
- import net from "net";
1304
- import { spawn } from "child_process";
1305
- import { randomUUID } from "crypto";
1306
- import { existsSync as existsSync4, unlinkSync, readFileSync as readFileSync2, openSync, closeSync, statSync } from "fs";
1307
- import path4 from "path";
1308
- import { fileURLToPath } from "url";
1309
- function handleData(chunk) {
1310
- _buffer += chunk.toString();
1311
- let newlineIdx;
1312
- while ((newlineIdx = _buffer.indexOf("\n")) !== -1) {
1313
- const line = _buffer.slice(0, newlineIdx).trim();
1314
- _buffer = _buffer.slice(newlineIdx + 1);
1315
- if (!line) continue;
1316
- try {
1317
- const response = JSON.parse(line);
1318
- const entry = _pending.get(response.id);
1319
- if (entry) {
1320
- clearTimeout(entry.timer);
1321
- _pending.delete(response.id);
1322
- entry.resolve(response);
1323
- }
1324
- } catch {
1325
- }
1326
- }
1327
- }
1328
- function cleanupStaleFiles() {
1329
- if (existsSync4(PID_PATH)) {
1330
- try {
1331
- const pid = parseInt(readFileSync2(PID_PATH, "utf8").trim(), 10);
1332
- if (pid > 0) {
1333
- try {
1334
- process.kill(pid, 0);
1335
- return;
1336
- } catch {
1337
- }
1338
- }
1339
- } catch {
1340
- }
1341
- try {
1342
- unlinkSync(PID_PATH);
1343
- } catch {
1344
- }
1345
- try {
1346
- unlinkSync(SOCKET_PATH);
1347
- } catch {
1348
- }
1349
- }
1350
- }
1351
- function findPackageRoot() {
1352
- let dir = path4.dirname(fileURLToPath(import.meta.url));
1353
- const { root } = path4.parse(dir);
1354
- while (dir !== root) {
1355
- if (existsSync4(path4.join(dir, "package.json"))) return dir;
1356
- dir = path4.dirname(dir);
1357
- }
1358
- return null;
1359
- }
1360
- function spawnDaemon() {
1361
- const pkgRoot = findPackageRoot();
1362
- if (!pkgRoot) {
1363
- process.stderr.write("[exed-client] WARN: cannot find package root\n");
1364
- return;
1365
- }
1366
- const daemonPath = path4.join(pkgRoot, "dist", "lib", "exe-daemon.js");
1367
- if (!existsSync4(daemonPath)) {
1368
- process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
1369
- `);
1370
- return;
1371
- }
1372
- const resolvedPath = daemonPath;
1373
- process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
1374
- `);
1375
- const logPath = path4.join(path4.dirname(SOCKET_PATH), "exed.log");
1376
- let stderrFd = "ignore";
1377
- try {
1378
- stderrFd = openSync(logPath, "a");
1379
- } catch {
1380
- }
1381
- const child = spawn(process.execPath, [resolvedPath], {
1382
- detached: true,
1383
- stdio: ["ignore", "ignore", stderrFd],
1384
- env: {
1385
- ...process.env,
1386
- EXE_DAEMON_SOCK: SOCKET_PATH,
1387
- EXE_DAEMON_PID: PID_PATH
1388
- }
1389
- });
1390
- child.unref();
1391
- if (typeof stderrFd === "number") {
1392
- try {
1393
- closeSync(stderrFd);
1394
- } catch {
1395
- }
1396
- }
1397
- }
1398
- function acquireSpawnLock() {
1399
- try {
1400
- const fd = openSync(SPAWN_LOCK_PATH, "wx");
1401
- closeSync(fd);
1402
- return true;
1403
- } catch {
1404
- try {
1405
- const stat = statSync(SPAWN_LOCK_PATH);
1406
- if (Date.now() - stat.mtimeMs > SPAWN_LOCK_STALE_MS) {
1407
- try {
1408
- unlinkSync(SPAWN_LOCK_PATH);
1409
- } catch {
1410
- }
1411
- try {
1412
- const fd = openSync(SPAWN_LOCK_PATH, "wx");
1413
- closeSync(fd);
1414
- return true;
1415
- } catch {
1416
- }
1417
- }
1418
- } catch {
1419
- }
1420
- return false;
1421
- }
1422
- }
1423
- function releaseSpawnLock() {
1424
- try {
1425
- unlinkSync(SPAWN_LOCK_PATH);
1426
- } catch {
1427
- }
1428
- }
1429
- function connectToSocket() {
1430
- return new Promise((resolve) => {
1431
- if (_socket && _connected) {
1432
- resolve(true);
1433
- return;
1434
- }
1435
- const socket = net.createConnection({ path: SOCKET_PATH });
1436
- const connectTimeout = setTimeout(() => {
1437
- socket.destroy();
1438
- resolve(false);
1439
- }, 2e3);
1440
- socket.on("connect", () => {
1441
- clearTimeout(connectTimeout);
1442
- _socket = socket;
1443
- _connected = true;
1444
- _buffer = "";
1445
- socket.on("data", handleData);
1446
- socket.on("close", () => {
1447
- _connected = false;
1448
- _socket = null;
1449
- for (const [id, entry] of _pending) {
1450
- clearTimeout(entry.timer);
1451
- _pending.delete(id);
1452
- entry.resolve({ error: "Connection closed" });
1453
- }
1454
- });
1455
- socket.on("error", () => {
1456
- _connected = false;
1457
- _socket = null;
1458
- });
1459
- resolve(true);
1460
- });
1461
- socket.on("error", () => {
1462
- clearTimeout(connectTimeout);
1463
- resolve(false);
1464
- });
1465
- });
1466
- }
1467
- async function connectEmbedDaemon() {
1468
- if (_socket && _connected) return true;
1469
- if (await connectToSocket()) return true;
1470
- if (acquireSpawnLock()) {
1471
- try {
1472
- cleanupStaleFiles();
1473
- spawnDaemon();
1474
- } finally {
1475
- releaseSpawnLock();
1476
- }
1477
- }
1478
- const start = Date.now();
1479
- let delay = 100;
1480
- while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1481
- await new Promise((r) => setTimeout(r, delay));
1482
- if (await connectToSocket()) return true;
1483
- delay = Math.min(delay * 2, 3e3);
1484
- }
1485
- return false;
1486
- }
1487
- function sendRequest(texts, priority) {
1488
- return new Promise((resolve) => {
1489
- if (!_socket || !_connected) {
1490
- resolve({ error: "Not connected" });
1491
- return;
1492
- }
1493
- const id = randomUUID();
1494
- const timer = setTimeout(() => {
1495
- _pending.delete(id);
1496
- resolve({ error: "Request timeout" });
1497
- }, REQUEST_TIMEOUT_MS);
1498
- _pending.set(id, { resolve, timer });
1499
- try {
1500
- _socket.write(JSON.stringify({ id, texts, priority }) + "\n");
1501
- } catch {
1502
- clearTimeout(timer);
1503
- _pending.delete(id);
1504
- resolve({ error: "Write failed" });
1505
- }
1506
- });
1507
- }
1508
- async function pingDaemon() {
1509
- if (!_socket || !_connected) return null;
1510
- return new Promise((resolve) => {
1511
- const id = randomUUID();
1512
- const timer = setTimeout(() => {
1513
- _pending.delete(id);
1514
- resolve(null);
1515
- }, 5e3);
1516
- _pending.set(id, {
1517
- resolve: (data) => {
1518
- if (data.health) {
1519
- resolve(data.health);
1520
- } else {
1521
- resolve(null);
1522
- }
1523
- },
1524
- timer
1525
- });
1526
- try {
1527
- _socket.write(JSON.stringify({ id, type: "health" }) + "\n");
1528
- } catch {
1529
- clearTimeout(timer);
1530
- _pending.delete(id);
1531
- resolve(null);
1532
- }
1533
- });
1534
- }
1535
- function killAndRespawnDaemon() {
1536
- process.stderr.write("[exed-client] Killing daemon for restart...\n");
1537
- if (existsSync4(PID_PATH)) {
1538
- try {
1539
- const pid = parseInt(readFileSync2(PID_PATH, "utf8").trim(), 10);
1540
- if (pid > 0) {
1541
- try {
1542
- process.kill(pid, "SIGKILL");
1543
- } catch {
1544
- }
1545
- }
1546
- } catch {
1547
- }
1548
- }
1549
- if (_socket) {
1550
- _socket.destroy();
1551
- _socket = null;
1552
- }
1553
- _connected = false;
1554
- _buffer = "";
1555
- try {
1556
- unlinkSync(PID_PATH);
1557
- } catch {
1558
- }
1559
- try {
1560
- unlinkSync(SOCKET_PATH);
1561
- } catch {
1562
- }
1563
- spawnDaemon();
1564
- }
1565
- async function embedViaClient(text, priority = "high") {
1566
- if (!_connected && !await connectEmbedDaemon()) return null;
1567
- _requestCount++;
1568
- if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
1569
- const health = await pingDaemon();
1570
- if (!health) {
1571
- process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
1572
- `);
1573
- killAndRespawnDaemon();
1574
- const start = Date.now();
1575
- let delay = 200;
1576
- while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1577
- await new Promise((r) => setTimeout(r, delay));
1578
- if (await connectToSocket()) break;
1579
- delay = Math.min(delay * 2, 3e3);
1580
- }
1581
- if (!_connected) return null;
1582
- }
1583
- }
1584
- const result = await sendRequest([text], priority);
1585
- if (!result.error && result.vectors?.[0]) return result.vectors[0];
1586
- if (result.error) {
1587
- process.stderr.write(`[exed-client] Embed failed (${result.error}) \u2014 attempting restart
1588
- `);
1589
- killAndRespawnDaemon();
1590
- const start = Date.now();
1591
- let delay = 200;
1592
- while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1593
- await new Promise((r) => setTimeout(r, delay));
1594
- if (await connectToSocket()) break;
1595
- delay = Math.min(delay * 2, 3e3);
1596
- }
1597
- if (!_connected) return null;
1598
- const retry = await sendRequest([text], priority);
1599
- if (!retry.error && retry.vectors?.[0]) return retry.vectors[0];
1600
- process.stderr.write(`[exed-client] Embed retry also failed: ${retry.error ?? "no vector"}
1601
- `);
1602
- }
1603
- return null;
1604
- }
1605
- function disconnectClient() {
1606
- if (_socket) {
1607
- _socket.destroy();
1608
- _socket = null;
1609
- }
1610
- _connected = false;
1611
- _buffer = "";
1612
- for (const [id, entry] of _pending) {
1613
- clearTimeout(entry.timer);
1614
- _pending.delete(id);
1615
- entry.resolve({ error: "Client disconnected" });
1616
- }
1617
- }
1618
- 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;
1619
- var init_exe_daemon_client = __esm({
1620
- "src/lib/exe-daemon-client.ts"() {
1621
- "use strict";
1622
- init_config();
1623
- SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path4.join(EXE_AI_DIR, "exed.sock");
1624
- PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path4.join(EXE_AI_DIR, "exed.pid");
1625
- SPAWN_LOCK_PATH = path4.join(EXE_AI_DIR, "exed-spawn.lock");
1626
- SPAWN_LOCK_STALE_MS = 3e4;
1627
- CONNECT_TIMEOUT_MS = 15e3;
1628
- REQUEST_TIMEOUT_MS = 3e4;
1629
- _socket = null;
1630
- _connected = false;
1631
- _buffer = "";
1632
- _requestCount = 0;
1633
- HEALTH_CHECK_INTERVAL = 100;
1634
- _pending = /* @__PURE__ */ new Map();
1635
- }
1636
- });
1637
-
1638
- // src/lib/embedder.ts
1639
- var embedder_exports = {};
1640
- __export(embedder_exports, {
1641
- disposeEmbedder: () => disposeEmbedder,
1642
- embed: () => embed,
1643
- embedDirect: () => embedDirect,
1644
- getEmbedder: () => getEmbedder
1645
- });
1646
- async function getEmbedder() {
1647
- const ok = await connectEmbedDaemon();
1648
- if (!ok) {
1649
- throw new Error(
1650
- "Could not connect to embedding daemon. Ensure the model is installed (run /exe-setup)."
1651
- );
1652
- }
1653
- }
1654
- async function embed(text) {
1655
- const priority = process.env.EXE_EMBED_PRIORITY === "low" ? "low" : "high";
1656
- const vector = await embedViaClient(text, priority);
1657
- if (!vector) {
1658
- throw new Error(
1659
- "Embedding failed: daemon unavailable. Run /exe-setup to verify model installation."
1660
- );
1661
- }
1662
- if (vector.length !== EMBEDDING_DIM) {
1663
- throw new Error(
1664
- `Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}. Ensure the correct Jina v5-small Q4_K_M GGUF model is installed.`
1665
- );
1666
- }
1667
- return vector;
1668
- }
1669
- async function disposeEmbedder() {
1670
- disconnectClient();
1671
- }
1672
- async function embedDirect(text) {
1673
- const llamaCpp = await import("node-llama-cpp");
1674
- const { MODELS_DIR: MODELS_DIR2 } = await Promise.resolve().then(() => (init_config(), config_exports));
1675
- const { existsSync: existsSync18 } = await import("fs");
1676
- const path20 = await import("path");
1677
- const modelPath = path20.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
1678
- if (!existsSync18(modelPath)) {
1679
- throw new Error(`Embedding model not found at ${modelPath}. Run '/exe-setup' to download it.`);
1680
- }
1681
- const llama = await llamaCpp.getLlama();
1682
- const model = await llama.loadModel({ modelPath });
1683
- const context = await model.createEmbeddingContext();
1684
- try {
1685
- const embedding = await context.getEmbeddingFor(text);
1686
- const vector = Array.from(embedding.vector);
1687
- if (vector.length !== EMBEDDING_DIM) {
1688
- throw new Error(
1689
- `Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}.`
1690
- );
1691
- }
1692
- return vector;
1693
- } finally {
1694
- await context.dispose();
1695
- await model.dispose();
1696
- }
1697
- }
1698
- var init_embedder = __esm({
1699
- "src/lib/embedder.ts"() {
1700
- "use strict";
1701
- init_memory();
1702
- init_exe_daemon_client();
1703
- }
1704
- });
1705
-
1706
- // src/lib/project-name.ts
1707
- var project_name_exports = {};
1708
- __export(project_name_exports, {
1709
- _resetCache: () => _resetCache,
1710
- getProjectName: () => getProjectName
1711
- });
1712
- import { execSync } from "child_process";
1713
- import path5 from "path";
1714
- function getProjectName(cwd) {
1715
- const dir = cwd ?? process.cwd();
1716
- if (_cached && _cachedCwd === dir) return _cached;
1717
- try {
1718
- const repoRoot = execSync("git rev-parse --show-toplevel", {
1719
- cwd: dir,
1720
- encoding: "utf8",
1721
- timeout: 2e3,
1722
- stdio: ["pipe", "pipe", "pipe"]
1723
- }).trim();
1724
- _cached = path5.basename(repoRoot);
1725
- _cachedCwd = dir;
1726
- return _cached;
1727
- } catch {
1728
- _cached = path5.basename(dir);
1729
- _cachedCwd = dir;
1730
- return _cached;
1731
- }
1732
- }
1733
- function _resetCache() {
1734
- _cached = null;
1735
- _cachedCwd = null;
1736
- }
1737
- var _cached, _cachedCwd;
1738
- var init_project_name = __esm({
1739
- "src/lib/project-name.ts"() {
1740
- "use strict";
1741
- _cached = null;
1742
- _cachedCwd = null;
1743
- }
1744
- });
1745
-
1746
- // src/lib/file-grep.ts
1747
- var file_grep_exports = {};
1748
- __export(file_grep_exports, {
1749
- grepProjectFiles: () => grepProjectFiles
1750
- });
1751
- import { execSync as execSync2 } from "child_process";
1752
- import { readFileSync as readFileSync3, readdirSync, statSync as statSync2, existsSync as existsSync5 } from "fs";
1753
- import path6 from "path";
1754
- import crypto2 from "crypto";
1755
- async function grepProjectFiles(query, projectRoot, options) {
1756
- const maxResults = options?.maxResults ?? 10;
1757
- const terms = query.toLowerCase().split(/\s+/).filter((t) => t.length >= 3).map((t) => t.replace(/[^a-z0-9_-]/g, "")).filter((t) => t.length >= 3);
1758
- if (terms.length === 0) return [];
1759
- const pattern = terms.join("|");
1760
- let hits;
1761
- try {
1762
- hits = grepWithRipgrep(pattern, projectRoot, options?.patterns);
1763
- } catch {
1764
- hits = grepWithNodeFs(pattern, projectRoot, options?.patterns);
1765
- }
1766
- hits.sort((a, b) => b.density - a.density);
1767
- const topHits = hits.slice(0, maxResults);
1768
- return topHits.map((hit) => {
1769
- const chunkCtx = getChunkContext(hit.filePath, hit.lineNumber);
1770
- const prefix = chunkCtx ? `[file: ${hit.filePath}:${hit.lineNumber} in ${chunkCtx}]` : `[file: ${hit.filePath}:${hit.lineNumber}]`;
1771
- return {
1772
- id: crypto2.createHash("sha256").update(`${hit.filePath}:${hit.lineNumber}`).digest("hex").slice(0, 36),
1773
- agent_id: "project",
1774
- agent_role: "file",
1775
- session_id: "file-grep",
1776
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1777
- tool_name: "file_grep",
1778
- project_name: path6.basename(projectRoot),
1779
- has_error: false,
1780
- raw_text: `${prefix} ${buildSnippet(hit, projectRoot)}`,
1781
- vector: null,
1782
- task_id: null
1783
- };
1784
- });
1785
- }
1786
- function getChunkContext(filePath, lineNumber) {
1787
- try {
1788
- const ext = filePath.split(".").pop()?.toLowerCase();
1789
- if (ext !== "ts" && ext !== "tsx" && ext !== "js" && ext !== "jsx") return "";
1790
- const source = readFileSync3(filePath, "utf8");
1791
- const lines = source.split("\n");
1792
- for (let i = Math.min(lineNumber - 1, lines.length - 1); i >= 0; i--) {
1793
- const line = lines[i];
1794
- const fnMatch = line.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);
1795
- if (fnMatch) return `function ${fnMatch[1]}`;
1796
- const classMatch = line.match(/(?:export\s+)?class\s+(\w+)/);
1797
- if (classMatch) return `class ${classMatch[1]}`;
1798
- const arrowMatch = line.match(/(?:export\s+)?(?:const|let)\s+(\w+)\s*=\s*(?:async\s+)?\(/);
1799
- if (arrowMatch) return `function ${arrowMatch[1]}`;
1800
- }
1801
- } catch {
1802
- }
1803
- return "";
1804
- }
1805
- function grepWithRipgrep(pattern, projectRoot, patterns) {
1806
- const globs = (patterns ?? DEFAULT_PATTERNS).map((p) => `--glob '${p}'`).join(" ");
1807
- const excludes = EXCLUDE_DIRS.map((d) => `--glob '!${d}'`).join(" ");
1808
- const cmd = `rg -i -c --hidden '${pattern.replace(/'/g, "\\'")}' . ${globs} ${excludes} --max-filesize ${MAX_FILE_SIZE} 2>/dev/null || true`;
1809
- const output = execSync2(cmd, {
1810
- cwd: projectRoot,
1811
- encoding: "utf8",
1812
- timeout: 3e3,
1813
- maxBuffer: 1024 * 1024
1814
- });
1815
- if (!output.trim()) return [];
1816
- const hits = [];
1817
- for (const line of output.trim().split("\n")) {
1818
- const colonIdx = line.lastIndexOf(":");
1819
- if (colonIdx === -1) continue;
1820
- const filePath = line.slice(0, colonIdx);
1821
- const matchCount = parseInt(line.slice(colonIdx + 1));
1822
- if (isNaN(matchCount) || matchCount === 0) continue;
1823
- try {
1824
- const firstMatch = execSync2(
1825
- `rg -i -n --hidden '${pattern.replace(/'/g, "\\'")}' '${filePath}' --max-count 1 2>/dev/null | head -1`,
1826
- { cwd: projectRoot, encoding: "utf8", timeout: 1e3 }
1827
- ).trim();
1828
- const lineNum = parseInt(firstMatch.split(":")[0] ?? "1");
1829
- const totalLines = execSync2(`wc -l < '${filePath}'`, {
1830
- cwd: projectRoot,
1831
- encoding: "utf8",
1832
- timeout: 1e3
1833
- }).trim();
1834
- hits.push({
1835
- filePath,
1836
- lineNumber: isNaN(lineNum) ? 1 : lineNum,
1837
- matchLine: firstMatch.slice(firstMatch.indexOf(":") + 1).slice(0, 200),
1838
- matchCount,
1839
- totalLines: parseInt(totalLines) || 1,
1840
- density: matchCount / (parseInt(totalLines) || 1)
1841
- });
1842
- } catch {
1843
- }
1844
- }
1845
- return hits;
1846
- }
1847
- function grepWithNodeFs(pattern, projectRoot, patterns) {
1848
- const regex = new RegExp(pattern, "gi");
1849
- const files = collectFiles(projectRoot, patterns ?? DEFAULT_PATTERNS);
1850
- const hits = [];
1851
- for (const filePath of files.slice(0, MAX_FILES)) {
1852
- const absPath = path6.join(projectRoot, filePath);
1853
- try {
1854
- const stat = statSync2(absPath);
1855
- if (stat.size > MAX_FILE_SIZE) continue;
1856
- const content = readFileSync3(absPath, "utf8");
1857
- const lines = content.split("\n");
1858
- const matches = content.match(regex);
1859
- if (!matches || matches.length === 0) continue;
1860
- const firstMatchIdx = lines.findIndex((l) => regex.test(l));
1861
- regex.lastIndex = 0;
1862
- hits.push({
1863
- filePath,
1864
- lineNumber: firstMatchIdx >= 0 ? firstMatchIdx + 1 : 1,
1865
- matchLine: firstMatchIdx >= 0 ? lines[firstMatchIdx].slice(0, 200) : "",
1866
- matchCount: matches.length,
1867
- totalLines: lines.length,
1868
- density: matches.length / lines.length
1869
- });
1870
- } catch {
1871
- }
1872
- }
1873
- return hits;
1874
- }
1875
- function collectFiles(root, patterns) {
1876
- const files = [];
1877
- function walk(dir, relative) {
1878
- if (files.length >= MAX_FILES) return;
1879
- const basename = path6.basename(dir);
1880
- if (EXCLUDE_DIRS.includes(basename)) return;
1881
- try {
1882
- const entries = readdirSync(dir, { withFileTypes: true });
1883
- for (const entry of entries) {
1884
- if (files.length >= MAX_FILES) return;
1885
- const rel = path6.join(relative, entry.name);
1886
- if (entry.isDirectory()) {
1887
- walk(path6.join(dir, entry.name), rel);
1888
- } else if (entry.isFile()) {
1889
- for (const pat of patterns) {
1890
- if (matchGlob(rel, pat)) {
1891
- files.push(rel);
1892
- break;
1893
- }
1894
- }
1895
- }
1896
- }
1897
- } catch {
1898
- }
1899
- }
1900
- walk(root, "");
1901
- return files;
1902
- }
1903
- function matchGlob(filePath, pattern) {
1904
- if (!pattern.includes("*")) return filePath === pattern;
1905
- const doubleStarMatch = pattern.match(/^(.+?)\/\*\*\/\*(\.\w+)$/);
1906
- if (doubleStarMatch) {
1907
- const dir = doubleStarMatch[1];
1908
- const ext2 = doubleStarMatch[2];
1909
- return filePath.startsWith(dir + "/") && filePath.endsWith(ext2);
1910
- }
1911
- if (pattern.startsWith("**/")) {
1912
- const ext2 = pattern.slice(3).replace("*", "");
1913
- return filePath.endsWith(ext2);
1914
- }
1915
- const slashIdx = pattern.lastIndexOf("/");
1916
- if (slashIdx !== -1) {
1917
- const dir = pattern.slice(0, slashIdx);
1918
- const ext2 = pattern.slice(slashIdx + 1).replace("*", "");
1919
- const fileDir = path6.dirname(filePath);
1920
- return fileDir === dir && filePath.endsWith(ext2);
1921
- }
1922
- const ext = pattern.replace("*", "");
1923
- return filePath.endsWith(ext) && !filePath.includes("/");
1924
- }
1925
- function buildSnippet(hit, projectRoot) {
1926
- try {
1927
- const absPath = path6.join(projectRoot, hit.filePath);
1928
- if (!existsSync5(absPath)) return hit.matchLine;
1929
- const lines = readFileSync3(absPath, "utf8").split("\n");
1930
- const start = Math.max(0, hit.lineNumber - 3);
1931
- const end = Math.min(lines.length, hit.lineNumber + 2);
1932
- return lines.slice(start, end).join("\n").slice(0, 500);
1933
- } catch {
1934
- return hit.matchLine;
1935
- }
1936
- }
1937
- var DEFAULT_PATTERNS, EXCLUDE_DIRS, MAX_FILE_SIZE, MAX_FILES;
1938
- var init_file_grep = __esm({
1939
- "src/lib/file-grep.ts"() {
1940
- "use strict";
1941
- DEFAULT_PATTERNS = [
1942
- ".planning/*.md",
1943
- "exe/output/*.md",
1944
- "README.md",
1945
- "src/**/*.ts"
1946
- ];
1947
- EXCLUDE_DIRS = ["node_modules", "dist", ".git", "coverage", ".worktrees"];
1948
- MAX_FILE_SIZE = 100 * 1024;
1949
- MAX_FILES = 500;
1950
- }
1951
- });
1952
-
1953
- // src/lib/reranker.ts
1954
- var reranker_exports = {};
1955
- __export(reranker_exports, {
1956
- disposeReranker: () => disposeReranker,
1957
- getRerankerModelPath: () => getRerankerModelPath,
1958
- isRerankerAvailable: () => isRerankerAvailable,
1959
- rerank: () => rerank,
1960
- rerankWithScores: () => rerankWithScores
1961
- });
1962
- import path7 from "path";
1963
- import { existsSync as existsSync6 } from "fs";
1964
- function resetIdleTimer() {
1965
- if (_idleTimer) clearTimeout(_idleTimer);
1966
- _idleTimer = setTimeout(() => {
1967
- void disposeReranker();
1968
- }, IDLE_TIMEOUT_MS);
1969
- if (_idleTimer && typeof _idleTimer === "object" && "unref" in _idleTimer) {
1970
- _idleTimer.unref();
1971
- }
1972
- }
1973
- function isRerankerAvailable() {
1974
- return existsSync6(path7.join(MODELS_DIR, RERANKER_MODEL_FILE));
1975
- }
1976
- function getRerankerModelPath() {
1977
- return path7.join(MODELS_DIR, RERANKER_MODEL_FILE);
1978
- }
1979
- async function ensureLoaded() {
1980
- if (_rerankerContext) {
1981
- resetIdleTimer();
1982
- return;
1983
- }
1984
- const modelPath = path7.join(MODELS_DIR, RERANKER_MODEL_FILE);
1985
- if (!existsSync6(modelPath)) {
1986
- throw new Error(
1987
- `Reranker model not found at ${modelPath}. Run /exe-setup to download it.`
1988
- );
1989
- }
1990
- process.stderr.write("[reranker] Loading Jina Reranker v3...\n");
1991
- const { getLlama } = await import("node-llama-cpp");
1992
- const llama = await getLlama();
1993
- _rerankerModel = await llama.loadModel({ modelPath });
1994
- _rerankerContext = await _rerankerModel.createEmbeddingContext();
1995
- process.stderr.write("[reranker] Jina Reranker v3 loaded.\n");
1996
- resetIdleTimer();
1997
- }
1998
- async function disposeReranker() {
1999
- if (_idleTimer) {
2000
- clearTimeout(_idleTimer);
2001
- _idleTimer = null;
2002
- }
2003
- if (_rerankerContext) {
2004
- try {
2005
- await _rerankerContext.dispose();
2006
- } catch {
2007
- }
2008
- _rerankerContext = null;
2009
- }
2010
- if (_rerankerModel) {
2011
- try {
2012
- await _rerankerModel.dispose();
2013
- } catch {
2014
- }
2015
- _rerankerModel = null;
2016
- }
2017
- process.stderr.write("[reranker] Unloaded (idle timeout).\n");
2018
- }
2019
- async function rerankWithScores(query, texts, topK) {
2020
- if (texts.length === 0) return [];
2021
- await ensureLoaded();
2022
- const ctx = _rerankerContext;
2023
- const scored = [];
2024
- for (let i = 0; i < texts.length; i++) {
2025
- const text = texts[i] ?? "";
2026
- try {
2027
- const input2 = `query: ${query} document: ${text.slice(0, 512)}`;
2028
- const embedding = await ctx.getEmbeddingFor(input2);
2029
- const score = embedding.vector[0] ?? 0;
2030
- scored.push({ text, score, index: i });
2031
- } catch {
2032
- scored.push({ text, score: -1, index: i });
2033
- }
2034
- }
2035
- scored.sort((a, b) => b.score - a.score);
2036
- return typeof topK === "number" ? scored.slice(0, topK) : scored;
2037
- }
2038
- async function rerank(query, candidates, topK = 5) {
2039
- if (candidates.length === 0) return [];
2040
- if (candidates.length <= topK) return candidates;
2041
- const scored = await rerankWithScores(
2042
- query,
2043
- candidates.map((c) => c.raw_text),
2044
- topK
2045
- );
2046
- return scored.map((s) => candidates[s.index]);
2047
- }
2048
- var RERANKER_MODEL_FILE, IDLE_TIMEOUT_MS, _rerankerContext, _rerankerModel, _idleTimer;
2049
- var init_reranker = __esm({
2050
- "src/lib/reranker.ts"() {
2051
- "use strict";
2052
- init_config();
2053
- RERANKER_MODEL_FILE = "jina-reranker-v3-q4_k_m.gguf";
2054
- IDLE_TIMEOUT_MS = 6e4;
2055
- _rerankerContext = null;
2056
- _rerankerModel = null;
2057
- _idleTimer = null;
2058
- }
2059
- });
2060
-
2061
- // src/lib/session-key.ts
2062
- import { execSync as execSync3 } from "child_process";
2063
- function getSessionKey() {
2064
- if (_cached2) return _cached2;
2065
- let pid = process.ppid;
2066
- for (let i = 0; i < 10; i++) {
2067
- try {
2068
- const info = execSync3(`ps -p ${pid} -o ppid=,comm=`, {
2069
- encoding: "utf8",
2070
- timeout: 2e3
2071
- }).trim();
2072
- const match = info.match(/^\s*(\d+)\s+(.+)$/);
2073
- if (!match) break;
2074
- const [, ppid, cmd] = match;
2075
- if (cmd === "claude" || cmd.endsWith("/claude")) {
2076
- _cached2 = String(pid);
2077
- return _cached2;
2078
- }
2079
- pid = parseInt(ppid, 10);
2080
- if (pid <= 1) break;
2081
- } catch {
2082
- break;
2083
- }
2084
- }
2085
- _cached2 = process.env.CLAUDE_CODE_SSE_PORT ?? String(process.ppid);
2086
- return _cached2;
2087
- }
2088
- var _cached2;
2089
- var init_session_key = __esm({
2090
- "src/lib/session-key.ts"() {
2091
- "use strict";
2092
- _cached2 = null;
2093
- }
2094
- });
2095
-
2096
- // src/lib/session-registry.ts
2097
- import { readFileSync as readFileSync5, writeFileSync as writeFileSync2, mkdirSync as mkdirSync3, existsSync as existsSync7 } from "fs";
2098
- import path9 from "path";
2099
- import os2 from "os";
2100
- function registerSession(entry) {
2101
- const dir = path9.dirname(REGISTRY_PATH);
2102
- if (!existsSync7(dir)) {
2103
- mkdirSync3(dir, { recursive: true });
2104
- }
2105
- const sessions = listSessions();
2106
- const idx = sessions.findIndex((s) => s.windowName === entry.windowName);
2107
- if (idx >= 0) {
2108
- sessions[idx] = entry;
2109
- } else {
2110
- sessions.push(entry);
2111
- }
2112
- writeFileSync2(REGISTRY_PATH, JSON.stringify(sessions, null, 2));
2113
- }
2114
- function listSessions() {
2115
- try {
2116
- const raw = readFileSync5(REGISTRY_PATH, "utf8");
2117
- return JSON.parse(raw);
2118
- } catch {
2119
- return [];
2120
- }
2121
- }
2122
- var REGISTRY_PATH;
2123
- var init_session_registry = __esm({
2124
- "src/lib/session-registry.ts"() {
2125
- "use strict";
2126
- REGISTRY_PATH = path9.join(os2.homedir(), ".exe-os", "session-registry.json");
2127
- }
2128
- });
2129
-
2130
- // src/lib/tmux-transport.ts
2131
- var tmux_transport_exports = {};
2132
- __export(tmux_transport_exports, {
2133
- TmuxTransport: () => TmuxTransport
2134
- });
2135
- import { execFileSync } from "child_process";
2136
- var QUIET, TmuxTransport;
2137
- var init_tmux_transport = __esm({
2138
- "src/lib/tmux-transport.ts"() {
2139
- "use strict";
2140
- QUIET = {
2141
- encoding: "utf8",
2142
- stdio: ["pipe", "pipe", "pipe"]
2143
- };
2144
- TmuxTransport = class {
2145
- getMySession() {
2146
- try {
2147
- return execFileSync("tmux", ["display-message", "-p", "#{session_name}"], QUIET).trim() || null;
2148
- } catch {
2149
- return null;
2150
- }
2151
- }
2152
- listSessions() {
2153
- try {
2154
- return execFileSync("tmux", ["list-sessions", "-F", "#{session_name}"], QUIET).trim().split("\n").filter(Boolean);
2155
- } catch {
2156
- return [];
2157
- }
2158
- }
2159
- isAlive(target) {
2160
- try {
2161
- const sessions = this.listSessions();
2162
- if (!sessions.includes(target)) return false;
2163
- const paneStatus = execFileSync(
2164
- "tmux",
2165
- ["list-panes", "-t", target, "-F", "#{pane_dead}"],
2166
- QUIET
2167
- ).trim();
2168
- return paneStatus !== "1";
2169
- } catch {
2170
- return false;
2171
- }
2172
- }
2173
- sendKeys(target, keys) {
2174
- execFileSync("tmux", ["send-keys", "-t", target, keys, "Enter"], QUIET);
2175
- }
2176
- capturePane(target, lines) {
2177
- const args = ["capture-pane", "-t", target, "-p"];
2178
- if (lines) args.push("-S", `-${lines}`);
2179
- return execFileSync("tmux", args, { ...QUIET, timeout: 3e3 });
2180
- }
2181
- isPaneInCopyMode(target) {
2182
- try {
2183
- const result = execFileSync(
2184
- "tmux",
2185
- ["display-message", "-p", "-t", target, "#{pane_in_mode}"],
2186
- { ...QUIET, timeout: 3e3 }
2187
- ).trim();
2188
- return result === "1";
2189
- } catch {
2190
- return false;
2191
- }
2192
- }
2193
- spawn(name, config) {
2194
- try {
2195
- const args = ["new-session", "-d", "-s", name];
2196
- if (config.cwd) args.push("-c", config.cwd);
2197
- args.push(config.command);
2198
- execFileSync("tmux", args);
2199
- return { sessionName: name };
2200
- } catch (e) {
2201
- return { sessionName: name, error: `spawn failed: ${e}` };
2202
- }
2203
- }
2204
- kill(target) {
2205
- try {
2206
- execFileSync("tmux", ["kill-session", "-t", target], QUIET);
2207
- } catch {
2208
- }
2209
- }
2210
- pipeLog(target, logFile) {
2211
- try {
2212
- const safePath = logFile.replace(/'/g, "'\\''");
2213
- execFileSync("tmux", ["pipe-pane", "-t", target, `cat >> '${safePath}'`], QUIET);
2214
- } catch {
2215
- }
2216
- }
2217
- };
2218
- }
2219
- });
2220
-
2221
- // src/lib/transport.ts
2222
- var transport_exports = {};
2223
- __export(transport_exports, {
2224
- getTransport: () => getTransport,
2225
- setTransport: () => setTransport
2226
- });
2227
- function getTransport() {
2228
- if (!_transport) {
2229
- const { TmuxTransport: TmuxTransport2 } = (init_tmux_transport(), __toCommonJS(tmux_transport_exports));
2230
- _transport = new TmuxTransport2();
2231
- }
2232
- return _transport;
2233
- }
2234
- function setTransport(t) {
2235
- _transport = t;
2236
- }
2237
- var _transport;
2238
- var init_transport = __esm({
2239
- "src/lib/transport.ts"() {
2240
- "use strict";
2241
- _transport = null;
2242
- }
2243
- });
2244
-
2245
- // src/lib/cc-agent-support.ts
2246
- import { execSync as execSync5 } from "child_process";
2247
- function _resetCcAgentSupportCache() {
2248
- _cachedSupport = null;
2249
- }
2250
- function claudeSupportsAgentFlag() {
2251
- if (_cachedSupport !== null) return _cachedSupport;
2252
- try {
2253
- const helpOutput = execSync5("claude --help 2>&1", {
2254
- encoding: "utf-8",
2255
- timeout: 5e3
2256
- });
2257
- _cachedSupport = /(^|\s)--agent(\b|=)/.test(helpOutput);
2258
- } catch {
2259
- _cachedSupport = false;
2260
- }
2261
- return _cachedSupport;
2262
- }
2263
- var _cachedSupport;
2264
- var init_cc_agent_support = __esm({
2265
- "src/lib/cc-agent-support.ts"() {
2266
- "use strict";
2267
- _cachedSupport = null;
2268
- }
2269
- });
2270
-
2271
- // src/lib/mcp-prefix.ts
2272
- function expandDualPrefixTools(shortNames) {
2273
- const out = [];
2274
- for (const name of shortNames) {
2275
- for (const prefix of MCP_TOOL_PREFIXES) {
2276
- out.push(prefix + name);
2277
- }
2278
- }
2279
- return out;
2280
- }
2281
- var MCP_PRIMARY_KEY, MCP_LEGACY_KEY, MCP_TOOL_PREFIXES;
2282
- var init_mcp_prefix = __esm({
2283
- "src/lib/mcp-prefix.ts"() {
2284
- "use strict";
2285
- MCP_PRIMARY_KEY = "exe-os";
2286
- MCP_LEGACY_KEY = "exe-mem";
2287
- MCP_TOOL_PREFIXES = [
2288
- `mcp__${MCP_PRIMARY_KEY}__`,
2289
- `mcp__${MCP_LEGACY_KEY}__`
2290
- ];
2291
- }
2292
- });
2293
-
2294
- // src/lib/provider-table.ts
2295
- function detectActiveProvider(env = process.env) {
2296
- const baseUrl = env.ANTHROPIC_BASE_URL;
2297
- if (!baseUrl) return DEFAULT_PROVIDER;
2298
- for (const [name, cfg] of Object.entries(PROVIDER_TABLE)) {
2299
- if (cfg.baseUrl === baseUrl) return name;
2300
- }
2301
- return DEFAULT_PROVIDER;
2302
- }
2303
- var PROVIDER_TABLE, DEFAULT_PROVIDER;
2304
- var init_provider_table = __esm({
2305
- "src/lib/provider-table.ts"() {
2306
- "use strict";
2307
- PROVIDER_TABLE = {
2308
- opencode: {
2309
- baseUrl: "https://opencode.ai/zen/go",
2310
- apiKeyEnv: "OPENCODE_API_KEY",
2311
- defaultModel: "minimax-m2.7"
2312
- }
2313
- };
2314
- DEFAULT_PROVIDER = "default";
2315
- }
2316
- });
2317
-
2318
- // src/lib/intercom-queue.ts
2319
- var intercom_queue_exports = {};
2320
- __export(intercom_queue_exports, {
2321
- drainForSession: () => drainForSession,
2322
- drainQueue: () => drainQueue,
2323
- queueIntercom: () => queueIntercom,
2324
- readQueue: () => readQueue
2325
- });
2326
- import { readFileSync as readFileSync6, writeFileSync as writeFileSync3, renameSync as renameSync2, existsSync as existsSync8, mkdirSync as mkdirSync4 } from "fs";
2327
- import path10 from "path";
2328
- import os3 from "os";
2329
- function ensureDir() {
2330
- const dir = path10.dirname(QUEUE_PATH);
2331
- if (!existsSync8(dir)) mkdirSync4(dir, { recursive: true });
2332
- }
2333
- function readQueue() {
2334
- try {
2335
- if (!existsSync8(QUEUE_PATH)) return [];
2336
- return JSON.parse(readFileSync6(QUEUE_PATH, "utf8"));
2337
- } catch {
2338
- return [];
2339
- }
2340
- }
2341
- function writeQueue(queue) {
2342
- ensureDir();
2343
- const tmp = `${QUEUE_PATH}.tmp`;
2344
- writeFileSync3(tmp, JSON.stringify(queue, null, 2));
2345
- renameSync2(tmp, QUEUE_PATH);
2346
- }
2347
- function queueIntercom(targetSession, reason) {
2348
- const queue = readQueue();
2349
- const existing = queue.find((q) => q.targetSession === targetSession);
2350
- if (existing) {
2351
- existing.attempts++;
2352
- existing.queuedAt = (/* @__PURE__ */ new Date()).toISOString();
2353
- existing.reason = reason;
2354
- } else {
2355
- queue.push({
2356
- targetSession,
2357
- queuedAt: (/* @__PURE__ */ new Date()).toISOString(),
2358
- attempts: 0,
2359
- reason
2360
- });
2361
- }
2362
- writeQueue(queue);
2363
- }
2364
- function drainQueue(isSessionBusy2, sendKeys) {
2365
- const queue = readQueue();
2366
- if (queue.length === 0) return { drained: 0, failed: 0 };
2367
- const remaining = [];
2368
- let drained = 0;
2369
- let failed = 0;
2370
- for (const item of queue) {
2371
- try {
2372
- if (!isSessionBusy2(item.targetSession)) {
2373
- const success = sendKeys(item.targetSession);
2374
- if (success) {
2375
- logQueue(`DRAINED \u2192 ${item.targetSession} (after ${item.attempts} retries)`);
2376
- drained++;
2377
- continue;
2378
- }
2379
- }
2380
- } catch {
2381
- }
2382
- item.attempts++;
2383
- if (item.attempts >= MAX_RETRIES) {
2384
- logQueue(`FAILED \u2192 ${item.targetSession} (${MAX_RETRIES} retries exhausted, reason: ${item.reason})`);
2385
- failed++;
2386
- continue;
2387
- }
2388
- remaining.push(item);
2389
- }
2390
- writeQueue(remaining);
2391
- return { drained, failed };
2392
- }
2393
- function drainForSession(targetSession, sendKeys) {
2394
- const queue = readQueue();
2395
- const match = queue.findIndex((q) => q.targetSession === targetSession);
2396
- if (match < 0) return false;
2397
- const success = sendKeys(targetSession);
2398
- if (success) {
2399
- queue.splice(match, 1);
2400
- writeQueue(queue);
2401
- logQueue(`DRAINED \u2192 ${targetSession} (prompt-submit trigger)`);
2402
- return true;
2403
- }
2404
- return false;
2405
- }
2406
- function logQueue(msg) {
2407
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] [queue] ${msg}
2408
- `;
2409
- process.stderr.write(`[intercom-queue] ${msg}
2410
- `);
2411
- try {
2412
- const { appendFileSync: appendFileSync3 } = __require("fs");
2413
- appendFileSync3(INTERCOM_LOG, line);
2414
- } catch {
2415
- }
2416
- }
2417
- var QUEUE_PATH, MAX_RETRIES, INTERCOM_LOG;
2418
- var init_intercom_queue = __esm({
2419
- "src/lib/intercom-queue.ts"() {
2420
- "use strict";
2421
- QUEUE_PATH = path10.join(os3.homedir(), ".exe-os", "intercom-queue.json");
2422
- MAX_RETRIES = 5;
2423
- INTERCOM_LOG = path10.join(os3.homedir(), ".exe-os", "intercom.log");
2424
- }
2425
- });
2426
-
2427
- // src/lib/employees.ts
2428
- import { readFile as readFile3, writeFile as writeFile3, mkdir as mkdir3 } from "fs/promises";
2429
- import { existsSync as existsSync9, symlinkSync, readlinkSync } from "fs";
2430
- import { execSync as execSync6 } from "child_process";
2431
- import path11 from "path";
2432
- async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
2433
- if (!existsSync9(employeesPath)) {
2434
- return [];
2435
- }
2436
- const raw = await readFile3(employeesPath, "utf-8");
2437
- try {
2438
- return JSON.parse(raw);
2439
- } catch {
2440
- return [];
2441
- }
2442
- }
2443
- function getEmployee(employees, name) {
2444
- return employees.find((e) => e.name === name);
2445
- }
2446
- var EMPLOYEES_PATH;
2447
- var init_employees = __esm({
2448
- "src/lib/employees.ts"() {
2449
- "use strict";
2450
- init_config();
2451
- EMPLOYEES_PATH = path11.join(EXE_AI_DIR, "exe-employees.json");
2452
- }
2453
- });
2454
-
2455
- // src/lib/license.ts
2456
- import { readFileSync as readFileSync7, writeFileSync as writeFileSync4, existsSync as existsSync10, mkdirSync as mkdirSync5 } from "fs";
2457
- import { randomUUID as randomUUID2 } from "crypto";
2458
- import path12 from "path";
2459
- import { jwtVerify, importSPKI } from "jose";
2460
- var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH, PLAN_LIMITS;
2461
- var init_license = __esm({
2462
- "src/lib/license.ts"() {
2463
- "use strict";
2464
- init_config();
2465
- LICENSE_PATH = path12.join(EXE_AI_DIR, "license.key");
2466
- CACHE_PATH = path12.join(EXE_AI_DIR, "license-cache.json");
2467
- DEVICE_ID_PATH = path12.join(EXE_AI_DIR, "device-id");
2468
- PLAN_LIMITS = {
2469
- free: { devices: 1, employees: 1, memories: 5e3 },
2470
- pro: { devices: 2, employees: 5, memories: 1e5 },
2471
- team: { devices: 10, employees: 20, memories: 1e6 },
2472
- agency: { devices: 50, employees: 100, memories: 1e7 },
2473
- enterprise: { devices: -1, employees: -1, memories: -1 }
2474
- };
2475
- }
2476
- });
2477
-
2478
- // src/lib/plan-limits.ts
2479
- import { readFileSync as readFileSync8, existsSync as existsSync11 } from "fs";
2480
- import path13 from "path";
2481
- function getLicenseSync() {
2482
- try {
2483
- if (!existsSync11(CACHE_PATH2)) return freeLicense();
2484
- const raw = JSON.parse(readFileSync8(CACHE_PATH2, "utf8"));
2485
- if (!raw.token || typeof raw.token !== "string") return freeLicense();
2486
- const parts = raw.token.split(".");
2487
- if (parts.length !== 3) return freeLicense();
2488
- const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
2489
- const plan = payload.plan ?? "free";
2490
- const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
2491
- return {
2492
- valid: true,
2493
- plan,
2494
- email: payload.sub ?? "",
2495
- expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
2496
- deviceLimit: limits.devices,
2497
- employeeLimit: limits.employees,
2498
- memoryLimit: limits.memories
2499
- };
2500
- } catch {
2501
- return freeLicense();
2502
- }
2503
- }
2504
- function freeLicense() {
2505
- const limits = PLAN_LIMITS.free;
2506
- return {
2507
- valid: true,
2508
- plan: "free",
2509
- email: "",
2510
- expiresAt: null,
2511
- deviceLimit: limits.devices,
2512
- employeeLimit: limits.employees,
2513
- memoryLimit: limits.memories
2514
- };
2515
- }
2516
- function assertEmployeeLimitSync(rosterPath) {
2517
- const license = getLicenseSync();
2518
- if (license.employeeLimit < 0) return;
2519
- const filePath = rosterPath ?? EMPLOYEES_PATH;
2520
- let count = 0;
2521
- try {
2522
- if (existsSync11(filePath)) {
2523
- const raw = readFileSync8(filePath, "utf8");
2524
- const employees = JSON.parse(raw);
2525
- count = Array.isArray(employees) ? employees.length : 0;
2526
- }
2527
- } catch {
2528
- throw new PlanLimitError(
2529
- `Cannot verify employee count: roster unreadable at ${filePath}. Refusing to proceed. Check file permissions or upgrade plan.`
2530
- );
2531
- }
2532
- if (count >= license.employeeLimit) {
2533
- throw new PlanLimitError(
2534
- `Employee limit reached: ${count}/${license.employeeLimit} employees on the ${license.plan} plan. Upgrade at https://askexe.com to add more.`
2535
- );
2536
- }
2537
- }
2538
- var PlanLimitError, CACHE_PATH2;
2539
- var init_plan_limits = __esm({
2540
- "src/lib/plan-limits.ts"() {
2541
- "use strict";
2542
- init_database();
2543
- init_employees();
2544
- init_license();
2545
- init_config();
2546
- PlanLimitError = class extends Error {
2547
- constructor(message) {
2548
- super(message);
2549
- this.name = "PlanLimitError";
2550
- }
2551
- };
2552
- CACHE_PATH2 = path13.join(EXE_AI_DIR, "license-cache.json");
2553
- }
2554
- });
2555
-
2556
- // src/lib/worktree.ts
2557
- import { execSync as execSync7 } from "child_process";
2558
- import { existsSync as existsSync12, readFileSync as readFileSync9, appendFileSync, mkdirSync as mkdirSync6, realpathSync } from "fs";
2559
- import path14 from "path";
2560
- function getGitRoot(dir) {
2561
- try {
2562
- const root = execSync7("git rev-parse --show-toplevel", {
2563
- cwd: dir,
2564
- encoding: "utf-8",
2565
- timeout: GIT_TIMEOUT_MS,
2566
- stdio: ["pipe", "pipe", "pipe"]
2567
- }).trim();
2568
- return realpath(root);
2569
- } catch {
2570
- return null;
2571
- }
2572
- }
2573
- function worktreePath(repoRoot, employeeName, instance) {
2574
- const label = instanceLabel(employeeName, instance);
2575
- return path14.join(repoRoot, ".worktrees", label);
2576
- }
2577
- function worktreeBranch(employeeName, instance) {
2578
- return `${instanceLabel(employeeName, instance)}-work`;
2579
- }
2580
- function instanceLabel(name, instance) {
2581
- return instance != null && instance > 0 ? `${name}${instance}` : name;
2582
- }
2583
- function ensureWorktree(projectDir, employeeName, instance) {
2584
- const repoRoot = getGitRoot(projectDir);
2585
- if (!repoRoot) return null;
2586
- const wtPath = worktreePath(repoRoot, employeeName, instance);
2587
- const branch = worktreeBranch(employeeName, instance);
2588
- if (existsSync12(path14.join(wtPath, ".git"))) {
2589
- return wtPath;
2590
- }
2591
- const worktreesDir = path14.join(repoRoot, ".worktrees");
2592
- mkdirSync6(worktreesDir, { recursive: true });
2593
- ensureGitignoreEntry(repoRoot, "/.worktrees/");
2594
- try {
2595
- execSync7("git worktree prune", {
2596
- cwd: repoRoot,
2597
- encoding: "utf-8",
2598
- timeout: GIT_TIMEOUT_MS,
2599
- stdio: ["pipe", "pipe", "pipe"]
2600
- });
2601
- } catch {
2602
- }
2603
- const branchExists = branchExistsLocally(repoRoot, branch);
2604
- try {
2605
- if (branchExists) {
2606
- execSync7(`git worktree add "${wtPath}" "${branch}"`, {
2607
- cwd: repoRoot,
2608
- encoding: "utf-8",
2609
- timeout: GIT_TIMEOUT_MS,
2610
- stdio: ["pipe", "pipe", "pipe"]
2611
- });
2612
- } else {
2613
- execSync7(`git worktree add "${wtPath}" -b "${branch}" HEAD`, {
2614
- cwd: repoRoot,
2615
- encoding: "utf-8",
2616
- timeout: GIT_TIMEOUT_MS,
2617
- stdio: ["pipe", "pipe", "pipe"]
2618
- });
2619
- }
2620
- return wtPath;
2621
- } catch (err) {
2622
- process.stderr.write(
2623
- `[worktree] Failed to create worktree for ${employeeName}: ${err instanceof Error ? err.message : String(err)}
2624
- `
2625
- );
2626
- return null;
2627
- }
2628
- }
2629
- function branchExistsLocally(repoRoot, branch) {
2630
- try {
2631
- execSync7(`git rev-parse --verify "refs/heads/${branch}"`, {
2632
- cwd: repoRoot,
2633
- encoding: "utf-8",
2634
- timeout: GIT_TIMEOUT_MS,
2635
- stdio: ["pipe", "pipe", "pipe"]
2636
- });
2637
- return true;
2638
- } catch {
2639
- return false;
2640
- }
2641
- }
2642
- function realpath(p) {
2643
- try {
2644
- return realpathSync(p);
2645
- } catch {
2646
- return p;
2647
- }
2648
- }
2649
- function ensureGitignoreEntry(repoRoot, entry) {
2650
- try {
2651
- const gitignorePath = path14.join(repoRoot, ".gitignore");
2652
- if (existsSync12(gitignorePath)) {
2653
- const content = readFileSync9(gitignorePath, "utf-8");
2654
- if (content.includes(entry)) return;
2655
- appendFileSync(gitignorePath, `
2656
- # Agent worktrees (exe-os)
2657
- ${entry}
2658
- `);
2659
- } else {
2660
- }
2661
- } catch {
2662
- }
2663
- }
2664
- var GIT_TIMEOUT_MS;
2665
- var init_worktree = __esm({
2666
- "src/lib/worktree.ts"() {
2667
- "use strict";
2668
- GIT_TIMEOUT_MS = 1e4;
2669
- }
2670
- });
2671
-
2672
- // src/lib/tmux-routing.ts
2673
- import { execFileSync as execFileSync2, execSync as execSync8 } from "child_process";
2674
- import { readFileSync as readFileSync10, writeFileSync as writeFileSync5, mkdirSync as mkdirSync7, existsSync as existsSync13, appendFileSync as appendFileSync2 } from "fs";
2675
- import path15 from "path";
2676
- import os4 from "os";
2677
- import { fileURLToPath as fileURLToPath2 } from "url";
2678
- function resolveBehaviorsExporterScript() {
2679
- try {
2680
- const thisFile = fileURLToPath2(import.meta.url);
2681
- const scriptPath = path15.join(
2682
- path15.dirname(thisFile),
2683
- "..",
2684
- "bin",
2685
- "exe-export-behaviors.js"
2686
- );
2687
- return existsSync13(scriptPath) ? scriptPath : null;
2688
- } catch {
2689
- return null;
2690
- }
2691
- }
2692
- function exportBehaviorsSync(agentId, projectName, sessionKey) {
2693
- const script = resolveBehaviorsExporterScript();
2694
- if (!script) return null;
2695
- try {
2696
- const output = execFileSync2(
2697
- process.execPath,
2698
- [script, agentId, projectName, sessionKey],
2699
- { encoding: "utf-8", timeout: BEHAVIORS_EXPORT_TIMEOUT_MS }
2700
- ).trim();
2701
- return output.length > 0 ? output : null;
2702
- } catch (err) {
2703
- process.stderr.write(
2704
- `[tmux-routing] behaviors export failed for ${agentId}: ${err instanceof Error ? err.message : String(err)}
2705
- `
2706
- );
2707
- return null;
2708
- }
2709
- }
2710
- function getMySession() {
2711
- return getTransport().getMySession();
2712
- }
2713
- function employeeSessionName(employee, exeSession, instance) {
2714
- const suffix = instance != null && instance > 0 ? String(instance) : "";
2715
- return `${employee}${suffix}-${exeSession}`;
2716
- }
2717
- function extractRootExe(name) {
2718
- const match = name.match(/(exe\d+)$/);
2719
- return match?.[1] ?? null;
2720
- }
2721
- function getParentExe(sessionKey) {
2722
- try {
2723
- const data = JSON.parse(readFileSync10(path15.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
2724
- return data.parentExe || null;
2725
- } catch {
2726
- return null;
2727
- }
2728
- }
2729
- function resolveExeSession() {
2730
- const mySession = getMySession();
2731
- if (!mySession) return null;
2732
- try {
2733
- const key = getSessionKey();
2734
- const parentExe = getParentExe(key);
2735
- if (parentExe) {
2736
- return extractRootExe(parentExe) ?? parentExe;
2737
- }
2738
- } catch {
2739
- }
2740
- return extractRootExe(mySession) ?? mySession;
2741
- }
2742
- function isEmployeeAlive(sessionName) {
2743
- return getTransport().isAlive(sessionName);
2744
- }
2745
- function findFreeInstance(employeeName, exeSession, maxInstances = 10, isAlive = isEmployeeAlive) {
2746
- const base = employeeSessionName(employeeName, exeSession);
2747
- if (!isAlive(base)) return 0;
2748
- for (let i = 2; i <= maxInstances; i++) {
2749
- const candidate = employeeSessionName(employeeName, exeSession, i);
2750
- if (!isAlive(candidate)) return i;
2751
- }
2752
- return null;
2753
- }
2754
- function readDebounceState() {
2755
- try {
2756
- if (!existsSync13(DEBOUNCE_FILE)) return {};
2757
- return JSON.parse(readFileSync10(DEBOUNCE_FILE, "utf8"));
2758
- } catch {
2759
- return {};
2760
- }
2761
- }
2762
- function writeDebounceState(state) {
2763
- try {
2764
- if (!existsSync13(SESSION_CACHE)) mkdirSync7(SESSION_CACHE, { recursive: true });
2765
- writeFileSync5(DEBOUNCE_FILE, JSON.stringify(state));
2766
- } catch {
2767
- }
2768
- }
2769
- function isDebounced(targetSession) {
2770
- const state = readDebounceState();
2771
- const lastSent = state[targetSession] ?? 0;
2772
- return Date.now() - lastSent < INTERCOM_DEBOUNCE_MS;
2773
- }
2774
- function recordDebounce(targetSession) {
2775
- const state = readDebounceState();
2776
- state[targetSession] = Date.now();
2777
- const cutoff = Date.now() - DEBOUNCE_CLEANUP_AGE_MS;
2778
- for (const key of Object.keys(state)) {
2779
- if ((state[key] ?? 0) < cutoff) delete state[key];
2780
- }
2781
- writeDebounceState(state);
2782
- }
2783
- function logIntercom(msg) {
2784
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${msg}
2785
- `;
2786
- process.stderr.write(`[intercom] ${msg}
2787
- `);
2788
- try {
2789
- appendFileSync2(INTERCOM_LOG2, line);
2790
- } catch {
2791
- }
2792
- }
2793
- function getSessionState(sessionName) {
2794
- const transport = getTransport();
2795
- if (!transport.isAlive(sessionName)) return "offline";
2796
- try {
2797
- const pane = transport.capturePane(sessionName, 5);
2798
- if (/Running…/.test(pane)) return "tool";
2799
- if (BUSY_PATTERN.test(pane)) return "thinking";
2800
- return "idle";
2801
- } catch {
2802
- return "offline";
2803
- }
2804
- }
2805
- function isSessionBusy(sessionName) {
2806
- const state = getSessionState(sessionName);
2807
- return state === "thinking" || state === "tool";
2808
- }
2809
- function isExeSession(sessionName) {
2810
- return /^exe\d*$/.test(sessionName);
2811
- }
2812
- function sendIntercom(targetSession) {
2813
- const transport = getTransport();
2814
- if (isExeSession(targetSession)) {
2815
- logIntercom(`SKIP_EXE \u2192 ${targetSession} (exe sessions use prompt-submit hook)`);
2816
- return "skipped_exe";
2817
- }
2818
- if (isDebounced(targetSession)) {
2819
- logIntercom(`DEBOUNCE \u2192 ${targetSession} (cross-process file debounce)`);
2820
- return "debounced";
2821
- }
2822
- try {
2823
- const sessions = transport.listSessions();
2824
- if (!sessions.includes(targetSession)) {
2825
- logIntercom(`SKIP \u2192 ${targetSession} (session not found)`);
2826
- return "failed";
2827
- }
2828
- if (isSessionBusy(targetSession)) {
2829
- queueIntercom(targetSession, "session busy at send time");
2830
- recordDebounce(targetSession);
2831
- logIntercom(`QUEUED \u2192 ${targetSession} (session busy, will retry from queue)`);
2832
- return "queued";
2833
- }
2834
- if (transport.isPaneInCopyMode(targetSession)) {
2835
- logIntercom(`COPY_MODE \u2192 ${targetSession} (exiting copy mode first)`);
2836
- transport.sendKeys(targetSession, "q");
2837
- }
2838
- transport.sendKeys(targetSession, "/exe-intercom");
2839
- recordDebounce(targetSession);
2840
- for (let i = 0; i < INTERCOM_POLL_MAX_ATTEMPTS; i++) {
2841
- try {
2842
- execSync8(`sleep ${INTERCOM_POLL_INTERVAL_S}`);
2843
- } catch {
2844
- }
2845
- const state = getSessionState(targetSession);
2846
- if (state === "thinking" || state === "tool") {
2847
- logIntercom(`ACKNOWLEDGED \u2192 ${targetSession} (state=${state}, poll=${i + 1})`);
2848
- return "acknowledged";
2849
- }
2850
- }
2851
- logIntercom(`DELIVERED \u2192 ${targetSession} (no state transition after ${INTERCOM_POLL_MAX_ATTEMPTS}s)`);
2852
- return "delivered";
2853
- } catch {
2854
- logIntercom(`FAIL \u2192 ${targetSession}`);
2855
- return "failed";
2856
- }
2857
- }
2858
- function ensureEmployee(employeeName, exeSession, projectDir, opts) {
2859
- if (employeeName === "exe") {
2860
- return { status: "failed", sessionName: "", error: "exe is the COO, not a dispatchable employee" };
2861
- }
2862
- try {
2863
- assertEmployeeLimitSync();
2864
- } catch (err) {
2865
- if (err instanceof PlanLimitError) {
2866
- return { status: "failed", sessionName: "", error: err.message };
2867
- }
2868
- }
2869
- if (/-exe\d*$/.test(employeeName)) {
2870
- const bare = employeeName.replace(/-exe\d*$/, "").replace(/\d+$/, "");
2871
- return {
2872
- status: "failed",
2873
- sessionName: "",
2874
- error: `Error: pass employee name ('${bare}'), not session name ('${employeeName}')`
2875
- };
2876
- }
2877
- let effectiveInstance = opts?.instance;
2878
- if (effectiveInstance === void 0 && opts?.autoInstance) {
2879
- const free = findFreeInstance(
2880
- employeeName,
2881
- exeSession,
2882
- opts.maxAutoInstances ?? 10
2883
- );
2884
- if (free === null) {
2885
- return {
2886
- status: "failed",
2887
- sessionName: employeeSessionName(employeeName, exeSession),
2888
- error: `All ${opts.maxAutoInstances ?? 10} instances of ${employeeName} are alive \u2014 cap reached`
2889
- };
2890
- }
2891
- effectiveInstance = free === 0 ? void 0 : free;
2892
- }
2893
- const sessionName = employeeSessionName(employeeName, exeSession, effectiveInstance);
2894
- if (isEmployeeAlive(sessionName)) {
2895
- const result2 = sendIntercom(sessionName);
2896
- if (result2 === "acknowledged" || result2 === "skipped_exe" || result2 === "debounced" || result2 === "queued") {
2897
- return { status: "intercom_sent", sessionName };
2898
- }
2899
- if (result2 === "delivered") {
2900
- return { status: "intercom_unprocessed", sessionName };
2901
- }
2902
- return { status: "failed", sessionName, error: "intercom delivery failed" };
2903
- }
2904
- const spawnOpts = { ...opts, instance: effectiveInstance };
2905
- const wtPath = ensureWorktree(projectDir, employeeName, effectiveInstance);
2906
- if (wtPath) {
2907
- spawnOpts.cwd = wtPath;
2908
- }
2909
- const result = spawnEmployee(employeeName, exeSession, projectDir, spawnOpts);
2910
- if (result.error) {
2911
- return { status: "failed", sessionName, error: result.error };
2912
- }
2913
- return { status: "spawned", sessionName };
2914
- }
2915
- function spawnEmployee(employeeName, exeSession, projectDir, opts) {
2916
- const transport = getTransport();
2917
- const sessionName = employeeSessionName(employeeName, exeSession, opts?.instance);
2918
- const instanceLabel2 = opts?.instance != null && opts.instance > 0 ? `${employeeName}${opts.instance}` : employeeName;
2919
- const logDir = path15.join(os4.homedir(), ".exe-os", "session-logs");
2920
- const logFile = path15.join(logDir, `${instanceLabel2}-${Date.now()}.log`);
2921
- if (!existsSync13(logDir)) {
2922
- mkdirSync7(logDir, { recursive: true });
2923
- }
2924
- transport.kill(sessionName);
2925
- let cleanupSuffix = "";
2926
- try {
2927
- const thisFile = fileURLToPath2(import.meta.url);
2928
- const cleanupScript = path15.join(path15.dirname(thisFile), "..", "bin", "exe-session-cleanup.js");
2929
- if (existsSync13(cleanupScript)) {
2930
- cleanupSuffix = `; ${process.execPath} "${cleanupScript}" "${employeeName}" "${exeSession}"`;
2931
- }
2932
- } catch {
2933
- }
2934
- try {
2935
- const claudeJsonPath = path15.join(os4.homedir(), ".claude.json");
2936
- let claudeJson = {};
2937
- try {
2938
- claudeJson = JSON.parse(readFileSync10(claudeJsonPath, "utf8"));
2939
- } catch {
2940
- }
2941
- if (!claudeJson.projects) claudeJson.projects = {};
2942
- const projects = claudeJson.projects;
2943
- const trustDir = opts?.cwd ?? projectDir;
2944
- if (!projects[trustDir]) projects[trustDir] = {};
2945
- projects[trustDir].hasTrustDialogAccepted = true;
2946
- writeFileSync5(claudeJsonPath, JSON.stringify(claudeJson, null, 2) + "\n");
2947
- } catch {
2948
- }
2949
- try {
2950
- const settingsDir = path15.join(os4.homedir(), ".claude", "projects");
2951
- const normalizedKey = (opts?.cwd ?? projectDir).replace(/\//g, "-").replace(/^-/, "");
2952
- const projSettingsDir = path15.join(settingsDir, normalizedKey);
2953
- const settingsPath = path15.join(projSettingsDir, "settings.json");
2954
- let settings = {};
2955
- try {
2956
- settings = JSON.parse(readFileSync10(settingsPath, "utf8"));
2957
- } catch {
2958
- }
2959
- const perms = settings.permissions ?? {};
2960
- const allow = perms.allow ?? [];
2961
- const toolNames = [
2962
- "recall_my_memory",
2963
- "store_memory",
2964
- "create_task",
2965
- "update_task",
2966
- "list_tasks",
2967
- "get_task",
2968
- "ask_team_memory",
2969
- "store_behavior",
2970
- "get_identity",
2971
- "send_message"
2972
- ];
2973
- const requiredTools = expandDualPrefixTools(toolNames);
2974
- let changed = false;
2975
- for (const tool of requiredTools) {
2976
- if (!allow.includes(tool)) {
2977
- allow.push(tool);
2978
- changed = true;
2979
- }
2980
- }
2981
- if (changed) {
2982
- perms.allow = allow;
2983
- settings.permissions = perms;
2984
- mkdirSync7(projSettingsDir, { recursive: true });
2985
- writeFileSync5(settingsPath, JSON.stringify(settings, null, 2) + "\n");
2986
- }
2987
- } catch {
2988
- }
2989
- const spawnCwd = opts?.cwd ?? projectDir;
2990
- const useExeAgent = !!(opts?.model && opts?.provider);
2991
- const ccProvider = useExeAgent ? DEFAULT_PROVIDER : detectActiveProvider();
2992
- const useBinSymlink = ccProvider !== DEFAULT_PROVIDER;
2993
- let identityFlag = "";
2994
- let behaviorsFlag = "";
2995
- let legacyFallbackWarned = false;
2996
- if (!useExeAgent && !useBinSymlink) {
2997
- const identityPath = path15.join(
2998
- os4.homedir(),
2999
- ".exe-os",
3000
- "identity",
3001
- `${employeeName}.md`
3002
- );
3003
- _resetCcAgentSupportCache();
3004
- const hasAgentFlag = claudeSupportsAgentFlag();
3005
- if (hasAgentFlag) {
3006
- identityFlag = ` --agent ${employeeName}`;
3007
- } else if (existsSync13(identityPath)) {
3008
- identityFlag = ` --append-system-prompt-file ${identityPath}`;
3009
- legacyFallbackWarned = true;
3010
- }
3011
- const behaviorsFile = exportBehaviorsSync(
3012
- employeeName,
3013
- path15.basename(spawnCwd),
3014
- sessionName
3015
- );
3016
- if (behaviorsFile) {
3017
- behaviorsFlag = ` --append-system-prompt-file ${behaviorsFile}`;
3018
- }
3019
- }
3020
- if (legacyFallbackWarned) {
3021
- process.stderr.write(
3022
- `[tmux-routing] claude --agent not supported by installed CC. Falling back to --append-system-prompt-file for ${employeeName}. Upgrade Claude Code to enable native --agent launch.
3023
- `
3024
- );
3025
- }
3026
- let sessionContextFlag = "";
3027
- try {
3028
- const ctxDir = path15.join(os4.homedir(), ".exe-os", "session-cache");
3029
- mkdirSync7(ctxDir, { recursive: true });
3030
- const ctxFile = path15.join(ctxDir, `session-context-${sessionName}.md`);
3031
- const ctxContent = [
3032
- `## Session Context`,
3033
- `You are running in tmux session: ${sessionName}.`,
3034
- `Your parent exe session is ${exeSession}.`,
3035
- `Your employees (if any) use the -${exeSession} suffix (e.g., tom-${exeSession}).`
3036
- ].join("\n");
3037
- writeFileSync5(ctxFile, ctxContent);
3038
- sessionContextFlag = ` --append-system-prompt-file ${ctxFile}`;
3039
- } catch {
3040
- }
3041
- let envPrefix = `EXE_SESSION=${exeSession} EXE_SESSION_NAME=${sessionName}`;
3042
- if (ccProvider !== DEFAULT_PROVIDER) {
3043
- const cfg = PROVIDER_TABLE[ccProvider];
3044
- if (cfg?.apiKeyEnv) {
3045
- const keyVal = process.env[cfg.apiKeyEnv];
3046
- if (keyVal) {
3047
- envPrefix = `${envPrefix} ${cfg.apiKeyEnv}=${keyVal}`;
3048
- }
3049
- }
3050
- }
3051
- let spawnCommand;
3052
- if (useExeAgent) {
3053
- spawnCommand = `${envPrefix} exe-agent --employee ${employeeName} --model ${opts.model} --provider ${opts.provider}${cleanupSuffix}`;
3054
- } else if (useBinSymlink) {
3055
- const binName = `${employeeName}-${ccProvider}`;
3056
- process.stderr.write(
3057
- `[tmux-routing] provider cascade: ${ccProvider} \u2192 spawning ${binName}
3058
- `
3059
- );
3060
- spawnCommand = `${envPrefix} ${binName}${cleanupSuffix}`;
3061
- } else {
3062
- spawnCommand = `${envPrefix} claude --dangerously-skip-permissions${identityFlag}${behaviorsFlag}${sessionContextFlag}${cleanupSuffix}`;
3063
- }
3064
- const spawnResult = transport.spawn(sessionName, {
3065
- cwd: spawnCwd,
3066
- command: spawnCommand
3067
- });
3068
- if (spawnResult.error) {
3069
- return { sessionName, error: `tmux new-session failed: ${spawnResult.error}` };
3070
- }
3071
- transport.pipeLog(sessionName, logFile);
3072
- try {
3073
- const mySession = getMySession();
3074
- const dispatchInfo = path15.join(SESSION_CACHE, `dispatch-info-${sessionName}.json`);
3075
- writeFileSync5(dispatchInfo, JSON.stringify({
3076
- dispatchedBy: mySession,
3077
- rootExe: exeSession,
3078
- provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
3079
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
3080
- }));
3081
- } catch {
3082
- }
3083
- let booted = false;
3084
- for (let i = 0; i < 30; i++) {
3085
- try {
3086
- execSync8("sleep 1");
3087
- } catch {
3088
- }
3089
- try {
3090
- const pane = transport.capturePane(sessionName);
3091
- if (useExeAgent) {
3092
- if (pane.includes("[exe-agent]") || pane.includes("online")) {
3093
- booted = true;
3094
- break;
3095
- }
3096
- } else {
3097
- if (pane.includes("Claude Code") || pane.includes("\u276F")) {
3098
- booted = true;
3099
- break;
3100
- }
3101
- }
3102
- } catch {
3103
- }
3104
- }
3105
- if (!booted) {
3106
- return { sessionName, error: `${useExeAgent ? "exe-agent" : "claude"} did not boot within 30s` };
3107
- }
3108
- if (!useExeAgent) {
3109
- try {
3110
- transport.sendKeys(sessionName, `/exe-call ${employeeName}`);
3111
- } catch {
3112
- }
3113
- }
3114
- registerSession({
3115
- windowName: sessionName,
3116
- agentId: employeeName,
3117
- projectDir: spawnCwd,
3118
- parentExe: exeSession,
3119
- pid: 0,
3120
- registeredAt: (/* @__PURE__ */ new Date()).toISOString()
3121
- });
3122
- return { sessionName };
3123
- }
3124
- var SESSION_CACHE, BEHAVIORS_EXPORT_TIMEOUT_MS, INTERCOM_DEBOUNCE_MS, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS, BUSY_PATTERN, INTERCOM_POLL_INTERVAL_S, INTERCOM_POLL_MAX_ATTEMPTS;
3125
- var init_tmux_routing = __esm({
3126
- "src/lib/tmux-routing.ts"() {
3127
- "use strict";
3128
- init_session_registry();
3129
- init_session_key();
3130
- init_transport();
3131
- init_cc_agent_support();
3132
- init_mcp_prefix();
3133
- init_provider_table();
3134
- init_intercom_queue();
3135
- init_plan_limits();
3136
- init_worktree();
3137
- SESSION_CACHE = path15.join(os4.homedir(), ".exe-os", "session-cache");
3138
- BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
3139
- INTERCOM_DEBOUNCE_MS = 3e4;
3140
- INTERCOM_LOG2 = path15.join(os4.homedir(), ".exe-os", "intercom.log");
3141
- DEBOUNCE_FILE = path15.join(SESSION_CACHE, "intercom-debounce.json");
3142
- DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
3143
- BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
3144
- INTERCOM_POLL_INTERVAL_S = 1;
3145
- INTERCOM_POLL_MAX_ATTEMPTS = 8;
3146
- }
3147
- });
3148
-
3149
- // src/lib/messaging.ts
3150
- var messaging_exports = {};
3151
- __export(messaging_exports, {
3152
- deliverLocalMessage: () => deliverLocalMessage,
3153
- getFailedMessages: () => getFailedMessages,
3154
- getMessageStatus: () => getMessageStatus,
3155
- getPendingMessages: () => getPendingMessages,
3156
- getReadMessages: () => getReadMessages,
3157
- getUnacknowledgedMessages: () => getUnacknowledgedMessages,
3158
- markAcknowledged: () => markAcknowledged,
3159
- markFailed: () => markFailed,
3160
- markProcessed: () => markProcessed,
3161
- markRead: () => markRead,
3162
- retryPendingMessages: () => retryPendingMessages,
3163
- sendMessage: () => sendMessage,
3164
- setWsClientSend: () => setWsClientSend
3165
- });
3166
- import crypto3 from "crypto";
3167
- function generateUlid() {
3168
- const timestamp = Date.now().toString(36).padStart(10, "0");
3169
- const random = crypto3.randomBytes(10).toString("hex").slice(0, 16);
3170
- return (timestamp + random).toUpperCase();
3171
- }
3172
- function rowToMessage(row) {
3173
- return {
3174
- id: row.id,
3175
- fromAgent: row.from_agent,
3176
- fromDevice: row.from_device,
3177
- targetAgent: row.target_agent,
3178
- targetProject: row.target_project ?? null,
3179
- targetDevice: row.target_device,
3180
- content: row.content,
3181
- priority: row.priority ?? "normal",
3182
- status: row.status ?? "pending",
3183
- serverSeq: row.server_seq != null ? Number(row.server_seq) : null,
3184
- retryCount: Number(row.retry_count ?? 0),
3185
- createdAt: row.created_at,
3186
- deliveredAt: row.delivered_at ?? null,
3187
- processedAt: row.processed_at ?? null,
3188
- failedAt: row.failed_at ?? null,
3189
- failureReason: row.failure_reason ?? null
3190
- };
3191
- }
3192
- async function sendMessage(input2) {
3193
- const client = getClient();
3194
- const id = generateUlid();
3195
- const now = (/* @__PURE__ */ new Date()).toISOString();
3196
- const targetDevice = input2.targetDevice ?? "local";
3197
- await client.execute({
3198
- sql: `INSERT INTO messages (id, from_agent, from_device, target_agent, target_project, target_device, content, priority, status, created_at)
3199
- VALUES (?, ?, 'local', ?, ?, ?, ?, ?, 'pending', ?)`,
3200
- args: [
3201
- id,
3202
- input2.fromAgent,
3203
- input2.targetAgent,
3204
- input2.targetProject ?? null,
3205
- targetDevice,
3206
- input2.content,
3207
- input2.priority ?? "normal",
3208
- now
3209
- ]
3210
- });
3211
- try {
3212
- if (targetDevice !== "local") {
3213
- await deliverCrossMachineMessage(id, targetDevice);
3214
- } else {
3215
- await deliverLocalMessage(id);
3216
- }
3217
- } catch {
3218
- }
3219
- const result = await client.execute({
3220
- sql: "SELECT * FROM messages WHERE id = ?",
3221
- args: [id]
3222
- });
3223
- return rowToMessage(result.rows[0]);
3224
- }
3225
- function setWsClientSend(fn) {
3226
- _wsClientSend = fn;
3227
- }
3228
- async function deliverCrossMachineMessage(messageId, targetDevice) {
3229
- const client = getClient();
3230
- const result = await client.execute({
3231
- sql: "SELECT * FROM messages WHERE id = ?",
3232
- args: [messageId]
3233
- });
3234
- if (result.rows.length === 0) return false;
3235
- const msg = rowToMessage(result.rows[0]);
3236
- if (msg.status !== "pending") return false;
3237
- if (!_wsClientSend) {
3238
- return false;
3239
- }
3240
- const payload = JSON.stringify({
3241
- id: msg.id,
3242
- fromAgent: msg.fromAgent,
3243
- targetAgent: msg.targetAgent,
3244
- targetProject: msg.targetProject,
3245
- content: msg.content,
3246
- priority: msg.priority,
3247
- createdAt: msg.createdAt
3248
- });
3249
- const sent = _wsClientSend(targetDevice, payload);
3250
- if (sent) {
3251
- await client.execute({
3252
- sql: "UPDATE messages SET status = 'synced' WHERE id = ?",
3253
- args: [messageId]
3254
- });
3255
- return true;
3256
- }
3257
- return false;
3258
- }
3259
- async function deliverLocalMessage(messageId) {
3260
- const client = getClient();
3261
- const result = await client.execute({
3262
- sql: "SELECT * FROM messages WHERE id = ?",
3263
- args: [messageId]
3264
- });
3265
- if (result.rows.length === 0) return false;
3266
- const msg = rowToMessage(result.rows[0]);
3267
- if (msg.status !== "pending") return false;
3268
- const targetAgent = msg.targetAgent;
3269
- const now = (/* @__PURE__ */ new Date()).toISOString();
3270
- try {
3271
- const exeSession = resolveExeSession();
3272
- if (!exeSession) {
3273
- throw new Error("No exe session found");
3274
- }
3275
- const ensureResult = ensureEmployee(targetAgent, exeSession, process.cwd());
3276
- if (ensureResult.status === "failed") {
3277
- throw new Error(ensureResult.error ?? "ensureEmployee failed");
3278
- }
3279
- await client.execute({
3280
- sql: "UPDATE messages SET status = 'delivered', delivered_at = ? WHERE id = ?",
3281
- args: [now, messageId]
3282
- });
3283
- return true;
3284
- } catch {
3285
- const newRetryCount = msg.retryCount + 1;
3286
- if (newRetryCount >= MAX_RETRIES2) {
3287
- await markFailed(messageId, "session unavailable after 10 retries");
3288
- } else {
3289
- await client.execute({
3290
- sql: "UPDATE messages SET retry_count = ? WHERE id = ?",
3291
- args: [newRetryCount, messageId]
3292
- });
3293
- }
3294
- return false;
3295
- }
3296
- }
3297
- async function getPendingMessages(targetAgent) {
3298
- const client = getClient();
3299
- const result = await client.execute({
3300
- sql: `SELECT * FROM messages
3301
- WHERE target_agent = ? AND status IN ('pending', 'delivered')
3302
- ORDER BY id`,
3303
- args: [targetAgent]
3304
- });
3305
- return result.rows.map((row) => rowToMessage(row));
3306
- }
3307
- async function markRead(messageId) {
3308
- const client = getClient();
3309
- await client.execute({
3310
- sql: "UPDATE messages SET status = 'read' WHERE id = ? AND status IN ('pending', 'delivered')",
3311
- args: [messageId]
3312
- });
3313
- }
3314
- async function markAcknowledged(messageId) {
3315
- const client = getClient();
3316
- await client.execute({
3317
- sql: "UPDATE messages SET status = 'acknowledged', processed_at = ? WHERE id = ? AND status = 'read'",
3318
- args: [(/* @__PURE__ */ new Date()).toISOString(), messageId]
3319
- });
3320
- }
3321
- async function markProcessed(messageId) {
3322
- const client = getClient();
3323
- await client.execute({
3324
- sql: "UPDATE messages SET status = 'processed', processed_at = ? WHERE id = ?",
3325
- args: [(/* @__PURE__ */ new Date()).toISOString(), messageId]
3326
- });
3327
- }
3328
- async function getMessageStatus(messageId) {
3329
- const client = getClient();
3330
- const result = await client.execute({
3331
- sql: "SELECT status FROM messages WHERE id = ?",
3332
- args: [messageId]
3333
- });
3334
- return result.rows[0]?.status ?? null;
3335
- }
3336
- async function getUnacknowledgedMessages(targetAgent) {
3337
- const client = getClient();
3338
- const result = await client.execute({
3339
- sql: `SELECT * FROM messages
3340
- WHERE target_agent = ? AND status IN ('pending', 'delivered', 'read')
3341
- ORDER BY id`,
3342
- args: [targetAgent]
3343
- });
3344
- return result.rows.map((row) => rowToMessage(row));
3345
- }
3346
- async function getReadMessages(targetAgent) {
3347
- const client = getClient();
3348
- const result = await client.execute({
3349
- sql: "SELECT * FROM messages WHERE target_agent = ? AND status = 'read' ORDER BY id",
3350
- args: [targetAgent]
3351
- });
3352
- return result.rows.map((row) => rowToMessage(row));
3353
- }
3354
- async function markFailed(messageId, reason) {
3355
- const client = getClient();
3356
- await client.execute({
3357
- sql: "UPDATE messages SET status = 'failed', failed_at = ?, failure_reason = ? WHERE id = ?",
3358
- args: [(/* @__PURE__ */ new Date()).toISOString(), reason, messageId]
3359
- });
3360
- }
3361
- async function getFailedMessages() {
3362
- const client = getClient();
3363
- const result = await client.execute({
3364
- sql: "SELECT * FROM messages WHERE status = 'failed' ORDER BY created_at DESC",
3365
- args: []
3366
- });
3367
- return result.rows.map((row) => rowToMessage(row));
3368
- }
3369
- async function retryPendingMessages() {
3370
- const client = getClient();
3371
- const result = await client.execute({
3372
- sql: `SELECT * FROM messages
3373
- WHERE status = 'pending' AND retry_count < ?
3374
- ORDER BY id`,
3375
- args: [MAX_RETRIES2]
3376
- });
3377
- let delivered = 0;
3378
- for (const row of result.rows) {
3379
- const msg = rowToMessage(row);
3380
- try {
3381
- const success = await deliverLocalMessage(msg.id);
3382
- if (success) delivered++;
3383
- } catch {
3384
- }
3385
- }
3386
- return delivered;
3387
- }
3388
- var MAX_RETRIES2, _wsClientSend;
3389
- var init_messaging = __esm({
3390
- "src/lib/messaging.ts"() {
3391
- "use strict";
3392
- init_database();
3393
- init_tmux_routing();
3394
- MAX_RETRIES2 = 10;
3395
- _wsClientSend = null;
3396
- }
3397
- });
3398
-
3399
- // src/lib/notifications.ts
3400
- import crypto4 from "crypto";
3401
- import path16 from "path";
3402
- import os5 from "os";
3403
- import {
3404
- readFileSync as readFileSync11,
3405
- readdirSync as readdirSync3,
3406
- unlinkSync as unlinkSync3,
3407
- existsSync as existsSync14,
3408
- rmdirSync
3409
- } from "fs";
3410
- async function writeNotification(notification) {
3411
- try {
3412
- const client = getClient();
3413
- const id = crypto4.randomUUID();
3414
- const now = (/* @__PURE__ */ new Date()).toISOString();
3415
- await client.execute({
3416
- sql: `INSERT INTO notifications (id, agent_id, agent_role, event, project, summary, task_file, read, created_at)
3417
- VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)`,
3418
- args: [
3419
- id,
3420
- notification.agentId,
3421
- notification.agentRole,
3422
- notification.event,
3423
- notification.project,
3424
- notification.summary,
3425
- notification.taskFile ?? null,
3426
- now
3427
- ]
3428
- });
3429
- } catch (err) {
3430
- process.stderr.write(`[notifications] WRITE FAILED: ${err instanceof Error ? err.message : String(err)}
3431
- `);
3432
- }
3433
- }
3434
- var init_notifications = __esm({
3435
- "src/lib/notifications.ts"() {
3436
- "use strict";
3437
- init_database();
3438
- }
3439
- });
3440
-
3441
- // src/lib/tasks-crud.ts
3442
- import crypto5 from "crypto";
3443
- import path17 from "path";
3444
- import { execSync as execSync9 } from "child_process";
3445
- import { mkdir as mkdir4, writeFile as writeFile4, appendFile } from "fs/promises";
3446
- import { existsSync as existsSync15, readFileSync as readFileSync12 } from "fs";
3447
- function extractParentFromContext(contextBody) {
3448
- if (!contextBody) return null;
3449
- const match = contextBody.match(
3450
- /Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
3451
- );
3452
- return match ? match[1].toLowerCase() : null;
3453
- }
3454
- function slugify(title) {
3455
- return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
3456
- }
3457
- async function resolveTask(client, identifier) {
3458
- let result = await client.execute({
3459
- sql: "SELECT * FROM tasks WHERE id = ?",
3460
- args: [identifier]
3461
- });
3462
- if (result.rows.length === 1) return result.rows[0];
3463
- result = await client.execute({
3464
- sql: "SELECT * FROM tasks WHERE task_file LIKE ?",
3465
- args: [`%${identifier}%`]
3466
- });
3467
- if (result.rows.length === 1) return result.rows[0];
3468
- if (result.rows.length > 1) {
3469
- const exact = result.rows.filter(
3470
- (r) => String(r.task_file).endsWith(`/${identifier}.md`)
3471
- );
3472
- if (exact.length === 1) return exact[0];
3473
- const candidates = exact.length > 1 ? exact : result.rows;
3474
- const active = candidates.filter(
3475
- (r) => !["done", "cancelled"].includes(String(r.status))
3476
- );
3477
- if (active.length === 1) return active[0];
3478
- const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
3479
- throw new Error(
3480
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
3481
- );
3482
- }
3483
- result = await client.execute({
3484
- sql: "SELECT * FROM tasks WHERE title LIKE ?",
3485
- args: [`%${identifier}%`]
3486
- });
3487
- if (result.rows.length === 1) return result.rows[0];
3488
- if (result.rows.length > 1) {
3489
- const active = result.rows.filter(
3490
- (r) => !["done", "cancelled"].includes(String(r.status))
3491
- );
3492
- if (active.length === 1) return active[0];
3493
- const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
3494
- throw new Error(
3495
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
3496
- );
3497
- }
3498
- throw new Error(`Task not found: ${identifier}`);
3499
- }
3500
- async function createTaskCore(input2) {
3501
- const client = getClient();
3502
- const id = crypto5.randomUUID();
3503
- const now = (/* @__PURE__ */ new Date()).toISOString();
3504
- const slug = slugify(input2.title);
3505
- const taskFile = input2.taskFile ?? `exe/${input2.assignedTo}/${slug}.md`;
3506
- let blockedById = null;
3507
- const initialStatus = input2.blockedBy ? "blocked" : "open";
3508
- if (input2.blockedBy) {
3509
- const blocker = await resolveTask(client, input2.blockedBy);
3510
- blockedById = String(blocker.id);
3511
- }
3512
- let parentTaskId = null;
3513
- let parentRef = input2.parentTaskId;
3514
- if (!parentRef) {
3515
- const extracted = extractParentFromContext(input2.context);
3516
- if (extracted) {
3517
- parentRef = extracted;
3518
- process.stderr.write(
3519
- "[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
3520
- );
3521
- }
3522
- }
3523
- if (parentRef) {
3524
- try {
3525
- const parent = await resolveTask(client, parentRef);
3526
- parentTaskId = String(parent.id);
3527
- } catch (err) {
3528
- if (!input2.parentTaskId) {
3529
- throw new Error(
3530
- `create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
3531
- );
3532
- }
3533
- throw err;
3534
- }
3535
- }
3536
- let warning;
3537
- const dupCheck = await client.execute({
3538
- sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
3539
- args: [input2.title, input2.assignedTo]
3540
- });
3541
- if (dupCheck.rows.length > 0) {
3542
- warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
3543
- }
3544
- if (input2.baseDir) {
3545
- try {
3546
- await mkdir4(path17.join(input2.baseDir, "exe", "output"), { recursive: true });
3547
- await mkdir4(path17.join(input2.baseDir, "exe", "research"), { recursive: true });
3548
- await ensureArchitectureDoc(input2.baseDir, input2.projectName);
3549
- await ensureGitignoreExe(input2.baseDir);
3550
- } catch {
3551
- }
3552
- }
3553
- await client.execute({
3554
- sql: `INSERT INTO tasks (id, title, assigned_to, assigned_by, project_name, priority, status, task_file, blocked_by, parent_task_id, reviewer, context, created_at, updated_at)
3555
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
3556
- args: [
3557
- id,
3558
- input2.title,
3559
- input2.assignedTo,
3560
- input2.assignedBy,
3561
- input2.projectName,
3562
- input2.priority,
3563
- initialStatus,
3564
- taskFile,
3565
- blockedById,
3566
- parentTaskId,
3567
- input2.reviewer ?? null,
3568
- input2.context,
3569
- now,
3570
- now
3571
- ]
3572
- });
3573
- return {
3574
- id,
3575
- title: input2.title,
3576
- assignedTo: input2.assignedTo,
3577
- assignedBy: input2.assignedBy,
3578
- projectName: input2.projectName,
3579
- priority: input2.priority,
3580
- status: initialStatus,
3581
- taskFile,
3582
- createdAt: now,
3583
- updatedAt: now,
3584
- warning
3585
- };
3586
- }
3587
- async function ensureArchitectureDoc(baseDir, projectName) {
3588
- const archPath = path17.join(baseDir, "exe", "ARCHITECTURE.md");
3589
- try {
3590
- if (existsSync15(archPath)) return;
3591
- const template = [
3592
- `# ${projectName} \u2014 System Architecture`,
3593
- "",
3594
- "> Employees: read this before every task. Update it when you change system structure.",
3595
- `> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
3596
- "",
3597
- "## Overview",
3598
- "",
3599
- "<!-- Describe what this system does, its main components, and how they connect. -->",
3600
- "",
3601
- "## Key Components",
3602
- "",
3603
- "<!-- List the major modules, services, or subsystems. -->",
3604
- "",
3605
- "## Data Flow",
3606
- "",
3607
- "<!-- How does data move through the system? What writes where? -->",
3608
- "",
3609
- "## Invariants",
3610
- "",
3611
- "<!-- Rules that must never be violated. What breaks if these are wrong? -->",
3612
- "",
3613
- "## Dependencies",
3614
- "",
3615
- "<!-- What depends on what? If I change X, what else is affected? -->",
3616
- ""
3617
- ].join("\n");
3618
- await writeFile4(archPath, template, "utf-8");
3619
- } catch {
3620
- }
3621
- }
3622
- async function ensureGitignoreExe(baseDir) {
3623
- const gitignorePath = path17.join(baseDir, ".gitignore");
3624
- try {
3625
- if (existsSync15(gitignorePath)) {
3626
- const content = readFileSync12(gitignorePath, "utf-8");
3627
- if (/^\/?exe\/?$/m.test(content)) return;
3628
- await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
3629
- } else {
3630
- await writeFile4(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
3631
- }
3632
- } catch {
3633
- }
3634
- }
3635
- var init_tasks_crud = __esm({
3636
- "src/lib/tasks-crud.ts"() {
3637
- "use strict";
3638
- init_database();
3639
- }
3640
- });
3641
-
3642
- // src/lib/tasks-review.ts
3643
- var tasks_review_exports = {};
3644
- __export(tasks_review_exports, {
3645
- cleanupReviewFile: () => cleanupReviewFile,
3646
- countNewPendingReviewsSince: () => countNewPendingReviewsSince,
3647
- countPendingReviews: () => countPendingReviews,
3648
- createReviewForCompletedTask: () => createReviewForCompletedTask,
3649
- getReviewChecklist: () => getReviewChecklist,
3650
- listPendingReviews: () => listPendingReviews
3651
- });
3652
- import path18 from "path";
3653
- import { existsSync as existsSync16, readdirSync as readdirSync4, unlinkSync as unlinkSync4 } from "fs";
3654
- async function countPendingReviews() {
3655
- const client = getClient();
3656
- const result = await client.execute({
3657
- sql: "SELECT COUNT(*) as cnt FROM tasks WHERE status = 'needs_review'",
3658
- args: []
3659
- });
3660
- return Number(result.rows[0]?.cnt) || 0;
3661
- }
3662
- async function countNewPendingReviewsSince(sinceIso) {
3663
- const client = getClient();
3664
- const result = await client.execute({
3665
- sql: `SELECT COUNT(*) as cnt FROM tasks
3666
- WHERE status = 'needs_review' AND updated_at > ?`,
3667
- args: [sinceIso]
3668
- });
3669
- return Number(result.rows[0]?.cnt) || 0;
3670
- }
3671
- async function listPendingReviews(limit) {
3672
- const client = getClient();
3673
- const result = await client.execute({
3674
- sql: `SELECT title, assigned_to, project_name FROM tasks
3675
- WHERE status = 'needs_review'
3676
- ORDER BY priority ASC, created_at DESC LIMIT ?`,
3677
- args: [limit]
3678
- });
3679
- return result.rows;
3680
- }
3681
- function getReviewChecklist(role, agent, taskSlug) {
3682
- const roleLower = role.toLowerCase();
3683
- if (roleLower.includes("engineer") || roleLower === "principal engineer") {
3684
- return {
3685
- lens: "Code Quality (Engineer)",
3686
- checklist: [
3687
- "1. Do all tests pass? Any new tests needed?",
3688
- "2. Is the code clean \u2014 no dead code, no TODOs left?",
3689
- "3. Does it follow existing patterns and conventions in the codebase?",
3690
- "4. Any regressions in the test suite?"
3691
- ]
3692
- };
3693
- }
3694
- if (roleLower === "cto" || roleLower.includes("architect")) {
3695
- return {
3696
- lens: "Architecture (CTO)",
3697
- checklist: [
3698
- "1. Does this fit the existing architecture? Consistent with ARCHITECTURE.md?",
3699
- "2. Is it backward compatible? Any breaking changes?",
3700
- "3. Does it introduce technical debt? Is that debt justified?",
3701
- "4. Security implications? Any new attack surface?",
3702
- "5. Does it scale? Performance considerations?",
3703
- "6. Coordination: does this affect other employees' work or other projects?"
3704
- ]
3705
- };
3706
- }
3707
- if (roleLower === "coo" || roleLower.includes("operations")) {
3708
- return {
3709
- lens: "Strategic (COO)",
3710
- checklist: [
3711
- "1. Does this serve the project mission?",
3712
- "2. Is this the right work at the right time?",
3713
- "3. Does the architectural assessment make sense for the business?",
3714
- "4. Any cross-project implications?"
3715
- ]
3716
- };
3717
- }
3718
- return {
3719
- lens: "General",
3720
- checklist: [
3721
- "1. Read the original task's acceptance criteria",
3722
- `2. Check git log for related commits: \`git log --oneline --author-date-order -10\``,
3723
- "3. Verify code changes match requirements",
3724
- "4. Check if tests were added/updated",
3725
- `5. Look for output files in exe/output/${agent}-${taskSlug}*`
3726
- ]
3727
- };
3728
- }
3729
- async function createReviewForCompletedTask(row, result, _baseDir, now) {
3730
- const taskFile = String(row.task_file);
3731
- if (String(row.assigned_to) === "exe") return;
3732
- if (String(row.title).startsWith("Review:")) return;
3733
- const fileName = taskFile.split("/").pop() ?? "";
3734
- if (fileName.startsWith("review-") && String(row.assigned_by) === "system") return;
3735
- if (fileName.startsWith("review-") && String(row.assigned_to) === "system") return;
3736
- const client = getClient();
3737
- const agent = String(row.assigned_to);
3738
- const reviewer = String(row.reviewer || row.assigned_by) || "exe";
3739
- let reviewerRole = "unknown";
3740
- try {
3741
- const employees = await loadEmployees();
3742
- const emp = getEmployee(employees, reviewer);
3743
- if (emp) reviewerRole = emp.role;
3744
- } catch {
3745
- }
3746
- const taskTitle = String(row.title);
3747
- const taskSlug = taskFile.split("/").pop()?.replace(".md", "") ?? "unknown";
3748
- const { lens, checklist } = getReviewChecklist(reviewerRole, agent, taskSlug);
3749
- const reviewSlug = `review-${agent}-${taskSlug}`;
3750
- const reviewFile = `exe/${reviewer}/${reviewSlug}.md`;
3751
- await client.execute({
3752
- sql: "DELETE FROM tasks WHERE task_file = ?",
3753
- args: [reviewFile]
3754
- });
3755
- process.stderr.write(
3756
- `[review] Creating review for "${taskTitle}" \u2192 assigned to ${reviewer} (${reviewerRole})
3757
- `
3758
- );
3759
- const reviewContext = [
3760
- `${agent} marked this task as done:`,
3761
- `- Original task: ${taskFile}`,
3762
- `- Result: ${result ?? "No result summary provided"}`,
3763
- "",
3764
- `## Review lens: ${lens}`,
3765
- `You are reviewing as **${reviewer}** (${reviewerRole}).`,
3766
- "",
3767
- "## Review checklist",
3768
- ...checklist,
3769
- "",
3770
- "## Verdict",
3771
- "After review, update this task:",
3772
- "- **Approved:** mark this review task as done",
3773
- "- **Needs work:** re-open the original task with notes, mark this review as done"
3774
- ].join("\n");
3775
- const reviewTask = await createTaskCore({
3776
- title: `Review: ${agent} completed "${taskTitle}"`,
3777
- assignedTo: reviewer,
3778
- assignedBy: "system",
3779
- projectName: String(row.project_name),
3780
- priority: "p1",
3781
- context: reviewContext,
3782
- taskFile: reviewFile,
3783
- skipDispatch: true
3784
- });
3785
- const reviewId = reviewTask.id;
3786
- await writeNotification({
3787
- agentId: agent,
3788
- agentRole: String(row.assigned_to),
3789
- event: "task_complete",
3790
- project: String(row.project_name),
3791
- summary: `completed "${taskTitle}" \u2014 review task created`,
3792
- taskFile: reviewFile
3793
- });
3794
- const originalPriority = String(row.priority).toLowerCase();
3795
- const autoApprove = originalPriority === "p2" && result?.toLowerCase().includes("tests pass");
3796
- if (!autoApprove) {
3797
- try {
3798
- const key = getSessionKey();
3799
- const exeSession = getParentExe(key);
3800
- if (exeSession) {
3801
- sendIntercom(exeSession);
3802
- }
3803
- } catch {
3804
- }
3805
- }
3806
- if (autoApprove) {
3807
- process.stderr.write(
3808
- `[review] Auto-approving review for "${taskTitle}" (P2 + tests pass)
3809
- `
3810
- );
3811
- await client.execute({
3812
- sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ?",
3813
- args: [now, reviewId]
3814
- });
3815
- }
3816
- }
3817
- async function cleanupReviewFile(row, taskFile, _baseDir) {
3818
- if (String(row.assigned_by) !== "system" || !taskFile.includes("review-")) return;
3819
- try {
3820
- const client = getClient();
3821
- const fileName = taskFile.split("/").pop() ?? "";
3822
- const reviewPrefix = fileName.replace(".md", "");
3823
- const parts = reviewPrefix.split("-");
3824
- if (parts.length >= 3 && parts[0] === "review") {
3825
- const agent = parts[1];
3826
- const slug = parts.slice(2).join("-");
3827
- const originalTaskFile = `exe/${agent}/${slug}.md`;
3828
- const result = await client.execute({
3829
- sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE task_file = ? AND status = 'needs_review'",
3830
- args: [(/* @__PURE__ */ new Date()).toISOString(), originalTaskFile]
3831
- });
3832
- if (result.rowsAffected > 0) {
3833
- process.stderr.write(
3834
- `[review-cleanup] Cascaded original task to done: ${originalTaskFile}
3835
- `
3836
- );
3837
- }
3838
- }
3839
- } catch (err) {
3840
- process.stderr.write(
3841
- `[review-cleanup] Failed to cascade original task: ${err instanceof Error ? err.message : String(err)}
3842
- `
3843
- );
3844
- }
3845
- try {
3846
- const cacheDir = path18.join(EXE_AI_DIR, "session-cache");
3847
- if (existsSync16(cacheDir)) {
3848
- for (const f of readdirSync4(cacheDir)) {
3849
- if (f.startsWith("review-notified-")) {
3850
- unlinkSync4(path18.join(cacheDir, f));
3851
- }
3852
- }
3853
- }
3854
- } catch {
3855
- }
3856
- }
3857
- var init_tasks_review = __esm({
3858
- "src/lib/tasks-review.ts"() {
3859
- "use strict";
3860
- init_database();
3861
- init_config();
3862
- init_employees();
3863
- init_notifications();
3864
- init_tasks_crud();
3865
- init_tmux_routing();
3866
- init_session_key();
3867
- }
3868
- });
3869
-
3870
- // src/adapters/claude/hooks/prompt-submit.ts
3871
- init_config();
3872
- init_config();
3873
- import { spawn as spawn2 } from "child_process";
3874
- import { readFileSync as readFileSync13, writeFileSync as writeFileSync6, mkdirSync as mkdirSync8, existsSync as existsSync17, openSync as openSync2, closeSync as closeSync2 } from "fs";
3875
- import path19 from "path";
3876
- import { fileURLToPath as fileURLToPath3 } from "url";
3877
-
3878
- // src/lib/store.ts
3879
- init_memory();
3880
- init_database();
3881
-
3882
- // src/lib/keychain.ts
3883
- import { readFile as readFile2, writeFile as writeFile2, unlink, mkdir as mkdir2, chmod } from "fs/promises";
3884
- import { existsSync as existsSync2 } from "fs";
3885
- import path2 from "path";
3886
- import crypto from "crypto";
3887
- var SERVICE = "exe-mem";
3888
- var ACCOUNT = "master-key";
3889
- function getKeyDir() {
3890
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path2.join(process.env.HOME ?? "/tmp", ".exe-os");
3891
- }
3892
- function getKeyPath() {
3893
- return path2.join(getKeyDir(), "master.key");
3894
- }
3895
- async function tryKeytar() {
3896
- try {
3897
- return await import("keytar");
3898
- } catch {
3899
- return null;
3900
- }
3901
- }
3902
- async function getMasterKey() {
3903
- const keytar = await tryKeytar();
3904
- if (keytar) {
3905
- try {
3906
- const stored = await keytar.getPassword(SERVICE, ACCOUNT);
3907
- if (stored) {
3908
- return Buffer.from(stored, "base64");
3909
- }
3910
- } catch {
3911
- }
3912
- }
3913
- const keyPath = getKeyPath();
3914
- if (!existsSync2(keyPath)) {
3915
- return null;
3916
- }
3917
- try {
3918
- const content = await readFile2(keyPath, "utf-8");
3919
- return Buffer.from(content.trim(), "base64");
3920
- } catch {
3921
- return null;
3922
- }
3923
- }
3924
-
3925
- // src/lib/store.ts
3926
- init_config();
3927
- var _pendingRecords = [];
3928
- var _batchSize = 20;
3929
- var _flushIntervalMs = 1e4;
3930
- var _flushTimer = null;
3931
- var _flushing = false;
3932
- var _nextVersion = 1;
3933
- async function initStore(options) {
3934
- if (_flushTimer !== null) {
3935
- clearInterval(_flushTimer);
3936
- _flushTimer = null;
3937
- }
3938
- _pendingRecords = [];
3939
- _flushing = false;
3940
- _batchSize = options?.batchSize ?? 20;
3941
- _flushIntervalMs = options?.flushIntervalMs ?? 1e4;
3942
- let dbPath = options?.dbPath;
3943
- if (!dbPath) {
3944
- const config = await loadConfig();
3945
- dbPath = config.dbPath;
3946
- }
3947
- let masterKey = options?.masterKey ?? null;
3948
- if (!masterKey) {
3949
- masterKey = await getMasterKey();
3950
- if (!masterKey) {
3951
- throw new Error(
3952
- "No encryption key found. Run /exe-setup to generate one."
3953
- );
3954
- }
3955
- }
3956
- const hexKey = masterKey.toString("hex");
3957
- await initTurso({
3958
- dbPath,
3959
- encryptionKey: hexKey
3960
- });
3961
- await ensureSchema();
3962
- try {
3963
- const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
3964
- initShardManager2(hexKey);
3965
- } catch {
3966
- }
3967
- const client = getClient();
3968
- const vResult = await client.execute("SELECT MAX(version) as max_v FROM memories");
3969
- _nextVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
3970
- }
3971
- function buildWikiScopeFilter(options, columnPrefix) {
3972
- const args = [];
3973
- let clause = "";
3974
- if (options?.workspaceId !== void 0) {
3975
- clause += ` AND ${columnPrefix}workspace_id = ?`;
3976
- args.push(options.workspaceId);
3977
- }
3978
- if (options?.userId === void 0) {
3979
- clause += ` AND ${columnPrefix}user_id IS NULL`;
3980
- } else if (options.userId === null) {
3981
- clause += ` AND ${columnPrefix}user_id IS NULL`;
3982
- } else {
3983
- clause += ` AND (${columnPrefix}user_id = ? OR ${columnPrefix}user_id IS NULL)`;
3984
- args.push(options.userId);
3985
- }
3986
- return { clause, args };
3987
- }
3988
- async function searchMemories(queryVector, agentId, options) {
3989
- let client;
3990
- try {
3991
- const { isShardingEnabled: isShardingEnabled2, shardExists: shardExists2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
3992
- if (isShardingEnabled2() && options?.projectName && shardExists2(options.projectName)) {
3993
- client = await getReadyShardClient2(options.projectName);
3994
- } else {
3995
- client = getClient();
3996
- }
3997
- } catch {
3998
- client = getClient();
3999
- }
4000
- const limit = options?.limit ?? 10;
4001
- const statusFilter = options?.includeArchived ? "" : `
4002
- AND COALESCE(status, 'active') = 'active'`;
4003
- let sql = `SELECT id, agent_id, agent_role, session_id, timestamp,
4004
- tool_name, project_name,
4005
- has_error, raw_text, vector, importance, status,
4006
- confidence, last_accessed,
4007
- workspace_id, document_id, user_id,
4008
- char_offset, page_number
4009
- FROM memories
4010
- WHERE agent_id = ?
4011
- AND vector IS NOT NULL${statusFilter}
4012
- AND COALESCE(confidence, 0.7) >= 0.3`;
4013
- const args = [agentId];
4014
- const scope = buildWikiScopeFilter(options, "");
4015
- sql += scope.clause;
4016
- args.push(...scope.args);
4017
- if (options?.projectName) {
4018
- sql += ` AND project_name = ?`;
4019
- args.push(options.projectName);
4020
- }
4021
- if (options?.toolName) {
4022
- sql += ` AND tool_name = ?`;
4023
- args.push(options.toolName);
4024
- }
4025
- if (options?.hasError !== void 0) {
4026
- sql += ` AND has_error = ?`;
4027
- args.push(options.hasError ? 1 : 0);
4028
- }
4029
- if (options?.since) {
4030
- sql += ` AND timestamp >= ?`;
4031
- args.push(options.since);
4032
- }
4033
- sql += ` ORDER BY vector_distance_cos(vector, vector32(?))`;
4034
- args.push(vectorToBlob(queryVector));
4035
- sql += ` LIMIT ?`;
4036
- args.push(limit);
4037
- const result = await client.execute({ sql, args });
4038
- return result.rows.map((row) => ({
4039
- id: row.id,
4040
- agent_id: row.agent_id,
4041
- agent_role: row.agent_role,
4042
- session_id: row.session_id,
4043
- timestamp: row.timestamp,
4044
- tool_name: row.tool_name,
4045
- project_name: row.project_name,
4046
- has_error: row.has_error === 1,
4047
- raw_text: row.raw_text,
4048
- vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
4049
- importance: row.importance ?? 5,
4050
- status: row.status ?? "active",
4051
- confidence: row.confidence ?? 0.7,
4052
- last_accessed: row.last_accessed ?? row.timestamp,
4053
- workspace_id: row.workspace_id ?? null,
4054
- document_id: row.document_id ?? null,
4055
- user_id: row.user_id ?? null,
4056
- char_offset: row.char_offset ?? null,
4057
- page_number: row.page_number ?? null
4058
- }));
4059
- }
4060
- async function attachDocumentMetadata(records) {
4061
- const docIds = [
4062
- ...new Set(
4063
- records.map((r) => r.document_id).filter((id) => typeof id === "string" && id.length > 0)
4064
- )
4065
- ];
4066
- if (docIds.length === 0) return records;
4067
- try {
4068
- const client = getClient();
4069
- const placeholders = docIds.map(() => "?").join(",");
4070
- const result = await client.execute({
4071
- sql: `SELECT id, filename, mime, source_type, uploaded_at
4072
- FROM documents
4073
- WHERE id IN (${placeholders})`,
4074
- args: docIds
4075
- });
4076
- const byId = /* @__PURE__ */ new Map();
4077
- for (const row of result.rows) {
4078
- const id = row.id;
4079
- byId.set(id, {
4080
- document_id: id,
4081
- filename: row.filename,
4082
- mime: row.mime ?? null,
4083
- source_type: row.source_type ?? null,
4084
- uploaded_at: row.uploaded_at
4085
- });
4086
- }
4087
- for (const record of records) {
4088
- if (!record.document_id) continue;
4089
- record.document_metadata = byId.get(record.document_id) ?? null;
4090
- }
4091
- } catch {
4092
- }
4093
- return records;
4094
- }
4095
- function vectorToBlob(vector) {
4096
- const f32 = vector instanceof Float32Array ? vector : new Float32Array(vector);
4097
- return JSON.stringify(Array.from(f32));
4098
- }
4099
-
4100
- // src/lib/hybrid-search.ts
4101
- init_database();
4102
- var RRF_K = 60;
4103
- async function hybridSearch(queryText, agentId, options) {
4104
- const { loadConfig: loadConfig2 } = await Promise.resolve().then(() => (init_config(), config_exports));
4105
- const config = await loadConfig2();
4106
- if (config.searchMode === "fts") {
4107
- return lightweightSearch(queryText, agentId, options);
4108
- }
4109
- const limit = options?.limit ?? 10;
4110
- let effectiveQuery = queryText;
4111
- let effectiveOptions = { ...options };
4112
- let _isBroadQuery = false;
4113
- if (config.selfQueryRouter && process.env.ANTHROPIC_API_KEY) {
4114
- try {
4115
- const { routeQuery: routeQuery2 } = await Promise.resolve().then(() => (init_self_query_router(), self_query_router_exports));
4116
- const routed = await routeQuery2(queryText, config.selfQueryModel);
4117
- effectiveQuery = routed.semanticQuery;
4118
- _isBroadQuery = routed.isBroadQuery;
4119
- if (routed.projectFilter && !effectiveOptions.projectName) {
4120
- effectiveOptions.projectName = routed.projectFilter;
4121
- }
4122
- if (routed.timeFilter && !effectiveOptions.since) {
4123
- effectiveOptions.since = routed.timeFilter;
4124
- }
4125
- } catch {
4126
- }
4127
- }
4128
- const broadFetchTopK = config.scalingRoadmap?.rerankerAutoTrigger?.fetchTopK ?? 150;
4129
- const fetchLimit = _isBroadQuery ? Math.max(limit * 5, broadFetchTopK) : Math.max(limit * 3, 30);
4130
- const fetchOptions = { ...effectiveOptions, limit: fetchLimit, includeSource: false };
4131
- let queryVector = null;
4132
- try {
4133
- const { embed: embed2 } = await Promise.resolve().then(() => (init_embedder(), embedder_exports));
4134
- queryVector = await embed2(effectiveQuery);
4135
- } catch {
4136
- process.stderr.write("[hybrid-search] Embed daemon unavailable \u2014 FTS-only mode\n");
4137
- }
4138
- let grepPromise = Promise.resolve([]);
4139
- if (config.fileGrepEnabled !== false) {
4140
- try {
4141
- const { getProjectName: getProjectName2 } = await Promise.resolve().then(() => (init_project_name(), project_name_exports));
4142
- const projectRoot = process.cwd();
4143
- const projectName = getProjectName2(projectRoot);
4144
- if (projectName && projectName !== "tmp") {
4145
- const { grepProjectFiles: grepProjectFiles2 } = await Promise.resolve().then(() => (init_file_grep(), file_grep_exports));
4146
- grepPromise = grepProjectFiles2(effectiveQuery, projectRoot, {
4147
- maxResults: 10
4148
- }).catch(() => []);
4149
- }
4150
- } catch {
4151
- }
4152
- }
4153
- const [ftsResults, vectorResults, grepResults] = await Promise.all([
4154
- lightweightSearch(effectiveQuery, agentId, fetchOptions),
4155
- queryVector ? searchMemories(queryVector, agentId, fetchOptions) : Promise.resolve([]),
4156
- grepPromise
4157
- ]);
4158
- const lists = [];
4159
- const weights = [];
4160
- if (ftsResults.length > 0) {
4161
- lists.push(ftsResults);
4162
- weights.push(1);
4163
- }
4164
- if (vectorResults.length > 0) {
4165
- lists.push(vectorResults);
4166
- weights.push(1);
4167
- }
4168
- if (grepResults.length > 0) {
4169
- lists.push(grepResults);
4170
- weights.push(0.5);
4171
- }
4172
- if (lists.length === 0) return [];
4173
- if (lists.length === 1 && !_isBroadQuery) return lists[0].slice(0, limit);
4174
- const rrfLimit = _isBroadQuery ? Math.max(limit * 5, 150) : limit;
4175
- const merged = lists.length === 1 ? lists[0].slice(0, rrfLimit) : rrfMergeMulti(lists, rrfLimit, RRF_K, weights);
4176
- const auto = config.scalingRoadmap?.rerankerAutoTrigger ?? {
4177
- enabled: config.rerankerEnabled ?? true,
4178
- broadQueryMinCardinality: 5e4,
4179
- fetchTopK: 150,
4180
- returnTopK: 5
4181
- };
4182
- let rerankedAndBlended = null;
4183
- if (_isBroadQuery && auto.enabled) {
4184
- const cardinality = await estimateCardinality(agentId, effectiveOptions);
4185
- if (cardinality > auto.broadQueryMinCardinality) {
4186
- try {
4187
- const { isRerankerAvailable: isRerankerAvailable2, rerank: rerank2 } = await Promise.resolve().then(() => (init_reranker(), reranker_exports));
4188
- if (isRerankerAvailable2()) {
4189
- const reranked = await rerank2(effectiveQuery, merged, auto.returnTopK);
4190
- if (reranked.length > 0) {
4191
- rerankedAndBlended = rrfMergeMulti(
4192
- [reranked],
4193
- auto.returnTopK,
4194
- RRF_K
4195
- );
4196
- }
4197
- }
4198
- } catch {
4199
- }
4200
- }
4201
- }
4202
- const finalResults = (rerankedAndBlended ?? merged).slice(
4203
- 0,
4204
- rerankedAndBlended ? auto.returnTopK : limit
4205
- );
4206
- if (options?.includeSource && finalResults.length > 0) {
4207
- await attachDocumentMetadata(finalResults);
4208
- }
4209
- if (finalResults.length > 0) {
4210
- const now = (/* @__PURE__ */ new Date()).toISOString();
4211
- const ids = finalResults.map((r) => r.id);
4212
- const placeholders = ids.map(() => "?").join(",");
4213
- try {
4214
- const client = getClient();
4215
- void client.execute({
4216
- sql: `UPDATE memories SET last_accessed = ? WHERE id IN (${placeholders})`,
4217
- args: [now, ...ids]
4218
- }).catch(() => {
4219
- });
4220
- } catch {
4221
- }
4222
- }
4223
- return finalResults;
4224
- }
4225
- async function estimateCardinality(agentId, options) {
4226
- const client = getClient();
4227
- let sql = `SELECT COUNT(*) as cnt FROM memories
4228
- WHERE agent_id = ?
4229
- AND COALESCE(status, 'active') = 'active'
4230
- AND COALESCE(confidence, 0.7) >= 0.3`;
4231
- const args = [agentId];
4232
- if (options?.projectName) {
4233
- sql += ` AND project_name = ?`;
4234
- args.push(options.projectName);
4235
- }
4236
- if (options?.toolName) {
4237
- sql += ` AND tool_name = ?`;
4238
- args.push(options.toolName);
4239
- }
4240
- if (options?.hasError !== void 0) {
4241
- sql += ` AND has_error = ?`;
4242
- args.push(options.hasError ? 1 : 0);
4243
- }
4244
- if (options?.since) {
4245
- sql += ` AND timestamp >= ?`;
4246
- args.push(options.since);
4247
- }
4248
- try {
4249
- const result = await client.execute({ sql, args });
4250
- return Number(result.rows[0]?.cnt) || 0;
4251
- } catch {
4252
- return 0;
4253
- }
4254
- }
4255
- function recencyScore(timestamp) {
4256
- const daysSince = (Date.now() - new Date(timestamp).getTime()) / (1e3 * 60 * 60 * 24);
4257
- return 1 / (1 + daysSince * 0.01);
4258
- }
4259
- function normalizedImportance(importance) {
4260
- return ((importance ?? 5) - 1) / 9;
4261
- }
4262
- function rrfMergeMulti(lists, limit, k = RRF_K, weights) {
4263
- const scores = /* @__PURE__ */ new Map();
4264
- for (let listIdx = 0; listIdx < lists.length; listIdx++) {
4265
- const list = lists[listIdx];
4266
- const weight = weights?.[listIdx] ?? 1;
4267
- for (let i = 0; i < list.length; i++) {
4268
- const rec = list[i];
4269
- const entry = scores.get(rec.id) ?? { rrfScore: 0, record: rec };
4270
- entry.rrfScore += weight * (1 / (k + i + 1));
4271
- scores.set(rec.id, entry);
4272
- }
4273
- }
4274
- const entries = Array.from(scores.values()).map((e) => {
4275
- const recency = recencyScore(e.record.timestamp);
4276
- const importance = normalizedImportance(e.record.importance);
4277
- const confidence = e.record.confidence ?? 0.7;
4278
- const finalScore = e.rrfScore * 0.35 + recency * 0.14 + importance * 0.21 + confidence * 0.3;
4279
- return { score: finalScore, record: e.record };
4280
- });
4281
- return entries.sort((a, b) => b.score - a.score).slice(0, limit).map((e) => e.record);
4282
- }
4283
- async function lightweightSearch(queryText, agentId, options) {
4284
- const client = getClient();
4285
- const limit = options?.limit ?? 5;
4286
- const terms = queryText.toLowerCase().split(/\s+/).filter((t) => t.length >= 3).map((t) => t.replace(/[^a-z0-9_]/g, "")).filter((t) => t.length >= 3);
4287
- if (terms.length === 0) {
4288
- return recentRecords(agentId, options, limit);
4289
- }
4290
- const prefixTerms = terms.map((t) => `${t}*`);
4291
- const useAnd = terms.length >= 3;
4292
- const matchExpr = useAnd ? prefixTerms.join(" AND ") : prefixTerms.join(" OR ");
4293
- const results = await ftsQuery(client, matchExpr, agentId, options, limit);
4294
- if (useAnd && results.length < limit) {
4295
- const orExpr = prefixTerms.join(" OR ");
4296
- const orResults = await ftsQuery(client, orExpr, agentId, options, limit);
4297
- const seen = new Set(results.map((r) => r.id));
4298
- for (const r of orResults) {
4299
- if (!seen.has(r.id) && results.length < limit) {
4300
- results.push(r);
4301
- seen.add(r.id);
4302
- }
4303
- }
4304
- }
4305
- if (options?.includeSource && results.length > 0) {
4306
- await attachDocumentMetadata(results);
4307
- }
4308
- return results;
4309
- }
4310
- async function ftsQuery(client, matchExpr, agentId, options, limit) {
4311
- const statusFilter = options?.includeArchived ? "" : `
4312
- AND COALESCE(m.status, 'active') = 'active'`;
4313
- let sql = `SELECT m.id, m.agent_id, m.agent_role, m.session_id, m.timestamp,
4314
- m.tool_name, m.project_name,
4315
- m.has_error, m.raw_text, m.vector, m.task_id,
4316
- m.importance, m.status, m.confidence, m.last_accessed,
4317
- m.workspace_id, m.document_id, m.user_id,
4318
- m.char_offset, m.page_number
4319
- FROM memories m
4320
- JOIN memories_fts fts ON m.rowid = fts.rowid
4321
- WHERE memories_fts MATCH ?
4322
- AND m.agent_id = ?${statusFilter}
4323
- AND COALESCE(m.confidence, 0.7) >= 0.3`;
4324
- const args = [matchExpr, agentId];
4325
- const scope = buildWikiScopeFilter(options, "m.");
4326
- sql += scope.clause;
4327
- args.push(...scope.args);
4328
- if (options?.projectName) {
4329
- sql += ` AND m.project_name = ?`;
4330
- args.push(options.projectName);
4331
- }
4332
- if (options?.toolName) {
4333
- sql += ` AND m.tool_name = ?`;
4334
- args.push(options.toolName);
4335
- }
4336
- if (options?.hasError !== void 0) {
4337
- sql += ` AND m.has_error = ?`;
4338
- args.push(options.hasError ? 1 : 0);
4339
- }
4340
- if (options?.since) {
4341
- sql += ` AND m.timestamp >= ?`;
4342
- args.push(options.since);
4343
- }
4344
- sql += ` ORDER BY rank LIMIT ?`;
4345
- args.push(limit);
4346
- const result = await client.execute({ sql, args });
4347
- return result.rows.map((row) => ({
4348
- id: row.id,
4349
- agent_id: row.agent_id,
4350
- agent_role: row.agent_role,
4351
- session_id: row.session_id,
4352
- timestamp: row.timestamp,
4353
- tool_name: row.tool_name,
4354
- project_name: row.project_name,
4355
- has_error: row.has_error === 1,
4356
- raw_text: row.raw_text,
4357
- vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
4358
- task_id: row.task_id ?? null,
4359
- importance: row.importance ?? 5,
4360
- status: row.status ?? "active",
4361
- confidence: row.confidence ?? 0.7,
4362
- last_accessed: row.last_accessed ?? row.timestamp,
4363
- workspace_id: row.workspace_id ?? null,
4364
- document_id: row.document_id ?? null,
4365
- user_id: row.user_id ?? null,
4366
- char_offset: row.char_offset ?? null,
4367
- page_number: row.page_number ?? null
4368
- }));
4369
- }
4370
- async function recentRecords(agentId, options, limit) {
4371
- const client = getClient();
4372
- const statusFilter = options?.includeArchived ? "" : `
4373
- AND COALESCE(status, 'active') = 'active'`;
4374
- let sql = `SELECT id, agent_id, agent_role, session_id, timestamp,
4375
- tool_name, project_name,
4376
- has_error, raw_text, vector, task_id,
4377
- importance, status, confidence, last_accessed,
4378
- workspace_id, document_id, user_id,
4379
- char_offset, page_number
4380
- FROM memories
4381
- WHERE agent_id = ?${statusFilter}
4382
- AND COALESCE(confidence, 0.7) >= 0.3`;
4383
- const args = [agentId];
4384
- const scope = buildWikiScopeFilter(options, "");
4385
- sql += scope.clause;
4386
- args.push(...scope.args);
4387
- if (options?.projectName) {
4388
- sql += ` AND project_name = ?`;
4389
- args.push(options.projectName);
4390
- }
4391
- if (options?.toolName) {
4392
- sql += ` AND tool_name = ?`;
4393
- args.push(options.toolName);
4394
- }
4395
- if (options?.hasError !== void 0) {
4396
- sql += ` AND has_error = ?`;
4397
- args.push(options.hasError ? 1 : 0);
4398
- }
4399
- if (options?.since) {
4400
- sql += ` AND timestamp >= ?`;
4401
- args.push(options.since);
4402
- }
4403
- sql += ` ORDER BY timestamp DESC LIMIT ?`;
4404
- args.push(limit);
4405
- const result = await client.execute({ sql, args });
4406
- return result.rows.map((row) => ({
4407
- id: row.id,
4408
- agent_id: row.agent_id,
4409
- agent_role: row.agent_role,
4410
- session_id: row.session_id,
4411
- timestamp: row.timestamp,
4412
- tool_name: row.tool_name,
4413
- project_name: row.project_name,
4414
- has_error: row.has_error === 1,
4415
- raw_text: row.raw_text,
4416
- vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
4417
- task_id: row.task_id ?? null,
4418
- importance: row.importance ?? 5,
4419
- status: row.status ?? "active",
4420
- confidence: row.confidence ?? 0.7,
4421
- last_accessed: row.last_accessed ?? row.timestamp,
4422
- workspace_id: row.workspace_id ?? null,
4423
- document_id: row.document_id ?? null,
4424
- user_id: row.user_id ?? null,
4425
- char_offset: row.char_offset ?? null,
4426
- page_number: row.page_number ?? null
4427
- }));
4428
- }
4429
-
4430
- // src/adapters/claude/active-agent.ts
4431
- init_config();
4432
- import { readFileSync as readFileSync4, writeFileSync, mkdirSync as mkdirSync2, unlinkSync as unlinkSync2, readdirSync as readdirSync2 } from "fs";
4433
- import { execSync as execSync4 } from "child_process";
4434
- import path8 from "path";
4435
-
4436
- // src/adapters/claude/session-key.ts
4437
- init_session_key();
4438
-
4439
- // src/adapters/claude/active-agent.ts
4440
- var CACHE_DIR = path8.join(EXE_AI_DIR, "session-cache");
4441
- var STALE_MS = 24 * 60 * 60 * 1e3;
4442
- function getMarkerPath() {
4443
- return path8.join(CACHE_DIR, `active-agent-${getSessionKey()}.json`);
4444
- }
4445
- function getActiveAgent() {
4446
- try {
4447
- const markerPath = getMarkerPath();
4448
- const raw = readFileSync4(markerPath, "utf8");
4449
- const data = JSON.parse(raw);
4450
- if (data.agentId) {
4451
- if (data.startedAt) {
4452
- const age = Date.now() - new Date(data.startedAt).getTime();
4453
- if (age > STALE_MS) {
4454
- try {
4455
- unlinkSync2(markerPath);
4456
- } catch {
4457
- }
4458
- } else {
4459
- return {
4460
- agentId: data.agentId,
4461
- agentRole: data.agentRole || "employee"
4462
- };
4463
- }
4464
- } else {
4465
- return {
4466
- agentId: data.agentId,
4467
- agentRole: data.agentRole || "employee"
4468
- };
4469
- }
4470
- }
4471
- } catch {
4472
- }
4473
- try {
4474
- const sessionName = execSync4(
4475
- "tmux display-message -p '#{session_name}' 2>/dev/null",
4476
- { encoding: "utf8", timeout: 2e3 }
4477
- ).trim();
4478
- const empMatch = sessionName.match(/^(\w+)-exe\d+$/);
4479
- if (empMatch && empMatch[1] !== "exe") {
4480
- return { agentId: empMatch[1], agentRole: "employee" };
4481
- }
4482
- if (/^exe\d+$/.test(sessionName)) {
4483
- return { agentId: "exe", agentRole: "COO" };
4484
- }
4485
- } catch {
4486
- }
4487
- return {
4488
- agentId: process.env.AGENT_ID || "default",
4489
- agentRole: process.env.AGENT_ROLE || "employee"
4490
- };
4491
- }
4492
-
4493
- // src/adapters/claude/hooks/prompt-submit.ts
4494
- if (!process.env.AGENT_ID) {
4495
- process.env.AGENT_ID = "default";
4496
- process.env.AGENT_ROLE = "employee";
4497
- }
4498
- if (!loadConfigSync().autoRetrieval) {
4499
- process.exit(0);
4500
- }
4501
- var WORKER_LOG_PATH = path19.join(EXE_AI_DIR, "workers.log");
4502
- function openWorkerLog() {
4503
- try {
4504
- return openSync2(WORKER_LOG_PATH, "a");
4505
- } catch {
4506
- return "ignore";
4507
- }
4508
- }
4509
- var CACHE_DIR2 = path19.join(EXE_AI_DIR, "session-cache");
4510
- function loadInjectedIds(sessionId) {
4511
- try {
4512
- const raw = readFileSync13(path19.join(CACHE_DIR2, `${sessionId}.json`), "utf8");
4513
- return new Set(JSON.parse(raw));
4514
- } catch {
4515
- return /* @__PURE__ */ new Set();
4516
- }
4517
- }
4518
- function saveInjectedIds(sessionId, ids) {
4519
- try {
4520
- mkdirSync8(CACHE_DIR2, { recursive: true });
4521
- writeFileSync6(
4522
- path19.join(CACHE_DIR2, `${sessionId}.json`),
4523
- JSON.stringify([...ids])
4524
- );
4525
- } catch {
4526
- }
4527
- }
4528
- var timeout = setTimeout(() => {
4529
- process.exit(0);
4530
- }, 5e3);
4531
- timeout.unref();
4532
- var input = "";
4533
- process.stdin.setEncoding("utf8");
4534
- process.stdin.on("data", (chunk) => {
4535
- input += chunk;
4536
- });
4537
- process.stdin.on("end", async () => {
4538
- try {
4539
- const data = JSON.parse(input);
4540
- const prompt = data.prompt;
4541
- const agent = getActiveAgent();
4542
- if (prompt.length < 20) {
4543
- if (prompt.length >= 10) {
4544
- spawnPromptWorker(prompt, data.session_id, agent);
4545
- }
4546
- process.exit(0);
4547
- }
4548
- await initStore();
4549
- if (agent.agentId !== "default" && agent.agentId !== "exe") {
4550
- try {
4551
- const { getReadMessages: getReadMessages2, markAcknowledged: markAcknowledged2 } = await Promise.resolve().then(() => (init_messaging(), messaging_exports));
4552
- const readMsgs = await getReadMessages2(agent.agentId);
4553
- for (const msg of readMsgs) {
4554
- await markAcknowledged2(msg.id);
4555
- }
4556
- } catch {
4557
- }
4558
- }
4559
- try {
4560
- const { execSync: execSync10 } = await import("child_process");
4561
- const currentSession = execSync10("tmux display-message -p '#{session_name}' 2>/dev/null", {
4562
- encoding: "utf8",
4563
- timeout: 2e3
4564
- }).trim();
4565
- if (currentSession) {
4566
- const { drainForSession: drainForSession2 } = await Promise.resolve().then(() => (init_intercom_queue(), intercom_queue_exports));
4567
- const transport = (await Promise.resolve().then(() => (init_transport(), transport_exports))).getTransport();
4568
- drainForSession2(currentSession, (session) => {
4569
- try {
4570
- transport.sendKeys(session, "/exe-intercom");
4571
- return true;
4572
- } catch {
4573
- return false;
4574
- }
4575
- });
4576
- }
4577
- } catch {
4578
- }
4579
- const config = await loadConfig();
4580
- const search = config.hookSearchMode === "hybrid" ? hybridSearch : lightweightSearch;
4581
- const memories = await search(
4582
- prompt.slice(0, 200),
4583
- agent.agentId,
4584
- { limit: 5 }
4585
- );
4586
- let memoryContext = "";
4587
- if (memories.length > 0) {
4588
- const injected = loadInjectedIds(data.session_id);
4589
- const fresh = memories.filter((m) => !injected.has(m.id));
4590
- if (fresh.length > 0) {
4591
- for (const m of fresh) injected.add(m.id);
4592
- saveInjectedIds(data.session_id, injected);
4593
- memoryContext = `## Relevant Memories
4594
- ${fresh.map(
4595
- (m) => `[${m.timestamp}] ${m.tool_name}: ${m.raw_text.slice(0, 300)}`
4596
- ).join("\n")}`;
4597
- }
4598
- }
4599
- let reviewContext = "";
4600
- if (agent.agentId === "exe" || agent.agentId === "default") {
4601
- try {
4602
- const { countPendingReviews: countPendingReviews2, countNewPendingReviewsSince: countNewPendingReviewsSince2 } = await Promise.resolve().then(() => (init_tasks_review(), tasks_review_exports));
4603
- const sessionKey = getSessionKey();
4604
- const lastCheckPath = path19.join(CACHE_DIR2, `review-lastcheck-${sessionKey}.json`);
4605
- let lastCheckedAt = "";
4606
- try {
4607
- lastCheckedAt = readFileSync13(lastCheckPath, "utf8").trim();
4608
- } catch {
4609
- }
4610
- const totalCount = await countPendingReviews2();
4611
- if (totalCount > 0) {
4612
- const newCount = lastCheckedAt ? await countNewPendingReviewsSince2(lastCheckedAt) : totalCount;
4613
- const trimmedPrompt = prompt.trim().toLowerCase();
4614
- const idleCommands = /* @__PURE__ */ new Set([
4615
- "c",
4616
- "continue",
4617
- "ok",
4618
- "yes",
4619
- "go",
4620
- "y",
4621
- "k",
4622
- "/exe-intercom",
4623
- "/exe-review",
4624
- "review",
4625
- "check reviews"
4626
- ]);
4627
- const isIdle = trimmedPrompt.length < 20 || idleCommands.has(trimmedPrompt);
4628
- if (newCount > 0) {
4629
- reviewContext = `
4630
- [\u{1F4CB} ${newCount} NEW review${newCount === 1 ? "" : "s"} since your last response \u2014 run /exe-review to process]`;
4631
- if (isIdle) {
4632
- reviewContext += `
4633
-
4634
- IMPORTANT: After completing your current task, you MUST address the pending review above. Do not ignore it.`;
4635
- }
4636
- } else {
4637
- reviewContext = `
4638
- [\u{1F4CB} ${totalCount} review${totalCount === 1 ? "" : "s"} pending \u2014 run /exe-review to process]`;
4639
- }
4640
- }
4641
- const { writeFileSync: wf, mkdirSync: md } = await import("fs");
4642
- md(CACHE_DIR2, { recursive: true });
4643
- wf(lastCheckPath, (/* @__PURE__ */ new Date()).toISOString());
4644
- } catch {
4645
- }
4646
- }
4647
- const combined = [memoryContext, reviewContext].filter(Boolean).join("\n");
4648
- if (combined.length > 0) {
4649
- const output = JSON.stringify({
4650
- hookSpecificOutput: {
4651
- hookEventName: "UserPromptSubmit",
4652
- additionalContext: combined
4653
- }
4654
- });
4655
- process.stdout.write(output);
4656
- }
4657
- spawnPromptWorker(prompt, data.session_id, agent);
4658
- } catch {
4659
- }
4660
- process.exit(0);
4661
- });
4662
- function spawnPromptWorker(prompt, sessionId, agent) {
4663
- if (!loadConfigSync().autoIngestion) return;
4664
- try {
4665
- const workerPath = path19.resolve(
4666
- path19.dirname(fileURLToPath3(import.meta.url)),
4667
- "prompt-ingest-worker.js"
4668
- );
4669
- if (!existsSync17(workerPath)) {
4670
- process.stderr.write(`[prompt-submit] WARN: prompt-ingest-worker not found at ${workerPath}
4671
- `);
4672
- return;
4673
- }
4674
- const stderrFd = openWorkerLog();
4675
- const worker = spawn2(process.execPath, [workerPath], {
4676
- detached: true,
4677
- stdio: ["ignore", "ignore", stderrFd],
4678
- env: {
4679
- ...process.env,
4680
- AGENT_ID: agent.agentId,
4681
- AGENT_ROLE: agent.agentRole,
4682
- EXE_PROMPT_TEXT: prompt.slice(0, 2e3),
4683
- EXE_SESSION_ID: sessionId
4684
- }
4685
- });
4686
- worker.unref();
4687
- if (typeof stderrFd === "number") try {
4688
- closeSync2(stderrFd);
4689
- } catch {
4690
- }
4691
- } catch {
4692
- }
4693
- }