@askexenow/exe-os 0.8.0 → 0.8.2

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