@askexenow/exe-os 0.8.1 → 0.8.3

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,1903 +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/database.ts
23
- import { createClient } from "@libsql/client";
24
- function getClient() {
25
- if (!_client) {
26
- throw new Error("Database client not initialized. Call initDatabase() first.");
27
- }
28
- return _client;
29
- }
30
- var _client;
31
- var init_database = __esm({
32
- "src/lib/database.ts"() {
33
- "use strict";
34
- _client = null;
35
- }
36
- });
37
-
38
- // src/lib/config.ts
39
- var config_exports = {};
40
- __export(config_exports, {
41
- CONFIG_MIGRATIONS: () => CONFIG_MIGRATIONS,
42
- CONFIG_PATH: () => CONFIG_PATH,
43
- CURRENT_CONFIG_VERSION: () => CURRENT_CONFIG_VERSION,
44
- DB_PATH: () => DB_PATH,
45
- EXE_AI_DIR: () => EXE_AI_DIR,
46
- LEGACY_LANCE_PATH: () => LEGACY_LANCE_PATH,
47
- MODELS_DIR: () => MODELS_DIR,
48
- loadConfig: () => loadConfig,
49
- loadConfigFrom: () => loadConfigFrom,
50
- loadConfigSync: () => loadConfigSync,
51
- migrateConfig: () => migrateConfig,
52
- saveConfig: () => saveConfig
53
- });
54
- import { readFile, writeFile, mkdir } from "fs/promises";
55
- import { readFileSync, existsSync, renameSync } from "fs";
56
- import path from "path";
57
- import os from "os";
58
- function resolveDataDir() {
59
- if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
60
- if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
61
- const newDir = path.join(os.homedir(), ".exe-os");
62
- const legacyDir = path.join(os.homedir(), ".exe-mem");
63
- if (!existsSync(newDir) && existsSync(legacyDir)) {
64
- try {
65
- renameSync(legacyDir, newDir);
66
- process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
67
- `);
68
- } catch {
69
- return legacyDir;
70
- }
71
- }
72
- return newDir;
73
- }
74
- function migrateLegacyConfig(raw) {
75
- if ("r2" in raw) {
76
- process.stderr.write(
77
- "[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"
78
- );
79
- delete raw.r2;
80
- }
81
- if ("syncIntervalMs" in raw) {
82
- delete raw.syncIntervalMs;
83
- }
84
- return raw;
85
- }
86
- function migrateConfig(raw) {
87
- const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
88
- let currentVersion = fromVersion;
89
- let migrated = false;
90
- if (currentVersion > CURRENT_CONFIG_VERSION) {
91
- return { config: raw, migrated: false, fromVersion };
92
- }
93
- for (const migration of CONFIG_MIGRATIONS) {
94
- if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
95
- raw = migration.migrate(raw);
96
- currentVersion = migration.to;
97
- migrated = true;
98
- }
99
- }
100
- return { config: raw, migrated, fromVersion };
101
- }
102
- function normalizeScalingRoadmap(raw) {
103
- const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
104
- const userRoadmap = raw.scalingRoadmap ?? {};
105
- const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
106
- if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
107
- userAuto.enabled = raw.rerankerEnabled;
108
- }
109
- raw.scalingRoadmap = {
110
- ...userRoadmap,
111
- rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
112
- };
113
- }
114
- function normalizeSessionLifecycle(raw) {
115
- const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
116
- const userSL = raw.sessionLifecycle ?? {};
117
- raw.sessionLifecycle = { ...defaultSL, ...userSL };
118
- }
119
- function normalizeAutoUpdate(raw) {
120
- const defaultAU = DEFAULT_CONFIG.autoUpdate;
121
- const userAU = raw.autoUpdate ?? {};
122
- raw.autoUpdate = { ...defaultAU, ...userAU };
123
- }
124
- async function loadConfig() {
125
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
126
- await mkdir(dir, { recursive: true });
127
- const configPath = path.join(dir, "config.json");
128
- if (!existsSync(configPath)) {
129
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
130
- }
131
- const raw = await readFile(configPath, "utf-8");
132
- try {
133
- let parsed = JSON.parse(raw);
134
- parsed = migrateLegacyConfig(parsed);
135
- const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
136
- if (migrated) {
137
- process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
138
- `);
139
- try {
140
- await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
141
- } catch {
142
- }
143
- }
144
- normalizeScalingRoadmap(migratedCfg);
145
- normalizeSessionLifecycle(migratedCfg);
146
- normalizeAutoUpdate(migratedCfg);
147
- const config = { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
148
- if (config.dbPath.startsWith("~")) {
149
- config.dbPath = config.dbPath.replace(/^~/, os.homedir());
150
- }
151
- return config;
152
- } catch {
153
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
154
- }
155
- }
156
- function loadConfigSync() {
157
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
158
- const configPath = path.join(dir, "config.json");
159
- if (!existsSync(configPath)) {
160
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
161
- }
162
- try {
163
- const raw = readFileSync(configPath, "utf-8");
164
- let parsed = JSON.parse(raw);
165
- parsed = migrateLegacyConfig(parsed);
166
- const { config: migratedCfg } = migrateConfig(parsed);
167
- normalizeScalingRoadmap(migratedCfg);
168
- normalizeSessionLifecycle(migratedCfg);
169
- normalizeAutoUpdate(migratedCfg);
170
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
171
- } catch {
172
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
173
- }
174
- }
175
- async function saveConfig(config) {
176
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
177
- await mkdir(dir, { recursive: true });
178
- const configPath = path.join(dir, "config.json");
179
- await writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
180
- }
181
- async function loadConfigFrom(configPath) {
182
- const raw = await readFile(configPath, "utf-8");
183
- try {
184
- let parsed = JSON.parse(raw);
185
- parsed = migrateLegacyConfig(parsed);
186
- const { config: migratedCfg } = migrateConfig(parsed);
187
- normalizeScalingRoadmap(migratedCfg);
188
- normalizeSessionLifecycle(migratedCfg);
189
- normalizeAutoUpdate(migratedCfg);
190
- return { ...DEFAULT_CONFIG, ...migratedCfg };
191
- } catch {
192
- return { ...DEFAULT_CONFIG };
193
- }
194
- }
195
- var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
196
- var init_config = __esm({
197
- "src/lib/config.ts"() {
198
- "use strict";
199
- EXE_AI_DIR = resolveDataDir();
200
- DB_PATH = path.join(EXE_AI_DIR, "memories.db");
201
- MODELS_DIR = path.join(EXE_AI_DIR, "models");
202
- CONFIG_PATH = path.join(EXE_AI_DIR, "config.json");
203
- LEGACY_LANCE_PATH = path.join(EXE_AI_DIR, "local.lance");
204
- CURRENT_CONFIG_VERSION = 1;
205
- DEFAULT_CONFIG = {
206
- config_version: CURRENT_CONFIG_VERSION,
207
- dbPath: DB_PATH,
208
- modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
209
- embeddingDim: 1024,
210
- batchSize: 20,
211
- flushIntervalMs: 1e4,
212
- autoIngestion: true,
213
- autoRetrieval: true,
214
- searchMode: "hybrid",
215
- hookSearchMode: "hybrid",
216
- fileGrepEnabled: true,
217
- splashEffect: true,
218
- consolidationEnabled: true,
219
- consolidationIntervalMs: 6 * 60 * 60 * 1e3,
220
- consolidationModel: "claude-haiku-4-5-20251001",
221
- consolidationMaxCallsPerRun: 20,
222
- selfQueryRouter: true,
223
- selfQueryModel: "claude-haiku-4-5-20251001",
224
- rerankerEnabled: true,
225
- scalingRoadmap: {
226
- rerankerAutoTrigger: {
227
- enabled: true,
228
- broadQueryMinCardinality: 5e4,
229
- fetchTopK: 150,
230
- returnTopK: 5
231
- }
232
- },
233
- graphRagEnabled: true,
234
- wikiEnabled: false,
235
- wikiUrl: "",
236
- wikiApiKey: "",
237
- wikiSyncIntervalMs: 30 * 60 * 1e3,
238
- wikiWorkspaceMapping: {
239
- exe: "Executive",
240
- yoshi: "Engineering",
241
- mari: "Marketing",
242
- tom: "Engineering",
243
- sasha: "Production"
244
- },
245
- wikiAutoUpdate: true,
246
- wikiAutoUpdateThreshold: 0.5,
247
- wikiAutoUpdateCreateNew: true,
248
- skillLearning: true,
249
- skillThreshold: 3,
250
- skillModel: "claude-haiku-4-5-20251001",
251
- exeHeartbeat: {
252
- enabled: true,
253
- intervalSeconds: 60,
254
- staleInProgressThresholdHours: 2
255
- },
256
- sessionLifecycle: {
257
- idleKillEnabled: true,
258
- idleKillTicksRequired: 3,
259
- idleKillIntercomAckWindowMs: 1e4,
260
- maxAutoInstances: 10
261
- },
262
- autoUpdate: {
263
- checkOnBoot: true,
264
- autoInstall: false,
265
- checkIntervalMs: 24 * 60 * 60 * 1e3
266
- }
267
- };
268
- CONFIG_MIGRATIONS = [
269
- {
270
- from: 0,
271
- to: 1,
272
- migrate: (cfg) => {
273
- cfg.config_version = 1;
274
- return cfg;
275
- }
276
- }
277
- ];
278
- }
279
- });
280
-
281
- // src/lib/notifications.ts
282
- import crypto from "crypto";
283
- import path2 from "path";
284
- import os2 from "os";
285
- import {
286
- readFileSync as readFileSync2,
287
- readdirSync,
288
- unlinkSync,
289
- existsSync as existsSync2,
290
- rmdirSync
291
- } from "fs";
292
- var init_notifications = __esm({
293
- "src/lib/notifications.ts"() {
294
- "use strict";
295
- init_database();
296
- }
297
- });
298
-
299
- // src/lib/tasks-crud.ts
300
- import crypto2 from "crypto";
301
- import path3 from "path";
302
- import { execSync } from "child_process";
303
- import { mkdir as mkdir2, writeFile as writeFile2, appendFile } from "fs/promises";
304
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
305
- function extractParentFromContext(contextBody) {
306
- if (!contextBody) return null;
307
- const match = contextBody.match(
308
- /Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
309
- );
310
- return match ? match[1].toLowerCase() : null;
311
- }
312
- function slugify(title) {
313
- return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
314
- }
315
- async function resolveTask(client, identifier) {
316
- let result = await client.execute({
317
- sql: "SELECT * FROM tasks WHERE id = ?",
318
- args: [identifier]
319
- });
320
- if (result.rows.length === 1) return result.rows[0];
321
- result = await client.execute({
322
- sql: "SELECT * FROM tasks WHERE task_file LIKE ?",
323
- args: [`%${identifier}%`]
324
- });
325
- if (result.rows.length === 1) return result.rows[0];
326
- if (result.rows.length > 1) {
327
- const exact = result.rows.filter(
328
- (r) => String(r.task_file).endsWith(`/${identifier}.md`)
329
- );
330
- if (exact.length === 1) return exact[0];
331
- const candidates = exact.length > 1 ? exact : result.rows;
332
- const active = candidates.filter(
333
- (r) => !["done", "cancelled"].includes(String(r.status))
334
- );
335
- if (active.length === 1) return active[0];
336
- const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
337
- throw new Error(
338
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
339
- );
340
- }
341
- result = await client.execute({
342
- sql: "SELECT * FROM tasks WHERE title LIKE ?",
343
- args: [`%${identifier}%`]
344
- });
345
- if (result.rows.length === 1) return result.rows[0];
346
- if (result.rows.length > 1) {
347
- const active = result.rows.filter(
348
- (r) => !["done", "cancelled"].includes(String(r.status))
349
- );
350
- if (active.length === 1) return active[0];
351
- const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
352
- throw new Error(
353
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
354
- );
355
- }
356
- throw new Error(`Task not found: ${identifier}`);
357
- }
358
- async function createTaskCore(input) {
359
- const client = getClient();
360
- const id = crypto2.randomUUID();
361
- const now = (/* @__PURE__ */ new Date()).toISOString();
362
- const slug = slugify(input.title);
363
- const taskFile = input.taskFile ?? `exe/${input.assignedTo}/${slug}.md`;
364
- let blockedById = null;
365
- const initialStatus = input.blockedBy ? "blocked" : "open";
366
- if (input.blockedBy) {
367
- const blocker = await resolveTask(client, input.blockedBy);
368
- blockedById = String(blocker.id);
369
- }
370
- let parentTaskId = null;
371
- let parentRef = input.parentTaskId;
372
- if (!parentRef) {
373
- const extracted = extractParentFromContext(input.context);
374
- if (extracted) {
375
- parentRef = extracted;
376
- process.stderr.write(
377
- "[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
378
- );
379
- }
380
- }
381
- if (parentRef) {
382
- try {
383
- const parent = await resolveTask(client, parentRef);
384
- parentTaskId = String(parent.id);
385
- } catch (err) {
386
- if (!input.parentTaskId) {
387
- throw new Error(
388
- `create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
389
- );
390
- }
391
- throw err;
392
- }
393
- }
394
- let warning;
395
- const dupCheck = await client.execute({
396
- sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
397
- args: [input.title, input.assignedTo]
398
- });
399
- if (dupCheck.rows.length > 0) {
400
- warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
401
- }
402
- if (input.baseDir) {
403
- try {
404
- await mkdir2(path3.join(input.baseDir, "exe", "output"), { recursive: true });
405
- await mkdir2(path3.join(input.baseDir, "exe", "research"), { recursive: true });
406
- await ensureArchitectureDoc(input.baseDir, input.projectName);
407
- await ensureGitignoreExe(input.baseDir);
408
- } catch {
409
- }
410
- }
411
- const complexity = input.complexity ?? "standard";
412
- await client.execute({
413
- 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)
414
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
415
- args: [
416
- id,
417
- input.title,
418
- input.assignedTo,
419
- input.assignedBy,
420
- input.projectName,
421
- input.priority,
422
- initialStatus,
423
- taskFile,
424
- blockedById,
425
- parentTaskId,
426
- input.reviewer ?? null,
427
- input.context,
428
- input.budgetTokens ?? null,
429
- input.budgetFallbackModel ?? null,
430
- 0,
431
- null,
432
- complexity,
433
- now,
434
- now
435
- ]
436
- });
437
- return {
438
- id,
439
- title: input.title,
440
- assignedTo: input.assignedTo,
441
- assignedBy: input.assignedBy,
442
- projectName: input.projectName,
443
- priority: input.priority,
444
- status: initialStatus,
445
- taskFile,
446
- createdAt: now,
447
- updatedAt: now,
448
- warning,
449
- budgetTokens: input.budgetTokens ?? null,
450
- budgetFallbackModel: input.budgetFallbackModel ?? null,
451
- tokensUsed: 0,
452
- tokensWarnedAt: null
453
- };
454
- }
455
- async function ensureArchitectureDoc(baseDir, projectName) {
456
- const archPath = path3.join(baseDir, "exe", "ARCHITECTURE.md");
457
- try {
458
- if (existsSync3(archPath)) return;
459
- const template = [
460
- `# ${projectName} \u2014 System Architecture`,
461
- "",
462
- "> Employees: read this before every task. Update it when you change system structure.",
463
- `> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
464
- "",
465
- "## Overview",
466
- "",
467
- "<!-- Describe what this system does, its main components, and how they connect. -->",
468
- "",
469
- "## Key Components",
470
- "",
471
- "<!-- List the major modules, services, or subsystems. -->",
472
- "",
473
- "## Data Flow",
474
- "",
475
- "<!-- How does data move through the system? What writes where? -->",
476
- "",
477
- "## Invariants",
478
- "",
479
- "<!-- Rules that must never be violated. What breaks if these are wrong? -->",
480
- "",
481
- "## Dependencies",
482
- "",
483
- "<!-- What depends on what? If I change X, what else is affected? -->",
484
- ""
485
- ].join("\n");
486
- await writeFile2(archPath, template, "utf-8");
487
- } catch {
488
- }
489
- }
490
- async function ensureGitignoreExe(baseDir) {
491
- const gitignorePath = path3.join(baseDir, ".gitignore");
492
- try {
493
- if (existsSync3(gitignorePath)) {
494
- const content = readFileSync3(gitignorePath, "utf-8");
495
- if (/^\/?exe\/?$/m.test(content)) return;
496
- await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
497
- } else {
498
- await writeFile2(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
499
- }
500
- } catch {
501
- }
502
- }
503
- var init_tasks_crud = __esm({
504
- "src/lib/tasks-crud.ts"() {
505
- "use strict";
506
- init_database();
507
- }
508
- });
509
-
510
- // src/lib/employees.ts
511
- import { readFile as readFile2, writeFile as writeFile3, mkdir as mkdir3 } from "fs/promises";
512
- import { existsSync as existsSync4, symlinkSync, readlinkSync } from "fs";
513
- import { execSync as execSync2 } from "child_process";
514
- import path4 from "path";
515
- var EMPLOYEES_PATH;
516
- var init_employees = __esm({
517
- "src/lib/employees.ts"() {
518
- "use strict";
519
- init_config();
520
- EMPLOYEES_PATH = path4.join(EXE_AI_DIR, "exe-employees.json");
521
- }
522
- });
523
-
524
- // src/lib/session-registry.ts
525
- import { readFileSync as readFileSync4, writeFileSync, mkdirSync, existsSync as existsSync5 } from "fs";
526
- import path5 from "path";
527
- import os3 from "os";
528
- function registerSession(entry) {
529
- const dir = path5.dirname(REGISTRY_PATH);
530
- if (!existsSync5(dir)) {
531
- mkdirSync(dir, { recursive: true });
532
- }
533
- const sessions = listSessions();
534
- const idx = sessions.findIndex((s) => s.windowName === entry.windowName);
535
- if (idx >= 0) {
536
- sessions[idx] = entry;
537
- } else {
538
- sessions.push(entry);
539
- }
540
- writeFileSync(REGISTRY_PATH, JSON.stringify(sessions, null, 2));
541
- }
542
- function listSessions() {
543
- try {
544
- const raw = readFileSync4(REGISTRY_PATH, "utf8");
545
- return JSON.parse(raw);
546
- } catch {
547
- return [];
548
- }
549
- }
550
- var REGISTRY_PATH;
551
- var init_session_registry = __esm({
552
- "src/lib/session-registry.ts"() {
553
- "use strict";
554
- REGISTRY_PATH = path5.join(os3.homedir(), ".exe-os", "session-registry.json");
555
- }
556
- });
557
-
558
- // src/lib/session-key.ts
559
- import { execSync as execSync3 } from "child_process";
560
- function getSessionKey() {
561
- if (_cached) return _cached;
562
- let pid = process.ppid;
563
- for (let i = 0; i < 10; i++) {
564
- try {
565
- const info = execSync3(`ps -p ${pid} -o ppid=,comm=`, {
566
- encoding: "utf8",
567
- timeout: 2e3
568
- }).trim();
569
- const match = info.match(/^\s*(\d+)\s+(.+)$/);
570
- if (!match) break;
571
- const [, ppid, cmd] = match;
572
- if (cmd === "claude" || cmd.endsWith("/claude")) {
573
- _cached = String(pid);
574
- return _cached;
575
- }
576
- pid = parseInt(ppid, 10);
577
- if (pid <= 1) break;
578
- } catch {
579
- break;
580
- }
581
- }
582
- _cached = process.env.CLAUDE_CODE_SSE_PORT ?? String(process.ppid);
583
- return _cached;
584
- }
585
- var _cached;
586
- var init_session_key = __esm({
587
- "src/lib/session-key.ts"() {
588
- "use strict";
589
- _cached = null;
590
- }
591
- });
592
-
593
- // src/lib/tmux-transport.ts
594
- var tmux_transport_exports = {};
595
- __export(tmux_transport_exports, {
596
- TmuxTransport: () => TmuxTransport
597
- });
598
- import { execFileSync } from "child_process";
599
- var QUIET, TmuxTransport;
600
- var init_tmux_transport = __esm({
601
- "src/lib/tmux-transport.ts"() {
602
- "use strict";
603
- QUIET = {
604
- encoding: "utf8",
605
- stdio: ["pipe", "pipe", "pipe"]
606
- };
607
- TmuxTransport = class {
608
- getMySession() {
609
- try {
610
- return execFileSync("tmux", ["display-message", "-p", "#{session_name}"], QUIET).trim() || null;
611
- } catch {
612
- return null;
613
- }
614
- }
615
- listSessions() {
616
- try {
617
- return execFileSync("tmux", ["list-sessions", "-F", "#{session_name}"], QUIET).trim().split("\n").filter(Boolean);
618
- } catch {
619
- return [];
620
- }
621
- }
622
- isAlive(target) {
623
- try {
624
- const sessions = this.listSessions();
625
- if (!sessions.includes(target)) return false;
626
- const paneStatus = execFileSync(
627
- "tmux",
628
- ["list-panes", "-t", target, "-F", "#{pane_dead}"],
629
- QUIET
630
- ).trim();
631
- return paneStatus !== "1";
632
- } catch {
633
- return false;
634
- }
635
- }
636
- sendKeys(target, keys) {
637
- execFileSync("tmux", ["send-keys", "-t", target, keys, "Enter"], QUIET);
638
- }
639
- capturePane(target, lines) {
640
- const args = ["capture-pane", "-t", target, "-p"];
641
- if (lines) args.push("-S", `-${lines}`);
642
- return execFileSync("tmux", args, { ...QUIET, timeout: 3e3 });
643
- }
644
- isPaneInCopyMode(target) {
645
- try {
646
- const result = execFileSync(
647
- "tmux",
648
- ["display-message", "-p", "-t", target, "#{pane_in_mode}"],
649
- { ...QUIET, timeout: 3e3 }
650
- ).trim();
651
- return result === "1";
652
- } catch {
653
- return false;
654
- }
655
- }
656
- spawn(name, config) {
657
- try {
658
- const args = ["new-session", "-d", "-s", name];
659
- if (config.cwd) args.push("-c", config.cwd);
660
- args.push(config.command);
661
- execFileSync("tmux", args);
662
- return { sessionName: name };
663
- } catch (e) {
664
- return { sessionName: name, error: `spawn failed: ${e}` };
665
- }
666
- }
667
- kill(target) {
668
- try {
669
- execFileSync("tmux", ["kill-session", "-t", target], QUIET);
670
- } catch {
671
- }
672
- }
673
- pipeLog(target, logFile) {
674
- try {
675
- const safePath = logFile.replace(/'/g, "'\\''");
676
- execFileSync("tmux", ["pipe-pane", "-t", target, `cat >> '${safePath}'`], QUIET);
677
- } catch {
678
- }
679
- }
680
- };
681
- }
682
- });
683
-
684
- // src/lib/transport.ts
685
- function getTransport() {
686
- if (!_transport) {
687
- const { TmuxTransport: TmuxTransport2 } = (init_tmux_transport(), __toCommonJS(tmux_transport_exports));
688
- _transport = new TmuxTransport2();
689
- }
690
- return _transport;
691
- }
692
- var _transport;
693
- var init_transport = __esm({
694
- "src/lib/transport.ts"() {
695
- "use strict";
696
- _transport = null;
697
- }
698
- });
699
-
700
- // src/lib/cc-agent-support.ts
701
- import { execSync as execSync4 } from "child_process";
702
- function _resetCcAgentSupportCache() {
703
- _cachedSupport = null;
704
- }
705
- function claudeSupportsAgentFlag() {
706
- if (_cachedSupport !== null) return _cachedSupport;
707
- try {
708
- const helpOutput = execSync4("claude --help 2>&1", {
709
- encoding: "utf-8",
710
- timeout: 5e3
711
- });
712
- _cachedSupport = /(^|\s)--agent(\b|=)/.test(helpOutput);
713
- } catch {
714
- _cachedSupport = false;
715
- }
716
- return _cachedSupport;
717
- }
718
- var _cachedSupport;
719
- var init_cc_agent_support = __esm({
720
- "src/lib/cc-agent-support.ts"() {
721
- "use strict";
722
- _cachedSupport = null;
723
- }
724
- });
725
-
726
- // src/lib/mcp-prefix.ts
727
- function expandDualPrefixTools(shortNames) {
728
- const out = [];
729
- for (const name of shortNames) {
730
- for (const prefix of MCP_TOOL_PREFIXES) {
731
- out.push(prefix + name);
732
- }
733
- }
734
- return out;
735
- }
736
- var MCP_PRIMARY_KEY, MCP_LEGACY_KEY, MCP_TOOL_PREFIXES;
737
- var init_mcp_prefix = __esm({
738
- "src/lib/mcp-prefix.ts"() {
739
- "use strict";
740
- MCP_PRIMARY_KEY = "exe-os";
741
- MCP_LEGACY_KEY = "exe-mem";
742
- MCP_TOOL_PREFIXES = [
743
- `mcp__${MCP_PRIMARY_KEY}__`,
744
- `mcp__${MCP_LEGACY_KEY}__`
745
- ];
746
- }
747
- });
748
-
749
- // src/lib/provider-table.ts
750
- function detectActiveProvider(env = process.env) {
751
- const baseUrl = env.ANTHROPIC_BASE_URL;
752
- if (!baseUrl) return DEFAULT_PROVIDER;
753
- for (const [name, cfg] of Object.entries(PROVIDER_TABLE)) {
754
- if (cfg.baseUrl === baseUrl) return name;
755
- }
756
- return DEFAULT_PROVIDER;
757
- }
758
- var PROVIDER_TABLE, DEFAULT_PROVIDER;
759
- var init_provider_table = __esm({
760
- "src/lib/provider-table.ts"() {
761
- "use strict";
762
- PROVIDER_TABLE = {
763
- opencode: {
764
- baseUrl: "https://opencode.ai/zen/go",
765
- apiKeyEnv: "OPENCODE_API_KEY",
766
- defaultModel: "minimax-m2.7"
767
- }
768
- };
769
- DEFAULT_PROVIDER = "default";
770
- }
771
- });
772
-
773
- // src/lib/intercom-queue.ts
774
- import { readFileSync as readFileSync5, writeFileSync as writeFileSync2, renameSync as renameSync2, existsSync as existsSync6, mkdirSync as mkdirSync2 } from "fs";
775
- import path6 from "path";
776
- import os4 from "os";
777
- function ensureDir() {
778
- const dir = path6.dirname(QUEUE_PATH);
779
- if (!existsSync6(dir)) mkdirSync2(dir, { recursive: true });
780
- }
781
- function readQueue() {
782
- try {
783
- if (!existsSync6(QUEUE_PATH)) return [];
784
- return JSON.parse(readFileSync5(QUEUE_PATH, "utf8"));
785
- } catch {
786
- return [];
787
- }
788
- }
789
- function writeQueue(queue) {
790
- ensureDir();
791
- const tmp = `${QUEUE_PATH}.tmp`;
792
- writeFileSync2(tmp, JSON.stringify(queue, null, 2));
793
- renameSync2(tmp, QUEUE_PATH);
794
- }
795
- function queueIntercom(targetSession, reason) {
796
- const queue = readQueue();
797
- const existing = queue.find((q) => q.targetSession === targetSession);
798
- if (existing) {
799
- existing.attempts++;
800
- existing.queuedAt = (/* @__PURE__ */ new Date()).toISOString();
801
- existing.reason = reason;
802
- } else {
803
- queue.push({
804
- targetSession,
805
- queuedAt: (/* @__PURE__ */ new Date()).toISOString(),
806
- attempts: 0,
807
- reason
808
- });
809
- }
810
- writeQueue(queue);
811
- }
812
- var QUEUE_PATH, TTL_MS, INTERCOM_LOG;
813
- var init_intercom_queue = __esm({
814
- "src/lib/intercom-queue.ts"() {
815
- "use strict";
816
- QUEUE_PATH = path6.join(os4.homedir(), ".exe-os", "intercom-queue.json");
817
- TTL_MS = 60 * 60 * 1e3;
818
- INTERCOM_LOG = path6.join(os4.homedir(), ".exe-os", "intercom.log");
819
- }
820
- });
821
-
822
- // src/lib/license.ts
823
- import { readFileSync as readFileSync6, writeFileSync as writeFileSync3, existsSync as existsSync7, mkdirSync as mkdirSync3 } from "fs";
824
- import { randomUUID } from "crypto";
825
- import path7 from "path";
826
- import { jwtVerify, importSPKI } from "jose";
827
- var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH, PLAN_LIMITS;
828
- var init_license = __esm({
829
- "src/lib/license.ts"() {
830
- "use strict";
831
- init_config();
832
- LICENSE_PATH = path7.join(EXE_AI_DIR, "license.key");
833
- CACHE_PATH = path7.join(EXE_AI_DIR, "license-cache.json");
834
- DEVICE_ID_PATH = path7.join(EXE_AI_DIR, "device-id");
835
- PLAN_LIMITS = {
836
- free: { devices: 1, employees: 1, memories: 5e3 },
837
- pro: { devices: 2, employees: 5, memories: 1e5 },
838
- team: { devices: 10, employees: 20, memories: 1e6 },
839
- agency: { devices: 50, employees: 100, memories: 1e7 },
840
- enterprise: { devices: -1, employees: -1, memories: -1 }
841
- };
842
- }
843
- });
844
-
845
- // src/lib/plan-limits.ts
846
- import { readFileSync as readFileSync7, existsSync as existsSync8 } from "fs";
847
- import path8 from "path";
848
- function getLicenseSync() {
849
- try {
850
- if (!existsSync8(CACHE_PATH2)) return freeLicense();
851
- const raw = JSON.parse(readFileSync7(CACHE_PATH2, "utf8"));
852
- if (!raw.token || typeof raw.token !== "string") return freeLicense();
853
- const parts = raw.token.split(".");
854
- if (parts.length !== 3) return freeLicense();
855
- const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
856
- const plan = payload.plan ?? "free";
857
- const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
858
- return {
859
- valid: true,
860
- plan,
861
- email: payload.sub ?? "",
862
- expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
863
- deviceLimit: limits.devices,
864
- employeeLimit: limits.employees,
865
- memoryLimit: limits.memories
866
- };
867
- } catch {
868
- return freeLicense();
869
- }
870
- }
871
- function freeLicense() {
872
- const limits = PLAN_LIMITS.free;
873
- return {
874
- valid: true,
875
- plan: "free",
876
- email: "",
877
- expiresAt: null,
878
- deviceLimit: limits.devices,
879
- employeeLimit: limits.employees,
880
- memoryLimit: limits.memories
881
- };
882
- }
883
- function assertEmployeeLimitSync(rosterPath) {
884
- const license = getLicenseSync();
885
- if (license.employeeLimit < 0) return;
886
- const filePath = rosterPath ?? EMPLOYEES_PATH;
887
- let count = 0;
888
- try {
889
- if (existsSync8(filePath)) {
890
- const raw = readFileSync7(filePath, "utf8");
891
- const employees = JSON.parse(raw);
892
- count = Array.isArray(employees) ? employees.length : 0;
893
- }
894
- } catch {
895
- throw new PlanLimitError(
896
- `Cannot verify employee count: roster unreadable at ${filePath}. Refusing to proceed. Check file permissions or upgrade plan.`
897
- );
898
- }
899
- if (count >= license.employeeLimit) {
900
- throw new PlanLimitError(
901
- `Employee limit reached: ${count}/${license.employeeLimit} employees on the ${license.plan} plan. Upgrade at https://askexe.com to add more.`
902
- );
903
- }
904
- }
905
- var PlanLimitError, CACHE_PATH2;
906
- var init_plan_limits = __esm({
907
- "src/lib/plan-limits.ts"() {
908
- "use strict";
909
- init_database();
910
- init_employees();
911
- init_license();
912
- init_config();
913
- PlanLimitError = class extends Error {
914
- constructor(message) {
915
- super(message);
916
- this.name = "PlanLimitError";
917
- }
918
- };
919
- CACHE_PATH2 = path8.join(EXE_AI_DIR, "license-cache.json");
920
- }
921
- });
922
-
923
- // src/lib/worktree.ts
924
- import { execSync as execSync5 } from "child_process";
925
- import { existsSync as existsSync9, readFileSync as readFileSync8, appendFileSync, mkdirSync as mkdirSync4, realpathSync } from "fs";
926
- import path9 from "path";
927
- function getGitRoot(dir) {
928
- try {
929
- const root = execSync5("git rev-parse --show-toplevel", {
930
- cwd: dir,
931
- encoding: "utf-8",
932
- timeout: GIT_TIMEOUT_MS,
933
- stdio: ["pipe", "pipe", "pipe"]
934
- }).trim();
935
- return realpath(root);
936
- } catch {
937
- return null;
938
- }
939
- }
940
- function getMainRepoRoot(dir) {
941
- try {
942
- const commonDir = execSync5(
943
- "git rev-parse --path-format=absolute --git-common-dir",
944
- { cwd: dir, encoding: "utf-8", timeout: GIT_TIMEOUT_MS, stdio: ["pipe", "pipe", "pipe"] }
945
- ).trim();
946
- return realpath(path9.dirname(commonDir));
947
- } catch {
948
- return null;
949
- }
950
- }
951
- function worktreePath(repoRoot, employeeName, instance) {
952
- const label = instanceLabel(employeeName, instance);
953
- return path9.join(repoRoot, ".worktrees", label);
954
- }
955
- function worktreeBranch(employeeName, instance) {
956
- return `${instanceLabel(employeeName, instance)}-work`;
957
- }
958
- function instanceLabel(name, instance) {
959
- return instance != null && instance > 0 ? `${name}${instance}` : name;
960
- }
961
- function ensureWorktree(projectDir, employeeName, instance) {
962
- const repoRoot = getGitRoot(projectDir);
963
- if (!repoRoot) return null;
964
- const wtPath = worktreePath(repoRoot, employeeName, instance);
965
- const branch = worktreeBranch(employeeName, instance);
966
- if (existsSync9(path9.join(wtPath, ".git"))) {
967
- return wtPath;
968
- }
969
- const worktreesDir = path9.join(repoRoot, ".worktrees");
970
- mkdirSync4(worktreesDir, { recursive: true });
971
- ensureGitignoreEntry(repoRoot, "/.worktrees/");
972
- try {
973
- execSync5("git worktree prune", {
974
- cwd: repoRoot,
975
- encoding: "utf-8",
976
- timeout: GIT_TIMEOUT_MS,
977
- stdio: ["pipe", "pipe", "pipe"]
978
- });
979
- } catch {
980
- }
981
- const branchExists = branchExistsLocally(repoRoot, branch);
982
- try {
983
- if (branchExists) {
984
- execSync5(`git worktree add "${wtPath}" "${branch}"`, {
985
- cwd: repoRoot,
986
- encoding: "utf-8",
987
- timeout: GIT_TIMEOUT_MS,
988
- stdio: ["pipe", "pipe", "pipe"]
989
- });
990
- } else {
991
- execSync5(`git worktree add "${wtPath}" -b "${branch}" HEAD`, {
992
- cwd: repoRoot,
993
- encoding: "utf-8",
994
- timeout: GIT_TIMEOUT_MS,
995
- stdio: ["pipe", "pipe", "pipe"]
996
- });
997
- }
998
- return wtPath;
999
- } catch (err) {
1000
- process.stderr.write(
1001
- `[worktree] Failed to create worktree for ${employeeName}: ${err instanceof Error ? err.message : String(err)}
1002
- `
1003
- );
1004
- return null;
1005
- }
1006
- }
1007
- function branchExistsLocally(repoRoot, branch) {
1008
- try {
1009
- execSync5(`git rev-parse --verify "refs/heads/${branch}"`, {
1010
- cwd: repoRoot,
1011
- encoding: "utf-8",
1012
- timeout: GIT_TIMEOUT_MS,
1013
- stdio: ["pipe", "pipe", "pipe"]
1014
- });
1015
- return true;
1016
- } catch {
1017
- return false;
1018
- }
1019
- }
1020
- function realpath(p) {
1021
- try {
1022
- return realpathSync(p);
1023
- } catch {
1024
- return p;
1025
- }
1026
- }
1027
- function ensureGitignoreEntry(repoRoot, entry) {
1028
- try {
1029
- const gitignorePath = path9.join(repoRoot, ".gitignore");
1030
- if (existsSync9(gitignorePath)) {
1031
- const content = readFileSync8(gitignorePath, "utf-8");
1032
- if (content.includes(entry)) return;
1033
- appendFileSync(gitignorePath, `
1034
- # Agent worktrees (exe-os)
1035
- ${entry}
1036
- `);
1037
- } else {
1038
- }
1039
- } catch {
1040
- }
1041
- }
1042
- var GIT_TIMEOUT_MS;
1043
- var init_worktree = __esm({
1044
- "src/lib/worktree.ts"() {
1045
- "use strict";
1046
- GIT_TIMEOUT_MS = 1e4;
1047
- }
1048
- });
1049
-
1050
- // src/lib/tmux-routing.ts
1051
- import { execFileSync as execFileSync2, execSync as execSync6 } from "child_process";
1052
- import { readFileSync as readFileSync9, writeFileSync as writeFileSync4, mkdirSync as mkdirSync5, existsSync as existsSync10, appendFileSync as appendFileSync2 } from "fs";
1053
- import path10 from "path";
1054
- import os5 from "os";
1055
- import { fileURLToPath } from "url";
1056
- function resolveBehaviorsExporterScript() {
1057
- try {
1058
- const thisFile = fileURLToPath(import.meta.url);
1059
- const scriptPath = path10.join(
1060
- path10.dirname(thisFile),
1061
- "..",
1062
- "bin",
1063
- "exe-export-behaviors.js"
1064
- );
1065
- return existsSync10(scriptPath) ? scriptPath : null;
1066
- } catch {
1067
- return null;
1068
- }
1069
- }
1070
- function exportBehaviorsSync(agentId, projectName, sessionKey) {
1071
- const script = resolveBehaviorsExporterScript();
1072
- if (!script) return null;
1073
- try {
1074
- const output = execFileSync2(
1075
- process.execPath,
1076
- [script, agentId, projectName, sessionKey],
1077
- { encoding: "utf-8", timeout: BEHAVIORS_EXPORT_TIMEOUT_MS }
1078
- ).trim();
1079
- return output.length > 0 ? output : null;
1080
- } catch (err) {
1081
- process.stderr.write(
1082
- `[tmux-routing] behaviors export failed for ${agentId}: ${err instanceof Error ? err.message : String(err)}
1083
- `
1084
- );
1085
- return null;
1086
- }
1087
- }
1088
- function getMySession() {
1089
- return getTransport().getMySession();
1090
- }
1091
- function employeeSessionName(employee, exeSession, instance) {
1092
- const suffix = instance != null && instance > 0 ? String(instance) : "";
1093
- return `${employee}${suffix}-${exeSession}`;
1094
- }
1095
- function extractRootExe(name) {
1096
- const match = name.match(/(exe\d+)$/);
1097
- return match?.[1] ?? null;
1098
- }
1099
- function getParentExe(sessionKey) {
1100
- try {
1101
- const data = JSON.parse(readFileSync9(path10.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
1102
- return data.parentExe || null;
1103
- } catch {
1104
- return null;
1105
- }
1106
- }
1107
- function resolveExeSession() {
1108
- const mySession = getMySession();
1109
- if (!mySession) return null;
1110
- try {
1111
- const key = getSessionKey();
1112
- const parentExe = getParentExe(key);
1113
- if (parentExe) {
1114
- return extractRootExe(parentExe) ?? parentExe;
1115
- }
1116
- } catch {
1117
- }
1118
- return extractRootExe(mySession) ?? mySession;
1119
- }
1120
- function isEmployeeAlive(sessionName) {
1121
- return getTransport().isAlive(sessionName);
1122
- }
1123
- function findFreeInstance(employeeName, exeSession, maxInstances = 10, isAlive = isEmployeeAlive) {
1124
- const base = employeeSessionName(employeeName, exeSession);
1125
- if (!isAlive(base)) return 0;
1126
- for (let i = 2; i <= maxInstances; i++) {
1127
- const candidate = employeeSessionName(employeeName, exeSession, i);
1128
- if (!isAlive(candidate)) return i;
1129
- }
1130
- return null;
1131
- }
1132
- function readDebounceState() {
1133
- try {
1134
- if (!existsSync10(DEBOUNCE_FILE)) return {};
1135
- return JSON.parse(readFileSync9(DEBOUNCE_FILE, "utf8"));
1136
- } catch {
1137
- return {};
1138
- }
1139
- }
1140
- function writeDebounceState(state) {
1141
- try {
1142
- if (!existsSync10(SESSION_CACHE)) mkdirSync5(SESSION_CACHE, { recursive: true });
1143
- writeFileSync4(DEBOUNCE_FILE, JSON.stringify(state));
1144
- } catch {
1145
- }
1146
- }
1147
- function isDebounced(targetSession) {
1148
- const state = readDebounceState();
1149
- const lastSent = state[targetSession] ?? 0;
1150
- return Date.now() - lastSent < INTERCOM_DEBOUNCE_MS;
1151
- }
1152
- function recordDebounce(targetSession) {
1153
- const state = readDebounceState();
1154
- state[targetSession] = Date.now();
1155
- const cutoff = Date.now() - DEBOUNCE_CLEANUP_AGE_MS;
1156
- for (const key of Object.keys(state)) {
1157
- if ((state[key] ?? 0) < cutoff) delete state[key];
1158
- }
1159
- writeDebounceState(state);
1160
- }
1161
- function logIntercom(msg) {
1162
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${msg}
1163
- `;
1164
- process.stderr.write(`[intercom] ${msg}
1165
- `);
1166
- try {
1167
- appendFileSync2(INTERCOM_LOG2, line);
1168
- } catch {
1169
- }
1170
- }
1171
- function getSessionState(sessionName) {
1172
- const transport = getTransport();
1173
- if (!transport.isAlive(sessionName)) return "offline";
1174
- try {
1175
- const pane = transport.capturePane(sessionName, 5);
1176
- if (!pane.includes("\u276F") && !pane.includes("Claude Code") && !BUSY_PATTERN.test(pane) && !/Running…/.test(pane)) {
1177
- if (/\$\s*$/.test(pane) || /% $/.test(pane.trimEnd())) {
1178
- return "no_claude";
1179
- }
1180
- }
1181
- if (/Running…/.test(pane)) return "tool";
1182
- if (BUSY_PATTERN.test(pane)) return "thinking";
1183
- return "idle";
1184
- } catch {
1185
- return "offline";
1186
- }
1187
- }
1188
- function isExeSession(sessionName) {
1189
- return /^exe\d*$/.test(sessionName);
1190
- }
1191
- function sendIntercom(targetSession) {
1192
- const transport = getTransport();
1193
- if (isExeSession(targetSession)) {
1194
- logIntercom(`SKIP_EXE \u2192 ${targetSession} (exe sessions use prompt-submit hook)`);
1195
- return "skipped_exe";
1196
- }
1197
- if (isDebounced(targetSession)) {
1198
- logIntercom(`DEBOUNCE \u2192 ${targetSession} (cross-process file debounce)`);
1199
- return "debounced";
1200
- }
1201
- try {
1202
- const sessions = transport.listSessions();
1203
- if (!sessions.includes(targetSession)) {
1204
- logIntercom(`SKIP \u2192 ${targetSession} (session not found)`);
1205
- return "failed";
1206
- }
1207
- const sessionState = getSessionState(targetSession);
1208
- if (sessionState === "no_claude") {
1209
- queueIntercom(targetSession, "claude not running in session");
1210
- recordDebounce(targetSession);
1211
- logIntercom(`QUEUED \u2192 ${targetSession} (no claude process \u2014 raw shell detected)`);
1212
- return "queued";
1213
- }
1214
- if (sessionState === "thinking" || sessionState === "tool") {
1215
- queueIntercom(targetSession, "session busy at send time");
1216
- recordDebounce(targetSession);
1217
- logIntercom(`QUEUED \u2192 ${targetSession} (session busy, will retry from queue)`);
1218
- return "queued";
1219
- }
1220
- if (transport.isPaneInCopyMode(targetSession)) {
1221
- logIntercom(`COPY_MODE \u2192 ${targetSession} (exiting copy mode first)`);
1222
- transport.sendKeys(targetSession, "q");
1223
- }
1224
- transport.sendKeys(targetSession, "/exe-intercom");
1225
- recordDebounce(targetSession);
1226
- logIntercom(`DELIVERED \u2192 ${targetSession} (fire-and-forget)`);
1227
- return "delivered";
1228
- } catch {
1229
- logIntercom(`FAIL \u2192 ${targetSession}`);
1230
- return "failed";
1231
- }
1232
- }
1233
- function ensureEmployee(employeeName, exeSession, projectDir, opts) {
1234
- if (employeeName === "exe") {
1235
- return { status: "failed", sessionName: "", error: "exe is the COO, not a dispatchable employee" };
1236
- }
1237
- try {
1238
- assertEmployeeLimitSync();
1239
- } catch (err) {
1240
- if (err instanceof PlanLimitError) {
1241
- return { status: "failed", sessionName: "", error: err.message };
1242
- }
1243
- }
1244
- if (/-exe\d*$/.test(employeeName)) {
1245
- const bare = employeeName.replace(/-exe\d*$/, "").replace(/\d+$/, "");
1246
- return {
1247
- status: "failed",
1248
- sessionName: "",
1249
- error: `Error: pass employee name ('${bare}'), not session name ('${employeeName}')`
1250
- };
1251
- }
1252
- let effectiveInstance = opts?.instance;
1253
- if (effectiveInstance === void 0 && opts?.autoInstance) {
1254
- const free = findFreeInstance(
1255
- employeeName,
1256
- exeSession,
1257
- opts.maxAutoInstances ?? 10
1258
- );
1259
- if (free === null) {
1260
- return {
1261
- status: "failed",
1262
- sessionName: employeeSessionName(employeeName, exeSession),
1263
- error: `All ${opts.maxAutoInstances ?? 10} instances of ${employeeName} are alive \u2014 cap reached`
1264
- };
1265
- }
1266
- effectiveInstance = free === 0 ? void 0 : free;
1267
- }
1268
- const sessionName = employeeSessionName(employeeName, exeSession, effectiveInstance);
1269
- if (isEmployeeAlive(sessionName)) {
1270
- const result2 = sendIntercom(sessionName);
1271
- if (result2 === "acknowledged" || result2 === "skipped_exe" || result2 === "debounced" || result2 === "queued") {
1272
- return { status: "intercom_sent", sessionName };
1273
- }
1274
- if (result2 === "delivered") {
1275
- return { status: "intercom_unprocessed", sessionName };
1276
- }
1277
- return { status: "failed", sessionName, error: "intercom delivery failed" };
1278
- }
1279
- const spawnOpts = { ...opts, instance: effectiveInstance };
1280
- const mainRoot = getMainRepoRoot(projectDir) ?? projectDir;
1281
- const wtPath = ensureWorktree(mainRoot, employeeName, effectiveInstance);
1282
- if (wtPath) {
1283
- spawnOpts.cwd = wtPath;
1284
- }
1285
- const result = spawnEmployee(employeeName, exeSession, projectDir, spawnOpts);
1286
- if (result.error) {
1287
- return { status: "failed", sessionName, error: result.error };
1288
- }
1289
- return { status: "spawned", sessionName };
1290
- }
1291
- function spawnEmployee(employeeName, exeSession, projectDir, opts) {
1292
- const transport = getTransport();
1293
- const sessionName = employeeSessionName(employeeName, exeSession, opts?.instance);
1294
- const instanceLabel2 = opts?.instance != null && opts.instance > 0 ? `${employeeName}${opts.instance}` : employeeName;
1295
- const logDir = path10.join(os5.homedir(), ".exe-os", "session-logs");
1296
- const logFile = path10.join(logDir, `${instanceLabel2}-${Date.now()}.log`);
1297
- if (!existsSync10(logDir)) {
1298
- mkdirSync5(logDir, { recursive: true });
1299
- }
1300
- transport.kill(sessionName);
1301
- let cleanupSuffix = "";
1302
- try {
1303
- const thisFile = fileURLToPath(import.meta.url);
1304
- const cleanupScript = path10.join(path10.dirname(thisFile), "..", "bin", "exe-session-cleanup.js");
1305
- if (existsSync10(cleanupScript)) {
1306
- cleanupSuffix = `; ${process.execPath} "${cleanupScript}" "${employeeName}" "${exeSession}"`;
1307
- }
1308
- } catch {
1309
- }
1310
- try {
1311
- const claudeJsonPath = path10.join(os5.homedir(), ".claude.json");
1312
- let claudeJson = {};
1313
- try {
1314
- claudeJson = JSON.parse(readFileSync9(claudeJsonPath, "utf8"));
1315
- } catch {
1316
- }
1317
- if (!claudeJson.projects) claudeJson.projects = {};
1318
- const projects = claudeJson.projects;
1319
- const trustDir = opts?.cwd ?? projectDir;
1320
- if (!projects[trustDir]) projects[trustDir] = {};
1321
- projects[trustDir].hasTrustDialogAccepted = true;
1322
- writeFileSync4(claudeJsonPath, JSON.stringify(claudeJson, null, 2) + "\n");
1323
- } catch {
1324
- }
1325
- try {
1326
- const settingsDir = path10.join(os5.homedir(), ".claude", "projects");
1327
- const normalizedKey = (opts?.cwd ?? projectDir).replace(/\//g, "-").replace(/^-/, "");
1328
- const projSettingsDir = path10.join(settingsDir, normalizedKey);
1329
- const settingsPath = path10.join(projSettingsDir, "settings.json");
1330
- let settings = {};
1331
- try {
1332
- settings = JSON.parse(readFileSync9(settingsPath, "utf8"));
1333
- } catch {
1334
- }
1335
- const perms = settings.permissions ?? {};
1336
- const allow = perms.allow ?? [];
1337
- const toolNames = [
1338
- "recall_my_memory",
1339
- "store_memory",
1340
- "create_task",
1341
- "update_task",
1342
- "list_tasks",
1343
- "get_task",
1344
- "ask_team_memory",
1345
- "store_behavior",
1346
- "get_identity",
1347
- "send_message"
1348
- ];
1349
- const requiredTools = expandDualPrefixTools(toolNames);
1350
- let changed = false;
1351
- for (const tool of requiredTools) {
1352
- if (!allow.includes(tool)) {
1353
- allow.push(tool);
1354
- changed = true;
1355
- }
1356
- }
1357
- if (changed) {
1358
- perms.allow = allow;
1359
- settings.permissions = perms;
1360
- mkdirSync5(projSettingsDir, { recursive: true });
1361
- writeFileSync4(settingsPath, JSON.stringify(settings, null, 2) + "\n");
1362
- }
1363
- } catch {
1364
- }
1365
- const spawnCwd = opts?.cwd ?? projectDir;
1366
- const useExeAgent = !!(opts?.model && opts?.provider);
1367
- const ccProvider = useExeAgent ? DEFAULT_PROVIDER : detectActiveProvider();
1368
- const useBinSymlink = ccProvider !== DEFAULT_PROVIDER;
1369
- let identityFlag = "";
1370
- let behaviorsFlag = "";
1371
- let legacyFallbackWarned = false;
1372
- if (!useExeAgent && !useBinSymlink) {
1373
- const identityPath = path10.join(
1374
- os5.homedir(),
1375
- ".exe-os",
1376
- "identity",
1377
- `${employeeName}.md`
1378
- );
1379
- _resetCcAgentSupportCache();
1380
- const hasAgentFlag = claudeSupportsAgentFlag();
1381
- if (hasAgentFlag) {
1382
- identityFlag = ` --agent ${employeeName}`;
1383
- } else if (existsSync10(identityPath)) {
1384
- identityFlag = ` --append-system-prompt-file ${identityPath}`;
1385
- legacyFallbackWarned = true;
1386
- }
1387
- const behaviorsFile = exportBehaviorsSync(
1388
- employeeName,
1389
- path10.basename(spawnCwd),
1390
- sessionName
1391
- );
1392
- if (behaviorsFile) {
1393
- behaviorsFlag = ` --append-system-prompt-file ${behaviorsFile}`;
1394
- }
1395
- }
1396
- if (legacyFallbackWarned) {
1397
- process.stderr.write(
1398
- `[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.
1399
- `
1400
- );
1401
- }
1402
- let sessionContextFlag = "";
1403
- try {
1404
- const ctxDir = path10.join(os5.homedir(), ".exe-os", "session-cache");
1405
- mkdirSync5(ctxDir, { recursive: true });
1406
- const ctxFile = path10.join(ctxDir, `session-context-${sessionName}.md`);
1407
- const ctxContent = [
1408
- `## Session Context`,
1409
- `You are running in tmux session: ${sessionName}.`,
1410
- `Your parent exe session is ${exeSession}.`,
1411
- `Your employees (if any) use the -${exeSession} suffix (e.g., tom-${exeSession}).`
1412
- ].join("\n");
1413
- writeFileSync4(ctxFile, ctxContent);
1414
- sessionContextFlag = ` --append-system-prompt-file ${ctxFile}`;
1415
- } catch {
1416
- }
1417
- let envPrefix = `EXE_SESSION=${exeSession} EXE_SESSION_NAME=${sessionName}`;
1418
- if (ccProvider !== DEFAULT_PROVIDER) {
1419
- const cfg = PROVIDER_TABLE[ccProvider];
1420
- if (cfg?.apiKeyEnv) {
1421
- const keyVal = process.env[cfg.apiKeyEnv];
1422
- if (keyVal) {
1423
- envPrefix = `${envPrefix} ${cfg.apiKeyEnv}=${keyVal}`;
1424
- }
1425
- }
1426
- }
1427
- let spawnCommand;
1428
- if (useExeAgent) {
1429
- spawnCommand = `${envPrefix} exe-agent --employee ${employeeName} --model ${opts.model} --provider ${opts.provider}${cleanupSuffix}`;
1430
- } else if (useBinSymlink) {
1431
- const binName = `${employeeName}-${ccProvider}`;
1432
- process.stderr.write(
1433
- `[tmux-routing] provider cascade: ${ccProvider} \u2192 spawning ${binName}
1434
- `
1435
- );
1436
- spawnCommand = `${envPrefix} ${binName}${cleanupSuffix}`;
1437
- } else {
1438
- spawnCommand = `${envPrefix} claude --dangerously-skip-permissions${identityFlag}${behaviorsFlag}${sessionContextFlag}${cleanupSuffix}`;
1439
- }
1440
- const spawnResult = transport.spawn(sessionName, {
1441
- cwd: spawnCwd,
1442
- command: spawnCommand
1443
- });
1444
- if (spawnResult.error) {
1445
- return { sessionName, error: `tmux new-session failed: ${spawnResult.error}` };
1446
- }
1447
- transport.pipeLog(sessionName, logFile);
1448
- try {
1449
- const mySession = getMySession();
1450
- const dispatchInfo = path10.join(SESSION_CACHE, `dispatch-info-${sessionName}.json`);
1451
- writeFileSync4(dispatchInfo, JSON.stringify({
1452
- dispatchedBy: mySession,
1453
- rootExe: exeSession,
1454
- provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
1455
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
1456
- }));
1457
- } catch {
1458
- }
1459
- let booted = false;
1460
- for (let i = 0; i < 30; i++) {
1461
- try {
1462
- execSync6("sleep 0.5");
1463
- } catch {
1464
- }
1465
- try {
1466
- const pane = transport.capturePane(sessionName);
1467
- if (useExeAgent) {
1468
- if (pane.includes("[exe-agent]") || pane.includes("online")) {
1469
- booted = true;
1470
- break;
1471
- }
1472
- } else {
1473
- if (pane.includes("Claude Code") || pane.includes("\u276F")) {
1474
- booted = true;
1475
- break;
1476
- }
1477
- }
1478
- } catch {
1479
- }
1480
- }
1481
- if (!booted) {
1482
- return { sessionName, error: `${useExeAgent ? "exe-agent" : "claude"} did not boot within 15s` };
1483
- }
1484
- if (!useExeAgent) {
1485
- try {
1486
- transport.sendKeys(sessionName, `/exe-call ${employeeName}`);
1487
- } catch {
1488
- }
1489
- }
1490
- registerSession({
1491
- windowName: sessionName,
1492
- agentId: employeeName,
1493
- projectDir: spawnCwd,
1494
- parentExe: exeSession,
1495
- pid: 0,
1496
- registeredAt: (/* @__PURE__ */ new Date()).toISOString()
1497
- });
1498
- return { sessionName };
1499
- }
1500
- var SESSION_CACHE, BEHAVIORS_EXPORT_TIMEOUT_MS, INTERCOM_DEBOUNCE_MS, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS, BUSY_PATTERN;
1501
- var init_tmux_routing = __esm({
1502
- "src/lib/tmux-routing.ts"() {
1503
- "use strict";
1504
- init_session_registry();
1505
- init_session_key();
1506
- init_transport();
1507
- init_cc_agent_support();
1508
- init_mcp_prefix();
1509
- init_provider_table();
1510
- init_intercom_queue();
1511
- init_plan_limits();
1512
- init_worktree();
1513
- SESSION_CACHE = path10.join(os5.homedir(), ".exe-os", "session-cache");
1514
- BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
1515
- INTERCOM_DEBOUNCE_MS = 3e4;
1516
- INTERCOM_LOG2 = path10.join(os5.homedir(), ".exe-os", "intercom.log");
1517
- DEBOUNCE_FILE = path10.join(SESSION_CACHE, "intercom-debounce.json");
1518
- DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
1519
- BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
1520
- }
1521
- });
1522
-
1523
- // src/lib/tasks-review.ts
1524
- import path11 from "path";
1525
- import { existsSync as existsSync11, readdirSync as readdirSync2, unlinkSync as unlinkSync2 } from "fs";
1526
- var init_tasks_review = __esm({
1527
- "src/lib/tasks-review.ts"() {
1528
- "use strict";
1529
- init_database();
1530
- init_config();
1531
- init_employees();
1532
- init_notifications();
1533
- init_tasks_crud();
1534
- init_tmux_routing();
1535
- init_session_key();
1536
- }
1537
- });
1538
-
1539
- // src/lib/tasks-chain.ts
1540
- import path12 from "path";
1541
- import { readFile as readFile3, writeFile as writeFile4 } from "fs/promises";
1542
- var init_tasks_chain = __esm({
1543
- "src/lib/tasks-chain.ts"() {
1544
- "use strict";
1545
- init_database();
1546
- init_notifications();
1547
- }
1548
- });
1549
-
1550
- // src/lib/project-name.ts
1551
- import { execSync as execSync7 } from "child_process";
1552
- import path13 from "path";
1553
- function getProjectName(cwd) {
1554
- const dir = cwd ?? process.cwd();
1555
- if (_cached2 && _cachedCwd === dir) return _cached2;
1556
- try {
1557
- let repoRoot;
1558
- try {
1559
- const gitCommonDir = execSync7("git rev-parse --path-format=absolute --git-common-dir", {
1560
- cwd: dir,
1561
- encoding: "utf8",
1562
- timeout: 2e3,
1563
- stdio: ["pipe", "pipe", "pipe"]
1564
- }).trim();
1565
- repoRoot = path13.dirname(gitCommonDir);
1566
- } catch {
1567
- repoRoot = execSync7("git rev-parse --show-toplevel", {
1568
- cwd: dir,
1569
- encoding: "utf8",
1570
- timeout: 2e3,
1571
- stdio: ["pipe", "pipe", "pipe"]
1572
- }).trim();
1573
- }
1574
- _cached2 = path13.basename(repoRoot);
1575
- _cachedCwd = dir;
1576
- return _cached2;
1577
- } catch {
1578
- _cached2 = path13.basename(dir);
1579
- _cachedCwd = dir;
1580
- return _cached2;
1581
- }
1582
- }
1583
- var _cached2, _cachedCwd;
1584
- var init_project_name = __esm({
1585
- "src/lib/project-name.ts"() {
1586
- "use strict";
1587
- _cached2 = null;
1588
- _cachedCwd = null;
1589
- }
1590
- });
1591
-
1592
- // src/lib/session-scope.ts
1593
- var session_scope_exports = {};
1594
- __export(session_scope_exports, {
1595
- assertSessionScope: () => assertSessionScope,
1596
- findSessionForProject: () => findSessionForProject,
1597
- getSessionProject: () => getSessionProject
1598
- });
1599
- function getSessionProject(sessionName) {
1600
- const sessions = listSessions();
1601
- const entry = sessions.find((s) => s.windowName === sessionName);
1602
- if (!entry) return null;
1603
- const parts = entry.projectDir.split("/").filter(Boolean);
1604
- return parts[parts.length - 1] ?? null;
1605
- }
1606
- function findSessionForProject(projectName) {
1607
- const sessions = listSessions();
1608
- for (const s of sessions) {
1609
- const proj = s.projectDir.split("/").filter(Boolean).pop();
1610
- if (proj === projectName && s.agentId === "exe") return s;
1611
- }
1612
- return null;
1613
- }
1614
- function assertSessionScope(actionType, targetProject) {
1615
- try {
1616
- const currentProject = getProjectName();
1617
- const exeSession = resolveExeSession();
1618
- if (!exeSession) {
1619
- return { allowed: true, reason: "no_session" };
1620
- }
1621
- if (currentProject === targetProject) {
1622
- return {
1623
- allowed: true,
1624
- reason: "same_session",
1625
- currentProject,
1626
- targetProject
1627
- };
1628
- }
1629
- process.stderr.write(
1630
- `[session-scope] Cross-project ${actionType}: session project="${currentProject}" \u2260 target project="${targetProject}"
1631
- `
1632
- );
1633
- return {
1634
- allowed: true,
1635
- // v1: warn-only, don't block
1636
- reason: "cross_session_granted",
1637
- currentProject,
1638
- targetProject,
1639
- targetSession: findSessionForProject(targetProject)?.windowName
1640
- };
1641
- } catch {
1642
- return { allowed: true, reason: "no_session" };
1643
- }
1644
- }
1645
- var init_session_scope = __esm({
1646
- "src/lib/session-scope.ts"() {
1647
- "use strict";
1648
- init_session_registry();
1649
- init_project_name();
1650
- init_tmux_routing();
1651
- }
1652
- });
1653
-
1654
- // src/lib/tasks-notify.ts
1655
- async function dispatchTaskToEmployee(input) {
1656
- if (input.assignedTo === "exe") return { dispatched: "skipped" };
1657
- let crossProject = false;
1658
- if (input.projectName) {
1659
- try {
1660
- const { assertSessionScope: assertSessionScope2 } = (init_session_scope(), __toCommonJS(session_scope_exports));
1661
- const check = assertSessionScope2("dispatch_task", input.projectName);
1662
- if (check.reason === "cross_session_granted") {
1663
- crossProject = true;
1664
- }
1665
- } catch {
1666
- }
1667
- }
1668
- try {
1669
- const transport = getTransport();
1670
- const exeSession = resolveExeSession();
1671
- if (!exeSession) return { dispatched: "session_missing" };
1672
- const sessionName = employeeSessionName(input.assignedTo, exeSession);
1673
- if (transport.isAlive(sessionName)) {
1674
- const result = sendIntercom(sessionName);
1675
- const dispatched = result === "acknowledged" || result === "debounced" || result === "queued" ? "verified" : result === "delivered" ? "sent_unverified" : "session_dead";
1676
- return { dispatched, session: sessionName, crossProject };
1677
- } else {
1678
- const projectDir = input.projectDir ?? process.cwd();
1679
- const result = ensureEmployee(input.assignedTo, exeSession, projectDir, {
1680
- autoInstance: input.assignedTo === "tom" || input.assignedTo === "sasha"
1681
- });
1682
- if (result.status === "failed") {
1683
- process.stderr.write(
1684
- `[dispatch] Failed to spawn ${input.assignedTo}: ${result.error}
1685
- `
1686
- );
1687
- return { dispatched: "session_missing" };
1688
- }
1689
- return { dispatched: "spawned", session: result.sessionName, crossProject };
1690
- }
1691
- } catch {
1692
- return { dispatched: "session_missing" };
1693
- }
1694
- }
1695
- var init_tasks_notify = __esm({
1696
- "src/lib/tasks-notify.ts"() {
1697
- "use strict";
1698
- init_tmux_routing();
1699
- init_session_key();
1700
- init_notifications();
1701
- init_transport();
1702
- }
1703
- });
1704
-
1705
- // src/lib/tasks.ts
1706
- import path14 from "path";
1707
- import { writeFileSync as writeFileSync5, mkdirSync as mkdirSync6, unlinkSync as unlinkSync3 } from "fs";
1708
- async function createTask(input) {
1709
- const result = await createTaskCore(input);
1710
- if (!input.skipDispatch && result.status !== "blocked" && !process.env.VITEST) {
1711
- dispatchTaskToEmployee({
1712
- assignedTo: input.assignedTo,
1713
- title: input.title,
1714
- priority: input.priority,
1715
- taskFile: result.taskFile,
1716
- initialStatus: result.status,
1717
- projectName: input.projectName
1718
- });
1719
- }
1720
- return result;
1721
- }
1722
- var init_tasks = __esm({
1723
- "src/lib/tasks.ts"() {
1724
- "use strict";
1725
- init_database();
1726
- init_config();
1727
- init_notifications();
1728
- init_tasks_crud();
1729
- init_tasks_review();
1730
- init_tasks_crud();
1731
- init_tasks_chain();
1732
- init_tasks_review();
1733
- init_tasks_notify();
1734
- }
1735
- });
1736
-
1737
- // src/mcp/tools/create-task.ts
1738
- init_tasks();
1739
- import { z } from "zod";
1740
-
1741
- // src/adapters/claude/active-agent.ts
1742
- init_config();
1743
- import { readFileSync as readFileSync10, writeFileSync as writeFileSync6, mkdirSync as mkdirSync7, unlinkSync as unlinkSync4, readdirSync as readdirSync3 } from "fs";
1744
- import { execSync as execSync8 } from "child_process";
1745
- import path15 from "path";
1746
-
1747
- // src/adapters/claude/session-key.ts
1748
- init_session_key();
1749
-
1750
- // src/adapters/claude/active-agent.ts
1751
- var CACHE_DIR = path15.join(EXE_AI_DIR, "session-cache");
1752
- var STALE_MS = 24 * 60 * 60 * 1e3;
1753
- function getMarkerPath() {
1754
- return path15.join(CACHE_DIR, `active-agent-${getSessionKey()}.json`);
1755
- }
1756
- function getActiveAgent() {
1757
- try {
1758
- const markerPath = getMarkerPath();
1759
- const raw = readFileSync10(markerPath, "utf8");
1760
- const data = JSON.parse(raw);
1761
- if (data.agentId) {
1762
- if (data.startedAt) {
1763
- const age = Date.now() - new Date(data.startedAt).getTime();
1764
- if (age > STALE_MS) {
1765
- try {
1766
- unlinkSync4(markerPath);
1767
- } catch {
1768
- }
1769
- } else {
1770
- return {
1771
- agentId: data.agentId,
1772
- agentRole: data.agentRole || "employee"
1773
- };
1774
- }
1775
- } else {
1776
- return {
1777
- agentId: data.agentId,
1778
- agentRole: data.agentRole || "employee"
1779
- };
1780
- }
1781
- }
1782
- } catch {
1783
- }
1784
- try {
1785
- const sessionName = execSync8(
1786
- "tmux display-message -p '#{session_name}' 2>/dev/null",
1787
- { encoding: "utf8", timeout: 2e3 }
1788
- ).trim();
1789
- const empMatch = sessionName.match(/^(\w+)-exe\d+$/);
1790
- if (empMatch && empMatch[1] !== "exe") {
1791
- return { agentId: empMatch[1], agentRole: "employee" };
1792
- }
1793
- if (/^exe\d+$/.test(sessionName)) {
1794
- return { agentId: "exe", agentRole: "COO" };
1795
- }
1796
- } catch {
1797
- }
1798
- return {
1799
- agentId: process.env.AGENT_ID || "default",
1800
- agentRole: process.env.AGENT_ROLE || "employee"
1801
- };
1802
- }
1803
-
1804
- // src/mcp/tools/create-task.ts
1805
- init_tmux_routing();
1806
- function registerCreateTask(server) {
1807
- server.registerTool(
1808
- "create_task",
1809
- {
1810
- title: "Create Task",
1811
- description: "Create and assign a task to an employee. Writes a .md task file and DB row.",
1812
- inputSchema: {
1813
- title: z.string().describe("Task title"),
1814
- assigned_to: z.string().describe("Employee name to assign to"),
1815
- project_name: z.string().describe("Project name"),
1816
- priority: z.enum(["p0", "p1", "p2"]).default("p1").describe("Priority level"),
1817
- complexity: z.enum(["routine", "standard", "complex", "critical"]).default("standard").describe("Bloom taxonomy complexity level. Affects routing tier and review requirements."),
1818
- context: z.string().describe("Full task description and context"),
1819
- blocked_by: z.string().optional().describe("Task ID or slug of the blocking task. If set, task starts as 'blocked'."),
1820
- parent_task_id: z.string().optional().describe("Parent task ID or slug. Links this task as a subtask."),
1821
- reviewer: z.string().optional().describe("Who should review this task when done. Defaults to assigner."),
1822
- budget_tokens: z.number().optional().describe("Max tokens allowed for this task (null = unlimited)"),
1823
- budget_fallback_model: z.string().optional().describe("Model to route to when budget is exhausted")
1824
- }
1825
- },
1826
- async ({ title, assigned_to, project_name, priority, complexity, context, blocked_by, parent_task_id, reviewer, budget_tokens, budget_fallback_model }) => {
1827
- const { agentId: assignedBy } = getActiveAgent();
1828
- const task = await createTask({
1829
- title,
1830
- assignedTo: assigned_to,
1831
- assignedBy,
1832
- projectName: project_name,
1833
- priority,
1834
- complexity,
1835
- context,
1836
- baseDir: process.cwd(),
1837
- blockedBy: blocked_by,
1838
- parentTaskId: parent_task_id,
1839
- reviewer,
1840
- budgetTokens: budget_tokens,
1841
- budgetFallbackModel: budget_fallback_model,
1842
- // Skip internal dispatch — we handle it below with autoInstance
1843
- // support. Without this, createTask fires dispatchTaskToEmployee
1844
- // (no autoInstance) in parallel, racing with our ensureEmployee
1845
- // (autoInstance: true) and spawning duplicate sessions.
1846
- skipDispatch: true
1847
- });
1848
- let dispatchStatus = "";
1849
- if (task.status !== "blocked" && !process.env.VITEST) {
1850
- try {
1851
- const exeSession = resolveExeSession();
1852
- if (exeSession) {
1853
- const MULTI_INSTANCE_ROLES = /* @__PURE__ */ new Set(["tom", "sasha"]);
1854
- const useAutoInstance = MULTI_INSTANCE_ROLES.has(assigned_to);
1855
- const { loadConfigSync: loadConfigSync2 } = await Promise.resolve().then(() => (init_config(), config_exports));
1856
- const cfg = loadConfigSync2();
1857
- const result = ensureEmployee(assigned_to, exeSession, process.cwd(), {
1858
- autoInstance: useAutoInstance,
1859
- maxAutoInstances: useAutoInstance ? cfg.sessionLifecycle.maxAutoInstances : void 0
1860
- });
1861
- switch (result.status) {
1862
- case "intercom_sent":
1863
- dispatchStatus = `
1864
- Dispatched: intercom sent to ${result.sessionName}`;
1865
- break;
1866
- case "spawned":
1867
- dispatchStatus = `
1868
- Dispatched: spawned ${result.sessionName}`;
1869
- break;
1870
- case "failed":
1871
- dispatchStatus = `
1872
- Dispatch failed: ${result.error ?? "unknown"}`;
1873
- break;
1874
- }
1875
- }
1876
- } catch {
1877
- }
1878
- }
1879
- let text = `Task created: ${task.id}
1880
- File: ${task.taskFile}
1881
- Assigned to: ${task.assignedTo} [${task.priority.toUpperCase()}]${dispatchStatus}`;
1882
- if (task.status === "blocked") {
1883
- text += `
1884
- Status: blocked (waiting on ${blocked_by})`;
1885
- }
1886
- if (task.warning) {
1887
- text += `
1888
- Warning: ${task.warning}`;
1889
- }
1890
- return {
1891
- content: [
1892
- {
1893
- type: "text",
1894
- text
1895
- }
1896
- ]
1897
- };
1898
- }
1899
- );
1900
- }
1901
- export {
1902
- registerCreateTask
1903
- };