@askexenow/exe-os 0.8.1 → 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 (106) hide show
  1. package/package.json +1 -1
  2. package/dist/bin/backfill-responses.js +0 -2064
  3. package/dist/bin/backfill-vectors.js +0 -1771
  4. package/dist/bin/cleanup-stale-review-tasks.js +0 -1468
  5. package/dist/bin/cli.js +0 -21371
  6. package/dist/bin/exe-agent.js +0 -2016
  7. package/dist/bin/exe-assign.js +0 -2176
  8. package/dist/bin/exe-boot.js +0 -6332
  9. package/dist/bin/exe-call.js +0 -341
  10. package/dist/bin/exe-cloud.js +0 -861
  11. package/dist/bin/exe-dispatch.js +0 -1159
  12. package/dist/bin/exe-doctor.js +0 -1786
  13. package/dist/bin/exe-export-behaviors.js +0 -1637
  14. package/dist/bin/exe-forget.js +0 -1784
  15. package/dist/bin/exe-gateway.js +0 -8140
  16. package/dist/bin/exe-healthcheck.js +0 -207
  17. package/dist/bin/exe-heartbeat.js +0 -1778
  18. package/dist/bin/exe-kill.js +0 -1622
  19. package/dist/bin/exe-launch-agent.js +0 -1847
  20. package/dist/bin/exe-link.js +0 -192
  21. package/dist/bin/exe-new-employee.js +0 -1384
  22. package/dist/bin/exe-pending-messages.js +0 -1576
  23. package/dist/bin/exe-pending-notifications.js +0 -1450
  24. package/dist/bin/exe-pending-reviews.js +0 -1598
  25. package/dist/bin/exe-repo-drift.js +0 -95
  26. package/dist/bin/exe-review.js +0 -1742
  27. package/dist/bin/exe-search.js +0 -3116
  28. package/dist/bin/exe-session-cleanup.js +0 -3360
  29. package/dist/bin/exe-settings.js +0 -365
  30. package/dist/bin/exe-status.js +0 -1661
  31. package/dist/bin/exe-team.js +0 -1453
  32. package/dist/bin/git-sweep.js +0 -2441
  33. package/dist/bin/graph-backfill.js +0 -2111
  34. package/dist/bin/graph-export.js +0 -1747
  35. package/dist/bin/install.js +0 -661
  36. package/dist/bin/list-providers.js +0 -140
  37. package/dist/bin/scan-tasks.js +0 -2039
  38. package/dist/bin/setup.js +0 -2717
  39. package/dist/bin/shard-migrate.js +0 -1637
  40. package/dist/bin/update.js +0 -98
  41. package/dist/bin/wiki-sync.js +0 -1657
  42. package/dist/gateway/index.js +0 -9256
  43. package/dist/hooks/bug-report-worker.js +0 -2903
  44. package/dist/hooks/commit-complete.js +0 -2364
  45. package/dist/hooks/error-recall.js +0 -3327
  46. package/dist/hooks/exe-heartbeat-hook.js +0 -237
  47. package/dist/hooks/ingest-worker.js +0 -5065
  48. package/dist/hooks/ingest.js +0 -695
  49. package/dist/hooks/instructions-loaded.js +0 -2069
  50. package/dist/hooks/notification.js +0 -1915
  51. package/dist/hooks/post-compact.js +0 -1940
  52. package/dist/hooks/pre-compact.js +0 -1935
  53. package/dist/hooks/pre-tool-use.js +0 -2380
  54. package/dist/hooks/prompt-ingest-worker.js +0 -2291
  55. package/dist/hooks/prompt-submit.js +0 -5189
  56. package/dist/hooks/response-ingest-worker.js +0 -2431
  57. package/dist/hooks/session-end.js +0 -2196
  58. package/dist/hooks/session-start.js +0 -3259
  59. package/dist/hooks/stop.js +0 -2025
  60. package/dist/hooks/subagent-stop.js +0 -1915
  61. package/dist/hooks/summary-worker.js +0 -2931
  62. package/dist/index.js +0 -12327
  63. package/dist/lib/cloud-sync.js +0 -500
  64. package/dist/lib/config.js +0 -235
  65. package/dist/lib/consolidation.js +0 -481
  66. package/dist/lib/crypto.js +0 -51
  67. package/dist/lib/database.js +0 -834
  68. package/dist/lib/device-registry.js +0 -1009
  69. package/dist/lib/embedder.js +0 -645
  70. package/dist/lib/employee-templates.js +0 -570
  71. package/dist/lib/employees.js +0 -182
  72. package/dist/lib/error-detector.js +0 -156
  73. package/dist/lib/exe-daemon-client.js +0 -456
  74. package/dist/lib/exe-daemon.js +0 -8699
  75. package/dist/lib/file-grep.js +0 -215
  76. package/dist/lib/hybrid-search.js +0 -3064
  77. package/dist/lib/identity-templates.js +0 -441
  78. package/dist/lib/identity.js +0 -228
  79. package/dist/lib/keychain.js +0 -145
  80. package/dist/lib/license.js +0 -382
  81. package/dist/lib/messaging.js +0 -1389
  82. package/dist/lib/reminders.js +0 -63
  83. package/dist/lib/schedules.js +0 -1525
  84. package/dist/lib/session-registry.js +0 -52
  85. package/dist/lib/skill-learning.js +0 -488
  86. package/dist/lib/status-brief.js +0 -240
  87. package/dist/lib/store.js +0 -1740
  88. package/dist/lib/task-router.js +0 -128
  89. package/dist/lib/tasks.js +0 -2585
  90. package/dist/lib/tmux-routing.js +0 -2969
  91. package/dist/lib/tmux-status.js +0 -261
  92. package/dist/lib/tmux-transport.js +0 -83
  93. package/dist/lib/transport.js +0 -128
  94. package/dist/lib/ws-auth.js +0 -19
  95. package/dist/lib/ws-client.js +0 -160
  96. package/dist/mcp/server.js +0 -10812
  97. package/dist/mcp/tools/complete-reminder.js +0 -67
  98. package/dist/mcp/tools/create-reminder.js +0 -52
  99. package/dist/mcp/tools/create-task.js +0 -1903
  100. package/dist/mcp/tools/deactivate-behavior.js +0 -268
  101. package/dist/mcp/tools/list-reminders.js +0 -62
  102. package/dist/mcp/tools/list-tasks.js +0 -491
  103. package/dist/mcp/tools/send-message.js +0 -1395
  104. package/dist/mcp/tools/update-task.js +0 -1807
  105. package/dist/runtime/index.js +0 -7201
  106. package/dist/tui/App.js +0 -17874
@@ -1,2969 +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 __esm = (fn, res) => function __init() {
6
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
7
- };
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
21
-
22
- // src/lib/session-registry.ts
23
- import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs";
24
- import path from "path";
25
- import os from "os";
26
- function registerSession(entry) {
27
- const dir = path.dirname(REGISTRY_PATH);
28
- if (!existsSync(dir)) {
29
- mkdirSync(dir, { recursive: true });
30
- }
31
- const sessions = listSessions();
32
- const idx = sessions.findIndex((s) => s.windowName === entry.windowName);
33
- if (idx >= 0) {
34
- sessions[idx] = entry;
35
- } else {
36
- sessions.push(entry);
37
- }
38
- writeFileSync(REGISTRY_PATH, JSON.stringify(sessions, null, 2));
39
- }
40
- function listSessions() {
41
- try {
42
- const raw = readFileSync(REGISTRY_PATH, "utf8");
43
- return JSON.parse(raw);
44
- } catch {
45
- return [];
46
- }
47
- }
48
- var REGISTRY_PATH;
49
- var init_session_registry = __esm({
50
- "src/lib/session-registry.ts"() {
51
- "use strict";
52
- REGISTRY_PATH = path.join(os.homedir(), ".exe-os", "session-registry.json");
53
- }
54
- });
55
-
56
- // src/lib/session-key.ts
57
- import { execSync } from "child_process";
58
- function getSessionKey() {
59
- if (_cached) return _cached;
60
- let pid = process.ppid;
61
- for (let i = 0; i < 10; i++) {
62
- try {
63
- const info = execSync(`ps -p ${pid} -o ppid=,comm=`, {
64
- encoding: "utf8",
65
- timeout: 2e3
66
- }).trim();
67
- const match = info.match(/^\s*(\d+)\s+(.+)$/);
68
- if (!match) break;
69
- const [, ppid, cmd] = match;
70
- if (cmd === "claude" || cmd.endsWith("/claude")) {
71
- _cached = String(pid);
72
- return _cached;
73
- }
74
- pid = parseInt(ppid, 10);
75
- if (pid <= 1) break;
76
- } catch {
77
- break;
78
- }
79
- }
80
- _cached = process.env.CLAUDE_CODE_SSE_PORT ?? String(process.ppid);
81
- return _cached;
82
- }
83
- var _cached;
84
- var init_session_key = __esm({
85
- "src/lib/session-key.ts"() {
86
- "use strict";
87
- _cached = null;
88
- }
89
- });
90
-
91
- // src/lib/tmux-transport.ts
92
- var tmux_transport_exports = {};
93
- __export(tmux_transport_exports, {
94
- TmuxTransport: () => TmuxTransport
95
- });
96
- import { execFileSync } from "child_process";
97
- var QUIET, TmuxTransport;
98
- var init_tmux_transport = __esm({
99
- "src/lib/tmux-transport.ts"() {
100
- "use strict";
101
- QUIET = {
102
- encoding: "utf8",
103
- stdio: ["pipe", "pipe", "pipe"]
104
- };
105
- TmuxTransport = class {
106
- getMySession() {
107
- try {
108
- return execFileSync("tmux", ["display-message", "-p", "#{session_name}"], QUIET).trim() || null;
109
- } catch {
110
- return null;
111
- }
112
- }
113
- listSessions() {
114
- try {
115
- return execFileSync("tmux", ["list-sessions", "-F", "#{session_name}"], QUIET).trim().split("\n").filter(Boolean);
116
- } catch {
117
- return [];
118
- }
119
- }
120
- isAlive(target) {
121
- try {
122
- const sessions = this.listSessions();
123
- if (!sessions.includes(target)) return false;
124
- const paneStatus = execFileSync(
125
- "tmux",
126
- ["list-panes", "-t", target, "-F", "#{pane_dead}"],
127
- QUIET
128
- ).trim();
129
- return paneStatus !== "1";
130
- } catch {
131
- return false;
132
- }
133
- }
134
- sendKeys(target, keys) {
135
- execFileSync("tmux", ["send-keys", "-t", target, keys, "Enter"], QUIET);
136
- }
137
- capturePane(target, lines) {
138
- const args = ["capture-pane", "-t", target, "-p"];
139
- if (lines) args.push("-S", `-${lines}`);
140
- return execFileSync("tmux", args, { ...QUIET, timeout: 3e3 });
141
- }
142
- isPaneInCopyMode(target) {
143
- try {
144
- const result = execFileSync(
145
- "tmux",
146
- ["display-message", "-p", "-t", target, "#{pane_in_mode}"],
147
- { ...QUIET, timeout: 3e3 }
148
- ).trim();
149
- return result === "1";
150
- } catch {
151
- return false;
152
- }
153
- }
154
- spawn(name, config) {
155
- try {
156
- const args = ["new-session", "-d", "-s", name];
157
- if (config.cwd) args.push("-c", config.cwd);
158
- args.push(config.command);
159
- execFileSync("tmux", args);
160
- return { sessionName: name };
161
- } catch (e) {
162
- return { sessionName: name, error: `spawn failed: ${e}` };
163
- }
164
- }
165
- kill(target) {
166
- try {
167
- execFileSync("tmux", ["kill-session", "-t", target], QUIET);
168
- } catch {
169
- }
170
- }
171
- pipeLog(target, logFile) {
172
- try {
173
- const safePath = logFile.replace(/'/g, "'\\''");
174
- execFileSync("tmux", ["pipe-pane", "-t", target, `cat >> '${safePath}'`], QUIET);
175
- } catch {
176
- }
177
- }
178
- };
179
- }
180
- });
181
-
182
- // src/lib/transport.ts
183
- function getTransport() {
184
- if (!_transport) {
185
- const { TmuxTransport: TmuxTransport2 } = (init_tmux_transport(), __toCommonJS(tmux_transport_exports));
186
- _transport = new TmuxTransport2();
187
- }
188
- return _transport;
189
- }
190
- var _transport;
191
- var init_transport = __esm({
192
- "src/lib/transport.ts"() {
193
- "use strict";
194
- _transport = null;
195
- }
196
- });
197
-
198
- // src/lib/cc-agent-support.ts
199
- import { execSync as execSync2 } from "child_process";
200
- function _resetCcAgentSupportCache() {
201
- _cachedSupport = null;
202
- }
203
- function claudeSupportsAgentFlag() {
204
- if (_cachedSupport !== null) return _cachedSupport;
205
- try {
206
- const helpOutput = execSync2("claude --help 2>&1", {
207
- encoding: "utf-8",
208
- timeout: 5e3
209
- });
210
- _cachedSupport = /(^|\s)--agent(\b|=)/.test(helpOutput);
211
- } catch {
212
- _cachedSupport = false;
213
- }
214
- return _cachedSupport;
215
- }
216
- var _cachedSupport;
217
- var init_cc_agent_support = __esm({
218
- "src/lib/cc-agent-support.ts"() {
219
- "use strict";
220
- _cachedSupport = null;
221
- }
222
- });
223
-
224
- // src/lib/mcp-prefix.ts
225
- function expandDualPrefixTools(shortNames) {
226
- const out = [];
227
- for (const name of shortNames) {
228
- for (const prefix of MCP_TOOL_PREFIXES) {
229
- out.push(prefix + name);
230
- }
231
- }
232
- return out;
233
- }
234
- var MCP_PRIMARY_KEY, MCP_LEGACY_KEY, MCP_TOOL_PREFIXES;
235
- var init_mcp_prefix = __esm({
236
- "src/lib/mcp-prefix.ts"() {
237
- "use strict";
238
- MCP_PRIMARY_KEY = "exe-os";
239
- MCP_LEGACY_KEY = "exe-mem";
240
- MCP_TOOL_PREFIXES = [
241
- `mcp__${MCP_PRIMARY_KEY}__`,
242
- `mcp__${MCP_LEGACY_KEY}__`
243
- ];
244
- }
245
- });
246
-
247
- // src/lib/provider-table.ts
248
- function detectActiveProvider(env = process.env) {
249
- const baseUrl = env.ANTHROPIC_BASE_URL;
250
- if (!baseUrl) return DEFAULT_PROVIDER;
251
- for (const [name, cfg] of Object.entries(PROVIDER_TABLE)) {
252
- if (cfg.baseUrl === baseUrl) return name;
253
- }
254
- return DEFAULT_PROVIDER;
255
- }
256
- var PROVIDER_TABLE, DEFAULT_PROVIDER;
257
- var init_provider_table = __esm({
258
- "src/lib/provider-table.ts"() {
259
- "use strict";
260
- PROVIDER_TABLE = {
261
- opencode: {
262
- baseUrl: "https://opencode.ai/zen/go",
263
- apiKeyEnv: "OPENCODE_API_KEY",
264
- defaultModel: "minimax-m2.7"
265
- }
266
- };
267
- DEFAULT_PROVIDER = "default";
268
- }
269
- });
270
-
271
- // src/lib/intercom-queue.ts
272
- import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, renameSync, existsSync as existsSync2, mkdirSync as mkdirSync2 } from "fs";
273
- import path2 from "path";
274
- import os2 from "os";
275
- function ensureDir() {
276
- const dir = path2.dirname(QUEUE_PATH);
277
- if (!existsSync2(dir)) mkdirSync2(dir, { recursive: true });
278
- }
279
- function readQueue() {
280
- try {
281
- if (!existsSync2(QUEUE_PATH)) return [];
282
- return JSON.parse(readFileSync2(QUEUE_PATH, "utf8"));
283
- } catch {
284
- return [];
285
- }
286
- }
287
- function writeQueue(queue) {
288
- ensureDir();
289
- const tmp = `${QUEUE_PATH}.tmp`;
290
- writeFileSync2(tmp, JSON.stringify(queue, null, 2));
291
- renameSync(tmp, QUEUE_PATH);
292
- }
293
- function queueIntercom(targetSession, reason) {
294
- const queue = readQueue();
295
- const existing = queue.find((q) => q.targetSession === targetSession);
296
- if (existing) {
297
- existing.attempts++;
298
- existing.queuedAt = (/* @__PURE__ */ new Date()).toISOString();
299
- existing.reason = reason;
300
- } else {
301
- queue.push({
302
- targetSession,
303
- queuedAt: (/* @__PURE__ */ new Date()).toISOString(),
304
- attempts: 0,
305
- reason
306
- });
307
- }
308
- writeQueue(queue);
309
- }
310
- var QUEUE_PATH, TTL_MS, INTERCOM_LOG;
311
- var init_intercom_queue = __esm({
312
- "src/lib/intercom-queue.ts"() {
313
- "use strict";
314
- QUEUE_PATH = path2.join(os2.homedir(), ".exe-os", "intercom-queue.json");
315
- TTL_MS = 60 * 60 * 1e3;
316
- INTERCOM_LOG = path2.join(os2.homedir(), ".exe-os", "intercom.log");
317
- }
318
- });
319
-
320
- // src/lib/database.ts
321
- import { createClient } from "@libsql/client";
322
- function getClient() {
323
- if (!_client) {
324
- throw new Error("Database client not initialized. Call initDatabase() first.");
325
- }
326
- return _client;
327
- }
328
- var _client;
329
- var init_database = __esm({
330
- "src/lib/database.ts"() {
331
- "use strict";
332
- _client = null;
333
- }
334
- });
335
-
336
- // src/lib/config.ts
337
- import { readFile, writeFile, mkdir } from "fs/promises";
338
- import { readFileSync as readFileSync3, existsSync as existsSync3, renameSync as renameSync2 } from "fs";
339
- import path3 from "path";
340
- import os3 from "os";
341
- function resolveDataDir() {
342
- if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
343
- if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
344
- const newDir = path3.join(os3.homedir(), ".exe-os");
345
- const legacyDir = path3.join(os3.homedir(), ".exe-mem");
346
- if (!existsSync3(newDir) && existsSync3(legacyDir)) {
347
- try {
348
- renameSync2(legacyDir, newDir);
349
- process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
350
- `);
351
- } catch {
352
- return legacyDir;
353
- }
354
- }
355
- return newDir;
356
- }
357
- function migrateLegacyConfig(raw) {
358
- if ("r2" in raw) {
359
- process.stderr.write(
360
- "[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"
361
- );
362
- delete raw.r2;
363
- }
364
- if ("syncIntervalMs" in raw) {
365
- delete raw.syncIntervalMs;
366
- }
367
- return raw;
368
- }
369
- function migrateConfig(raw) {
370
- const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
371
- let currentVersion = fromVersion;
372
- let migrated = false;
373
- if (currentVersion > CURRENT_CONFIG_VERSION) {
374
- return { config: raw, migrated: false, fromVersion };
375
- }
376
- for (const migration of CONFIG_MIGRATIONS) {
377
- if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
378
- raw = migration.migrate(raw);
379
- currentVersion = migration.to;
380
- migrated = true;
381
- }
382
- }
383
- return { config: raw, migrated, fromVersion };
384
- }
385
- function normalizeScalingRoadmap(raw) {
386
- const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
387
- const userRoadmap = raw.scalingRoadmap ?? {};
388
- const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
389
- if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
390
- userAuto.enabled = raw.rerankerEnabled;
391
- }
392
- raw.scalingRoadmap = {
393
- ...userRoadmap,
394
- rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
395
- };
396
- }
397
- function normalizeSessionLifecycle(raw) {
398
- const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
399
- const userSL = raw.sessionLifecycle ?? {};
400
- raw.sessionLifecycle = { ...defaultSL, ...userSL };
401
- }
402
- function normalizeAutoUpdate(raw) {
403
- const defaultAU = DEFAULT_CONFIG.autoUpdate;
404
- const userAU = raw.autoUpdate ?? {};
405
- raw.autoUpdate = { ...defaultAU, ...userAU };
406
- }
407
- async function loadConfig() {
408
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
409
- await mkdir(dir, { recursive: true });
410
- const configPath = path3.join(dir, "config.json");
411
- if (!existsSync3(configPath)) {
412
- return { ...DEFAULT_CONFIG, dbPath: path3.join(dir, "memories.db") };
413
- }
414
- const raw = await readFile(configPath, "utf-8");
415
- try {
416
- let parsed = JSON.parse(raw);
417
- parsed = migrateLegacyConfig(parsed);
418
- const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
419
- if (migrated) {
420
- process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
421
- `);
422
- try {
423
- await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
424
- } catch {
425
- }
426
- }
427
- normalizeScalingRoadmap(migratedCfg);
428
- normalizeSessionLifecycle(migratedCfg);
429
- normalizeAutoUpdate(migratedCfg);
430
- const config = { ...DEFAULT_CONFIG, dbPath: path3.join(dir, "memories.db"), ...migratedCfg };
431
- if (config.dbPath.startsWith("~")) {
432
- config.dbPath = config.dbPath.replace(/^~/, os3.homedir());
433
- }
434
- return config;
435
- } catch {
436
- return { ...DEFAULT_CONFIG, dbPath: path3.join(dir, "memories.db") };
437
- }
438
- }
439
- var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
440
- var init_config = __esm({
441
- "src/lib/config.ts"() {
442
- "use strict";
443
- EXE_AI_DIR = resolveDataDir();
444
- DB_PATH = path3.join(EXE_AI_DIR, "memories.db");
445
- MODELS_DIR = path3.join(EXE_AI_DIR, "models");
446
- CONFIG_PATH = path3.join(EXE_AI_DIR, "config.json");
447
- LEGACY_LANCE_PATH = path3.join(EXE_AI_DIR, "local.lance");
448
- CURRENT_CONFIG_VERSION = 1;
449
- DEFAULT_CONFIG = {
450
- config_version: CURRENT_CONFIG_VERSION,
451
- dbPath: DB_PATH,
452
- modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
453
- embeddingDim: 1024,
454
- batchSize: 20,
455
- flushIntervalMs: 1e4,
456
- autoIngestion: true,
457
- autoRetrieval: true,
458
- searchMode: "hybrid",
459
- hookSearchMode: "hybrid",
460
- fileGrepEnabled: true,
461
- splashEffect: true,
462
- consolidationEnabled: true,
463
- consolidationIntervalMs: 6 * 60 * 60 * 1e3,
464
- consolidationModel: "claude-haiku-4-5-20251001",
465
- consolidationMaxCallsPerRun: 20,
466
- selfQueryRouter: true,
467
- selfQueryModel: "claude-haiku-4-5-20251001",
468
- rerankerEnabled: true,
469
- scalingRoadmap: {
470
- rerankerAutoTrigger: {
471
- enabled: true,
472
- broadQueryMinCardinality: 5e4,
473
- fetchTopK: 150,
474
- returnTopK: 5
475
- }
476
- },
477
- graphRagEnabled: true,
478
- wikiEnabled: false,
479
- wikiUrl: "",
480
- wikiApiKey: "",
481
- wikiSyncIntervalMs: 30 * 60 * 1e3,
482
- wikiWorkspaceMapping: {
483
- exe: "Executive",
484
- yoshi: "Engineering",
485
- mari: "Marketing",
486
- tom: "Engineering",
487
- sasha: "Production"
488
- },
489
- wikiAutoUpdate: true,
490
- wikiAutoUpdateThreshold: 0.5,
491
- wikiAutoUpdateCreateNew: true,
492
- skillLearning: true,
493
- skillThreshold: 3,
494
- skillModel: "claude-haiku-4-5-20251001",
495
- exeHeartbeat: {
496
- enabled: true,
497
- intervalSeconds: 60,
498
- staleInProgressThresholdHours: 2
499
- },
500
- sessionLifecycle: {
501
- idleKillEnabled: true,
502
- idleKillTicksRequired: 3,
503
- idleKillIntercomAckWindowMs: 1e4,
504
- maxAutoInstances: 10
505
- },
506
- autoUpdate: {
507
- checkOnBoot: true,
508
- autoInstall: false,
509
- checkIntervalMs: 24 * 60 * 60 * 1e3
510
- }
511
- };
512
- CONFIG_MIGRATIONS = [
513
- {
514
- from: 0,
515
- to: 1,
516
- migrate: (cfg) => {
517
- cfg.config_version = 1;
518
- return cfg;
519
- }
520
- }
521
- ];
522
- }
523
- });
524
-
525
- // src/lib/employees.ts
526
- import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
527
- import { existsSync as existsSync4, symlinkSync, readlinkSync } from "fs";
528
- import { execSync as execSync3 } from "child_process";
529
- import path4 from "path";
530
- var EMPLOYEES_PATH;
531
- var init_employees = __esm({
532
- "src/lib/employees.ts"() {
533
- "use strict";
534
- init_config();
535
- EMPLOYEES_PATH = path4.join(EXE_AI_DIR, "exe-employees.json");
536
- }
537
- });
538
-
539
- // src/lib/license.ts
540
- import { readFileSync as readFileSync4, writeFileSync as writeFileSync3, existsSync as existsSync5, mkdirSync as mkdirSync3 } from "fs";
541
- import { randomUUID } from "crypto";
542
- import path5 from "path";
543
- import { jwtVerify, importSPKI } from "jose";
544
- var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH, PLAN_LIMITS;
545
- var init_license = __esm({
546
- "src/lib/license.ts"() {
547
- "use strict";
548
- init_config();
549
- LICENSE_PATH = path5.join(EXE_AI_DIR, "license.key");
550
- CACHE_PATH = path5.join(EXE_AI_DIR, "license-cache.json");
551
- DEVICE_ID_PATH = path5.join(EXE_AI_DIR, "device-id");
552
- PLAN_LIMITS = {
553
- free: { devices: 1, employees: 1, memories: 5e3 },
554
- pro: { devices: 2, employees: 5, memories: 1e5 },
555
- team: { devices: 10, employees: 20, memories: 1e6 },
556
- agency: { devices: 50, employees: 100, memories: 1e7 },
557
- enterprise: { devices: -1, employees: -1, memories: -1 }
558
- };
559
- }
560
- });
561
-
562
- // src/lib/plan-limits.ts
563
- import { readFileSync as readFileSync5, existsSync as existsSync6 } from "fs";
564
- import path6 from "path";
565
- function getLicenseSync() {
566
- try {
567
- if (!existsSync6(CACHE_PATH2)) return freeLicense();
568
- const raw = JSON.parse(readFileSync5(CACHE_PATH2, "utf8"));
569
- if (!raw.token || typeof raw.token !== "string") return freeLicense();
570
- const parts = raw.token.split(".");
571
- if (parts.length !== 3) return freeLicense();
572
- const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
573
- const plan = payload.plan ?? "free";
574
- const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
575
- return {
576
- valid: true,
577
- plan,
578
- email: payload.sub ?? "",
579
- expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
580
- deviceLimit: limits.devices,
581
- employeeLimit: limits.employees,
582
- memoryLimit: limits.memories
583
- };
584
- } catch {
585
- return freeLicense();
586
- }
587
- }
588
- function freeLicense() {
589
- const limits = PLAN_LIMITS.free;
590
- return {
591
- valid: true,
592
- plan: "free",
593
- email: "",
594
- expiresAt: null,
595
- deviceLimit: limits.devices,
596
- employeeLimit: limits.employees,
597
- memoryLimit: limits.memories
598
- };
599
- }
600
- function assertEmployeeLimitSync(rosterPath) {
601
- const license = getLicenseSync();
602
- if (license.employeeLimit < 0) return;
603
- const filePath = rosterPath ?? EMPLOYEES_PATH;
604
- let count = 0;
605
- try {
606
- if (existsSync6(filePath)) {
607
- const raw = readFileSync5(filePath, "utf8");
608
- const employees = JSON.parse(raw);
609
- count = Array.isArray(employees) ? employees.length : 0;
610
- }
611
- } catch {
612
- throw new PlanLimitError(
613
- `Cannot verify employee count: roster unreadable at ${filePath}. Refusing to proceed. Check file permissions or upgrade plan.`
614
- );
615
- }
616
- if (count >= license.employeeLimit) {
617
- throw new PlanLimitError(
618
- `Employee limit reached: ${count}/${license.employeeLimit} employees on the ${license.plan} plan. Upgrade at https://askexe.com to add more.`
619
- );
620
- }
621
- }
622
- var PlanLimitError, CACHE_PATH2;
623
- var init_plan_limits = __esm({
624
- "src/lib/plan-limits.ts"() {
625
- "use strict";
626
- init_database();
627
- init_employees();
628
- init_license();
629
- init_config();
630
- PlanLimitError = class extends Error {
631
- constructor(message) {
632
- super(message);
633
- this.name = "PlanLimitError";
634
- }
635
- };
636
- CACHE_PATH2 = path6.join(EXE_AI_DIR, "license-cache.json");
637
- }
638
- });
639
-
640
- // src/lib/worktree.ts
641
- import { execSync as execSync4 } from "child_process";
642
- import { existsSync as existsSync7, readFileSync as readFileSync6, appendFileSync, mkdirSync as mkdirSync4, realpathSync } from "fs";
643
- import path7 from "path";
644
- function getGitRoot(dir) {
645
- try {
646
- const root = execSync4("git rev-parse --show-toplevel", {
647
- cwd: dir,
648
- encoding: "utf-8",
649
- timeout: GIT_TIMEOUT_MS,
650
- stdio: ["pipe", "pipe", "pipe"]
651
- }).trim();
652
- return realpath(root);
653
- } catch {
654
- return null;
655
- }
656
- }
657
- function getMainRepoRoot(dir) {
658
- try {
659
- const commonDir = execSync4(
660
- "git rev-parse --path-format=absolute --git-common-dir",
661
- { cwd: dir, encoding: "utf-8", timeout: GIT_TIMEOUT_MS, stdio: ["pipe", "pipe", "pipe"] }
662
- ).trim();
663
- return realpath(path7.dirname(commonDir));
664
- } catch {
665
- return null;
666
- }
667
- }
668
- function worktreePath(repoRoot, employeeName, instance) {
669
- const label = instanceLabel(employeeName, instance);
670
- return path7.join(repoRoot, ".worktrees", label);
671
- }
672
- function worktreeBranch(employeeName, instance) {
673
- return `${instanceLabel(employeeName, instance)}-work`;
674
- }
675
- function instanceLabel(name, instance) {
676
- return instance != null && instance > 0 ? `${name}${instance}` : name;
677
- }
678
- function ensureWorktree(projectDir, employeeName, instance) {
679
- const repoRoot = getGitRoot(projectDir);
680
- if (!repoRoot) return null;
681
- const wtPath = worktreePath(repoRoot, employeeName, instance);
682
- const branch = worktreeBranch(employeeName, instance);
683
- if (existsSync7(path7.join(wtPath, ".git"))) {
684
- return wtPath;
685
- }
686
- const worktreesDir = path7.join(repoRoot, ".worktrees");
687
- mkdirSync4(worktreesDir, { recursive: true });
688
- ensureGitignoreEntry(repoRoot, "/.worktrees/");
689
- try {
690
- execSync4("git worktree prune", {
691
- cwd: repoRoot,
692
- encoding: "utf-8",
693
- timeout: GIT_TIMEOUT_MS,
694
- stdio: ["pipe", "pipe", "pipe"]
695
- });
696
- } catch {
697
- }
698
- const branchExists = branchExistsLocally(repoRoot, branch);
699
- try {
700
- if (branchExists) {
701
- execSync4(`git worktree add "${wtPath}" "${branch}"`, {
702
- cwd: repoRoot,
703
- encoding: "utf-8",
704
- timeout: GIT_TIMEOUT_MS,
705
- stdio: ["pipe", "pipe", "pipe"]
706
- });
707
- } else {
708
- execSync4(`git worktree add "${wtPath}" -b "${branch}" HEAD`, {
709
- cwd: repoRoot,
710
- encoding: "utf-8",
711
- timeout: GIT_TIMEOUT_MS,
712
- stdio: ["pipe", "pipe", "pipe"]
713
- });
714
- }
715
- return wtPath;
716
- } catch (err) {
717
- process.stderr.write(
718
- `[worktree] Failed to create worktree for ${employeeName}: ${err instanceof Error ? err.message : String(err)}
719
- `
720
- );
721
- return null;
722
- }
723
- }
724
- function branchExistsLocally(repoRoot, branch) {
725
- try {
726
- execSync4(`git rev-parse --verify "refs/heads/${branch}"`, {
727
- cwd: repoRoot,
728
- encoding: "utf-8",
729
- timeout: GIT_TIMEOUT_MS,
730
- stdio: ["pipe", "pipe", "pipe"]
731
- });
732
- return true;
733
- } catch {
734
- return false;
735
- }
736
- }
737
- function realpath(p) {
738
- try {
739
- return realpathSync(p);
740
- } catch {
741
- return p;
742
- }
743
- }
744
- function ensureGitignoreEntry(repoRoot, entry) {
745
- try {
746
- const gitignorePath = path7.join(repoRoot, ".gitignore");
747
- if (existsSync7(gitignorePath)) {
748
- const content = readFileSync6(gitignorePath, "utf-8");
749
- if (content.includes(entry)) return;
750
- appendFileSync(gitignorePath, `
751
- # Agent worktrees (exe-os)
752
- ${entry}
753
- `);
754
- } else {
755
- }
756
- } catch {
757
- }
758
- }
759
- var GIT_TIMEOUT_MS;
760
- var init_worktree = __esm({
761
- "src/lib/worktree.ts"() {
762
- "use strict";
763
- GIT_TIMEOUT_MS = 1e4;
764
- }
765
- });
766
-
767
- // src/lib/notifications.ts
768
- import crypto from "crypto";
769
- import path8 from "path";
770
- import os4 from "os";
771
- import {
772
- readFileSync as readFileSync7,
773
- readdirSync,
774
- unlinkSync,
775
- existsSync as existsSync8,
776
- rmdirSync
777
- } from "fs";
778
- async function writeNotification(notification) {
779
- try {
780
- const client = getClient();
781
- const id = crypto.randomUUID();
782
- const now = (/* @__PURE__ */ new Date()).toISOString();
783
- await client.execute({
784
- sql: `INSERT INTO notifications (id, agent_id, agent_role, event, project, summary, task_file, read, created_at)
785
- VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)`,
786
- args: [
787
- id,
788
- notification.agentId,
789
- notification.agentRole,
790
- notification.event,
791
- notification.project,
792
- notification.summary,
793
- notification.taskFile ?? null,
794
- now
795
- ]
796
- });
797
- } catch (err) {
798
- process.stderr.write(`[notifications] WRITE FAILED: ${err instanceof Error ? err.message : String(err)}
799
- `);
800
- }
801
- }
802
- async function markAsReadByTaskFile(taskFile) {
803
- try {
804
- const client = getClient();
805
- await client.execute({
806
- sql: "UPDATE notifications SET read = 1 WHERE task_file = ? AND read = 0",
807
- args: [taskFile]
808
- });
809
- } catch {
810
- }
811
- }
812
- var init_notifications = __esm({
813
- "src/lib/notifications.ts"() {
814
- "use strict";
815
- init_database();
816
- }
817
- });
818
-
819
- // src/lib/session-kill-telemetry.ts
820
- import crypto2 from "crypto";
821
- async function recordSessionKill(input) {
822
- try {
823
- const client = getClient();
824
- await client.execute({
825
- sql: `INSERT INTO session_kills
826
- (id, session_name, agent_id, killed_at, reason,
827
- ticks_idle, estimated_tokens_saved)
828
- VALUES (?, ?, ?, ?, ?, ?, ?)`,
829
- args: [
830
- crypto2.randomUUID(),
831
- input.sessionName,
832
- input.agentId,
833
- (/* @__PURE__ */ new Date()).toISOString(),
834
- input.reason,
835
- input.ticksIdle ?? null,
836
- input.estimatedTokensSaved ?? null
837
- ]
838
- });
839
- } catch (err) {
840
- process.stderr.write(
841
- `[session-kill-telemetry] write failed: ${err instanceof Error ? err.message : String(err)}
842
- `
843
- );
844
- }
845
- }
846
- var init_session_kill_telemetry = __esm({
847
- "src/lib/session-kill-telemetry.ts"() {
848
- "use strict";
849
- init_database();
850
- }
851
- });
852
-
853
- // src/lib/tasks-crud.ts
854
- import crypto3 from "crypto";
855
- import path9 from "path";
856
- import { execSync as execSync5 } from "child_process";
857
- import { mkdir as mkdir3, writeFile as writeFile3, appendFile } from "fs/promises";
858
- import { existsSync as existsSync9, readFileSync as readFileSync8 } from "fs";
859
- async function writeCheckpoint(input) {
860
- const client = getClient();
861
- const row = await resolveTask(client, input.taskId);
862
- const taskId = String(row.id);
863
- const now = (/* @__PURE__ */ new Date()).toISOString();
864
- const blockedByIds = [];
865
- if (row.blocked_by) {
866
- blockedByIds.push(String(row.blocked_by));
867
- }
868
- const checkpoint = {
869
- step: input.step,
870
- context_summary: input.contextSummary,
871
- files_touched: input.filesTouched ?? [],
872
- blocked_by_ids: blockedByIds,
873
- last_checkpoint_at: now
874
- };
875
- const result = await client.execute({
876
- sql: `UPDATE tasks SET checkpoint = ?, checkpoint_count = checkpoint_count + 1, updated_at = ? WHERE id = ?`,
877
- args: [JSON.stringify(checkpoint), now, taskId]
878
- });
879
- if (result.rowsAffected === 0) {
880
- throw new Error(`Checkpoint write failed: task ${taskId} not found`);
881
- }
882
- const countResult = await client.execute({
883
- sql: "SELECT checkpoint_count FROM tasks WHERE id = ?",
884
- args: [taskId]
885
- });
886
- const checkpointCount = Number(countResult.rows[0]?.checkpoint_count ?? 1);
887
- return { checkpointCount };
888
- }
889
- function extractParentFromContext(contextBody) {
890
- if (!contextBody) return null;
891
- const match = contextBody.match(
892
- /Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
893
- );
894
- return match ? match[1].toLowerCase() : null;
895
- }
896
- function slugify(title) {
897
- return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
898
- }
899
- async function resolveTask(client, identifier) {
900
- let result = await client.execute({
901
- sql: "SELECT * FROM tasks WHERE id = ?",
902
- args: [identifier]
903
- });
904
- if (result.rows.length === 1) return result.rows[0];
905
- result = await client.execute({
906
- sql: "SELECT * FROM tasks WHERE task_file LIKE ?",
907
- args: [`%${identifier}%`]
908
- });
909
- if (result.rows.length === 1) return result.rows[0];
910
- if (result.rows.length > 1) {
911
- const exact = result.rows.filter(
912
- (r) => String(r.task_file).endsWith(`/${identifier}.md`)
913
- );
914
- if (exact.length === 1) return exact[0];
915
- const candidates = exact.length > 1 ? exact : result.rows;
916
- const active = candidates.filter(
917
- (r) => !["done", "cancelled"].includes(String(r.status))
918
- );
919
- if (active.length === 1) return active[0];
920
- const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
921
- throw new Error(
922
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
923
- );
924
- }
925
- result = await client.execute({
926
- sql: "SELECT * FROM tasks WHERE title LIKE ?",
927
- args: [`%${identifier}%`]
928
- });
929
- if (result.rows.length === 1) return result.rows[0];
930
- if (result.rows.length > 1) {
931
- const active = result.rows.filter(
932
- (r) => !["done", "cancelled"].includes(String(r.status))
933
- );
934
- if (active.length === 1) return active[0];
935
- const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
936
- throw new Error(
937
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
938
- );
939
- }
940
- throw new Error(`Task not found: ${identifier}`);
941
- }
942
- async function createTaskCore(input) {
943
- const client = getClient();
944
- const id = crypto3.randomUUID();
945
- const now = (/* @__PURE__ */ new Date()).toISOString();
946
- const slug = slugify(input.title);
947
- const taskFile = input.taskFile ?? `exe/${input.assignedTo}/${slug}.md`;
948
- let blockedById = null;
949
- const initialStatus = input.blockedBy ? "blocked" : "open";
950
- if (input.blockedBy) {
951
- const blocker = await resolveTask(client, input.blockedBy);
952
- blockedById = String(blocker.id);
953
- }
954
- let parentTaskId = null;
955
- let parentRef = input.parentTaskId;
956
- if (!parentRef) {
957
- const extracted = extractParentFromContext(input.context);
958
- if (extracted) {
959
- parentRef = extracted;
960
- process.stderr.write(
961
- "[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
962
- );
963
- }
964
- }
965
- if (parentRef) {
966
- try {
967
- const parent = await resolveTask(client, parentRef);
968
- parentTaskId = String(parent.id);
969
- } catch (err) {
970
- if (!input.parentTaskId) {
971
- throw new Error(
972
- `create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
973
- );
974
- }
975
- throw err;
976
- }
977
- }
978
- let warning;
979
- const dupCheck = await client.execute({
980
- sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
981
- args: [input.title, input.assignedTo]
982
- });
983
- if (dupCheck.rows.length > 0) {
984
- warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
985
- }
986
- if (input.baseDir) {
987
- try {
988
- await mkdir3(path9.join(input.baseDir, "exe", "output"), { recursive: true });
989
- await mkdir3(path9.join(input.baseDir, "exe", "research"), { recursive: true });
990
- await ensureArchitectureDoc(input.baseDir, input.projectName);
991
- await ensureGitignoreExe(input.baseDir);
992
- } catch {
993
- }
994
- }
995
- const complexity = input.complexity ?? "standard";
996
- await client.execute({
997
- sql: `INSERT INTO tasks (id, title, assigned_to, assigned_by, project_name, priority, status, task_file, blocked_by, parent_task_id, reviewer, context, complexity, budget_tokens, budget_fallback_model, tokens_used, tokens_warned_at, created_at, updated_at)
998
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
999
- args: [
1000
- id,
1001
- input.title,
1002
- input.assignedTo,
1003
- input.assignedBy,
1004
- input.projectName,
1005
- input.priority,
1006
- initialStatus,
1007
- taskFile,
1008
- blockedById,
1009
- parentTaskId,
1010
- input.reviewer ?? null,
1011
- input.context,
1012
- input.budgetTokens ?? null,
1013
- input.budgetFallbackModel ?? null,
1014
- 0,
1015
- null,
1016
- complexity,
1017
- now,
1018
- now
1019
- ]
1020
- });
1021
- return {
1022
- id,
1023
- title: input.title,
1024
- assignedTo: input.assignedTo,
1025
- assignedBy: input.assignedBy,
1026
- projectName: input.projectName,
1027
- priority: input.priority,
1028
- status: initialStatus,
1029
- taskFile,
1030
- createdAt: now,
1031
- updatedAt: now,
1032
- warning,
1033
- budgetTokens: input.budgetTokens ?? null,
1034
- budgetFallbackModel: input.budgetFallbackModel ?? null,
1035
- tokensUsed: 0,
1036
- tokensWarnedAt: null
1037
- };
1038
- }
1039
- async function listTasks(input) {
1040
- const client = getClient();
1041
- const conditions = [];
1042
- const args = [];
1043
- if (input.assignedTo) {
1044
- conditions.push("assigned_to = ?");
1045
- args.push(input.assignedTo);
1046
- }
1047
- if (input.status) {
1048
- conditions.push("status = ?");
1049
- args.push(input.status);
1050
- } else {
1051
- conditions.push("status IN ('open', 'in_progress', 'blocked')");
1052
- }
1053
- if (input.projectName) {
1054
- conditions.push("project_name = ?");
1055
- args.push(input.projectName);
1056
- }
1057
- if (input.priority) {
1058
- conditions.push("priority = ?");
1059
- args.push(input.priority);
1060
- }
1061
- const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1062
- const result = await client.execute({
1063
- sql: `SELECT * FROM tasks ${where} ORDER BY CASE status WHEN 'blocked' THEN 0 WHEN 'in_progress' THEN 1 WHEN 'open' THEN 2 ELSE 3 END, priority ASC, created_at DESC`,
1064
- args
1065
- });
1066
- return result.rows.map((r) => ({
1067
- id: String(r.id),
1068
- title: String(r.title),
1069
- assignedTo: String(r.assigned_to),
1070
- assignedBy: String(r.assigned_by),
1071
- projectName: String(r.project_name),
1072
- priority: String(r.priority),
1073
- status: String(r.status),
1074
- taskFile: String(r.task_file),
1075
- createdAt: String(r.created_at),
1076
- updatedAt: String(r.updated_at),
1077
- checkpointCount: Number(r.checkpoint_count ?? 0),
1078
- budgetTokens: r.budget_tokens !== null ? Number(r.budget_tokens) : null,
1079
- budgetFallbackModel: r.budget_fallback_model !== null ? String(r.budget_fallback_model) : null,
1080
- tokensUsed: Number(r.tokens_used ?? 0),
1081
- tokensWarnedAt: r.tokens_warned_at !== null ? Number(r.tokens_warned_at) : null
1082
- }));
1083
- }
1084
- function checkStaleCompletion(taskContext, taskCreatedAt) {
1085
- if (!taskContext) return null;
1086
- if (!DELEGATION_KEYWORDS.test(taskContext)) return null;
1087
- try {
1088
- const since = new Date(taskCreatedAt).toISOString();
1089
- const branch = execSync5(
1090
- "git rev-parse --abbrev-ref HEAD 2>/dev/null",
1091
- { encoding: "utf8", timeout: 3e3 }
1092
- ).trim();
1093
- const branchArg = branch && branch !== "HEAD" ? branch : "";
1094
- const commitCount = execSync5(
1095
- `git log --oneline --since="${since}" ${branchArg} 2>/dev/null | wc -l`,
1096
- { encoding: "utf8", timeout: 5e3 }
1097
- ).trim();
1098
- const count = parseInt(commitCount, 10);
1099
- if (count === 0) {
1100
- return "WARNING: task closed with no new commits since creation. Verify work was actually produced.";
1101
- }
1102
- return null;
1103
- } catch {
1104
- return null;
1105
- }
1106
- }
1107
- async function updateTaskStatus(input) {
1108
- const client = getClient();
1109
- const now = (/* @__PURE__ */ new Date()).toISOString();
1110
- const row = await resolveTask(client, input.taskId);
1111
- const taskId = String(row.id);
1112
- const taskFile = String(row.task_file);
1113
- if (input.status === "done" && String(row.assigned_by) === "system" && taskFile.includes("review-")) {
1114
- process.stderr.write(
1115
- `[updateTask] Review task "${String(row.title)}" being marked done (assigned to ${String(row.assigned_to)})
1116
- `
1117
- );
1118
- }
1119
- if (input.status === "done") {
1120
- const existingRow = await client.execute({
1121
- sql: "SELECT context, created_at FROM tasks WHERE id = ?",
1122
- args: [taskId]
1123
- });
1124
- if (existingRow.rows.length > 0) {
1125
- const ctx = existingRow.rows[0];
1126
- const warning = checkStaleCompletion(ctx.context, ctx.created_at);
1127
- if (warning) {
1128
- input.result = input.result ? `\u26A0\uFE0F ${warning}
1129
-
1130
- ${input.result}` : `\u26A0\uFE0F ${warning}`;
1131
- process.stderr.write(`[tasks] ${warning} (task: ${taskId})
1132
- `);
1133
- }
1134
- }
1135
- }
1136
- if (input.status === "in_progress") {
1137
- const tmuxSession = process.env.TMUX_PANE ?? process.env.MY_TMUX_SESSION ?? "unknown";
1138
- const claim = await client.execute({
1139
- sql: `UPDATE tasks
1140
- SET status = 'in_progress', assigned_tmux = ?, updated_at = ?
1141
- WHERE id = ? AND status = 'open'`,
1142
- args: [tmuxSession, now, taskId]
1143
- });
1144
- if (claim.rowsAffected === 0) {
1145
- const current = await client.execute({
1146
- sql: "SELECT status, assigned_tmux FROM tasks WHERE id = ?",
1147
- args: [taskId]
1148
- });
1149
- const cur = current.rows[0];
1150
- const status = cur?.status ?? "unknown";
1151
- const claimedBy = cur?.assigned_tmux ? ` (claimed by ${cur.assigned_tmux})` : "";
1152
- throw new Error(`${TASK_ALREADY_CLAIMED_PREFIX}: task ${taskId} is ${status}${claimedBy}`);
1153
- }
1154
- try {
1155
- await writeCheckpoint({
1156
- taskId,
1157
- step: "claimed",
1158
- contextSummary: `Task claimed by session. Transitioning open \u2192 in_progress.`
1159
- });
1160
- } catch {
1161
- }
1162
- return { row, taskFile, now, taskId };
1163
- }
1164
- if (input.result) {
1165
- await client.execute({
1166
- sql: "UPDATE tasks SET status = ?, result = ?, updated_at = ? WHERE id = ?",
1167
- args: [input.status, input.result, now, taskId]
1168
- });
1169
- } else {
1170
- await client.execute({
1171
- sql: "UPDATE tasks SET status = ?, updated_at = ? WHERE id = ?",
1172
- args: [input.status, now, taskId]
1173
- });
1174
- }
1175
- try {
1176
- await writeCheckpoint({
1177
- taskId,
1178
- step: `status_transition:${input.status}`,
1179
- contextSummary: input.result ? `Transitioned to ${input.status}. Result: ${input.result.slice(0, 500)}` : `Transitioned to ${input.status}.`
1180
- });
1181
- } catch {
1182
- }
1183
- return { row, taskFile, now, taskId };
1184
- }
1185
- async function deleteTaskCore(taskId, _baseDir) {
1186
- const client = getClient();
1187
- const row = await resolveTask(client, taskId);
1188
- const id = String(row.id);
1189
- const taskFile = String(row.task_file);
1190
- const assignedTo = String(row.assigned_to);
1191
- const assignedBy = String(row.assigned_by);
1192
- await client.execute({ sql: "DELETE FROM tasks WHERE id = ?", args: [id] });
1193
- const taskSlug = taskFile.split("/").pop()?.replace(".md", "") ?? "";
1194
- return { taskFile, assignedTo, assignedBy, taskSlug };
1195
- }
1196
- async function ensureArchitectureDoc(baseDir, projectName) {
1197
- const archPath = path9.join(baseDir, "exe", "ARCHITECTURE.md");
1198
- try {
1199
- if (existsSync9(archPath)) return;
1200
- const template = [
1201
- `# ${projectName} \u2014 System Architecture`,
1202
- "",
1203
- "> Employees: read this before every task. Update it when you change system structure.",
1204
- `> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
1205
- "",
1206
- "## Overview",
1207
- "",
1208
- "<!-- Describe what this system does, its main components, and how they connect. -->",
1209
- "",
1210
- "## Key Components",
1211
- "",
1212
- "<!-- List the major modules, services, or subsystems. -->",
1213
- "",
1214
- "## Data Flow",
1215
- "",
1216
- "<!-- How does data move through the system? What writes where? -->",
1217
- "",
1218
- "## Invariants",
1219
- "",
1220
- "<!-- Rules that must never be violated. What breaks if these are wrong? -->",
1221
- "",
1222
- "## Dependencies",
1223
- "",
1224
- "<!-- What depends on what? If I change X, what else is affected? -->",
1225
- ""
1226
- ].join("\n");
1227
- await writeFile3(archPath, template, "utf-8");
1228
- } catch {
1229
- }
1230
- }
1231
- async function ensureGitignoreExe(baseDir) {
1232
- const gitignorePath = path9.join(baseDir, ".gitignore");
1233
- try {
1234
- if (existsSync9(gitignorePath)) {
1235
- const content = readFileSync8(gitignorePath, "utf-8");
1236
- if (/^\/?exe\/?$/m.test(content)) return;
1237
- await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
1238
- } else {
1239
- await writeFile3(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
1240
- }
1241
- } catch {
1242
- }
1243
- }
1244
- var DELEGATION_KEYWORDS, TASK_ALREADY_CLAIMED_PREFIX;
1245
- var init_tasks_crud = __esm({
1246
- "src/lib/tasks-crud.ts"() {
1247
- "use strict";
1248
- init_database();
1249
- DELEGATION_KEYWORDS = /parallel|delegate|wave|tom\d*-exe/i;
1250
- TASK_ALREADY_CLAIMED_PREFIX = "TASK_ALREADY_CLAIMED";
1251
- }
1252
- });
1253
-
1254
- // src/lib/tasks-review.ts
1255
- import path10 from "path";
1256
- import { existsSync as existsSync10, readdirSync as readdirSync2, unlinkSync as unlinkSync2 } from "fs";
1257
- async function countPendingReviews() {
1258
- const client = getClient();
1259
- const result = await client.execute({
1260
- sql: "SELECT COUNT(*) as cnt FROM tasks WHERE status = 'needs_review'",
1261
- args: []
1262
- });
1263
- return Number(result.rows[0]?.cnt) || 0;
1264
- }
1265
- async function countNewPendingReviewsSince(sinceIso) {
1266
- const client = getClient();
1267
- const result = await client.execute({
1268
- sql: `SELECT COUNT(*) as cnt FROM tasks
1269
- WHERE status = 'needs_review' AND updated_at > ?`,
1270
- args: [sinceIso]
1271
- });
1272
- return Number(result.rows[0]?.cnt) || 0;
1273
- }
1274
- async function listPendingReviews(limit) {
1275
- const client = getClient();
1276
- const result = await client.execute({
1277
- sql: `SELECT title, assigned_to, project_name FROM tasks
1278
- WHERE status = 'needs_review'
1279
- ORDER BY priority ASC, created_at DESC LIMIT ?`,
1280
- args: [limit]
1281
- });
1282
- return result.rows;
1283
- }
1284
- function getReviewChecklist(role, agent, taskSlug) {
1285
- const roleLower = role.toLowerCase();
1286
- if (roleLower.includes("engineer") || roleLower === "principal engineer") {
1287
- return {
1288
- lens: "Code Quality (Engineer)",
1289
- checklist: [
1290
- "1. Do all tests pass? Any new tests needed?",
1291
- "2. Is the code clean \u2014 no dead code, no TODOs left?",
1292
- "3. Does it follow existing patterns and conventions in the codebase?",
1293
- "4. Any regressions in the test suite?"
1294
- ]
1295
- };
1296
- }
1297
- if (roleLower === "cto" || roleLower.includes("architect")) {
1298
- return {
1299
- lens: "Architecture (CTO)",
1300
- checklist: [
1301
- "1. Does this fit the existing architecture? Consistent with ARCHITECTURE.md?",
1302
- "2. Is it backward compatible? Any breaking changes?",
1303
- "3. Does it introduce technical debt? Is that debt justified?",
1304
- "4. Security implications? Any new attack surface?",
1305
- "5. Does it scale? Performance considerations?",
1306
- "6. Coordination: does this affect other employees' work or other projects?"
1307
- ]
1308
- };
1309
- }
1310
- if (roleLower === "coo" || roleLower.includes("operations")) {
1311
- return {
1312
- lens: "Strategic (COO)",
1313
- checklist: [
1314
- "1. Does this serve the project mission?",
1315
- "2. Is this the right work at the right time?",
1316
- "3. Does the architectural assessment make sense for the business?",
1317
- "4. Any cross-project implications?"
1318
- ]
1319
- };
1320
- }
1321
- return {
1322
- lens: "General",
1323
- checklist: [
1324
- "1. Read the original task's acceptance criteria",
1325
- `2. Check git log for related commits: \`git log --oneline --author-date-order -10\``,
1326
- "3. Verify code changes match requirements",
1327
- "4. Check if tests were added/updated",
1328
- `5. Look for output files in exe/output/${agent}-${taskSlug}*`
1329
- ]
1330
- };
1331
- }
1332
- async function cleanupReviewFile(row, taskFile, _baseDir) {
1333
- if (String(row.assigned_by) !== "system" || !taskFile.includes("review-")) return;
1334
- try {
1335
- const client = getClient();
1336
- const now = (/* @__PURE__ */ new Date()).toISOString();
1337
- const parentId = row.parent_task_id ? String(row.parent_task_id) : null;
1338
- if (parentId) {
1339
- const result = await client.execute({
1340
- sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ? AND status = 'needs_review'",
1341
- args: [now, parentId]
1342
- });
1343
- if (result.rowsAffected > 0) {
1344
- process.stderr.write(
1345
- `[review-cleanup] Cascaded original task to done via parent_task_id: ${parentId}
1346
- `
1347
- );
1348
- }
1349
- } else {
1350
- const fileName = taskFile.split("/").pop() ?? "";
1351
- const reviewPrefix = fileName.replace(".md", "");
1352
- const parts = reviewPrefix.split("-");
1353
- if (parts.length >= 3 && parts[0] === "review") {
1354
- const agent = parts[1];
1355
- const slug = parts.slice(2).join("-");
1356
- const originalTaskFile = `exe/${agent}/${slug}.md`;
1357
- const result = await client.execute({
1358
- sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE task_file = ? AND status = 'needs_review'",
1359
- args: [now, originalTaskFile]
1360
- });
1361
- if (result.rowsAffected > 0) {
1362
- process.stderr.write(
1363
- `[review-cleanup] Cascaded original task to done (legacy path): ${originalTaskFile}
1364
- `
1365
- );
1366
- }
1367
- }
1368
- }
1369
- } catch (err) {
1370
- process.stderr.write(
1371
- `[review-cleanup] Failed to cascade original task: ${err instanceof Error ? err.message : String(err)}
1372
- `
1373
- );
1374
- }
1375
- try {
1376
- const cacheDir = path10.join(EXE_AI_DIR, "session-cache");
1377
- if (existsSync10(cacheDir)) {
1378
- for (const f of readdirSync2(cacheDir)) {
1379
- if (f.startsWith("review-notified-")) {
1380
- unlinkSync2(path10.join(cacheDir, f));
1381
- }
1382
- }
1383
- }
1384
- } catch {
1385
- }
1386
- }
1387
- var init_tasks_review = __esm({
1388
- "src/lib/tasks-review.ts"() {
1389
- "use strict";
1390
- init_database();
1391
- init_config();
1392
- init_employees();
1393
- init_notifications();
1394
- init_tasks_crud();
1395
- init_tmux_routing();
1396
- init_session_key();
1397
- }
1398
- });
1399
-
1400
- // src/lib/tasks-chain.ts
1401
- import path11 from "path";
1402
- import { readFile as readFile3, writeFile as writeFile4 } from "fs/promises";
1403
- async function cascadeUnblock(taskId, baseDir, now) {
1404
- const client = getClient();
1405
- const unblocked = await client.execute({
1406
- sql: `UPDATE tasks SET status = 'open', blocked_by = NULL, updated_at = ?
1407
- WHERE blocked_by = ? AND status = 'blocked'`,
1408
- args: [now, taskId]
1409
- });
1410
- if (baseDir && unblocked.rowsAffected > 0) {
1411
- const unblockedRows = await client.execute({
1412
- sql: `SELECT task_file FROM tasks WHERE blocked_by IS NULL AND updated_at = ?`,
1413
- args: [now]
1414
- });
1415
- for (const ur of unblockedRows.rows) {
1416
- try {
1417
- const ubFile = path11.join(baseDir, String(ur.task_file));
1418
- let ubContent = await readFile3(ubFile, "utf-8");
1419
- ubContent = ubContent.replace(/\*\*Status:\*\* blocked/, "**Status:** open");
1420
- ubContent = ubContent.replace(/\n\*\*Blocked by:\*\*.*\n/, "\n");
1421
- await writeFile4(ubFile, ubContent, "utf-8");
1422
- } catch {
1423
- }
1424
- }
1425
- }
1426
- }
1427
- async function findNextTask(assignedTo) {
1428
- const client = getClient();
1429
- const nextResult = await client.execute({
1430
- sql: `SELECT title, task_file, priority FROM tasks
1431
- WHERE assigned_to = ? AND status = 'open'
1432
- ORDER BY priority ASC, created_at ASC
1433
- LIMIT 1`,
1434
- args: [assignedTo]
1435
- });
1436
- if (nextResult.rows.length === 1) {
1437
- const nr = nextResult.rows[0];
1438
- return {
1439
- title: String(nr.title),
1440
- priority: String(nr.priority),
1441
- taskFile: String(nr.task_file)
1442
- };
1443
- }
1444
- return void 0;
1445
- }
1446
- async function checkSubtaskCompletion(parentTaskId, projectName) {
1447
- const client = getClient();
1448
- const remaining = await client.execute({
1449
- sql: `SELECT COUNT(*) as cnt FROM tasks
1450
- WHERE parent_task_id = ? AND status NOT IN ('done', 'cancelled')`,
1451
- args: [parentTaskId]
1452
- });
1453
- const cnt = Number(remaining.rows[0]?.cnt ?? 1);
1454
- if (cnt === 0) {
1455
- const parentRow = await client.execute({
1456
- sql: `SELECT assigned_to, title, task_file, project_name FROM tasks WHERE id = ?`,
1457
- args: [parentTaskId]
1458
- });
1459
- if (parentRow.rows.length === 1) {
1460
- const pr = parentRow.rows[0];
1461
- const parentProject = pr.project_name == null ? projectName : String(pr.project_name);
1462
- await writeNotification({
1463
- agentId: String(pr.assigned_to),
1464
- agentRole: "system",
1465
- event: "subtasks_complete",
1466
- project: parentProject,
1467
- summary: `All subtasks complete for "${String(pr.title)}" \u2014 ready for rollup review`,
1468
- taskFile: String(pr.task_file)
1469
- });
1470
- }
1471
- }
1472
- }
1473
- var init_tasks_chain = __esm({
1474
- "src/lib/tasks-chain.ts"() {
1475
- "use strict";
1476
- init_database();
1477
- init_notifications();
1478
- }
1479
- });
1480
-
1481
- // src/lib/project-name.ts
1482
- import { execSync as execSync6 } from "child_process";
1483
- import path12 from "path";
1484
- function getProjectName(cwd) {
1485
- const dir = cwd ?? process.cwd();
1486
- if (_cached2 && _cachedCwd === dir) return _cached2;
1487
- try {
1488
- let repoRoot;
1489
- try {
1490
- const gitCommonDir = execSync6("git rev-parse --path-format=absolute --git-common-dir", {
1491
- cwd: dir,
1492
- encoding: "utf8",
1493
- timeout: 2e3,
1494
- stdio: ["pipe", "pipe", "pipe"]
1495
- }).trim();
1496
- repoRoot = path12.dirname(gitCommonDir);
1497
- } catch {
1498
- repoRoot = execSync6("git rev-parse --show-toplevel", {
1499
- cwd: dir,
1500
- encoding: "utf8",
1501
- timeout: 2e3,
1502
- stdio: ["pipe", "pipe", "pipe"]
1503
- }).trim();
1504
- }
1505
- _cached2 = path12.basename(repoRoot);
1506
- _cachedCwd = dir;
1507
- return _cached2;
1508
- } catch {
1509
- _cached2 = path12.basename(dir);
1510
- _cachedCwd = dir;
1511
- return _cached2;
1512
- }
1513
- }
1514
- var _cached2, _cachedCwd;
1515
- var init_project_name = __esm({
1516
- "src/lib/project-name.ts"() {
1517
- "use strict";
1518
- _cached2 = null;
1519
- _cachedCwd = null;
1520
- }
1521
- });
1522
-
1523
- // src/lib/session-scope.ts
1524
- var session_scope_exports = {};
1525
- __export(session_scope_exports, {
1526
- assertSessionScope: () => assertSessionScope,
1527
- findSessionForProject: () => findSessionForProject,
1528
- getSessionProject: () => getSessionProject
1529
- });
1530
- function getSessionProject(sessionName) {
1531
- const sessions = listSessions();
1532
- const entry = sessions.find((s) => s.windowName === sessionName);
1533
- if (!entry) return null;
1534
- const parts = entry.projectDir.split("/").filter(Boolean);
1535
- return parts[parts.length - 1] ?? null;
1536
- }
1537
- function findSessionForProject(projectName) {
1538
- const sessions = listSessions();
1539
- for (const s of sessions) {
1540
- const proj = s.projectDir.split("/").filter(Boolean).pop();
1541
- if (proj === projectName && s.agentId === "exe") return s;
1542
- }
1543
- return null;
1544
- }
1545
- function assertSessionScope(actionType, targetProject) {
1546
- try {
1547
- const currentProject = getProjectName();
1548
- const exeSession = resolveExeSession();
1549
- if (!exeSession) {
1550
- return { allowed: true, reason: "no_session" };
1551
- }
1552
- if (currentProject === targetProject) {
1553
- return {
1554
- allowed: true,
1555
- reason: "same_session",
1556
- currentProject,
1557
- targetProject
1558
- };
1559
- }
1560
- process.stderr.write(
1561
- `[session-scope] Cross-project ${actionType}: session project="${currentProject}" \u2260 target project="${targetProject}"
1562
- `
1563
- );
1564
- return {
1565
- allowed: true,
1566
- // v1: warn-only, don't block
1567
- reason: "cross_session_granted",
1568
- currentProject,
1569
- targetProject,
1570
- targetSession: findSessionForProject(targetProject)?.windowName
1571
- };
1572
- } catch {
1573
- return { allowed: true, reason: "no_session" };
1574
- }
1575
- }
1576
- var init_session_scope = __esm({
1577
- "src/lib/session-scope.ts"() {
1578
- "use strict";
1579
- init_session_registry();
1580
- init_project_name();
1581
- init_tmux_routing();
1582
- }
1583
- });
1584
-
1585
- // src/lib/tasks-notify.ts
1586
- async function dispatchTaskToEmployee(input) {
1587
- if (input.assignedTo === "exe") return { dispatched: "skipped" };
1588
- let crossProject = false;
1589
- if (input.projectName) {
1590
- try {
1591
- const { assertSessionScope: assertSessionScope2 } = (init_session_scope(), __toCommonJS(session_scope_exports));
1592
- const check = assertSessionScope2("dispatch_task", input.projectName);
1593
- if (check.reason === "cross_session_granted") {
1594
- crossProject = true;
1595
- }
1596
- } catch {
1597
- }
1598
- }
1599
- try {
1600
- const transport = getTransport();
1601
- const exeSession = resolveExeSession();
1602
- if (!exeSession) return { dispatched: "session_missing" };
1603
- const sessionName = employeeSessionName(input.assignedTo, exeSession);
1604
- if (transport.isAlive(sessionName)) {
1605
- const result = sendIntercom(sessionName);
1606
- const dispatched = result === "acknowledged" || result === "debounced" || result === "queued" ? "verified" : result === "delivered" ? "sent_unverified" : "session_dead";
1607
- return { dispatched, session: sessionName, crossProject };
1608
- } else {
1609
- const projectDir = input.projectDir ?? process.cwd();
1610
- const result = ensureEmployee(input.assignedTo, exeSession, projectDir, {
1611
- autoInstance: input.assignedTo === "tom" || input.assignedTo === "sasha"
1612
- });
1613
- if (result.status === "failed") {
1614
- process.stderr.write(
1615
- `[dispatch] Failed to spawn ${input.assignedTo}: ${result.error}
1616
- `
1617
- );
1618
- return { dispatched: "session_missing" };
1619
- }
1620
- return { dispatched: "spawned", session: result.sessionName, crossProject };
1621
- }
1622
- } catch {
1623
- return { dispatched: "session_missing" };
1624
- }
1625
- }
1626
- function notifyTaskDone() {
1627
- try {
1628
- const key = getSessionKey();
1629
- if (key && !process.env.VITEST) notifyParentExe(key);
1630
- } catch {
1631
- }
1632
- }
1633
- async function markTaskNotificationsRead(taskFile) {
1634
- try {
1635
- await markAsReadByTaskFile(taskFile);
1636
- } catch {
1637
- }
1638
- }
1639
- var init_tasks_notify = __esm({
1640
- "src/lib/tasks-notify.ts"() {
1641
- "use strict";
1642
- init_tmux_routing();
1643
- init_session_key();
1644
- init_notifications();
1645
- init_transport();
1646
- }
1647
- });
1648
-
1649
- // src/lib/behaviors.ts
1650
- import crypto4 from "crypto";
1651
- async function storeBehavior(opts) {
1652
- const client = getClient();
1653
- const id = crypto4.randomUUID();
1654
- const now = (/* @__PURE__ */ new Date()).toISOString();
1655
- await client.execute({
1656
- sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, priority, content, active, created_at, updated_at)
1657
- VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)`,
1658
- args: [id, opts.agentId, opts.projectName ?? null, opts.domain ?? null, opts.priority ?? "p1", opts.content, now, now]
1659
- });
1660
- return id;
1661
- }
1662
- var init_behaviors = __esm({
1663
- "src/lib/behaviors.ts"() {
1664
- "use strict";
1665
- init_database();
1666
- }
1667
- });
1668
-
1669
- // src/lib/skill-learning.ts
1670
- var skill_learning_exports = {};
1671
- __export(skill_learning_exports, {
1672
- captureAndLearn: () => captureAndLearn,
1673
- captureTrajectory: () => captureTrajectory,
1674
- editDistance: () => editDistance,
1675
- extractSkill: () => extractSkill,
1676
- extractTrajectory: () => extractTrajectory,
1677
- findSimilarTrajectories: () => findSimilarTrajectories,
1678
- hashSignature: () => hashSignature,
1679
- storeTrajectory: () => storeTrajectory,
1680
- sweepTrajectories: () => sweepTrajectories
1681
- });
1682
- import crypto5 from "crypto";
1683
- async function extractTrajectory(taskId, agentId) {
1684
- const client = getClient();
1685
- const result = await client.execute({
1686
- sql: `SELECT tool_name, raw_text
1687
- FROM memories
1688
- WHERE task_id = ? AND agent_id = ?
1689
- ORDER BY timestamp ASC`,
1690
- args: [taskId, agentId]
1691
- });
1692
- if (result.rows.length === 0) return [];
1693
- const rawTools = result.rows.map((r) => {
1694
- const toolName = String(r.tool_name);
1695
- if (toolName === "Bash") {
1696
- const text = String(r.raw_text);
1697
- const cmdMatch = text.match(/(?:command|Command).*?[:\s]+"?(\w+)/);
1698
- return cmdMatch ? `Bash:${cmdMatch[1]}` : "Bash";
1699
- }
1700
- return toolName;
1701
- });
1702
- const signature = [];
1703
- for (const tool of rawTools) {
1704
- if (signature.length === 0 || signature[signature.length - 1] !== tool) {
1705
- signature.push(tool);
1706
- }
1707
- }
1708
- return signature;
1709
- }
1710
- function hashSignature(signature) {
1711
- return crypto5.createHash("sha256").update(signature.join("|")).digest("hex").slice(0, 16);
1712
- }
1713
- async function storeTrajectory(opts) {
1714
- const client = getClient();
1715
- const id = crypto5.randomUUID();
1716
- const now = (/* @__PURE__ */ new Date()).toISOString();
1717
- const signatureHash = hashSignature(opts.signature);
1718
- await client.execute({
1719
- sql: `INSERT INTO trajectories (id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at)
1720
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1721
- args: [
1722
- id,
1723
- opts.taskId,
1724
- opts.agentId,
1725
- opts.projectName,
1726
- opts.taskTitle,
1727
- JSON.stringify(opts.signature),
1728
- signatureHash,
1729
- opts.signature.length,
1730
- now
1731
- ]
1732
- });
1733
- return id;
1734
- }
1735
- async function findSimilarTrajectories(signature, threshold = DEFAULT_SKILL_THRESHOLD) {
1736
- const client = getClient();
1737
- const hash = hashSignature(signature);
1738
- const result = await client.execute({
1739
- sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
1740
- FROM trajectories
1741
- WHERE signature_hash = ?
1742
- ORDER BY created_at DESC
1743
- LIMIT 20`,
1744
- args: [hash]
1745
- });
1746
- const mapRow = (r) => ({
1747
- id: String(r.id),
1748
- taskId: String(r.task_id),
1749
- agentId: String(r.agent_id),
1750
- projectName: String(r.project_name),
1751
- taskTitle: String(r.task_title),
1752
- signature: JSON.parse(String(r.signature)),
1753
- signatureHash: String(r.signature_hash),
1754
- toolCount: Number(r.tool_count),
1755
- skillId: r.skill_id ? String(r.skill_id) : null,
1756
- createdAt: String(r.created_at)
1757
- });
1758
- const matches = result.rows.map(mapRow);
1759
- if (matches.length >= threshold) return matches;
1760
- const nearResult = await client.execute({
1761
- sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
1762
- FROM trajectories
1763
- WHERE tool_count BETWEEN ? AND ?
1764
- AND signature_hash != ?
1765
- ORDER BY created_at DESC
1766
- LIMIT 50`,
1767
- args: [
1768
- Math.max(1, signature.length - 3),
1769
- signature.length + 3,
1770
- hash
1771
- ]
1772
- });
1773
- for (const r of nearResult.rows) {
1774
- const candidateSig = JSON.parse(String(r.signature));
1775
- if (editDistance(signature, candidateSig) <= 2) {
1776
- matches.push(mapRow(r));
1777
- }
1778
- }
1779
- return matches;
1780
- }
1781
- async function captureTrajectory(opts) {
1782
- const signature = await extractTrajectory(opts.taskId, opts.agentId);
1783
- if (signature.length < 3) {
1784
- return { trajectoryId: "", similarCount: 0, similar: [] };
1785
- }
1786
- const trajectoryId = await storeTrajectory({
1787
- taskId: opts.taskId,
1788
- agentId: opts.agentId,
1789
- projectName: opts.projectName,
1790
- taskTitle: opts.taskTitle,
1791
- signature
1792
- });
1793
- const similar = await findSimilarTrajectories(
1794
- signature,
1795
- opts.skillThreshold ?? DEFAULT_SKILL_THRESHOLD
1796
- );
1797
- return { trajectoryId, similarCount: similar.length, similar };
1798
- }
1799
- function buildExtractionPrompt(trajectories) {
1800
- const items = trajectories.map((t, i) => {
1801
- const sig = t.signature.join(" \u2192 ");
1802
- return `Task ${i + 1}: "${t.taskTitle}" (${t.agentId}, ${t.projectName}) \u2014 ${t.toolCount} tool calls
1803
- Signature: ${sig}`;
1804
- }).join("\n\n");
1805
- return `You are analyzing ${trajectories.length} completed tasks that followed similar procedures:
1806
-
1807
- ${items}
1808
-
1809
- Extract the reusable procedure. Format your response EXACTLY like this:
1810
-
1811
- SKILL: {name \u2014 short, descriptive}
1812
- TRIGGER: {when to use this \u2014 one sentence}
1813
- STEPS:
1814
- 1. ...
1815
- 2. ...
1816
- PITFALLS: {common mistakes to avoid}
1817
-
1818
- Be specific and actionable. Include tool names, file patterns, and concrete commands where applicable.`;
1819
- }
1820
- async function extractSkill(trajectories, model) {
1821
- if (trajectories.length === 0) return null;
1822
- const config = await loadConfig();
1823
- const skillModel = model ?? config.skillModel;
1824
- const Anthropic = (await import("@anthropic-ai/sdk")).default;
1825
- const client = new Anthropic();
1826
- const prompt = buildExtractionPrompt(trajectories);
1827
- const response = await client.messages.create({
1828
- model: skillModel,
1829
- max_tokens: 500,
1830
- messages: [{ role: "user", content: prompt }]
1831
- });
1832
- const textBlock = response.content.find((b) => b.type === "text");
1833
- const skillText = textBlock?.text;
1834
- if (!skillText) return null;
1835
- const agentId = trajectories[0].agentId;
1836
- const projectName = trajectories[0].projectName;
1837
- const skillId = await storeBehavior({
1838
- agentId,
1839
- content: skillText,
1840
- domain: "skill",
1841
- projectName
1842
- });
1843
- const dbClient = getClient();
1844
- for (const t of trajectories) {
1845
- await dbClient.execute({
1846
- sql: "UPDATE trajectories SET skill_id = ? WHERE id = ?",
1847
- args: [skillId, t.id]
1848
- });
1849
- }
1850
- process.stderr.write(
1851
- `[skill-learning] Skill extracted from ${trajectories.length} trajectories \u2192 behavior ${skillId}
1852
- `
1853
- );
1854
- return skillId;
1855
- }
1856
- async function captureAndLearn(opts) {
1857
- try {
1858
- const config = await loadConfig();
1859
- if (!config.skillLearning) return;
1860
- const { trajectoryId, similarCount, similar } = await captureTrajectory({
1861
- ...opts,
1862
- skillThreshold: config.skillThreshold
1863
- });
1864
- if (!trajectoryId) return;
1865
- if (similarCount >= config.skillThreshold) {
1866
- const unprocessed = similar.filter((t) => !t.skillId);
1867
- if (unprocessed.length >= config.skillThreshold) {
1868
- extractSkill(unprocessed, config.skillModel).catch((err) => {
1869
- process.stderr.write(
1870
- `[skill-learning] Extraction failed: ${err instanceof Error ? err.message : String(err)}
1871
- `
1872
- );
1873
- });
1874
- }
1875
- }
1876
- } catch (err) {
1877
- process.stderr.write(
1878
- `[skill-learning] captureAndLearn failed: ${err instanceof Error ? err.message : String(err)}
1879
- `
1880
- );
1881
- }
1882
- }
1883
- async function sweepTrajectories(threshold, model) {
1884
- const config = await loadConfig();
1885
- if (!config.skillLearning) return { clustersProcessed: 0, skillsExtracted: 0 };
1886
- const t = threshold ?? config.skillThreshold;
1887
- const client = getClient();
1888
- const result = await client.execute({
1889
- sql: `SELECT signature_hash, COUNT(*) as cnt
1890
- FROM trajectories
1891
- WHERE skill_id IS NULL
1892
- GROUP BY signature_hash
1893
- HAVING cnt >= ?
1894
- ORDER BY cnt DESC
1895
- LIMIT 10`,
1896
- args: [t]
1897
- });
1898
- let clustersProcessed = 0;
1899
- let skillsExtracted = 0;
1900
- for (const row of result.rows) {
1901
- const hash = String(row.signature_hash);
1902
- const trajResult = await client.execute({
1903
- sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at
1904
- FROM trajectories
1905
- WHERE signature_hash = ? AND skill_id IS NULL
1906
- ORDER BY created_at DESC
1907
- LIMIT 10`,
1908
- args: [hash]
1909
- });
1910
- const trajectories = trajResult.rows.map((r) => ({
1911
- id: String(r.id),
1912
- taskId: String(r.task_id),
1913
- agentId: String(r.agent_id),
1914
- projectName: String(r.project_name),
1915
- taskTitle: String(r.task_title),
1916
- signature: JSON.parse(String(r.signature)),
1917
- signatureHash: String(r.signature_hash),
1918
- toolCount: Number(r.tool_count),
1919
- skillId: null,
1920
- createdAt: String(r.created_at)
1921
- }));
1922
- if (trajectories.length >= t) {
1923
- clustersProcessed++;
1924
- const skillId = await extractSkill(trajectories, model ?? config.skillModel);
1925
- if (skillId) skillsExtracted++;
1926
- }
1927
- }
1928
- return { clustersProcessed, skillsExtracted };
1929
- }
1930
- function editDistance(a, b) {
1931
- const m = a.length;
1932
- const n = b.length;
1933
- const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
1934
- for (let i = 0; i <= m; i++) dp[i][0] = i;
1935
- for (let j = 0; j <= n; j++) dp[0][j] = j;
1936
- for (let i = 1; i <= m; i++) {
1937
- for (let j = 1; j <= n; j++) {
1938
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
1939
- dp[i][j] = Math.min(
1940
- dp[i - 1][j] + 1,
1941
- dp[i][j - 1] + 1,
1942
- dp[i - 1][j - 1] + cost
1943
- );
1944
- }
1945
- }
1946
- return dp[m][n];
1947
- }
1948
- var DEFAULT_SKILL_THRESHOLD;
1949
- var init_skill_learning = __esm({
1950
- "src/lib/skill-learning.ts"() {
1951
- "use strict";
1952
- init_database();
1953
- init_behaviors();
1954
- init_config();
1955
- DEFAULT_SKILL_THRESHOLD = 3;
1956
- }
1957
- });
1958
-
1959
- // src/lib/tasks.ts
1960
- var tasks_exports = {};
1961
- __export(tasks_exports, {
1962
- countNewPendingReviewsSince: () => countNewPendingReviewsSince,
1963
- countPendingReviews: () => countPendingReviews,
1964
- createTask: () => createTask,
1965
- createTaskCore: () => createTaskCore,
1966
- deleteTask: () => deleteTask,
1967
- deleteTaskCore: () => deleteTaskCore,
1968
- ensureArchitectureDoc: () => ensureArchitectureDoc,
1969
- ensureGitignoreExe: () => ensureGitignoreExe,
1970
- getReviewChecklist: () => getReviewChecklist,
1971
- listPendingReviews: () => listPendingReviews,
1972
- listTasks: () => listTasks,
1973
- resolveTask: () => resolveTask,
1974
- slugify: () => slugify,
1975
- updateTask: () => updateTask,
1976
- updateTaskStatus: () => updateTaskStatus,
1977
- writeCheckpoint: () => writeCheckpoint
1978
- });
1979
- import path13 from "path";
1980
- import { writeFileSync as writeFileSync4, mkdirSync as mkdirSync5, unlinkSync as unlinkSync3 } from "fs";
1981
- async function createTask(input) {
1982
- const result = await createTaskCore(input);
1983
- if (!input.skipDispatch && result.status !== "blocked" && !process.env.VITEST) {
1984
- dispatchTaskToEmployee({
1985
- assignedTo: input.assignedTo,
1986
- title: input.title,
1987
- priority: input.priority,
1988
- taskFile: result.taskFile,
1989
- initialStatus: result.status,
1990
- projectName: input.projectName
1991
- });
1992
- }
1993
- return result;
1994
- }
1995
- async function updateTask(input) {
1996
- const { row, taskFile, now, taskId } = await updateTaskStatus(input);
1997
- try {
1998
- const agent = String(row.assigned_to);
1999
- const cacheDir = path13.join(EXE_AI_DIR, "session-cache");
2000
- const cachePath = path13.join(cacheDir, `current-task-${agent}.json`);
2001
- if (input.status === "in_progress") {
2002
- mkdirSync5(cacheDir, { recursive: true });
2003
- writeFileSync4(cachePath, JSON.stringify({ taskId, title: String(row.title) }));
2004
- } else if (input.status === "done" || input.status === "blocked" || input.status === "cancelled") {
2005
- try {
2006
- unlinkSync3(cachePath);
2007
- } catch {
2008
- }
2009
- }
2010
- } catch {
2011
- }
2012
- if (input.status === "done") {
2013
- await cleanupReviewFile(row, taskFile, input.baseDir);
2014
- }
2015
- if (input.status === "done" || input.status === "cancelled") {
2016
- try {
2017
- const client = getClient();
2018
- const taskTitle = String(row.title);
2019
- const escaped = taskTitle.replace(/%/g, "\\%").replace(/_/g, "\\_");
2020
- await client.execute({
2021
- sql: `UPDATE tasks SET status = 'cancelled', updated_at = ?
2022
- WHERE title LIKE ? ESCAPE '\\' AND status IN ('open', 'in_progress')`,
2023
- args: [now, `%left '${escaped}' as in\\_progress%`]
2024
- });
2025
- } catch {
2026
- }
2027
- }
2028
- const isTerminal = input.status === "done" || input.status === "needs_review";
2029
- if (isTerminal) {
2030
- const isExe = String(row.assigned_to) === "exe";
2031
- if (!isExe) {
2032
- notifyTaskDone();
2033
- }
2034
- await markTaskNotificationsRead(taskFile);
2035
- if (input.status === "done") {
2036
- try {
2037
- await cascadeUnblock(taskId, input.baseDir, now);
2038
- } catch {
2039
- }
2040
- if (row.parent_task_id) {
2041
- try {
2042
- await checkSubtaskCompletion(String(row.parent_task_id), String(row.project_name));
2043
- } catch {
2044
- }
2045
- }
2046
- }
2047
- }
2048
- if (input.status === "done" && String(row.assigned_to) !== "exe" && !process.env.VITEST) {
2049
- Promise.resolve().then(() => (init_skill_learning(), skill_learning_exports)).then(
2050
- ({ captureAndLearn: captureAndLearn2 }) => captureAndLearn2({
2051
- taskId,
2052
- agentId: String(row.assigned_to),
2053
- projectName: String(row.project_name),
2054
- taskTitle: String(row.title)
2055
- })
2056
- ).catch((err) => {
2057
- process.stderr.write(
2058
- `[updateTask] skill learning failed: ${err instanceof Error ? err.message : String(err)}
2059
- `
2060
- );
2061
- });
2062
- }
2063
- let nextTask;
2064
- if (isTerminal && String(row.assigned_to) !== "exe") {
2065
- try {
2066
- nextTask = await findNextTask(String(row.assigned_to));
2067
- } catch {
2068
- }
2069
- }
2070
- return {
2071
- id: String(row.id),
2072
- title: String(row.title),
2073
- assignedTo: String(row.assigned_to),
2074
- assignedBy: String(row.assigned_by),
2075
- projectName: String(row.project_name),
2076
- priority: String(row.priority),
2077
- status: input.status,
2078
- taskFile,
2079
- createdAt: String(row.created_at),
2080
- updatedAt: now,
2081
- budgetTokens: row.budget_tokens !== void 0 && row.budget_tokens !== null ? Number(row.budget_tokens) : null,
2082
- budgetFallbackModel: row.budget_fallback_model !== void 0 && row.budget_fallback_model !== null ? String(row.budget_fallback_model) : null,
2083
- tokensUsed: Number(row.tokens_used ?? 0),
2084
- tokensWarnedAt: row.tokens_warned_at !== void 0 && row.tokens_warned_at !== null ? Number(row.tokens_warned_at) : null,
2085
- nextTask
2086
- };
2087
- }
2088
- async function deleteTask(taskId, baseDir) {
2089
- const client = getClient();
2090
- const { taskFile, assignedTo, assignedBy, taskSlug } = await deleteTaskCore(taskId, baseDir);
2091
- const reviewer = assignedBy || "exe";
2092
- const reviewSlug = `review-${assignedTo}-${taskSlug}`;
2093
- const reviewFile = `exe/${reviewer}/${reviewSlug}.md`;
2094
- await client.execute({
2095
- sql: "DELETE FROM tasks WHERE task_file = ? OR task_file = ?",
2096
- args: [reviewFile, `exe/exe/${reviewSlug}.md`]
2097
- });
2098
- await markAsReadByTaskFile(taskFile);
2099
- await markAsReadByTaskFile(reviewFile);
2100
- }
2101
- var init_tasks = __esm({
2102
- "src/lib/tasks.ts"() {
2103
- "use strict";
2104
- init_database();
2105
- init_config();
2106
- init_notifications();
2107
- init_tasks_crud();
2108
- init_tasks_review();
2109
- init_tasks_crud();
2110
- init_tasks_chain();
2111
- init_tasks_review();
2112
- init_tasks_notify();
2113
- }
2114
- });
2115
-
2116
- // src/lib/capacity-monitor.ts
2117
- var capacity_monitor_exports = {};
2118
- __export(capacity_monitor_exports, {
2119
- CTX_FLOOR_PERCENT: () => CTX_FLOOR_PERCENT,
2120
- _resetLastRelaunchCache: () => _resetLastRelaunchCache,
2121
- _resetPendingCapacityKills: () => _resetPendingCapacityKills,
2122
- confirmCapacityKill: () => confirmCapacityKill,
2123
- createOrRefreshResumeTask: () => createOrRefreshResumeTask,
2124
- extractContextPercent: () => extractContextPercent,
2125
- isAtCapacity: () => isAtCapacity,
2126
- isWithinRelaunchCooldown: () => isWithinRelaunchCooldown,
2127
- pollCapacityDead: () => pollCapacityDead
2128
- });
2129
- function resumeTaskTitle(agentId) {
2130
- return `${RESUME_TITLE_PREFIX} ${agentId} hit context capacity \u2014 continue open tasks`;
2131
- }
2132
- function buildResumeContext(agentId, openTasks) {
2133
- const taskList = openTasks.map(
2134
- (r, i) => `${i + 1}. [${String(r.priority).toUpperCase()}] ${String(r.title)} (${String(r.task_file)})`
2135
- ).join("\n");
2136
- return [
2137
- "## Context",
2138
- "",
2139
- `${agentId} hit context capacity and was auto-relaunched by the capacity monitor.`,
2140
- "Call recall_my_memory first \u2014 search for 'CONTEXT CHECKPOINT'. Pick up where the previous session stopped.",
2141
- "",
2142
- `You have ${openTasks.length} open task(s). Work through them in priority order:`,
2143
- "",
2144
- taskList,
2145
- "",
2146
- "Read each task file and chain through them. Build and commit after each one."
2147
- ].join("\n");
2148
- }
2149
- function filterPaneContent(paneOutput) {
2150
- return paneOutput.split("\n").filter((line) => {
2151
- if (CONTENT_LINE_PREFIX.test(line)) return false;
2152
- for (const marker of CONTENT_LINE_MARKERS) {
2153
- if (line.includes(marker)) return false;
2154
- }
2155
- for (const re of SOURCE_CODE_MARKERS) {
2156
- if (re.test(line)) return false;
2157
- }
2158
- return true;
2159
- }).join("\n");
2160
- }
2161
- function extractContextPercent(paneOutput) {
2162
- const match = paneOutput.match(CC_CONTEXT_BAR_RE);
2163
- if (!match) return null;
2164
- const parsed = Number.parseInt(match[2], 10);
2165
- return Number.isFinite(parsed) ? parsed : null;
2166
- }
2167
- function isAtCapacity(paneOutput) {
2168
- const filtered = filterPaneContent(paneOutput);
2169
- return CAPACITY_PATTERNS.some((p) => p.test(filtered));
2170
- }
2171
- function confirmCapacityKill(agentId, now = Date.now()) {
2172
- const pendingSince = _pendingCapacityKill.get(agentId);
2173
- if (pendingSince === void 0) {
2174
- _pendingCapacityKill.set(agentId, now);
2175
- return false;
2176
- }
2177
- if (now - pendingSince > CONFIRMATION_WINDOW_MS) {
2178
- _pendingCapacityKill.set(agentId, now);
2179
- return false;
2180
- }
2181
- _pendingCapacityKill.delete(agentId);
2182
- return true;
2183
- }
2184
- function _resetPendingCapacityKills() {
2185
- _pendingCapacityKill.clear();
2186
- }
2187
- function _resetLastRelaunchCache() {
2188
- _lastRelaunch.clear();
2189
- }
2190
- async function lastResumeCreatedAtMs(agentId) {
2191
- const client = getClient();
2192
- const result = await client.execute({
2193
- sql: `SELECT MAX(created_at) AS last_created_at
2194
- FROM tasks
2195
- WHERE assigned_to = ? AND title LIKE ?`,
2196
- args: [agentId, `${RESUME_TITLE_PREFIX} %`]
2197
- });
2198
- const raw = result.rows[0]?.last_created_at;
2199
- if (raw === null || raw === void 0) return null;
2200
- const parsed = Date.parse(String(raw));
2201
- return Number.isNaN(parsed) ? null : parsed;
2202
- }
2203
- async function isWithinRelaunchCooldown(agentId, now = Date.now()) {
2204
- const cached = _lastRelaunch.get(agentId);
2205
- if (cached !== void 0) return now - cached < RELAUNCH_COOLDOWN_MS;
2206
- const persisted = await lastResumeCreatedAtMs(agentId);
2207
- if (persisted === null) return false;
2208
- if (now - persisted >= RELAUNCH_COOLDOWN_MS) return false;
2209
- _lastRelaunch.set(agentId, persisted);
2210
- return true;
2211
- }
2212
- async function createOrRefreshResumeTask(agentId, projectDir, openTasks) {
2213
- const client = getClient();
2214
- const now = (/* @__PURE__ */ new Date()).toISOString();
2215
- const context = buildResumeContext(agentId, openTasks);
2216
- const existing = await client.execute({
2217
- sql: `SELECT id FROM tasks
2218
- WHERE assigned_to = ?
2219
- AND title LIKE ?
2220
- AND status IN (${RESUME_ACTIVE_STATUSES.map(() => "?").join(", ")})
2221
- ORDER BY created_at DESC
2222
- LIMIT 1`,
2223
- args: [agentId, RESUME_TITLE_LIKE_PATTERN, ...RESUME_ACTIVE_STATUSES]
2224
- });
2225
- if (existing.rows.length > 0) {
2226
- const taskId = String(existing.rows[0].id);
2227
- await client.execute({
2228
- sql: `UPDATE tasks SET context = ?, updated_at = ? WHERE id = ?`,
2229
- args: [context, now, taskId]
2230
- });
2231
- return { created: false, taskId };
2232
- }
2233
- const { createTask: createTask2 } = await Promise.resolve().then(() => (init_tasks(), tasks_exports));
2234
- const task = await createTask2({
2235
- title: resumeTaskTitle(agentId),
2236
- assignedTo: agentId,
2237
- assignedBy: "system",
2238
- projectName: projectDir.split("/").pop() ?? "unknown",
2239
- priority: "p0",
2240
- context,
2241
- baseDir: projectDir
2242
- });
2243
- return { created: true, taskId: task.id };
2244
- }
2245
- async function pollCapacityDead() {
2246
- const transport = getTransport();
2247
- const relaunched = [];
2248
- const registered = listSessions().filter(
2249
- (s) => s.agentId !== "exe"
2250
- );
2251
- if (registered.length === 0) return [];
2252
- let liveSessions;
2253
- try {
2254
- liveSessions = transport.listSessions();
2255
- } catch {
2256
- return [];
2257
- }
2258
- for (const entry of registered) {
2259
- const { windowName, agentId, projectDir } = entry;
2260
- if (!liveSessions.includes(windowName)) continue;
2261
- if (await isWithinRelaunchCooldown(agentId)) continue;
2262
- let pane;
2263
- try {
2264
- pane = transport.capturePane(windowName, 15);
2265
- } catch {
2266
- continue;
2267
- }
2268
- if (!isAtCapacity(pane)) continue;
2269
- const ctxPct = extractContextPercent(pane);
2270
- if (ctxPct !== null && ctxPct < CTX_FLOOR_PERCENT) {
2271
- process.stderr.write(
2272
- `[capacity-monitor] ctx-floor: ${agentId} at ${ctxPct}% in ${windowName} \u2014 below ${CTX_FLOOR_PERCENT}%. Skipping capacity kill (likely self-referential content or false positive).
2273
- `
2274
- );
2275
- continue;
2276
- }
2277
- if (!confirmCapacityKill(agentId)) {
2278
- process.stderr.write(
2279
- `[capacity-monitor] ${agentId} matched capacity pattern once in ${windowName}. Awaiting confirmation on next tick.
2280
- `
2281
- );
2282
- continue;
2283
- }
2284
- const verify = await verifyPaneAtCapacity(windowName);
2285
- if (!verify.atCapacity) {
2286
- process.stderr.write(
2287
- `[capacity-monitor] verifyPaneAtCapacity rejected kill for ${agentId} in ${windowName} (reason: ${verify.reason}). Skipping.
2288
- `
2289
- );
2290
- void recordSessionKill({
2291
- sessionName: windowName,
2292
- agentId,
2293
- reason: "capacity_false_positive_blocked"
2294
- });
2295
- continue;
2296
- }
2297
- process.stderr.write(
2298
- `[capacity-monitor] Detected ${agentId} at capacity in session ${windowName} (confirmed). Auto-relaunching.
2299
- `
2300
- );
2301
- try {
2302
- transport.kill(windowName);
2303
- void recordSessionKill({
2304
- sessionName: windowName,
2305
- agentId,
2306
- reason: "capacity"
2307
- });
2308
- const client = getClient();
2309
- const openTasks = await client.execute({
2310
- sql: `SELECT id, title, priority, task_file, status
2311
- FROM tasks
2312
- WHERE assigned_to = ? AND status IN ('open', 'in_progress')
2313
- ORDER BY
2314
- CASE priority WHEN 'p0' THEN 0 WHEN 'p1' THEN 1 WHEN 'p2' THEN 2 ELSE 3 END,
2315
- created_at ASC
2316
- LIMIT 10`,
2317
- args: [agentId]
2318
- });
2319
- if (openTasks.rows.length === 0) {
2320
- process.stderr.write(
2321
- `[capacity-monitor] ${agentId} has no open tasks \u2014 skipping relaunch.
2322
- `
2323
- );
2324
- continue;
2325
- }
2326
- const { created } = await createOrRefreshResumeTask(
2327
- agentId,
2328
- projectDir,
2329
- openTasks.rows
2330
- );
2331
- if (created) {
2332
- await writeNotification({
2333
- agentId: "system",
2334
- agentRole: "daemon",
2335
- event: "capacity_relaunch",
2336
- project: projectDir.split("/").pop() ?? "unknown",
2337
- summary: `${agentId} hit context capacity. Auto-relaunched with ${openTasks.rows.length} open task(s).`
2338
- });
2339
- }
2340
- _lastRelaunch.set(agentId, Date.now());
2341
- if (created) relaunched.push(agentId);
2342
- } catch (err) {
2343
- process.stderr.write(
2344
- `[capacity-monitor] Failed to relaunch ${agentId}: ${err instanceof Error ? err.message : String(err)}
2345
- `
2346
- );
2347
- }
2348
- }
2349
- return relaunched;
2350
- }
2351
- var CAPACITY_PATTERNS, CONTENT_LINE_PREFIX, CONTENT_LINE_MARKERS, SOURCE_CODE_MARKERS, RELAUNCH_COOLDOWN_MS, _lastRelaunch, RESUME_TITLE_PREFIX, RESUME_TITLE_LIKE_PATTERN, RESUME_ACTIVE_STATUSES, CONFIRMATION_WINDOW_MS, _pendingCapacityKill, CC_CONTEXT_BAR_RE, CTX_FLOOR_PERCENT;
2352
- var init_capacity_monitor = __esm({
2353
- "src/lib/capacity-monitor.ts"() {
2354
- "use strict";
2355
- init_session_registry();
2356
- init_transport();
2357
- init_notifications();
2358
- init_database();
2359
- init_session_kill_telemetry();
2360
- init_tmux_routing();
2361
- CAPACITY_PATTERNS = [
2362
- /conversation is too long/i,
2363
- /maximum context length/i,
2364
- /context window.*(?:limit|exceed|full)/i,
2365
- /reached.*(?:token|context).*limit/i
2366
- ];
2367
- CONTENT_LINE_PREFIX = /^[\s>#\-*[]/;
2368
- CONTENT_LINE_MARKERS = [
2369
- "RESUME:",
2370
- "intercom",
2371
- "capacity-monitor",
2372
- "CAPACITY_PATTERNS",
2373
- "isAtCapacity",
2374
- "CONTENT_LINE_MARKERS",
2375
- "pollCapacityDead",
2376
- "confirmCapacityKill",
2377
- "session_kills",
2378
- "capacity-monitor.test"
2379
- ];
2380
- SOURCE_CODE_MARKERS = [
2381
- /["'`/].*(?:maximum context length|conversation is too long)/i,
2382
- /(?:maximum context length|conversation is too long).*["'`/]/i
2383
- ];
2384
- RELAUNCH_COOLDOWN_MS = 5 * 60 * 1e3;
2385
- _lastRelaunch = /* @__PURE__ */ new Map();
2386
- RESUME_TITLE_PREFIX = "RESUME:";
2387
- RESUME_TITLE_LIKE_PATTERN = `${RESUME_TITLE_PREFIX} % hit context capacity%`;
2388
- RESUME_ACTIVE_STATUSES = ["open", "in_progress"];
2389
- CONFIRMATION_WINDOW_MS = 3 * 60 * 1e3;
2390
- _pendingCapacityKill = /* @__PURE__ */ new Map();
2391
- CC_CONTEXT_BAR_RE = /([\u2588\u2591\u2592\u2593]{10})\s+(\d+)%/;
2392
- CTX_FLOOR_PERCENT = 50;
2393
- }
2394
- });
2395
-
2396
- // src/lib/tmux-routing.ts
2397
- import { execFileSync as execFileSync2, execSync as execSync7 } from "child_process";
2398
- import { readFileSync as readFileSync9, writeFileSync as writeFileSync5, mkdirSync as mkdirSync6, existsSync as existsSync11, appendFileSync as appendFileSync2 } from "fs";
2399
- import path14 from "path";
2400
- import os5 from "os";
2401
- import { fileURLToPath } from "url";
2402
- function resolveBehaviorsExporterScript() {
2403
- try {
2404
- const thisFile = fileURLToPath(import.meta.url);
2405
- const scriptPath = path14.join(
2406
- path14.dirname(thisFile),
2407
- "..",
2408
- "bin",
2409
- "exe-export-behaviors.js"
2410
- );
2411
- return existsSync11(scriptPath) ? scriptPath : null;
2412
- } catch {
2413
- return null;
2414
- }
2415
- }
2416
- function exportBehaviorsSync(agentId, projectName, sessionKey) {
2417
- const script = resolveBehaviorsExporterScript();
2418
- if (!script) return null;
2419
- try {
2420
- const output = execFileSync2(
2421
- process.execPath,
2422
- [script, agentId, projectName, sessionKey],
2423
- { encoding: "utf-8", timeout: BEHAVIORS_EXPORT_TIMEOUT_MS }
2424
- ).trim();
2425
- return output.length > 0 ? output : null;
2426
- } catch (err) {
2427
- process.stderr.write(
2428
- `[tmux-routing] behaviors export failed for ${agentId}: ${err instanceof Error ? err.message : String(err)}
2429
- `
2430
- );
2431
- return null;
2432
- }
2433
- }
2434
- function getMySession() {
2435
- return getTransport().getMySession();
2436
- }
2437
- function employeeSessionName(employee, exeSession, instance) {
2438
- const suffix = instance != null && instance > 0 ? String(instance) : "";
2439
- return `${employee}${suffix}-${exeSession}`;
2440
- }
2441
- function parseParentExe(sessionName, agentId) {
2442
- const escaped = agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2443
- const regex = new RegExp(`^${escaped}\\d*-(.+)$`);
2444
- const match = sessionName.match(regex);
2445
- return match?.[1] ?? null;
2446
- }
2447
- function extractRootExe(name) {
2448
- const match = name.match(/(exe\d+)$/);
2449
- return match?.[1] ?? null;
2450
- }
2451
- function registerParentExe(sessionKey, parentExe, dispatchedBy) {
2452
- if (!existsSync11(SESSION_CACHE)) {
2453
- mkdirSync6(SESSION_CACHE, { recursive: true });
2454
- }
2455
- const rootExe = extractRootExe(parentExe) ?? parentExe;
2456
- const filePath = path14.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`);
2457
- writeFileSync5(filePath, JSON.stringify({
2458
- parentExe: rootExe,
2459
- dispatchedBy: dispatchedBy || rootExe,
2460
- registeredAt: (/* @__PURE__ */ new Date()).toISOString()
2461
- }));
2462
- }
2463
- function getParentExe(sessionKey) {
2464
- try {
2465
- const data = JSON.parse(readFileSync9(path14.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
2466
- return data.parentExe || null;
2467
- } catch {
2468
- return null;
2469
- }
2470
- }
2471
- function getDispatchedBy(sessionKey) {
2472
- try {
2473
- const data = JSON.parse(readFileSync9(
2474
- path14.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`),
2475
- "utf8"
2476
- ));
2477
- return data.dispatchedBy ?? data.parentExe ?? null;
2478
- } catch {
2479
- return null;
2480
- }
2481
- }
2482
- function resolveExeSession() {
2483
- const mySession = getMySession();
2484
- if (!mySession) return null;
2485
- try {
2486
- const key = getSessionKey();
2487
- const parentExe = getParentExe(key);
2488
- if (parentExe) {
2489
- return extractRootExe(parentExe) ?? parentExe;
2490
- }
2491
- } catch {
2492
- }
2493
- return extractRootExe(mySession) ?? mySession;
2494
- }
2495
- function isEmployeeAlive(sessionName) {
2496
- return getTransport().isAlive(sessionName);
2497
- }
2498
- function findFreeInstance(employeeName, exeSession, maxInstances = 10, isAlive = isEmployeeAlive) {
2499
- const base = employeeSessionName(employeeName, exeSession);
2500
- if (!isAlive(base)) return 0;
2501
- for (let i = 2; i <= maxInstances; i++) {
2502
- const candidate = employeeSessionName(employeeName, exeSession, i);
2503
- if (!isAlive(candidate)) return i;
2504
- }
2505
- return null;
2506
- }
2507
- async function verifyPaneAtCapacity(sessionName) {
2508
- const transport = getTransport();
2509
- if (!transport.isAlive(sessionName)) {
2510
- return { atCapacity: false, reason: `session ${sessionName} is not alive` };
2511
- }
2512
- let pane;
2513
- try {
2514
- pane = transport.capturePane(sessionName, VERIFY_PANE_LINES);
2515
- } catch (err) {
2516
- return {
2517
- atCapacity: false,
2518
- reason: `capture-pane failed: ${err instanceof Error ? err.message : String(err)}`
2519
- };
2520
- }
2521
- const { isAtCapacity: isAtCapacity2 } = await Promise.resolve().then(() => (init_capacity_monitor(), capacity_monitor_exports));
2522
- if (!isAtCapacity2(pane)) {
2523
- return {
2524
- atCapacity: false,
2525
- reason: `last ${VERIFY_PANE_LINES} lines show normal work, no capacity banner`
2526
- };
2527
- }
2528
- return {
2529
- atCapacity: true,
2530
- reason: "capacity banner matched in recent pane output"
2531
- };
2532
- }
2533
- function readDebounceState() {
2534
- try {
2535
- if (!existsSync11(DEBOUNCE_FILE)) return {};
2536
- return JSON.parse(readFileSync9(DEBOUNCE_FILE, "utf8"));
2537
- } catch {
2538
- return {};
2539
- }
2540
- }
2541
- function writeDebounceState(state) {
2542
- try {
2543
- if (!existsSync11(SESSION_CACHE)) mkdirSync6(SESSION_CACHE, { recursive: true });
2544
- writeFileSync5(DEBOUNCE_FILE, JSON.stringify(state));
2545
- } catch {
2546
- }
2547
- }
2548
- function isDebounced(targetSession) {
2549
- const state = readDebounceState();
2550
- const lastSent = state[targetSession] ?? 0;
2551
- return Date.now() - lastSent < INTERCOM_DEBOUNCE_MS;
2552
- }
2553
- function recordDebounce(targetSession) {
2554
- const state = readDebounceState();
2555
- state[targetSession] = Date.now();
2556
- const cutoff = Date.now() - DEBOUNCE_CLEANUP_AGE_MS;
2557
- for (const key of Object.keys(state)) {
2558
- if ((state[key] ?? 0) < cutoff) delete state[key];
2559
- }
2560
- writeDebounceState(state);
2561
- }
2562
- function logIntercom(msg) {
2563
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${msg}
2564
- `;
2565
- process.stderr.write(`[intercom] ${msg}
2566
- `);
2567
- try {
2568
- appendFileSync2(INTERCOM_LOG2, line);
2569
- } catch {
2570
- }
2571
- }
2572
- function getSessionState(sessionName) {
2573
- const transport = getTransport();
2574
- if (!transport.isAlive(sessionName)) return "offline";
2575
- try {
2576
- const pane = transport.capturePane(sessionName, 5);
2577
- if (!pane.includes("\u276F") && !pane.includes("Claude Code") && !BUSY_PATTERN.test(pane) && !/Running…/.test(pane)) {
2578
- if (/\$\s*$/.test(pane) || /% $/.test(pane.trimEnd())) {
2579
- return "no_claude";
2580
- }
2581
- }
2582
- if (/Running…/.test(pane)) return "tool";
2583
- if (BUSY_PATTERN.test(pane)) return "thinking";
2584
- return "idle";
2585
- } catch {
2586
- return "offline";
2587
- }
2588
- }
2589
- function isSessionBusy(sessionName) {
2590
- const state = getSessionState(sessionName);
2591
- return state === "thinking" || state === "tool";
2592
- }
2593
- function isExeSession(sessionName) {
2594
- return /^exe\d*$/.test(sessionName);
2595
- }
2596
- function sendIntercom(targetSession) {
2597
- const transport = getTransport();
2598
- if (isExeSession(targetSession)) {
2599
- logIntercom(`SKIP_EXE \u2192 ${targetSession} (exe sessions use prompt-submit hook)`);
2600
- return "skipped_exe";
2601
- }
2602
- if (isDebounced(targetSession)) {
2603
- logIntercom(`DEBOUNCE \u2192 ${targetSession} (cross-process file debounce)`);
2604
- return "debounced";
2605
- }
2606
- try {
2607
- const sessions = transport.listSessions();
2608
- if (!sessions.includes(targetSession)) {
2609
- logIntercom(`SKIP \u2192 ${targetSession} (session not found)`);
2610
- return "failed";
2611
- }
2612
- const sessionState = getSessionState(targetSession);
2613
- if (sessionState === "no_claude") {
2614
- queueIntercom(targetSession, "claude not running in session");
2615
- recordDebounce(targetSession);
2616
- logIntercom(`QUEUED \u2192 ${targetSession} (no claude process \u2014 raw shell detected)`);
2617
- return "queued";
2618
- }
2619
- if (sessionState === "thinking" || sessionState === "tool") {
2620
- queueIntercom(targetSession, "session busy at send time");
2621
- recordDebounce(targetSession);
2622
- logIntercom(`QUEUED \u2192 ${targetSession} (session busy, will retry from queue)`);
2623
- return "queued";
2624
- }
2625
- if (transport.isPaneInCopyMode(targetSession)) {
2626
- logIntercom(`COPY_MODE \u2192 ${targetSession} (exiting copy mode first)`);
2627
- transport.sendKeys(targetSession, "q");
2628
- }
2629
- transport.sendKeys(targetSession, "/exe-intercom");
2630
- recordDebounce(targetSession);
2631
- logIntercom(`DELIVERED \u2192 ${targetSession} (fire-and-forget)`);
2632
- return "delivered";
2633
- } catch {
2634
- logIntercom(`FAIL \u2192 ${targetSession}`);
2635
- return "failed";
2636
- }
2637
- }
2638
- function notifyParentExe(sessionKey) {
2639
- const target = getDispatchedBy(sessionKey);
2640
- if (!target) {
2641
- process.stderr.write(`[intercom] notifyParentExe: no dispatcher found for key ${sessionKey}
2642
- `);
2643
- return false;
2644
- }
2645
- process.stderr.write(`[intercom] notifyParentExe \u2192 ${target}
2646
- `);
2647
- const result = sendIntercom(target);
2648
- if (result === "failed") {
2649
- const rootExe = resolveExeSession();
2650
- if (rootExe && rootExe !== target) {
2651
- process.stderr.write(`[intercom] notifyParentExe: dispatcher ${target} dead, falling back to root exe ${rootExe}
2652
- `);
2653
- const fallback = sendIntercom(rootExe);
2654
- return fallback !== "failed";
2655
- }
2656
- return false;
2657
- }
2658
- return true;
2659
- }
2660
- function ensureEmployee(employeeName, exeSession, projectDir, opts) {
2661
- if (employeeName === "exe") {
2662
- return { status: "failed", sessionName: "", error: "exe is the COO, not a dispatchable employee" };
2663
- }
2664
- try {
2665
- assertEmployeeLimitSync();
2666
- } catch (err) {
2667
- if (err instanceof PlanLimitError) {
2668
- return { status: "failed", sessionName: "", error: err.message };
2669
- }
2670
- }
2671
- if (/-exe\d*$/.test(employeeName)) {
2672
- const bare = employeeName.replace(/-exe\d*$/, "").replace(/\d+$/, "");
2673
- return {
2674
- status: "failed",
2675
- sessionName: "",
2676
- error: `Error: pass employee name ('${bare}'), not session name ('${employeeName}')`
2677
- };
2678
- }
2679
- let effectiveInstance = opts?.instance;
2680
- if (effectiveInstance === void 0 && opts?.autoInstance) {
2681
- const free = findFreeInstance(
2682
- employeeName,
2683
- exeSession,
2684
- opts.maxAutoInstances ?? 10
2685
- );
2686
- if (free === null) {
2687
- return {
2688
- status: "failed",
2689
- sessionName: employeeSessionName(employeeName, exeSession),
2690
- error: `All ${opts.maxAutoInstances ?? 10} instances of ${employeeName} are alive \u2014 cap reached`
2691
- };
2692
- }
2693
- effectiveInstance = free === 0 ? void 0 : free;
2694
- }
2695
- const sessionName = employeeSessionName(employeeName, exeSession, effectiveInstance);
2696
- if (isEmployeeAlive(sessionName)) {
2697
- const result2 = sendIntercom(sessionName);
2698
- if (result2 === "acknowledged" || result2 === "skipped_exe" || result2 === "debounced" || result2 === "queued") {
2699
- return { status: "intercom_sent", sessionName };
2700
- }
2701
- if (result2 === "delivered") {
2702
- return { status: "intercom_unprocessed", sessionName };
2703
- }
2704
- return { status: "failed", sessionName, error: "intercom delivery failed" };
2705
- }
2706
- const spawnOpts = { ...opts, instance: effectiveInstance };
2707
- const mainRoot = getMainRepoRoot(projectDir) ?? projectDir;
2708
- const wtPath = ensureWorktree(mainRoot, employeeName, effectiveInstance);
2709
- if (wtPath) {
2710
- spawnOpts.cwd = wtPath;
2711
- }
2712
- const result = spawnEmployee(employeeName, exeSession, projectDir, spawnOpts);
2713
- if (result.error) {
2714
- return { status: "failed", sessionName, error: result.error };
2715
- }
2716
- return { status: "spawned", sessionName };
2717
- }
2718
- function spawnEmployee(employeeName, exeSession, projectDir, opts) {
2719
- const transport = getTransport();
2720
- const sessionName = employeeSessionName(employeeName, exeSession, opts?.instance);
2721
- const instanceLabel2 = opts?.instance != null && opts.instance > 0 ? `${employeeName}${opts.instance}` : employeeName;
2722
- const logDir = path14.join(os5.homedir(), ".exe-os", "session-logs");
2723
- const logFile = path14.join(logDir, `${instanceLabel2}-${Date.now()}.log`);
2724
- if (!existsSync11(logDir)) {
2725
- mkdirSync6(logDir, { recursive: true });
2726
- }
2727
- transport.kill(sessionName);
2728
- let cleanupSuffix = "";
2729
- try {
2730
- const thisFile = fileURLToPath(import.meta.url);
2731
- const cleanupScript = path14.join(path14.dirname(thisFile), "..", "bin", "exe-session-cleanup.js");
2732
- if (existsSync11(cleanupScript)) {
2733
- cleanupSuffix = `; ${process.execPath} "${cleanupScript}" "${employeeName}" "${exeSession}"`;
2734
- }
2735
- } catch {
2736
- }
2737
- try {
2738
- const claudeJsonPath = path14.join(os5.homedir(), ".claude.json");
2739
- let claudeJson = {};
2740
- try {
2741
- claudeJson = JSON.parse(readFileSync9(claudeJsonPath, "utf8"));
2742
- } catch {
2743
- }
2744
- if (!claudeJson.projects) claudeJson.projects = {};
2745
- const projects = claudeJson.projects;
2746
- const trustDir = opts?.cwd ?? projectDir;
2747
- if (!projects[trustDir]) projects[trustDir] = {};
2748
- projects[trustDir].hasTrustDialogAccepted = true;
2749
- writeFileSync5(claudeJsonPath, JSON.stringify(claudeJson, null, 2) + "\n");
2750
- } catch {
2751
- }
2752
- try {
2753
- const settingsDir = path14.join(os5.homedir(), ".claude", "projects");
2754
- const normalizedKey = (opts?.cwd ?? projectDir).replace(/\//g, "-").replace(/^-/, "");
2755
- const projSettingsDir = path14.join(settingsDir, normalizedKey);
2756
- const settingsPath = path14.join(projSettingsDir, "settings.json");
2757
- let settings = {};
2758
- try {
2759
- settings = JSON.parse(readFileSync9(settingsPath, "utf8"));
2760
- } catch {
2761
- }
2762
- const perms = settings.permissions ?? {};
2763
- const allow = perms.allow ?? [];
2764
- const toolNames = [
2765
- "recall_my_memory",
2766
- "store_memory",
2767
- "create_task",
2768
- "update_task",
2769
- "list_tasks",
2770
- "get_task",
2771
- "ask_team_memory",
2772
- "store_behavior",
2773
- "get_identity",
2774
- "send_message"
2775
- ];
2776
- const requiredTools = expandDualPrefixTools(toolNames);
2777
- let changed = false;
2778
- for (const tool of requiredTools) {
2779
- if (!allow.includes(tool)) {
2780
- allow.push(tool);
2781
- changed = true;
2782
- }
2783
- }
2784
- if (changed) {
2785
- perms.allow = allow;
2786
- settings.permissions = perms;
2787
- mkdirSync6(projSettingsDir, { recursive: true });
2788
- writeFileSync5(settingsPath, JSON.stringify(settings, null, 2) + "\n");
2789
- }
2790
- } catch {
2791
- }
2792
- const spawnCwd = opts?.cwd ?? projectDir;
2793
- const useExeAgent = !!(opts?.model && opts?.provider);
2794
- const ccProvider = useExeAgent ? DEFAULT_PROVIDER : detectActiveProvider();
2795
- const useBinSymlink = ccProvider !== DEFAULT_PROVIDER;
2796
- let identityFlag = "";
2797
- let behaviorsFlag = "";
2798
- let legacyFallbackWarned = false;
2799
- if (!useExeAgent && !useBinSymlink) {
2800
- const identityPath = path14.join(
2801
- os5.homedir(),
2802
- ".exe-os",
2803
- "identity",
2804
- `${employeeName}.md`
2805
- );
2806
- _resetCcAgentSupportCache();
2807
- const hasAgentFlag = claudeSupportsAgentFlag();
2808
- if (hasAgentFlag) {
2809
- identityFlag = ` --agent ${employeeName}`;
2810
- } else if (existsSync11(identityPath)) {
2811
- identityFlag = ` --append-system-prompt-file ${identityPath}`;
2812
- legacyFallbackWarned = true;
2813
- }
2814
- const behaviorsFile = exportBehaviorsSync(
2815
- employeeName,
2816
- path14.basename(spawnCwd),
2817
- sessionName
2818
- );
2819
- if (behaviorsFile) {
2820
- behaviorsFlag = ` --append-system-prompt-file ${behaviorsFile}`;
2821
- }
2822
- }
2823
- if (legacyFallbackWarned) {
2824
- process.stderr.write(
2825
- `[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.
2826
- `
2827
- );
2828
- }
2829
- let sessionContextFlag = "";
2830
- try {
2831
- const ctxDir = path14.join(os5.homedir(), ".exe-os", "session-cache");
2832
- mkdirSync6(ctxDir, { recursive: true });
2833
- const ctxFile = path14.join(ctxDir, `session-context-${sessionName}.md`);
2834
- const ctxContent = [
2835
- `## Session Context`,
2836
- `You are running in tmux session: ${sessionName}.`,
2837
- `Your parent exe session is ${exeSession}.`,
2838
- `Your employees (if any) use the -${exeSession} suffix (e.g., tom-${exeSession}).`
2839
- ].join("\n");
2840
- writeFileSync5(ctxFile, ctxContent);
2841
- sessionContextFlag = ` --append-system-prompt-file ${ctxFile}`;
2842
- } catch {
2843
- }
2844
- let envPrefix = `EXE_SESSION=${exeSession} EXE_SESSION_NAME=${sessionName}`;
2845
- if (ccProvider !== DEFAULT_PROVIDER) {
2846
- const cfg = PROVIDER_TABLE[ccProvider];
2847
- if (cfg?.apiKeyEnv) {
2848
- const keyVal = process.env[cfg.apiKeyEnv];
2849
- if (keyVal) {
2850
- envPrefix = `${envPrefix} ${cfg.apiKeyEnv}=${keyVal}`;
2851
- }
2852
- }
2853
- }
2854
- let spawnCommand;
2855
- if (useExeAgent) {
2856
- spawnCommand = `${envPrefix} exe-agent --employee ${employeeName} --model ${opts.model} --provider ${opts.provider}${cleanupSuffix}`;
2857
- } else if (useBinSymlink) {
2858
- const binName = `${employeeName}-${ccProvider}`;
2859
- process.stderr.write(
2860
- `[tmux-routing] provider cascade: ${ccProvider} \u2192 spawning ${binName}
2861
- `
2862
- );
2863
- spawnCommand = `${envPrefix} ${binName}${cleanupSuffix}`;
2864
- } else {
2865
- spawnCommand = `${envPrefix} claude --dangerously-skip-permissions${identityFlag}${behaviorsFlag}${sessionContextFlag}${cleanupSuffix}`;
2866
- }
2867
- const spawnResult = transport.spawn(sessionName, {
2868
- cwd: spawnCwd,
2869
- command: spawnCommand
2870
- });
2871
- if (spawnResult.error) {
2872
- return { sessionName, error: `tmux new-session failed: ${spawnResult.error}` };
2873
- }
2874
- transport.pipeLog(sessionName, logFile);
2875
- try {
2876
- const mySession = getMySession();
2877
- const dispatchInfo = path14.join(SESSION_CACHE, `dispatch-info-${sessionName}.json`);
2878
- writeFileSync5(dispatchInfo, JSON.stringify({
2879
- dispatchedBy: mySession,
2880
- rootExe: exeSession,
2881
- provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
2882
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
2883
- }));
2884
- } catch {
2885
- }
2886
- let booted = false;
2887
- for (let i = 0; i < 30; i++) {
2888
- try {
2889
- execSync7("sleep 0.5");
2890
- } catch {
2891
- }
2892
- try {
2893
- const pane = transport.capturePane(sessionName);
2894
- if (useExeAgent) {
2895
- if (pane.includes("[exe-agent]") || pane.includes("online")) {
2896
- booted = true;
2897
- break;
2898
- }
2899
- } else {
2900
- if (pane.includes("Claude Code") || pane.includes("\u276F")) {
2901
- booted = true;
2902
- break;
2903
- }
2904
- }
2905
- } catch {
2906
- }
2907
- }
2908
- if (!booted) {
2909
- return { sessionName, error: `${useExeAgent ? "exe-agent" : "claude"} did not boot within 15s` };
2910
- }
2911
- if (!useExeAgent) {
2912
- try {
2913
- transport.sendKeys(sessionName, `/exe-call ${employeeName}`);
2914
- } catch {
2915
- }
2916
- }
2917
- registerSession({
2918
- windowName: sessionName,
2919
- agentId: employeeName,
2920
- projectDir: spawnCwd,
2921
- parentExe: exeSession,
2922
- pid: 0,
2923
- registeredAt: (/* @__PURE__ */ new Date()).toISOString()
2924
- });
2925
- return { sessionName };
2926
- }
2927
- var SESSION_CACHE, BEHAVIORS_EXPORT_TIMEOUT_MS, VERIFY_PANE_LINES, INTERCOM_DEBOUNCE_MS, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS, BUSY_PATTERN;
2928
- var init_tmux_routing = __esm({
2929
- "src/lib/tmux-routing.ts"() {
2930
- init_session_registry();
2931
- init_session_key();
2932
- init_transport();
2933
- init_cc_agent_support();
2934
- init_mcp_prefix();
2935
- init_provider_table();
2936
- init_intercom_queue();
2937
- init_plan_limits();
2938
- init_worktree();
2939
- SESSION_CACHE = path14.join(os5.homedir(), ".exe-os", "session-cache");
2940
- BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
2941
- VERIFY_PANE_LINES = 200;
2942
- INTERCOM_DEBOUNCE_MS = 3e4;
2943
- INTERCOM_LOG2 = path14.join(os5.homedir(), ".exe-os", "intercom.log");
2944
- DEBOUNCE_FILE = path14.join(SESSION_CACHE, "intercom-debounce.json");
2945
- DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
2946
- BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
2947
- }
2948
- });
2949
- init_tmux_routing();
2950
- export {
2951
- employeeSessionName,
2952
- ensureEmployee,
2953
- extractRootExe,
2954
- findFreeInstance,
2955
- getDispatchedBy,
2956
- getMySession,
2957
- getParentExe,
2958
- getSessionState,
2959
- isEmployeeAlive,
2960
- isExeSession,
2961
- isSessionBusy,
2962
- notifyParentExe,
2963
- parseParentExe,
2964
- registerParentExe,
2965
- resolveExeSession,
2966
- sendIntercom,
2967
- spawnEmployee,
2968
- verifyPaneAtCapacity
2969
- };