@askexenow/exe-os 0.8.40 → 0.8.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/backfill-conversations.js +805 -642
- package/dist/bin/backfill-responses.js +804 -641
- package/dist/bin/backfill-vectors.js +791 -634
- package/dist/bin/cleanup-stale-review-tasks.js +788 -631
- package/dist/bin/cli.js +1376 -659
- package/dist/bin/exe-agent.js +20 -1
- package/dist/bin/exe-assign.js +1503 -1343
- package/dist/bin/exe-boot.js +2549 -1784
- package/dist/bin/exe-call.js +39 -1
- package/dist/bin/exe-cloud.js +12 -2
- package/dist/bin/exe-dispatch.js +39 -2
- package/dist/bin/exe-doctor.js +791 -634
- package/dist/bin/exe-export-behaviors.js +792 -637
- package/dist/bin/exe-forget.js +145 -0
- package/dist/bin/exe-gateway.js +2501 -1846
- package/dist/bin/exe-heartbeat.js +147 -1
- package/dist/bin/exe-kill.js +795 -640
- package/dist/bin/exe-launch-agent.js +2168 -2008
- package/dist/bin/exe-link.js +44 -12
- package/dist/bin/exe-new-employee.js +6 -2
- package/dist/bin/exe-pending-messages.js +146 -1
- package/dist/bin/exe-pending-notifications.js +788 -631
- package/dist/bin/exe-pending-reviews.js +176 -1
- package/dist/bin/exe-rename.js +23 -0
- package/dist/bin/exe-review.js +490 -327
- package/dist/bin/exe-search.js +157 -4
- package/dist/bin/exe-session-cleanup.js +2487 -403
- package/dist/bin/exe-settings.js +2 -1
- package/dist/bin/exe-status.js +474 -317
- package/dist/bin/exe-team.js +474 -317
- package/dist/bin/git-sweep.js +2691 -151
- package/dist/bin/graph-backfill.js +794 -637
- package/dist/bin/graph-export.js +798 -641
- package/dist/bin/scan-tasks.js +2951 -44
- package/dist/bin/setup.js +50 -26
- package/dist/bin/shard-migrate.js +792 -637
- package/dist/bin/wiki-sync.js +794 -637
- package/dist/gateway/index.js +2542 -1887
- package/dist/hooks/bug-report-worker.js +2118 -576
- package/dist/hooks/commit-complete.js +2690 -150
- package/dist/hooks/error-recall.js +157 -4
- package/dist/hooks/ingest-worker.js +1455 -803
- package/dist/hooks/instructions-loaded.js +151 -0
- package/dist/hooks/notification.js +153 -2
- package/dist/hooks/post-compact.js +164 -0
- package/dist/hooks/pre-compact.js +3073 -101
- package/dist/hooks/pre-tool-use.js +151 -0
- package/dist/hooks/prompt-ingest-worker.js +1670 -1509
- package/dist/hooks/prompt-submit.js +2650 -1074
- package/dist/hooks/response-ingest-worker.js +154 -6
- package/dist/hooks/session-end.js +153 -2
- package/dist/hooks/session-start.js +157 -4
- package/dist/hooks/stop.js +151 -0
- package/dist/hooks/subagent-stop.js +155 -2
- package/dist/hooks/summary-worker.js +190 -21
- package/dist/index.js +326 -102
- package/dist/lib/cloud-sync.js +31 -10
- package/dist/lib/config.js +2 -0
- package/dist/lib/consolidation.js +69 -2
- package/dist/lib/database.js +19 -0
- package/dist/lib/device-registry.js +19 -0
- package/dist/lib/embedder.js +3 -1
- package/dist/lib/employee-templates.js +20 -1
- package/dist/lib/exe-daemon.js +285 -18
- package/dist/lib/hybrid-search.js +157 -4
- package/dist/lib/messaging.js +39 -2
- package/dist/lib/schedules.js +792 -637
- package/dist/lib/store.js +796 -636
- package/dist/lib/tasks.js +1485 -918
- package/dist/lib/tmux-routing.js +194 -10
- package/dist/mcp/server.js +1643 -924
- package/dist/mcp/tools/create-task.js +2283 -829
- package/dist/mcp/tools/list-tasks.js +2788 -159
- package/dist/mcp/tools/send-message.js +39 -2
- package/dist/mcp/tools/update-task.js +79 -0
- package/dist/runtime/index.js +280 -68
- package/dist/tui/App.js +1485 -645
- package/package.json +3 -2
|
@@ -48,6 +48,7 @@ var config_exports = {};
|
|
|
48
48
|
__export(config_exports, {
|
|
49
49
|
CONFIG_MIGRATIONS: () => CONFIG_MIGRATIONS,
|
|
50
50
|
CONFIG_PATH: () => CONFIG_PATH,
|
|
51
|
+
COO_AGENT_NAME: () => COO_AGENT_NAME,
|
|
51
52
|
CURRENT_CONFIG_VERSION: () => CURRENT_CONFIG_VERSION,
|
|
52
53
|
DB_PATH: () => DB_PATH,
|
|
53
54
|
EXE_AI_DIR: () => EXE_AI_DIR,
|
|
@@ -203,7 +204,7 @@ async function loadConfigFrom(configPath) {
|
|
|
203
204
|
return { ...DEFAULT_CONFIG };
|
|
204
205
|
}
|
|
205
206
|
}
|
|
206
|
-
var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
|
|
207
|
+
var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, COO_AGENT_NAME, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
|
|
207
208
|
var init_config = __esm({
|
|
208
209
|
"src/lib/config.ts"() {
|
|
209
210
|
"use strict";
|
|
@@ -211,6 +212,7 @@ var init_config = __esm({
|
|
|
211
212
|
DB_PATH = path.join(EXE_AI_DIR, "memories.db");
|
|
212
213
|
MODELS_DIR = path.join(EXE_AI_DIR, "models");
|
|
213
214
|
CONFIG_PATH = path.join(EXE_AI_DIR, "config.json");
|
|
215
|
+
COO_AGENT_NAME = "exe";
|
|
214
216
|
LEGACY_LANCE_PATH = path.join(EXE_AI_DIR, "local.lance");
|
|
215
217
|
CURRENT_CONFIG_VERSION = 1;
|
|
216
218
|
DEFAULT_CONFIG = {
|
|
@@ -300,6 +302,40 @@ import {
|
|
|
300
302
|
existsSync as existsSync2,
|
|
301
303
|
rmdirSync
|
|
302
304
|
} from "fs";
|
|
305
|
+
async function writeNotification(notification) {
|
|
306
|
+
try {
|
|
307
|
+
const client = getClient();
|
|
308
|
+
const id = crypto.randomUUID();
|
|
309
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
310
|
+
await client.execute({
|
|
311
|
+
sql: `INSERT INTO notifications (id, agent_id, agent_role, event, project, summary, task_file, read, created_at)
|
|
312
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)`,
|
|
313
|
+
args: [
|
|
314
|
+
id,
|
|
315
|
+
notification.agentId,
|
|
316
|
+
notification.agentRole,
|
|
317
|
+
notification.event,
|
|
318
|
+
notification.project,
|
|
319
|
+
notification.summary,
|
|
320
|
+
notification.taskFile ?? null,
|
|
321
|
+
now
|
|
322
|
+
]
|
|
323
|
+
});
|
|
324
|
+
} catch (err) {
|
|
325
|
+
process.stderr.write(`[notifications] WRITE FAILED: ${err instanceof Error ? err.message : String(err)}
|
|
326
|
+
`);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
async function markAsReadByTaskFile(taskFile) {
|
|
330
|
+
try {
|
|
331
|
+
const client = getClient();
|
|
332
|
+
await client.execute({
|
|
333
|
+
sql: "UPDATE notifications SET read = 1 WHERE task_file = ? AND read = 0",
|
|
334
|
+
args: [taskFile]
|
|
335
|
+
});
|
|
336
|
+
} catch {
|
|
337
|
+
}
|
|
338
|
+
}
|
|
303
339
|
var init_notifications = __esm({
|
|
304
340
|
"src/lib/notifications.ts"() {
|
|
305
341
|
"use strict";
|
|
@@ -307,396 +343,103 @@ var init_notifications = __esm({
|
|
|
307
343
|
}
|
|
308
344
|
});
|
|
309
345
|
|
|
310
|
-
// src/lib/
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
});
|
|
336
|
-
if (result.rows.length === 1) return result.rows[0];
|
|
337
|
-
if (result.rows.length > 1) {
|
|
338
|
-
const exact = result.rows.filter(
|
|
339
|
-
(r) => String(r.task_file).endsWith(`/${identifier}.md`)
|
|
340
|
-
);
|
|
341
|
-
if (exact.length === 1) return exact[0];
|
|
342
|
-
const candidates = exact.length > 1 ? exact : result.rows;
|
|
343
|
-
const active = candidates.filter(
|
|
344
|
-
(r) => !["done", "cancelled"].includes(String(r.status))
|
|
345
|
-
);
|
|
346
|
-
if (active.length === 1) return active[0];
|
|
347
|
-
const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
|
|
348
|
-
throw new Error(
|
|
349
|
-
`Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
|
|
350
|
-
);
|
|
351
|
-
}
|
|
352
|
-
result = await client.execute({
|
|
353
|
-
sql: "SELECT * FROM tasks WHERE title LIKE ?",
|
|
354
|
-
args: [`%${identifier}%`]
|
|
355
|
-
});
|
|
356
|
-
if (result.rows.length === 1) return result.rows[0];
|
|
357
|
-
if (result.rows.length > 1) {
|
|
358
|
-
const active = result.rows.filter(
|
|
359
|
-
(r) => !["done", "cancelled"].includes(String(r.status))
|
|
360
|
-
);
|
|
361
|
-
if (active.length === 1) return active[0];
|
|
362
|
-
const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
|
|
363
|
-
throw new Error(
|
|
364
|
-
`Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
|
|
365
|
-
);
|
|
366
|
-
}
|
|
367
|
-
throw new Error(`Task not found: ${identifier}`);
|
|
368
|
-
}
|
|
369
|
-
async function createTaskCore(input) {
|
|
370
|
-
const client = getClient();
|
|
371
|
-
const id = crypto2.randomUUID();
|
|
372
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
373
|
-
const slug = slugify(input.title);
|
|
374
|
-
const taskFile = input.taskFile ?? `exe/${input.assignedTo}/${slug}.md`;
|
|
375
|
-
let blockedById = null;
|
|
376
|
-
const initialStatus = input.blockedBy ? "blocked" : "open";
|
|
377
|
-
if (input.blockedBy) {
|
|
378
|
-
const blocker = await resolveTask(client, input.blockedBy);
|
|
379
|
-
blockedById = String(blocker.id);
|
|
380
|
-
}
|
|
381
|
-
let parentTaskId = null;
|
|
382
|
-
let parentRef = input.parentTaskId;
|
|
383
|
-
if (!parentRef) {
|
|
384
|
-
const extracted = extractParentFromContext(input.context);
|
|
385
|
-
if (extracted) {
|
|
386
|
-
parentRef = extracted;
|
|
387
|
-
process.stderr.write(
|
|
388
|
-
"[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
|
|
389
|
-
);
|
|
390
|
-
}
|
|
391
|
-
}
|
|
392
|
-
if (parentRef) {
|
|
393
|
-
try {
|
|
394
|
-
const parent = await resolveTask(client, parentRef);
|
|
395
|
-
parentTaskId = String(parent.id);
|
|
396
|
-
} catch (err) {
|
|
397
|
-
if (!input.parentTaskId) {
|
|
398
|
-
throw new Error(
|
|
399
|
-
`create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
|
|
400
|
-
);
|
|
346
|
+
// src/lib/state-bus.ts
|
|
347
|
+
var StateBus, orgBus;
|
|
348
|
+
var init_state_bus = __esm({
|
|
349
|
+
"src/lib/state-bus.ts"() {
|
|
350
|
+
"use strict";
|
|
351
|
+
StateBus = class {
|
|
352
|
+
handlers = /* @__PURE__ */ new Map();
|
|
353
|
+
globalHandlers = /* @__PURE__ */ new Set();
|
|
354
|
+
/** Emit an event to all subscribers */
|
|
355
|
+
emit(event) {
|
|
356
|
+
const typeHandlers = this.handlers.get(event.type);
|
|
357
|
+
if (typeHandlers) {
|
|
358
|
+
for (const handler of typeHandlers) {
|
|
359
|
+
try {
|
|
360
|
+
handler(event);
|
|
361
|
+
} catch {
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
for (const handler of this.globalHandlers) {
|
|
366
|
+
try {
|
|
367
|
+
handler(event);
|
|
368
|
+
} catch {
|
|
369
|
+
}
|
|
370
|
+
}
|
|
401
371
|
}
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
372
|
+
/** Subscribe to a specific event type */
|
|
373
|
+
on(type, handler) {
|
|
374
|
+
if (!this.handlers.has(type)) {
|
|
375
|
+
this.handlers.set(type, /* @__PURE__ */ new Set());
|
|
376
|
+
}
|
|
377
|
+
this.handlers.get(type).add(handler);
|
|
378
|
+
}
|
|
379
|
+
/** Subscribe to ALL events */
|
|
380
|
+
onAny(handler) {
|
|
381
|
+
this.globalHandlers.add(handler);
|
|
382
|
+
}
|
|
383
|
+
/** Unsubscribe from a specific event type */
|
|
384
|
+
off(type, handler) {
|
|
385
|
+
this.handlers.get(type)?.delete(handler);
|
|
386
|
+
}
|
|
387
|
+
/** Unsubscribe from ALL events */
|
|
388
|
+
offAny(handler) {
|
|
389
|
+
this.globalHandlers.delete(handler);
|
|
390
|
+
}
|
|
391
|
+
/** Remove all listeners */
|
|
392
|
+
clear() {
|
|
393
|
+
this.handlers.clear();
|
|
394
|
+
this.globalHandlers.clear();
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
orgBus = new StateBus();
|
|
412
398
|
}
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
// src/lib/session-registry.ts
|
|
402
|
+
import { readFileSync as readFileSync3, writeFileSync, mkdirSync, existsSync as existsSync3 } from "fs";
|
|
403
|
+
import path3 from "path";
|
|
404
|
+
import os3 from "os";
|
|
405
|
+
function registerSession(entry) {
|
|
406
|
+
const dir = path3.dirname(REGISTRY_PATH);
|
|
407
|
+
if (!existsSync3(dir)) {
|
|
408
|
+
mkdirSync(dir, { recursive: true });
|
|
421
409
|
}
|
|
422
|
-
const
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
input.title,
|
|
429
|
-
input.assignedTo,
|
|
430
|
-
input.assignedBy,
|
|
431
|
-
input.projectName,
|
|
432
|
-
input.priority,
|
|
433
|
-
initialStatus,
|
|
434
|
-
taskFile,
|
|
435
|
-
blockedById,
|
|
436
|
-
parentTaskId,
|
|
437
|
-
input.reviewer ?? null,
|
|
438
|
-
input.context,
|
|
439
|
-
complexity,
|
|
440
|
-
input.budgetTokens ?? null,
|
|
441
|
-
input.budgetFallbackModel ?? null,
|
|
442
|
-
0,
|
|
443
|
-
null,
|
|
444
|
-
now,
|
|
445
|
-
now
|
|
446
|
-
]
|
|
447
|
-
});
|
|
448
|
-
return {
|
|
449
|
-
id,
|
|
450
|
-
title: input.title,
|
|
451
|
-
assignedTo: input.assignedTo,
|
|
452
|
-
assignedBy: input.assignedBy,
|
|
453
|
-
projectName: input.projectName,
|
|
454
|
-
priority: input.priority,
|
|
455
|
-
status: initialStatus,
|
|
456
|
-
taskFile,
|
|
457
|
-
createdAt: now,
|
|
458
|
-
updatedAt: now,
|
|
459
|
-
warning,
|
|
460
|
-
budgetTokens: input.budgetTokens ?? null,
|
|
461
|
-
budgetFallbackModel: input.budgetFallbackModel ?? null,
|
|
462
|
-
tokensUsed: 0,
|
|
463
|
-
tokensWarnedAt: null
|
|
464
|
-
};
|
|
465
|
-
}
|
|
466
|
-
async function ensureArchitectureDoc(baseDir, projectName) {
|
|
467
|
-
const archPath = path3.join(baseDir, "exe", "ARCHITECTURE.md");
|
|
468
|
-
try {
|
|
469
|
-
if (existsSync3(archPath)) return;
|
|
470
|
-
const template = [
|
|
471
|
-
`# ${projectName} \u2014 System Architecture`,
|
|
472
|
-
"",
|
|
473
|
-
"> Employees: read this before every task. Update it when you change system structure.",
|
|
474
|
-
`> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
|
|
475
|
-
"",
|
|
476
|
-
"## Overview",
|
|
477
|
-
"",
|
|
478
|
-
"<!-- Describe what this system does, its main components, and how they connect. -->",
|
|
479
|
-
"",
|
|
480
|
-
"## Key Components",
|
|
481
|
-
"",
|
|
482
|
-
"<!-- List the major modules, services, or subsystems. -->",
|
|
483
|
-
"",
|
|
484
|
-
"## Data Flow",
|
|
485
|
-
"",
|
|
486
|
-
"<!-- How does data move through the system? What writes where? -->",
|
|
487
|
-
"",
|
|
488
|
-
"## Invariants",
|
|
489
|
-
"",
|
|
490
|
-
"<!-- Rules that must never be violated. What breaks if these are wrong? -->",
|
|
491
|
-
"",
|
|
492
|
-
"## Dependencies",
|
|
493
|
-
"",
|
|
494
|
-
"<!-- What depends on what? If I change X, what else is affected? -->",
|
|
495
|
-
""
|
|
496
|
-
].join("\n");
|
|
497
|
-
await writeFile2(archPath, template, "utf-8");
|
|
498
|
-
} catch {
|
|
410
|
+
const sessions = listSessions();
|
|
411
|
+
const idx = sessions.findIndex((s) => s.windowName === entry.windowName);
|
|
412
|
+
if (idx >= 0) {
|
|
413
|
+
sessions[idx] = entry;
|
|
414
|
+
} else {
|
|
415
|
+
sessions.push(entry);
|
|
499
416
|
}
|
|
417
|
+
writeFileSync(REGISTRY_PATH, JSON.stringify(sessions, null, 2));
|
|
500
418
|
}
|
|
501
|
-
|
|
502
|
-
const gitignorePath = path3.join(baseDir, ".gitignore");
|
|
419
|
+
function listSessions() {
|
|
503
420
|
try {
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
if (/^\/?exe\/?$/m.test(content)) return;
|
|
507
|
-
await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
|
|
508
|
-
} else {
|
|
509
|
-
await writeFile2(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
|
|
510
|
-
}
|
|
421
|
+
const raw = readFileSync3(REGISTRY_PATH, "utf8");
|
|
422
|
+
return JSON.parse(raw);
|
|
511
423
|
} catch {
|
|
424
|
+
return [];
|
|
512
425
|
}
|
|
513
426
|
}
|
|
514
|
-
var
|
|
515
|
-
|
|
427
|
+
var REGISTRY_PATH;
|
|
428
|
+
var init_session_registry = __esm({
|
|
429
|
+
"src/lib/session-registry.ts"() {
|
|
516
430
|
"use strict";
|
|
517
|
-
|
|
518
|
-
}
|
|
519
|
-
});
|
|
520
|
-
|
|
521
|
-
// src/lib/employees.ts
|
|
522
|
-
var employees_exports = {};
|
|
523
|
-
__export(employees_exports, {
|
|
524
|
-
EMPLOYEES_PATH: () => EMPLOYEES_PATH,
|
|
525
|
-
addEmployee: () => addEmployee,
|
|
526
|
-
getEmployee: () => getEmployee,
|
|
527
|
-
getEmployeeByRole: () => getEmployeeByRole,
|
|
528
|
-
getEmployeeNamesByRole: () => getEmployeeNamesByRole,
|
|
529
|
-
hasRole: () => hasRole,
|
|
530
|
-
isMultiInstance: () => isMultiInstance,
|
|
531
|
-
loadEmployees: () => loadEmployees,
|
|
532
|
-
loadEmployeesSync: () => loadEmployeesSync,
|
|
533
|
-
registerBinSymlinks: () => registerBinSymlinks,
|
|
534
|
-
saveEmployees: () => saveEmployees,
|
|
535
|
-
validateEmployeeName: () => validateEmployeeName
|
|
536
|
-
});
|
|
537
|
-
import { readFile as readFile2, writeFile as writeFile3, mkdir as mkdir3 } from "fs/promises";
|
|
538
|
-
import { existsSync as existsSync4, symlinkSync, readlinkSync, readFileSync as readFileSync4 } from "fs";
|
|
539
|
-
import { execSync as execSync2 } from "child_process";
|
|
540
|
-
import path4 from "path";
|
|
541
|
-
function validateEmployeeName(name) {
|
|
542
|
-
if (!name) {
|
|
543
|
-
return { valid: false, error: "Name is required" };
|
|
544
|
-
}
|
|
545
|
-
if (name.length > 32) {
|
|
546
|
-
return { valid: false, error: "Name must be 32 characters or fewer" };
|
|
547
|
-
}
|
|
548
|
-
if (!/^[a-z][a-z0-9]*$/.test(name)) {
|
|
549
|
-
return {
|
|
550
|
-
valid: false,
|
|
551
|
-
error: "Name must start with a letter and contain only lowercase alphanumeric characters"
|
|
552
|
-
};
|
|
553
|
-
}
|
|
554
|
-
return { valid: true };
|
|
555
|
-
}
|
|
556
|
-
async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
|
|
557
|
-
if (!existsSync4(employeesPath)) {
|
|
558
|
-
return [];
|
|
559
|
-
}
|
|
560
|
-
const raw = await readFile2(employeesPath, "utf-8");
|
|
561
|
-
try {
|
|
562
|
-
return JSON.parse(raw);
|
|
563
|
-
} catch {
|
|
564
|
-
return [];
|
|
565
|
-
}
|
|
566
|
-
}
|
|
567
|
-
async function saveEmployees(employees, employeesPath = EMPLOYEES_PATH) {
|
|
568
|
-
await mkdir3(path4.dirname(employeesPath), { recursive: true });
|
|
569
|
-
await writeFile3(employeesPath, JSON.stringify(employees, null, 2) + "\n", "utf-8");
|
|
570
|
-
}
|
|
571
|
-
function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
|
|
572
|
-
if (!existsSync4(employeesPath)) return [];
|
|
573
|
-
try {
|
|
574
|
-
return JSON.parse(readFileSync4(employeesPath, "utf-8"));
|
|
575
|
-
} catch {
|
|
576
|
-
return [];
|
|
577
|
-
}
|
|
578
|
-
}
|
|
579
|
-
function getEmployee(employees, name) {
|
|
580
|
-
return employees.find((e) => e.name.toLowerCase() === name.toLowerCase());
|
|
581
|
-
}
|
|
582
|
-
function getEmployeeByRole(employees, role) {
|
|
583
|
-
const lower = role.toLowerCase();
|
|
584
|
-
return employees.find((e) => e.role.toLowerCase() === lower);
|
|
585
|
-
}
|
|
586
|
-
function getEmployeeNamesByRole(employees, role) {
|
|
587
|
-
const lower = role.toLowerCase();
|
|
588
|
-
return employees.filter((e) => e.role.toLowerCase() === lower).map((e) => e.name);
|
|
589
|
-
}
|
|
590
|
-
function hasRole(agentName, role) {
|
|
591
|
-
const employees = loadEmployeesSync();
|
|
592
|
-
const emp = getEmployee(employees, agentName);
|
|
593
|
-
return emp ? emp.role.toLowerCase() === role.toLowerCase() : false;
|
|
594
|
-
}
|
|
595
|
-
function isMultiInstance(agentName, employees) {
|
|
596
|
-
const roster = employees ?? loadEmployeesSync();
|
|
597
|
-
const emp = getEmployee(roster, agentName);
|
|
598
|
-
if (!emp) return false;
|
|
599
|
-
return MULTI_INSTANCE_ROLES.has(emp.role.toLowerCase());
|
|
600
|
-
}
|
|
601
|
-
function addEmployee(employees, employee) {
|
|
602
|
-
const normalized = { ...employee, name: employee.name.toLowerCase() };
|
|
603
|
-
if (employees.some((e) => e.name.toLowerCase() === normalized.name)) {
|
|
604
|
-
throw new Error(`Employee '${normalized.name}' already exists`);
|
|
605
|
-
}
|
|
606
|
-
return [...employees, normalized];
|
|
607
|
-
}
|
|
608
|
-
function findExeBin() {
|
|
609
|
-
try {
|
|
610
|
-
return execSync2(process.platform === "win32" ? "where exe-os" : "which exe-os", { encoding: "utf8" }).trim();
|
|
611
|
-
} catch {
|
|
612
|
-
return null;
|
|
613
|
-
}
|
|
614
|
-
}
|
|
615
|
-
function registerBinSymlinks(name) {
|
|
616
|
-
const created = [];
|
|
617
|
-
const skipped = [];
|
|
618
|
-
const errors = [];
|
|
619
|
-
const exeBinPath = findExeBin();
|
|
620
|
-
if (!exeBinPath) {
|
|
621
|
-
errors.push("Could not find 'exe-os' in PATH");
|
|
622
|
-
return { created, skipped, errors };
|
|
623
|
-
}
|
|
624
|
-
const binDir = path4.dirname(exeBinPath);
|
|
625
|
-
let target;
|
|
626
|
-
try {
|
|
627
|
-
target = readlinkSync(exeBinPath);
|
|
628
|
-
} catch {
|
|
629
|
-
errors.push("Could not read 'exe' symlink");
|
|
630
|
-
return { created, skipped, errors };
|
|
631
|
-
}
|
|
632
|
-
for (const suffix of ["", "-opencode"]) {
|
|
633
|
-
const linkName = `${name}${suffix}`;
|
|
634
|
-
const linkPath = path4.join(binDir, linkName);
|
|
635
|
-
if (existsSync4(linkPath)) {
|
|
636
|
-
skipped.push(linkName);
|
|
637
|
-
continue;
|
|
638
|
-
}
|
|
639
|
-
try {
|
|
640
|
-
symlinkSync(target, linkPath);
|
|
641
|
-
created.push(linkName);
|
|
642
|
-
} catch (err) {
|
|
643
|
-
errors.push(`${linkName}: ${err instanceof Error ? err.message : String(err)}`);
|
|
644
|
-
}
|
|
645
|
-
}
|
|
646
|
-
return { created, skipped, errors };
|
|
647
|
-
}
|
|
648
|
-
var EMPLOYEES_PATH, MULTI_INSTANCE_ROLES;
|
|
649
|
-
var init_employees = __esm({
|
|
650
|
-
"src/lib/employees.ts"() {
|
|
651
|
-
"use strict";
|
|
652
|
-
init_config();
|
|
653
|
-
EMPLOYEES_PATH = path4.join(EXE_AI_DIR, "exe-employees.json");
|
|
654
|
-
MULTI_INSTANCE_ROLES = /* @__PURE__ */ new Set(["principal engineer", "content production specialist", "staff code reviewer"]);
|
|
655
|
-
}
|
|
656
|
-
});
|
|
657
|
-
|
|
658
|
-
// src/lib/session-registry.ts
|
|
659
|
-
import { readFileSync as readFileSync5, writeFileSync, mkdirSync, existsSync as existsSync5 } from "fs";
|
|
660
|
-
import path5 from "path";
|
|
661
|
-
import os3 from "os";
|
|
662
|
-
function registerSession(entry) {
|
|
663
|
-
const dir = path5.dirname(REGISTRY_PATH);
|
|
664
|
-
if (!existsSync5(dir)) {
|
|
665
|
-
mkdirSync(dir, { recursive: true });
|
|
666
|
-
}
|
|
667
|
-
const sessions = listSessions();
|
|
668
|
-
const idx = sessions.findIndex((s) => s.windowName === entry.windowName);
|
|
669
|
-
if (idx >= 0) {
|
|
670
|
-
sessions[idx] = entry;
|
|
671
|
-
} else {
|
|
672
|
-
sessions.push(entry);
|
|
673
|
-
}
|
|
674
|
-
writeFileSync(REGISTRY_PATH, JSON.stringify(sessions, null, 2));
|
|
675
|
-
}
|
|
676
|
-
function listSessions() {
|
|
677
|
-
try {
|
|
678
|
-
const raw = readFileSync5(REGISTRY_PATH, "utf8");
|
|
679
|
-
return JSON.parse(raw);
|
|
680
|
-
} catch {
|
|
681
|
-
return [];
|
|
682
|
-
}
|
|
683
|
-
}
|
|
684
|
-
var REGISTRY_PATH;
|
|
685
|
-
var init_session_registry = __esm({
|
|
686
|
-
"src/lib/session-registry.ts"() {
|
|
687
|
-
"use strict";
|
|
688
|
-
REGISTRY_PATH = path5.join(os3.homedir(), ".exe-os", "session-registry.json");
|
|
431
|
+
REGISTRY_PATH = path3.join(os3.homedir(), ".exe-os", "session-registry.json");
|
|
689
432
|
}
|
|
690
433
|
});
|
|
691
434
|
|
|
692
435
|
// src/lib/session-key.ts
|
|
693
|
-
import { execSync
|
|
436
|
+
import { execSync } from "child_process";
|
|
694
437
|
function getSessionKey() {
|
|
695
438
|
if (_cached) return _cached;
|
|
696
439
|
let pid = process.ppid;
|
|
697
440
|
for (let i = 0; i < 10; i++) {
|
|
698
441
|
try {
|
|
699
|
-
const info =
|
|
442
|
+
const info = execSync(`ps -p ${pid} -o ppid=,comm=`, {
|
|
700
443
|
encoding: "utf8",
|
|
701
444
|
timeout: 2e3
|
|
702
445
|
}).trim();
|
|
@@ -832,14 +575,14 @@ var init_transport = __esm({
|
|
|
832
575
|
});
|
|
833
576
|
|
|
834
577
|
// src/lib/cc-agent-support.ts
|
|
835
|
-
import { execSync as
|
|
578
|
+
import { execSync as execSync2 } from "child_process";
|
|
836
579
|
function _resetCcAgentSupportCache() {
|
|
837
580
|
_cachedSupport = null;
|
|
838
581
|
}
|
|
839
582
|
function claudeSupportsAgentFlag() {
|
|
840
583
|
if (_cachedSupport !== null) return _cachedSupport;
|
|
841
584
|
try {
|
|
842
|
-
const helpOutput =
|
|
585
|
+
const helpOutput = execSync2("claude --help 2>&1", {
|
|
843
586
|
encoding: "utf-8",
|
|
844
587
|
timeout: 5e3
|
|
845
588
|
});
|
|
@@ -905,17 +648,17 @@ var init_provider_table = __esm({
|
|
|
905
648
|
});
|
|
906
649
|
|
|
907
650
|
// src/lib/intercom-queue.ts
|
|
908
|
-
import { readFileSync as
|
|
909
|
-
import
|
|
651
|
+
import { readFileSync as readFileSync4, writeFileSync as writeFileSync2, renameSync as renameSync2, existsSync as existsSync4, mkdirSync as mkdirSync2 } from "fs";
|
|
652
|
+
import path4 from "path";
|
|
910
653
|
import os4 from "os";
|
|
911
654
|
function ensureDir() {
|
|
912
|
-
const dir =
|
|
913
|
-
if (!
|
|
655
|
+
const dir = path4.dirname(QUEUE_PATH);
|
|
656
|
+
if (!existsSync4(dir)) mkdirSync2(dir, { recursive: true });
|
|
914
657
|
}
|
|
915
658
|
function readQueue() {
|
|
916
659
|
try {
|
|
917
|
-
if (!
|
|
918
|
-
return JSON.parse(
|
|
660
|
+
if (!existsSync4(QUEUE_PATH)) return [];
|
|
661
|
+
return JSON.parse(readFileSync4(QUEUE_PATH, "utf8"));
|
|
919
662
|
} catch {
|
|
920
663
|
return [];
|
|
921
664
|
}
|
|
@@ -947,249 +690,798 @@ var QUEUE_PATH, TTL_MS, INTERCOM_LOG;
|
|
|
947
690
|
var init_intercom_queue = __esm({
|
|
948
691
|
"src/lib/intercom-queue.ts"() {
|
|
949
692
|
"use strict";
|
|
950
|
-
QUEUE_PATH =
|
|
693
|
+
QUEUE_PATH = path4.join(os4.homedir(), ".exe-os", "intercom-queue.json");
|
|
951
694
|
TTL_MS = 60 * 60 * 1e3;
|
|
952
|
-
INTERCOM_LOG =
|
|
695
|
+
INTERCOM_LOG = path4.join(os4.homedir(), ".exe-os", "intercom.log");
|
|
953
696
|
}
|
|
954
697
|
});
|
|
955
698
|
|
|
956
|
-
// src/lib/
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
pro: { devices: 2, employees: 5, memories: 1e5 },
|
|
972
|
-
team: { devices: 10, employees: 20, memories: 1e6 },
|
|
973
|
-
agency: { devices: 50, employees: 100, memories: 1e7 },
|
|
974
|
-
enterprise: { devices: -1, employees: -1, memories: -1 }
|
|
975
|
-
};
|
|
976
|
-
}
|
|
699
|
+
// src/lib/employees.ts
|
|
700
|
+
var employees_exports = {};
|
|
701
|
+
__export(employees_exports, {
|
|
702
|
+
EMPLOYEES_PATH: () => EMPLOYEES_PATH,
|
|
703
|
+
addEmployee: () => addEmployee,
|
|
704
|
+
getEmployee: () => getEmployee,
|
|
705
|
+
getEmployeeByRole: () => getEmployeeByRole,
|
|
706
|
+
getEmployeeNamesByRole: () => getEmployeeNamesByRole,
|
|
707
|
+
hasRole: () => hasRole,
|
|
708
|
+
isMultiInstance: () => isMultiInstance,
|
|
709
|
+
loadEmployees: () => loadEmployees,
|
|
710
|
+
loadEmployeesSync: () => loadEmployeesSync,
|
|
711
|
+
registerBinSymlinks: () => registerBinSymlinks,
|
|
712
|
+
saveEmployees: () => saveEmployees,
|
|
713
|
+
validateEmployeeName: () => validateEmployeeName
|
|
977
714
|
});
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
import {
|
|
981
|
-
import
|
|
982
|
-
function
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
const plan = payload.plan ?? "free";
|
|
991
|
-
const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
|
|
715
|
+
import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
|
|
716
|
+
import { existsSync as existsSync5, symlinkSync, readlinkSync, readFileSync as readFileSync5 } from "fs";
|
|
717
|
+
import { execSync as execSync3 } from "child_process";
|
|
718
|
+
import path5 from "path";
|
|
719
|
+
function validateEmployeeName(name) {
|
|
720
|
+
if (!name) {
|
|
721
|
+
return { valid: false, error: "Name is required" };
|
|
722
|
+
}
|
|
723
|
+
if (name.length > 32) {
|
|
724
|
+
return { valid: false, error: "Name must be 32 characters or fewer" };
|
|
725
|
+
}
|
|
726
|
+
if (!/^[a-z][a-z0-9]*$/.test(name)) {
|
|
992
727
|
return {
|
|
993
|
-
valid:
|
|
994
|
-
|
|
995
|
-
email: payload.sub ?? "",
|
|
996
|
-
expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
|
|
997
|
-
deviceLimit: limits.devices,
|
|
998
|
-
employeeLimit: limits.employees,
|
|
999
|
-
memoryLimit: limits.memories
|
|
728
|
+
valid: false,
|
|
729
|
+
error: "Name must start with a letter and contain only lowercase alphanumeric characters"
|
|
1000
730
|
};
|
|
731
|
+
}
|
|
732
|
+
return { valid: true };
|
|
733
|
+
}
|
|
734
|
+
async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
|
|
735
|
+
if (!existsSync5(employeesPath)) {
|
|
736
|
+
return [];
|
|
737
|
+
}
|
|
738
|
+
const raw = await readFile2(employeesPath, "utf-8");
|
|
739
|
+
try {
|
|
740
|
+
return JSON.parse(raw);
|
|
1001
741
|
} catch {
|
|
1002
|
-
return
|
|
742
|
+
return [];
|
|
1003
743
|
}
|
|
1004
744
|
}
|
|
1005
|
-
function
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
valid: true,
|
|
1009
|
-
plan: "free",
|
|
1010
|
-
email: "",
|
|
1011
|
-
expiresAt: null,
|
|
1012
|
-
deviceLimit: limits.devices,
|
|
1013
|
-
employeeLimit: limits.employees,
|
|
1014
|
-
memoryLimit: limits.memories
|
|
1015
|
-
};
|
|
745
|
+
async function saveEmployees(employees, employeesPath = EMPLOYEES_PATH) {
|
|
746
|
+
await mkdir2(path5.dirname(employeesPath), { recursive: true });
|
|
747
|
+
await writeFile2(employeesPath, JSON.stringify(employees, null, 2) + "\n", "utf-8");
|
|
1016
748
|
}
|
|
1017
|
-
function
|
|
1018
|
-
|
|
1019
|
-
if (license.employeeLimit < 0) return;
|
|
1020
|
-
const filePath = rosterPath ?? EMPLOYEES_PATH;
|
|
1021
|
-
let count = 0;
|
|
749
|
+
function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
|
|
750
|
+
if (!existsSync5(employeesPath)) return [];
|
|
1022
751
|
try {
|
|
1023
|
-
|
|
1024
|
-
const raw = readFileSync8(filePath, "utf8");
|
|
1025
|
-
const employees = JSON.parse(raw);
|
|
1026
|
-
count = Array.isArray(employees) ? employees.length : 0;
|
|
1027
|
-
}
|
|
752
|
+
return JSON.parse(readFileSync5(employeesPath, "utf-8"));
|
|
1028
753
|
} catch {
|
|
1029
|
-
|
|
1030
|
-
`Cannot verify employee count: roster unreadable at ${filePath}. Refusing to proceed. Check file permissions or upgrade plan.`
|
|
1031
|
-
);
|
|
1032
|
-
}
|
|
1033
|
-
if (count >= license.employeeLimit) {
|
|
1034
|
-
throw new PlanLimitError(
|
|
1035
|
-
`Employee limit reached: ${count}/${license.employeeLimit} employees on the ${license.plan} plan. Upgrade at https://askexe.com to add more.`
|
|
1036
|
-
);
|
|
754
|
+
return [];
|
|
1037
755
|
}
|
|
1038
756
|
}
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
"src/lib/plan-limits.ts"() {
|
|
1042
|
-
"use strict";
|
|
1043
|
-
init_database();
|
|
1044
|
-
init_employees();
|
|
1045
|
-
init_license();
|
|
1046
|
-
init_config();
|
|
1047
|
-
PlanLimitError = class extends Error {
|
|
1048
|
-
constructor(message) {
|
|
1049
|
-
super(message);
|
|
1050
|
-
this.name = "PlanLimitError";
|
|
1051
|
-
}
|
|
1052
|
-
};
|
|
1053
|
-
CACHE_PATH2 = path8.join(EXE_AI_DIR, "license-cache.json");
|
|
1054
|
-
}
|
|
1055
|
-
});
|
|
1056
|
-
|
|
1057
|
-
// src/lib/tmux-routing.ts
|
|
1058
|
-
import { execFileSync as execFileSync2, execSync as execSync5 } from "child_process";
|
|
1059
|
-
import { readFileSync as readFileSync9, writeFileSync as writeFileSync4, mkdirSync as mkdirSync4, existsSync as existsSync9, appendFileSync } from "fs";
|
|
1060
|
-
import path9 from "path";
|
|
1061
|
-
import os5 from "os";
|
|
1062
|
-
import { fileURLToPath } from "url";
|
|
1063
|
-
import { unlinkSync as unlinkSync2 } from "fs";
|
|
1064
|
-
function spawnLockPath(sessionName) {
|
|
1065
|
-
return path9.join(SPAWN_LOCK_DIR, `${sessionName}.lock`);
|
|
757
|
+
function getEmployee(employees, name) {
|
|
758
|
+
return employees.find((e) => e.name.toLowerCase() === name.toLowerCase());
|
|
1066
759
|
}
|
|
1067
|
-
function
|
|
760
|
+
function getEmployeeByRole(employees, role) {
|
|
761
|
+
const lower = role.toLowerCase();
|
|
762
|
+
return employees.find((e) => e.role.toLowerCase() === lower);
|
|
763
|
+
}
|
|
764
|
+
function getEmployeeNamesByRole(employees, role) {
|
|
765
|
+
const lower = role.toLowerCase();
|
|
766
|
+
return employees.filter((e) => e.role.toLowerCase() === lower).map((e) => e.name);
|
|
767
|
+
}
|
|
768
|
+
function hasRole(agentName, role) {
|
|
769
|
+
const employees = loadEmployeesSync();
|
|
770
|
+
const emp = getEmployee(employees, agentName);
|
|
771
|
+
return emp ? emp.role.toLowerCase() === role.toLowerCase() : false;
|
|
772
|
+
}
|
|
773
|
+
function isMultiInstance(agentName, employees) {
|
|
774
|
+
const roster = employees ?? loadEmployeesSync();
|
|
775
|
+
const emp = getEmployee(roster, agentName);
|
|
776
|
+
if (!emp) return false;
|
|
777
|
+
return MULTI_INSTANCE_ROLES.has(emp.role.toLowerCase());
|
|
778
|
+
}
|
|
779
|
+
function addEmployee(employees, employee) {
|
|
780
|
+
const normalized = { ...employee, name: employee.name.toLowerCase() };
|
|
781
|
+
if (employees.some((e) => e.name.toLowerCase() === normalized.name)) {
|
|
782
|
+
throw new Error(`Employee '${normalized.name}' already exists`);
|
|
783
|
+
}
|
|
784
|
+
return [...employees, normalized];
|
|
785
|
+
}
|
|
786
|
+
function findExeBin() {
|
|
1068
787
|
try {
|
|
1069
|
-
process.
|
|
1070
|
-
return true;
|
|
788
|
+
return execSync3(process.platform === "win32" ? "where exe-os" : "which exe-os", { encoding: "utf8" }).trim();
|
|
1071
789
|
} catch {
|
|
1072
|
-
return
|
|
790
|
+
return null;
|
|
1073
791
|
}
|
|
1074
792
|
}
|
|
1075
|
-
function
|
|
1076
|
-
|
|
1077
|
-
|
|
793
|
+
function registerBinSymlinks(name) {
|
|
794
|
+
const created = [];
|
|
795
|
+
const skipped = [];
|
|
796
|
+
const errors = [];
|
|
797
|
+
const exeBinPath = findExeBin();
|
|
798
|
+
if (!exeBinPath) {
|
|
799
|
+
errors.push("Could not find 'exe-os' in PATH");
|
|
800
|
+
return { created, skipped, errors };
|
|
1078
801
|
}
|
|
1079
|
-
const
|
|
1080
|
-
|
|
802
|
+
const binDir = path5.dirname(exeBinPath);
|
|
803
|
+
let target;
|
|
804
|
+
try {
|
|
805
|
+
target = readlinkSync(exeBinPath);
|
|
806
|
+
} catch {
|
|
807
|
+
errors.push("Could not read 'exe' symlink");
|
|
808
|
+
return { created, skipped, errors };
|
|
809
|
+
}
|
|
810
|
+
for (const suffix of ["", "-opencode"]) {
|
|
811
|
+
const linkName = `${name}${suffix}`;
|
|
812
|
+
const linkPath = path5.join(binDir, linkName);
|
|
813
|
+
if (existsSync5(linkPath)) {
|
|
814
|
+
skipped.push(linkName);
|
|
815
|
+
continue;
|
|
816
|
+
}
|
|
1081
817
|
try {
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
}
|
|
1087
|
-
} catch {
|
|
818
|
+
symlinkSync(target, linkPath);
|
|
819
|
+
created.push(linkName);
|
|
820
|
+
} catch (err) {
|
|
821
|
+
errors.push(`${linkName}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1088
822
|
}
|
|
1089
823
|
}
|
|
1090
|
-
|
|
1091
|
-
return true;
|
|
824
|
+
return { created, skipped, errors };
|
|
1092
825
|
}
|
|
1093
|
-
|
|
826
|
+
var EMPLOYEES_PATH, MULTI_INSTANCE_ROLES;
|
|
827
|
+
var init_employees = __esm({
|
|
828
|
+
"src/lib/employees.ts"() {
|
|
829
|
+
"use strict";
|
|
830
|
+
init_config();
|
|
831
|
+
EMPLOYEES_PATH = path5.join(EXE_AI_DIR, "exe-employees.json");
|
|
832
|
+
MULTI_INSTANCE_ROLES = /* @__PURE__ */ new Set(["principal engineer", "content production specialist", "staff code reviewer"]);
|
|
833
|
+
}
|
|
834
|
+
});
|
|
835
|
+
|
|
836
|
+
// src/lib/license.ts
|
|
837
|
+
import { readFileSync as readFileSync6, writeFileSync as writeFileSync3, existsSync as existsSync6, mkdirSync as mkdirSync3 } from "fs";
|
|
838
|
+
import { randomUUID } from "crypto";
|
|
839
|
+
import path6 from "path";
|
|
840
|
+
import { jwtVerify, importSPKI } from "jose";
|
|
841
|
+
var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH, PLAN_LIMITS;
|
|
842
|
+
var init_license = __esm({
|
|
843
|
+
"src/lib/license.ts"() {
|
|
844
|
+
"use strict";
|
|
845
|
+
init_config();
|
|
846
|
+
LICENSE_PATH = path6.join(EXE_AI_DIR, "license.key");
|
|
847
|
+
CACHE_PATH = path6.join(EXE_AI_DIR, "license-cache.json");
|
|
848
|
+
DEVICE_ID_PATH = path6.join(EXE_AI_DIR, "device-id");
|
|
849
|
+
PLAN_LIMITS = {
|
|
850
|
+
free: { devices: 1, employees: 1, memories: 5e3 },
|
|
851
|
+
pro: { devices: 2, employees: 5, memories: 1e5 },
|
|
852
|
+
team: { devices: 10, employees: 20, memories: 1e6 },
|
|
853
|
+
agency: { devices: 50, employees: 100, memories: 1e7 },
|
|
854
|
+
enterprise: { devices: -1, employees: -1, memories: -1 }
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
});
|
|
858
|
+
|
|
859
|
+
// src/lib/plan-limits.ts
|
|
860
|
+
import { readFileSync as readFileSync7, existsSync as existsSync7 } from "fs";
|
|
861
|
+
import path7 from "path";
|
|
862
|
+
function getLicenseSync() {
|
|
1094
863
|
try {
|
|
1095
|
-
|
|
864
|
+
if (!existsSync7(CACHE_PATH2)) return freeLicense();
|
|
865
|
+
const raw = JSON.parse(readFileSync7(CACHE_PATH2, "utf8"));
|
|
866
|
+
if (!raw.token || typeof raw.token !== "string") return freeLicense();
|
|
867
|
+
const parts = raw.token.split(".");
|
|
868
|
+
if (parts.length !== 3) return freeLicense();
|
|
869
|
+
const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
|
|
870
|
+
const plan = payload.plan ?? "free";
|
|
871
|
+
const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
|
|
872
|
+
return {
|
|
873
|
+
valid: true,
|
|
874
|
+
plan,
|
|
875
|
+
email: payload.sub ?? "",
|
|
876
|
+
expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
|
|
877
|
+
deviceLimit: limits.devices,
|
|
878
|
+
employeeLimit: limits.employees,
|
|
879
|
+
memoryLimit: limits.memories
|
|
880
|
+
};
|
|
1096
881
|
} catch {
|
|
882
|
+
return freeLicense();
|
|
1097
883
|
}
|
|
1098
884
|
}
|
|
1099
|
-
function
|
|
885
|
+
function freeLicense() {
|
|
886
|
+
const limits = PLAN_LIMITS.free;
|
|
887
|
+
return {
|
|
888
|
+
valid: true,
|
|
889
|
+
plan: "free",
|
|
890
|
+
email: "",
|
|
891
|
+
expiresAt: null,
|
|
892
|
+
deviceLimit: limits.devices,
|
|
893
|
+
employeeLimit: limits.employees,
|
|
894
|
+
memoryLimit: limits.memories
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
function assertEmployeeLimitSync(rosterPath) {
|
|
898
|
+
const license = getLicenseSync();
|
|
899
|
+
if (license.employeeLimit < 0) return;
|
|
900
|
+
const filePath = rosterPath ?? EMPLOYEES_PATH;
|
|
901
|
+
let count = 0;
|
|
1100
902
|
try {
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
"exe-export-behaviors.js"
|
|
1107
|
-
);
|
|
1108
|
-
return existsSync9(scriptPath) ? scriptPath : null;
|
|
903
|
+
if (existsSync7(filePath)) {
|
|
904
|
+
const raw = readFileSync7(filePath, "utf8");
|
|
905
|
+
const employees = JSON.parse(raw);
|
|
906
|
+
count = Array.isArray(employees) ? employees.length : 0;
|
|
907
|
+
}
|
|
1109
908
|
} catch {
|
|
1110
|
-
|
|
909
|
+
throw new PlanLimitError(
|
|
910
|
+
`Cannot verify employee count: roster unreadable at ${filePath}. Refusing to proceed. Check file permissions or upgrade plan.`
|
|
911
|
+
);
|
|
912
|
+
}
|
|
913
|
+
if (count >= license.employeeLimit) {
|
|
914
|
+
throw new PlanLimitError(
|
|
915
|
+
`Employee limit reached: ${count}/${license.employeeLimit} employees on the ${license.plan} plan. Upgrade at https://askexe.com to add more.`
|
|
916
|
+
);
|
|
1111
917
|
}
|
|
1112
918
|
}
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
919
|
+
var PlanLimitError, CACHE_PATH2;
|
|
920
|
+
var init_plan_limits = __esm({
|
|
921
|
+
"src/lib/plan-limits.ts"() {
|
|
922
|
+
"use strict";
|
|
923
|
+
init_database();
|
|
924
|
+
init_employees();
|
|
925
|
+
init_license();
|
|
926
|
+
init_config();
|
|
927
|
+
PlanLimitError = class extends Error {
|
|
928
|
+
constructor(message) {
|
|
929
|
+
super(message);
|
|
930
|
+
this.name = "PlanLimitError";
|
|
931
|
+
}
|
|
932
|
+
};
|
|
933
|
+
CACHE_PATH2 = path7.join(EXE_AI_DIR, "license-cache.json");
|
|
934
|
+
}
|
|
935
|
+
});
|
|
936
|
+
|
|
937
|
+
// src/lib/session-kill-telemetry.ts
|
|
938
|
+
import crypto2 from "crypto";
|
|
939
|
+
async function recordSessionKill(input) {
|
|
1116
940
|
try {
|
|
1117
|
-
const
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
941
|
+
const client = getClient();
|
|
942
|
+
await client.execute({
|
|
943
|
+
sql: `INSERT INTO session_kills
|
|
944
|
+
(id, session_name, agent_id, killed_at, reason,
|
|
945
|
+
ticks_idle, estimated_tokens_saved)
|
|
946
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
947
|
+
args: [
|
|
948
|
+
crypto2.randomUUID(),
|
|
949
|
+
input.sessionName,
|
|
950
|
+
input.agentId,
|
|
951
|
+
(/* @__PURE__ */ new Date()).toISOString(),
|
|
952
|
+
input.reason,
|
|
953
|
+
input.ticksIdle ?? null,
|
|
954
|
+
input.estimatedTokensSaved ?? null
|
|
955
|
+
]
|
|
956
|
+
});
|
|
1123
957
|
} catch (err) {
|
|
1124
958
|
process.stderr.write(
|
|
1125
|
-
`[
|
|
959
|
+
`[session-kill-telemetry] write failed: ${err instanceof Error ? err.message : String(err)}
|
|
1126
960
|
`
|
|
1127
961
|
);
|
|
1128
|
-
return null;
|
|
1129
962
|
}
|
|
1130
963
|
}
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
const suffix = instance != null && instance > 0 ? String(instance) : "";
|
|
1136
|
-
return `${employee}${suffix}-${exeSession}`;
|
|
1137
|
-
}
|
|
1138
|
-
function extractRootExe(name) {
|
|
1139
|
-
const match = name.match(/(exe\d+)$/);
|
|
1140
|
-
return match?.[1] ?? null;
|
|
1141
|
-
}
|
|
1142
|
-
function getParentExe(sessionKey) {
|
|
1143
|
-
try {
|
|
1144
|
-
const data = JSON.parse(readFileSync9(path9.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
|
|
1145
|
-
return data.parentExe || null;
|
|
1146
|
-
} catch {
|
|
1147
|
-
return null;
|
|
964
|
+
var init_session_kill_telemetry = __esm({
|
|
965
|
+
"src/lib/session-kill-telemetry.ts"() {
|
|
966
|
+
"use strict";
|
|
967
|
+
init_database();
|
|
1148
968
|
}
|
|
1149
|
-
}
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
969
|
+
});
|
|
970
|
+
|
|
971
|
+
// src/lib/capacity-monitor.ts
|
|
972
|
+
var capacity_monitor_exports = {};
|
|
973
|
+
__export(capacity_monitor_exports, {
|
|
974
|
+
CTX_FLOOR_PERCENT: () => CTX_FLOOR_PERCENT,
|
|
975
|
+
_resetLastRelaunchCache: () => _resetLastRelaunchCache,
|
|
976
|
+
_resetPendingCapacityKills: () => _resetPendingCapacityKills,
|
|
977
|
+
confirmCapacityKill: () => confirmCapacityKill,
|
|
978
|
+
createOrRefreshResumeTask: () => createOrRefreshResumeTask,
|
|
979
|
+
extractContextPercent: () => extractContextPercent,
|
|
980
|
+
isAtCapacity: () => isAtCapacity,
|
|
981
|
+
isWithinRelaunchCooldown: () => isWithinRelaunchCooldown,
|
|
982
|
+
pollCapacityDead: () => pollCapacityDead
|
|
983
|
+
});
|
|
984
|
+
function resumeTaskTitle(agentId) {
|
|
985
|
+
return `${RESUME_TITLE_PREFIX} ${agentId} hit context capacity \u2014 continue open tasks`;
|
|
986
|
+
}
|
|
987
|
+
function buildResumeContext(agentId, openTasks) {
|
|
988
|
+
const taskList = openTasks.map(
|
|
989
|
+
(r, i) => `${i + 1}. [${String(r.priority).toUpperCase()}] ${String(r.title)} (${String(r.task_file)})`
|
|
990
|
+
).join("\n");
|
|
991
|
+
return [
|
|
992
|
+
"## Context",
|
|
993
|
+
"",
|
|
994
|
+
`${agentId} hit context capacity and was auto-relaunched by the capacity monitor.`,
|
|
995
|
+
"Call recall_my_memory first \u2014 search for 'CONTEXT CHECKPOINT'. Pick up where the previous session stopped.",
|
|
996
|
+
"",
|
|
997
|
+
`You have ${openTasks.length} open task(s). Work through them in priority order:`,
|
|
998
|
+
"",
|
|
999
|
+
taskList,
|
|
1000
|
+
"",
|
|
1001
|
+
"Read each task file and chain through them. Build and commit after each one."
|
|
1002
|
+
].join("\n");
|
|
1003
|
+
}
|
|
1004
|
+
function filterPaneContent(paneOutput) {
|
|
1005
|
+
return paneOutput.split("\n").filter((line) => {
|
|
1006
|
+
if (CONTENT_LINE_PREFIX.test(line)) return false;
|
|
1007
|
+
for (const marker of CONTENT_LINE_MARKERS) {
|
|
1008
|
+
if (line.includes(marker)) return false;
|
|
1158
1009
|
}
|
|
1159
|
-
|
|
1010
|
+
for (const re of SOURCE_CODE_MARKERS) {
|
|
1011
|
+
if (re.test(line)) return false;
|
|
1012
|
+
}
|
|
1013
|
+
return true;
|
|
1014
|
+
}).join("\n");
|
|
1015
|
+
}
|
|
1016
|
+
function extractContextPercent(paneOutput) {
|
|
1017
|
+
const match = paneOutput.match(CC_CONTEXT_BAR_RE);
|
|
1018
|
+
if (!match) return null;
|
|
1019
|
+
const parsed = Number.parseInt(match[2], 10);
|
|
1020
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
1021
|
+
}
|
|
1022
|
+
function isAtCapacity(paneOutput) {
|
|
1023
|
+
const filtered = filterPaneContent(paneOutput);
|
|
1024
|
+
return CAPACITY_PATTERNS.some((p) => p.test(filtered));
|
|
1025
|
+
}
|
|
1026
|
+
function confirmCapacityKill(agentId, now = Date.now()) {
|
|
1027
|
+
const pendingSince = _pendingCapacityKill.get(agentId);
|
|
1028
|
+
if (pendingSince === void 0) {
|
|
1029
|
+
_pendingCapacityKill.set(agentId, now);
|
|
1030
|
+
return false;
|
|
1160
1031
|
}
|
|
1161
|
-
|
|
1032
|
+
if (now - pendingSince > CONFIRMATION_WINDOW_MS) {
|
|
1033
|
+
_pendingCapacityKill.set(agentId, now);
|
|
1034
|
+
return false;
|
|
1035
|
+
}
|
|
1036
|
+
_pendingCapacityKill.delete(agentId);
|
|
1037
|
+
return true;
|
|
1162
1038
|
}
|
|
1163
|
-
function
|
|
1164
|
-
|
|
1039
|
+
function _resetPendingCapacityKills() {
|
|
1040
|
+
_pendingCapacityKill.clear();
|
|
1165
1041
|
}
|
|
1166
|
-
function
|
|
1167
|
-
|
|
1168
|
-
if (!isAlive(base) && acquireSpawnLock(base)) return 0;
|
|
1169
|
-
for (let i = 2; i <= maxInstances; i++) {
|
|
1170
|
-
const candidate = employeeSessionName(employeeName, exeSession, i);
|
|
1171
|
-
if (!isAlive(candidate) && acquireSpawnLock(candidate)) return i;
|
|
1172
|
-
}
|
|
1173
|
-
return null;
|
|
1042
|
+
function _resetLastRelaunchCache() {
|
|
1043
|
+
_lastRelaunch.clear();
|
|
1174
1044
|
}
|
|
1175
|
-
function
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1045
|
+
async function lastResumeCreatedAtMs(agentId) {
|
|
1046
|
+
const client = getClient();
|
|
1047
|
+
const result = await client.execute({
|
|
1048
|
+
sql: `SELECT MAX(created_at) AS last_created_at
|
|
1049
|
+
FROM tasks
|
|
1050
|
+
WHERE assigned_to = ? AND title LIKE ?`,
|
|
1051
|
+
args: [agentId, `${RESUME_TITLE_PREFIX} %`]
|
|
1052
|
+
});
|
|
1053
|
+
const raw = result.rows[0]?.last_created_at;
|
|
1054
|
+
if (raw === null || raw === void 0) return null;
|
|
1055
|
+
const parsed = Date.parse(String(raw));
|
|
1056
|
+
return Number.isNaN(parsed) ? null : parsed;
|
|
1057
|
+
}
|
|
1058
|
+
async function isWithinRelaunchCooldown(agentId, now = Date.now()) {
|
|
1059
|
+
const cached = _lastRelaunch.get(agentId);
|
|
1060
|
+
if (cached !== void 0) return now - cached < RELAUNCH_COOLDOWN_MS;
|
|
1061
|
+
const persisted = await lastResumeCreatedAtMs(agentId);
|
|
1062
|
+
if (persisted === null) return false;
|
|
1063
|
+
if (now - persisted >= RELAUNCH_COOLDOWN_MS) return false;
|
|
1064
|
+
_lastRelaunch.set(agentId, persisted);
|
|
1065
|
+
return true;
|
|
1182
1066
|
}
|
|
1183
|
-
function
|
|
1067
|
+
async function createOrRefreshResumeTask(agentId, projectDir, openTasks) {
|
|
1068
|
+
const client = getClient();
|
|
1069
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1070
|
+
const context = buildResumeContext(agentId, openTasks);
|
|
1071
|
+
const existing = await client.execute({
|
|
1072
|
+
sql: `SELECT id FROM tasks
|
|
1073
|
+
WHERE assigned_to = ?
|
|
1074
|
+
AND title LIKE ?
|
|
1075
|
+
AND status IN (${RESUME_ACTIVE_STATUSES.map(() => "?").join(", ")})
|
|
1076
|
+
ORDER BY created_at DESC
|
|
1077
|
+
LIMIT 1`,
|
|
1078
|
+
args: [agentId, RESUME_TITLE_LIKE_PATTERN, ...RESUME_ACTIVE_STATUSES]
|
|
1079
|
+
});
|
|
1080
|
+
if (existing.rows.length > 0) {
|
|
1081
|
+
const taskId = String(existing.rows[0].id);
|
|
1082
|
+
await client.execute({
|
|
1083
|
+
sql: `UPDATE tasks SET context = ?, updated_at = ? WHERE id = ?`,
|
|
1084
|
+
args: [context, now, taskId]
|
|
1085
|
+
});
|
|
1086
|
+
return { created: false, taskId };
|
|
1087
|
+
}
|
|
1088
|
+
const { createTask: createTask2 } = await Promise.resolve().then(() => (init_tasks(), tasks_exports));
|
|
1089
|
+
const task = await createTask2({
|
|
1090
|
+
title: resumeTaskTitle(agentId),
|
|
1091
|
+
assignedTo: agentId,
|
|
1092
|
+
assignedBy: "system",
|
|
1093
|
+
projectName: projectDir.split("/").pop() ?? "unknown",
|
|
1094
|
+
priority: "p0",
|
|
1095
|
+
context,
|
|
1096
|
+
baseDir: projectDir
|
|
1097
|
+
});
|
|
1098
|
+
return { created: true, taskId: task.id };
|
|
1099
|
+
}
|
|
1100
|
+
async function pollCapacityDead() {
|
|
1101
|
+
const transport = getTransport();
|
|
1102
|
+
const relaunched = [];
|
|
1103
|
+
const registered = listSessions().filter(
|
|
1104
|
+
(s) => s.agentId !== "exe"
|
|
1105
|
+
);
|
|
1106
|
+
if (registered.length === 0) return [];
|
|
1107
|
+
let liveSessions;
|
|
1184
1108
|
try {
|
|
1185
|
-
|
|
1186
|
-
writeFileSync4(DEBOUNCE_FILE, JSON.stringify(state));
|
|
1109
|
+
liveSessions = transport.listSessions();
|
|
1187
1110
|
} catch {
|
|
1111
|
+
return [];
|
|
1188
1112
|
}
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1113
|
+
for (const entry of registered) {
|
|
1114
|
+
const { windowName, agentId, projectDir } = entry;
|
|
1115
|
+
if (!liveSessions.includes(windowName)) continue;
|
|
1116
|
+
if (await isWithinRelaunchCooldown(agentId)) continue;
|
|
1117
|
+
let pane;
|
|
1118
|
+
try {
|
|
1119
|
+
pane = transport.capturePane(windowName, 15);
|
|
1120
|
+
} catch {
|
|
1121
|
+
continue;
|
|
1122
|
+
}
|
|
1123
|
+
if (!isAtCapacity(pane)) continue;
|
|
1124
|
+
const ctxPct = extractContextPercent(pane);
|
|
1125
|
+
if (ctxPct !== null && ctxPct < CTX_FLOOR_PERCENT) {
|
|
1126
|
+
process.stderr.write(
|
|
1127
|
+
`[capacity-monitor] ctx-floor: ${agentId} at ${ctxPct}% in ${windowName} \u2014 below ${CTX_FLOOR_PERCENT}%. Skipping capacity kill (likely self-referential content or false positive).
|
|
1128
|
+
`
|
|
1129
|
+
);
|
|
1130
|
+
continue;
|
|
1131
|
+
}
|
|
1132
|
+
if (!confirmCapacityKill(agentId)) {
|
|
1133
|
+
process.stderr.write(
|
|
1134
|
+
`[capacity-monitor] ${agentId} matched capacity pattern once in ${windowName}. Awaiting confirmation on next tick.
|
|
1135
|
+
`
|
|
1136
|
+
);
|
|
1137
|
+
continue;
|
|
1138
|
+
}
|
|
1139
|
+
const verify = await verifyPaneAtCapacity(windowName);
|
|
1140
|
+
if (!verify.atCapacity) {
|
|
1141
|
+
process.stderr.write(
|
|
1142
|
+
`[capacity-monitor] verifyPaneAtCapacity rejected kill for ${agentId} in ${windowName} (reason: ${verify.reason}). Skipping.
|
|
1143
|
+
`
|
|
1144
|
+
);
|
|
1145
|
+
void recordSessionKill({
|
|
1146
|
+
sessionName: windowName,
|
|
1147
|
+
agentId,
|
|
1148
|
+
reason: "capacity_false_positive_blocked"
|
|
1149
|
+
});
|
|
1150
|
+
continue;
|
|
1151
|
+
}
|
|
1152
|
+
process.stderr.write(
|
|
1153
|
+
`[capacity-monitor] Detected ${agentId} at capacity in session ${windowName} (confirmed). Auto-relaunching.
|
|
1154
|
+
`
|
|
1155
|
+
);
|
|
1156
|
+
try {
|
|
1157
|
+
transport.kill(windowName);
|
|
1158
|
+
void recordSessionKill({
|
|
1159
|
+
sessionName: windowName,
|
|
1160
|
+
agentId,
|
|
1161
|
+
reason: "capacity"
|
|
1162
|
+
});
|
|
1163
|
+
const client = getClient();
|
|
1164
|
+
const openTasks = await client.execute({
|
|
1165
|
+
sql: `SELECT id, title, priority, task_file, status
|
|
1166
|
+
FROM tasks
|
|
1167
|
+
WHERE assigned_to = ? AND status IN ('open', 'in_progress')
|
|
1168
|
+
ORDER BY
|
|
1169
|
+
CASE priority WHEN 'p0' THEN 0 WHEN 'p1' THEN 1 WHEN 'p2' THEN 2 ELSE 3 END,
|
|
1170
|
+
created_at ASC
|
|
1171
|
+
LIMIT 10`,
|
|
1172
|
+
args: [agentId]
|
|
1173
|
+
});
|
|
1174
|
+
if (openTasks.rows.length === 0) {
|
|
1175
|
+
process.stderr.write(
|
|
1176
|
+
`[capacity-monitor] ${agentId} has no open tasks \u2014 skipping relaunch.
|
|
1177
|
+
`
|
|
1178
|
+
);
|
|
1179
|
+
continue;
|
|
1180
|
+
}
|
|
1181
|
+
const { created } = await createOrRefreshResumeTask(
|
|
1182
|
+
agentId,
|
|
1183
|
+
projectDir,
|
|
1184
|
+
openTasks.rows
|
|
1185
|
+
);
|
|
1186
|
+
if (created) {
|
|
1187
|
+
await writeNotification({
|
|
1188
|
+
agentId: "system",
|
|
1189
|
+
agentRole: "daemon",
|
|
1190
|
+
event: "capacity_relaunch",
|
|
1191
|
+
project: projectDir.split("/").pop() ?? "unknown",
|
|
1192
|
+
summary: `${agentId} hit context capacity. Auto-relaunched with ${openTasks.rows.length} open task(s).`
|
|
1193
|
+
});
|
|
1194
|
+
}
|
|
1195
|
+
_lastRelaunch.set(agentId, Date.now());
|
|
1196
|
+
if (created) relaunched.push(agentId);
|
|
1197
|
+
} catch (err) {
|
|
1198
|
+
process.stderr.write(
|
|
1199
|
+
`[capacity-monitor] Failed to relaunch ${agentId}: ${err instanceof Error ? err.message : String(err)}
|
|
1200
|
+
`
|
|
1201
|
+
);
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
return relaunched;
|
|
1205
|
+
}
|
|
1206
|
+
var CAPACITY_PATTERNS, CONTENT_LINE_PREFIX, CONTENT_LINE_MARKERS, SOURCE_CODE_MARKERS, RELAUNCH_COOLDOWN_MS, _lastRelaunch, RESUME_TITLE_PREFIX, RESUME_TITLE_LIKE_PATTERN, RESUME_ACTIVE_STATUSES, CONFIRMATION_WINDOW_MS, _pendingCapacityKill, CC_CONTEXT_BAR_RE, CTX_FLOOR_PERCENT;
|
|
1207
|
+
var init_capacity_monitor = __esm({
|
|
1208
|
+
"src/lib/capacity-monitor.ts"() {
|
|
1209
|
+
"use strict";
|
|
1210
|
+
init_session_registry();
|
|
1211
|
+
init_transport();
|
|
1212
|
+
init_notifications();
|
|
1213
|
+
init_database();
|
|
1214
|
+
init_session_kill_telemetry();
|
|
1215
|
+
init_tmux_routing();
|
|
1216
|
+
CAPACITY_PATTERNS = [
|
|
1217
|
+
/conversation is too long/i,
|
|
1218
|
+
/maximum context length/i,
|
|
1219
|
+
/context window.*(?:limit|exceed|full)/i,
|
|
1220
|
+
/reached.*(?:token|context).*limit/i
|
|
1221
|
+
];
|
|
1222
|
+
CONTENT_LINE_PREFIX = /^[\s>#\-*[]/;
|
|
1223
|
+
CONTENT_LINE_MARKERS = [
|
|
1224
|
+
"RESUME:",
|
|
1225
|
+
"intercom",
|
|
1226
|
+
"capacity-monitor",
|
|
1227
|
+
"CAPACITY_PATTERNS",
|
|
1228
|
+
"isAtCapacity",
|
|
1229
|
+
"CONTENT_LINE_MARKERS",
|
|
1230
|
+
"pollCapacityDead",
|
|
1231
|
+
"confirmCapacityKill",
|
|
1232
|
+
"session_kills",
|
|
1233
|
+
"capacity-monitor.test"
|
|
1234
|
+
];
|
|
1235
|
+
SOURCE_CODE_MARKERS = [
|
|
1236
|
+
/["'`/].*(?:maximum context length|conversation is too long)/i,
|
|
1237
|
+
/(?:maximum context length|conversation is too long).*["'`/]/i
|
|
1238
|
+
];
|
|
1239
|
+
RELAUNCH_COOLDOWN_MS = 5 * 60 * 1e3;
|
|
1240
|
+
_lastRelaunch = /* @__PURE__ */ new Map();
|
|
1241
|
+
RESUME_TITLE_PREFIX = "RESUME:";
|
|
1242
|
+
RESUME_TITLE_LIKE_PATTERN = `${RESUME_TITLE_PREFIX} % hit context capacity%`;
|
|
1243
|
+
RESUME_ACTIVE_STATUSES = ["open", "in_progress"];
|
|
1244
|
+
CONFIRMATION_WINDOW_MS = 3 * 60 * 1e3;
|
|
1245
|
+
_pendingCapacityKill = /* @__PURE__ */ new Map();
|
|
1246
|
+
CC_CONTEXT_BAR_RE = /([\u2588\u2591\u2592\u2593]{10})\s+(\d+)%/;
|
|
1247
|
+
CTX_FLOOR_PERCENT = 50;
|
|
1248
|
+
}
|
|
1249
|
+
});
|
|
1250
|
+
|
|
1251
|
+
// src/lib/tmux-routing.ts
|
|
1252
|
+
var tmux_routing_exports = {};
|
|
1253
|
+
__export(tmux_routing_exports, {
|
|
1254
|
+
acquireSpawnLock: () => acquireSpawnLock,
|
|
1255
|
+
employeeSessionName: () => employeeSessionName,
|
|
1256
|
+
ensureEmployee: () => ensureEmployee,
|
|
1257
|
+
extractRootExe: () => extractRootExe,
|
|
1258
|
+
findFreeInstance: () => findFreeInstance,
|
|
1259
|
+
getDispatchedBy: () => getDispatchedBy,
|
|
1260
|
+
getMySession: () => getMySession,
|
|
1261
|
+
getParentExe: () => getParentExe,
|
|
1262
|
+
getSessionState: () => getSessionState,
|
|
1263
|
+
isEmployeeAlive: () => isEmployeeAlive,
|
|
1264
|
+
isExeSession: () => isExeSession,
|
|
1265
|
+
isSessionBusy: () => isSessionBusy,
|
|
1266
|
+
notifyParentExe: () => notifyParentExe,
|
|
1267
|
+
parseParentExe: () => parseParentExe,
|
|
1268
|
+
registerParentExe: () => registerParentExe,
|
|
1269
|
+
releaseSpawnLock: () => releaseSpawnLock,
|
|
1270
|
+
resolveExeSession: () => resolveExeSession,
|
|
1271
|
+
sendIntercom: () => sendIntercom,
|
|
1272
|
+
spawnEmployee: () => spawnEmployee,
|
|
1273
|
+
verifyPaneAtCapacity: () => verifyPaneAtCapacity
|
|
1274
|
+
});
|
|
1275
|
+
import { execFileSync as execFileSync2, execSync as execSync4 } from "child_process";
|
|
1276
|
+
import { readFileSync as readFileSync8, writeFileSync as writeFileSync4, mkdirSync as mkdirSync4, existsSync as existsSync8, appendFileSync } from "fs";
|
|
1277
|
+
import path8 from "path";
|
|
1278
|
+
import os5 from "os";
|
|
1279
|
+
import { fileURLToPath } from "url";
|
|
1280
|
+
import { unlinkSync as unlinkSync2 } from "fs";
|
|
1281
|
+
function spawnLockPath(sessionName) {
|
|
1282
|
+
return path8.join(SPAWN_LOCK_DIR, `${sessionName}.lock`);
|
|
1283
|
+
}
|
|
1284
|
+
function isProcessAlive(pid) {
|
|
1285
|
+
try {
|
|
1286
|
+
process.kill(pid, 0);
|
|
1287
|
+
return true;
|
|
1288
|
+
} catch {
|
|
1289
|
+
return false;
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
function acquireSpawnLock(sessionName) {
|
|
1293
|
+
if (!existsSync8(SPAWN_LOCK_DIR)) {
|
|
1294
|
+
mkdirSync4(SPAWN_LOCK_DIR, { recursive: true });
|
|
1295
|
+
}
|
|
1296
|
+
const lockFile = spawnLockPath(sessionName);
|
|
1297
|
+
if (existsSync8(lockFile)) {
|
|
1298
|
+
try {
|
|
1299
|
+
const lock = JSON.parse(readFileSync8(lockFile, "utf8"));
|
|
1300
|
+
const age = Date.now() - lock.timestamp;
|
|
1301
|
+
if (isProcessAlive(lock.pid) && age < 6e4) {
|
|
1302
|
+
return false;
|
|
1303
|
+
}
|
|
1304
|
+
} catch {
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
writeFileSync4(lockFile, JSON.stringify({ pid: process.pid, timestamp: Date.now() }));
|
|
1308
|
+
return true;
|
|
1309
|
+
}
|
|
1310
|
+
function releaseSpawnLock(sessionName) {
|
|
1311
|
+
try {
|
|
1312
|
+
unlinkSync2(spawnLockPath(sessionName));
|
|
1313
|
+
} catch {
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
function resolveBehaviorsExporterScript() {
|
|
1317
|
+
try {
|
|
1318
|
+
const thisFile = fileURLToPath(import.meta.url);
|
|
1319
|
+
const scriptPath = path8.join(
|
|
1320
|
+
path8.dirname(thisFile),
|
|
1321
|
+
"..",
|
|
1322
|
+
"bin",
|
|
1323
|
+
"exe-export-behaviors.js"
|
|
1324
|
+
);
|
|
1325
|
+
return existsSync8(scriptPath) ? scriptPath : null;
|
|
1326
|
+
} catch {
|
|
1327
|
+
return null;
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
function exportBehaviorsSync(agentId, projectName, sessionKey) {
|
|
1331
|
+
const script = resolveBehaviorsExporterScript();
|
|
1332
|
+
if (!script) return null;
|
|
1333
|
+
try {
|
|
1334
|
+
const output = execFileSync2(
|
|
1335
|
+
process.execPath,
|
|
1336
|
+
[script, agentId, projectName, sessionKey],
|
|
1337
|
+
{ encoding: "utf-8", timeout: BEHAVIORS_EXPORT_TIMEOUT_MS }
|
|
1338
|
+
).trim();
|
|
1339
|
+
return output.length > 0 ? output : null;
|
|
1340
|
+
} catch (err) {
|
|
1341
|
+
process.stderr.write(
|
|
1342
|
+
`[tmux-routing] behaviors export failed for ${agentId}: ${err instanceof Error ? err.message : String(err)}
|
|
1343
|
+
`
|
|
1344
|
+
);
|
|
1345
|
+
return null;
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
function getMySession() {
|
|
1349
|
+
return getTransport().getMySession();
|
|
1350
|
+
}
|
|
1351
|
+
function employeeSessionName(employee, exeSession, instance) {
|
|
1352
|
+
if (!/^exe\d+$/.test(exeSession)) {
|
|
1353
|
+
const root = extractRootExe(exeSession);
|
|
1354
|
+
if (root) {
|
|
1355
|
+
process.stderr.write(
|
|
1356
|
+
`[tmux-routing] WARN: exeSession="${exeSession}" is not a root exe session, using "${root}" instead
|
|
1357
|
+
`
|
|
1358
|
+
);
|
|
1359
|
+
exeSession = root;
|
|
1360
|
+
} else {
|
|
1361
|
+
throw new Error(
|
|
1362
|
+
`Invalid exeSession "${exeSession}" \u2014 must be a root exe session (e.g., "exe1"), not an agent session`
|
|
1363
|
+
);
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
const suffix = instance != null && instance > 0 ? String(instance) : "";
|
|
1367
|
+
const name = `${employee}${suffix}-${exeSession}`;
|
|
1368
|
+
if (!VALID_SESSION_NAME.test(name)) {
|
|
1369
|
+
throw new Error(
|
|
1370
|
+
`Invalid session name "${name}" \u2014 must match {agent}-exe{N} or {agent}{instance}-exe{N}`
|
|
1371
|
+
);
|
|
1372
|
+
}
|
|
1373
|
+
return name;
|
|
1374
|
+
}
|
|
1375
|
+
function parseParentExe(sessionName, agentId) {
|
|
1376
|
+
const escaped = agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1377
|
+
const regex = new RegExp(`^${escaped}\\d*-(.+)$`);
|
|
1378
|
+
const match = sessionName.match(regex);
|
|
1379
|
+
return match?.[1] ?? null;
|
|
1380
|
+
}
|
|
1381
|
+
function extractRootExe(name) {
|
|
1382
|
+
const match = name.match(/(exe\d+)$/);
|
|
1383
|
+
return match?.[1] ?? null;
|
|
1384
|
+
}
|
|
1385
|
+
function registerParentExe(sessionKey, parentExe, dispatchedBy) {
|
|
1386
|
+
if (!existsSync8(SESSION_CACHE)) {
|
|
1387
|
+
mkdirSync4(SESSION_CACHE, { recursive: true });
|
|
1388
|
+
}
|
|
1389
|
+
const rootExe = extractRootExe(parentExe) ?? parentExe;
|
|
1390
|
+
const filePath = path8.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`);
|
|
1391
|
+
writeFileSync4(filePath, JSON.stringify({
|
|
1392
|
+
parentExe: rootExe,
|
|
1393
|
+
dispatchedBy: dispatchedBy || rootExe,
|
|
1394
|
+
registeredAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1395
|
+
}));
|
|
1396
|
+
}
|
|
1397
|
+
function getParentExe(sessionKey) {
|
|
1398
|
+
try {
|
|
1399
|
+
const data = JSON.parse(readFileSync8(path8.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
|
|
1400
|
+
return data.parentExe || null;
|
|
1401
|
+
} catch {
|
|
1402
|
+
return null;
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
function getDispatchedBy(sessionKey) {
|
|
1406
|
+
try {
|
|
1407
|
+
const data = JSON.parse(readFileSync8(
|
|
1408
|
+
path8.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`),
|
|
1409
|
+
"utf8"
|
|
1410
|
+
));
|
|
1411
|
+
return data.dispatchedBy ?? data.parentExe ?? null;
|
|
1412
|
+
} catch {
|
|
1413
|
+
return null;
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
function resolveExeSession() {
|
|
1417
|
+
const mySession = getMySession();
|
|
1418
|
+
if (!mySession) return null;
|
|
1419
|
+
try {
|
|
1420
|
+
const key = getSessionKey();
|
|
1421
|
+
const parentExe = getParentExe(key);
|
|
1422
|
+
if (parentExe) {
|
|
1423
|
+
return extractRootExe(parentExe) ?? parentExe;
|
|
1424
|
+
}
|
|
1425
|
+
} catch {
|
|
1426
|
+
}
|
|
1427
|
+
return extractRootExe(mySession) ?? mySession;
|
|
1428
|
+
}
|
|
1429
|
+
function isEmployeeAlive(sessionName) {
|
|
1430
|
+
return getTransport().isAlive(sessionName);
|
|
1431
|
+
}
|
|
1432
|
+
function findFreeInstance(employeeName, exeSession, maxInstances = 10, isAlive = isEmployeeAlive) {
|
|
1433
|
+
const base = employeeSessionName(employeeName, exeSession);
|
|
1434
|
+
if (!isAlive(base) && acquireSpawnLock(base)) return 0;
|
|
1435
|
+
for (let i = 2; i <= maxInstances; i++) {
|
|
1436
|
+
const candidate = employeeSessionName(employeeName, exeSession, i);
|
|
1437
|
+
if (!isAlive(candidate) && acquireSpawnLock(candidate)) return i;
|
|
1438
|
+
}
|
|
1439
|
+
return null;
|
|
1440
|
+
}
|
|
1441
|
+
async function verifyPaneAtCapacity(sessionName) {
|
|
1442
|
+
const transport = getTransport();
|
|
1443
|
+
if (!transport.isAlive(sessionName)) {
|
|
1444
|
+
return { atCapacity: false, reason: `session ${sessionName} is not alive` };
|
|
1445
|
+
}
|
|
1446
|
+
let pane;
|
|
1447
|
+
try {
|
|
1448
|
+
pane = transport.capturePane(sessionName, VERIFY_PANE_LINES);
|
|
1449
|
+
} catch (err) {
|
|
1450
|
+
return {
|
|
1451
|
+
atCapacity: false,
|
|
1452
|
+
reason: `capture-pane failed: ${err instanceof Error ? err.message : String(err)}`
|
|
1453
|
+
};
|
|
1454
|
+
}
|
|
1455
|
+
const { isAtCapacity: isAtCapacity2 } = await Promise.resolve().then(() => (init_capacity_monitor(), capacity_monitor_exports));
|
|
1456
|
+
if (!isAtCapacity2(pane)) {
|
|
1457
|
+
return {
|
|
1458
|
+
atCapacity: false,
|
|
1459
|
+
reason: `last ${VERIFY_PANE_LINES} lines show normal work, no capacity banner`
|
|
1460
|
+
};
|
|
1461
|
+
}
|
|
1462
|
+
return {
|
|
1463
|
+
atCapacity: true,
|
|
1464
|
+
reason: "capacity banner matched in recent pane output"
|
|
1465
|
+
};
|
|
1466
|
+
}
|
|
1467
|
+
function readDebounceState() {
|
|
1468
|
+
try {
|
|
1469
|
+
if (!existsSync8(DEBOUNCE_FILE)) return {};
|
|
1470
|
+
return JSON.parse(readFileSync8(DEBOUNCE_FILE, "utf8"));
|
|
1471
|
+
} catch {
|
|
1472
|
+
return {};
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
function writeDebounceState(state) {
|
|
1476
|
+
try {
|
|
1477
|
+
if (!existsSync8(SESSION_CACHE)) mkdirSync4(SESSION_CACHE, { recursive: true });
|
|
1478
|
+
writeFileSync4(DEBOUNCE_FILE, JSON.stringify(state));
|
|
1479
|
+
} catch {
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
function isDebounced(targetSession) {
|
|
1483
|
+
const state = readDebounceState();
|
|
1484
|
+
const lastSent = state[targetSession] ?? 0;
|
|
1193
1485
|
return Date.now() - lastSent < INTERCOM_DEBOUNCE_MS;
|
|
1194
1486
|
}
|
|
1195
1487
|
function recordDebounce(targetSession) {
|
|
@@ -1228,6 +1520,10 @@ function getSessionState(sessionName) {
|
|
|
1228
1520
|
return "offline";
|
|
1229
1521
|
}
|
|
1230
1522
|
}
|
|
1523
|
+
function isSessionBusy(sessionName) {
|
|
1524
|
+
const state = getSessionState(sessionName);
|
|
1525
|
+
return state === "thinking" || state === "tool";
|
|
1526
|
+
}
|
|
1231
1527
|
function isExeSession(sessionName) {
|
|
1232
1528
|
return /^exe\d*$/.test(sessionName);
|
|
1233
1529
|
}
|
|
@@ -1273,297 +1569,912 @@ function sendIntercom(targetSession) {
|
|
|
1273
1569
|
return "failed";
|
|
1274
1570
|
}
|
|
1275
1571
|
}
|
|
1276
|
-
function
|
|
1277
|
-
|
|
1278
|
-
|
|
1572
|
+
function notifyParentExe(sessionKey) {
|
|
1573
|
+
const target = getDispatchedBy(sessionKey);
|
|
1574
|
+
if (!target) {
|
|
1575
|
+
process.stderr.write(`[intercom] notifyParentExe: no dispatcher found for key ${sessionKey}
|
|
1576
|
+
`);
|
|
1577
|
+
return false;
|
|
1578
|
+
}
|
|
1579
|
+
process.stderr.write(`[intercom] notifyParentExe \u2192 ${target}
|
|
1580
|
+
`);
|
|
1581
|
+
const result = sendIntercom(target);
|
|
1582
|
+
if (result === "failed") {
|
|
1583
|
+
const rootExe = resolveExeSession();
|
|
1584
|
+
if (rootExe && rootExe !== target) {
|
|
1585
|
+
process.stderr.write(`[intercom] notifyParentExe: dispatcher ${target} dead, falling back to root exe ${rootExe}
|
|
1586
|
+
`);
|
|
1587
|
+
const fallback = sendIntercom(rootExe);
|
|
1588
|
+
return fallback !== "failed";
|
|
1589
|
+
}
|
|
1590
|
+
return false;
|
|
1591
|
+
}
|
|
1592
|
+
return true;
|
|
1593
|
+
}
|
|
1594
|
+
function ensureEmployee(employeeName, exeSession, projectDir, opts) {
|
|
1595
|
+
if (employeeName === "exe") {
|
|
1596
|
+
return { status: "failed", sessionName: "", error: "exe is the COO, not a dispatchable employee" };
|
|
1597
|
+
}
|
|
1598
|
+
try {
|
|
1599
|
+
assertEmployeeLimitSync();
|
|
1600
|
+
} catch (err) {
|
|
1601
|
+
if (err instanceof PlanLimitError) {
|
|
1602
|
+
return { status: "failed", sessionName: "", error: err.message };
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
if (/-exe\d*$/.test(employeeName)) {
|
|
1606
|
+
const bare = employeeName.replace(/-exe\d*$/, "").replace(/\d+$/, "");
|
|
1607
|
+
return {
|
|
1608
|
+
status: "failed",
|
|
1609
|
+
sessionName: "",
|
|
1610
|
+
error: `Error: pass employee name ('${bare}'), not session name ('${employeeName}')`
|
|
1611
|
+
};
|
|
1612
|
+
}
|
|
1613
|
+
if (!/^exe\d+$/.test(exeSession)) {
|
|
1614
|
+
const root = extractRootExe(exeSession);
|
|
1615
|
+
if (root) {
|
|
1616
|
+
process.stderr.write(
|
|
1617
|
+
`[ensureEmployee] WARN: caller passed exeSession="${exeSession}" (not a root exe). Auto-correcting to "${root}".
|
|
1618
|
+
`
|
|
1619
|
+
);
|
|
1620
|
+
exeSession = root;
|
|
1621
|
+
} else {
|
|
1622
|
+
return {
|
|
1623
|
+
status: "failed",
|
|
1624
|
+
sessionName: "",
|
|
1625
|
+
error: `Invalid exeSession "${exeSession}" \u2014 must be a root exe session (e.g., "exe1")`
|
|
1626
|
+
};
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
let effectiveInstance = opts?.instance;
|
|
1630
|
+
if (effectiveInstance === void 0 && opts?.autoInstance) {
|
|
1631
|
+
const free = findFreeInstance(
|
|
1632
|
+
employeeName,
|
|
1633
|
+
exeSession,
|
|
1634
|
+
opts.maxAutoInstances ?? 10
|
|
1635
|
+
);
|
|
1636
|
+
if (free === null) {
|
|
1637
|
+
return {
|
|
1638
|
+
status: "failed",
|
|
1639
|
+
sessionName: employeeSessionName(employeeName, exeSession),
|
|
1640
|
+
error: `All ${opts.maxAutoInstances ?? 10} instances of ${employeeName} are alive \u2014 cap reached`
|
|
1641
|
+
};
|
|
1642
|
+
}
|
|
1643
|
+
effectiveInstance = free === 0 ? void 0 : free;
|
|
1644
|
+
}
|
|
1645
|
+
const sessionName = employeeSessionName(employeeName, exeSession, effectiveInstance);
|
|
1646
|
+
if (isEmployeeAlive(sessionName)) {
|
|
1647
|
+
const result2 = sendIntercom(sessionName);
|
|
1648
|
+
if (result2 === "acknowledged" || result2 === "skipped_exe" || result2 === "debounced" || result2 === "queued") {
|
|
1649
|
+
return { status: "intercom_sent", sessionName };
|
|
1650
|
+
}
|
|
1651
|
+
if (result2 === "delivered") {
|
|
1652
|
+
return { status: "intercom_unprocessed", sessionName };
|
|
1653
|
+
}
|
|
1654
|
+
return { status: "failed", sessionName, error: "intercom delivery failed" };
|
|
1655
|
+
}
|
|
1656
|
+
const spawnOpts = { ...opts, instance: effectiveInstance };
|
|
1657
|
+
const result = spawnEmployee(employeeName, exeSession, projectDir, spawnOpts);
|
|
1658
|
+
if (result.error) {
|
|
1659
|
+
return { status: "failed", sessionName, error: result.error };
|
|
1660
|
+
}
|
|
1661
|
+
return { status: "spawned", sessionName };
|
|
1662
|
+
}
|
|
1663
|
+
function spawnEmployee(employeeName, exeSession, projectDir, opts) {
|
|
1664
|
+
const transport = getTransport();
|
|
1665
|
+
const sessionName = employeeSessionName(employeeName, exeSession, opts?.instance);
|
|
1666
|
+
const instanceLabel = opts?.instance != null && opts.instance > 0 ? `${employeeName}${opts.instance}` : employeeName;
|
|
1667
|
+
const logDir = path8.join(os5.homedir(), ".exe-os", "session-logs");
|
|
1668
|
+
const logFile = path8.join(logDir, `${instanceLabel}-${Date.now()}.log`);
|
|
1669
|
+
if (!existsSync8(logDir)) {
|
|
1670
|
+
mkdirSync4(logDir, { recursive: true });
|
|
1671
|
+
}
|
|
1672
|
+
transport.kill(sessionName);
|
|
1673
|
+
let cleanupSuffix = "";
|
|
1674
|
+
try {
|
|
1675
|
+
const thisFile = fileURLToPath(import.meta.url);
|
|
1676
|
+
const cleanupScript = path8.join(path8.dirname(thisFile), "..", "bin", "exe-session-cleanup.js");
|
|
1677
|
+
if (existsSync8(cleanupScript)) {
|
|
1678
|
+
cleanupSuffix = `; ${process.execPath} "${cleanupScript}" "${employeeName}" "${exeSession}"`;
|
|
1679
|
+
}
|
|
1680
|
+
} catch {
|
|
1681
|
+
}
|
|
1682
|
+
try {
|
|
1683
|
+
const claudeJsonPath = path8.join(os5.homedir(), ".claude.json");
|
|
1684
|
+
let claudeJson = {};
|
|
1685
|
+
try {
|
|
1686
|
+
claudeJson = JSON.parse(readFileSync8(claudeJsonPath, "utf8"));
|
|
1687
|
+
} catch {
|
|
1688
|
+
}
|
|
1689
|
+
if (!claudeJson.projects) claudeJson.projects = {};
|
|
1690
|
+
const projects = claudeJson.projects;
|
|
1691
|
+
const trustDir = opts?.cwd ?? projectDir;
|
|
1692
|
+
if (!projects[trustDir]) projects[trustDir] = {};
|
|
1693
|
+
projects[trustDir].hasTrustDialogAccepted = true;
|
|
1694
|
+
writeFileSync4(claudeJsonPath, JSON.stringify(claudeJson, null, 2) + "\n");
|
|
1695
|
+
} catch {
|
|
1696
|
+
}
|
|
1697
|
+
try {
|
|
1698
|
+
const settingsDir = path8.join(os5.homedir(), ".claude", "projects");
|
|
1699
|
+
const normalizedKey = (opts?.cwd ?? projectDir).replace(/\//g, "-").replace(/^-/, "");
|
|
1700
|
+
const projSettingsDir = path8.join(settingsDir, normalizedKey);
|
|
1701
|
+
const settingsPath = path8.join(projSettingsDir, "settings.json");
|
|
1702
|
+
let settings = {};
|
|
1703
|
+
try {
|
|
1704
|
+
settings = JSON.parse(readFileSync8(settingsPath, "utf8"));
|
|
1705
|
+
} catch {
|
|
1706
|
+
}
|
|
1707
|
+
const perms = settings.permissions ?? {};
|
|
1708
|
+
const allow = perms.allow ?? [];
|
|
1709
|
+
const toolNames = [
|
|
1710
|
+
"recall_my_memory",
|
|
1711
|
+
"store_memory",
|
|
1712
|
+
"create_task",
|
|
1713
|
+
"update_task",
|
|
1714
|
+
"list_tasks",
|
|
1715
|
+
"get_task",
|
|
1716
|
+
"ask_team_memory",
|
|
1717
|
+
"store_behavior",
|
|
1718
|
+
"get_identity",
|
|
1719
|
+
"send_message"
|
|
1720
|
+
];
|
|
1721
|
+
const requiredTools = expandDualPrefixTools(toolNames);
|
|
1722
|
+
let changed = false;
|
|
1723
|
+
for (const tool of requiredTools) {
|
|
1724
|
+
if (!allow.includes(tool)) {
|
|
1725
|
+
allow.push(tool);
|
|
1726
|
+
changed = true;
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
if (changed) {
|
|
1730
|
+
perms.allow = allow;
|
|
1731
|
+
settings.permissions = perms;
|
|
1732
|
+
mkdirSync4(projSettingsDir, { recursive: true });
|
|
1733
|
+
writeFileSync4(settingsPath, JSON.stringify(settings, null, 2) + "\n");
|
|
1734
|
+
}
|
|
1735
|
+
} catch {
|
|
1736
|
+
}
|
|
1737
|
+
const spawnCwd = opts?.cwd ?? projectDir;
|
|
1738
|
+
const useExeAgent = !!(opts?.model && opts?.provider);
|
|
1739
|
+
const ccProvider = useExeAgent ? DEFAULT_PROVIDER : detectActiveProvider();
|
|
1740
|
+
const useBinSymlink = ccProvider !== DEFAULT_PROVIDER;
|
|
1741
|
+
let identityFlag = "";
|
|
1742
|
+
let behaviorsFlag = "";
|
|
1743
|
+
let legacyFallbackWarned = false;
|
|
1744
|
+
if (!useExeAgent && !useBinSymlink) {
|
|
1745
|
+
const identityPath = path8.join(
|
|
1746
|
+
os5.homedir(),
|
|
1747
|
+
".exe-os",
|
|
1748
|
+
"identity",
|
|
1749
|
+
`${employeeName}.md`
|
|
1750
|
+
);
|
|
1751
|
+
_resetCcAgentSupportCache();
|
|
1752
|
+
const hasAgentFlag = claudeSupportsAgentFlag();
|
|
1753
|
+
if (hasAgentFlag) {
|
|
1754
|
+
identityFlag = ` --agent ${employeeName}`;
|
|
1755
|
+
} else if (existsSync8(identityPath)) {
|
|
1756
|
+
identityFlag = ` --append-system-prompt-file ${identityPath}`;
|
|
1757
|
+
legacyFallbackWarned = true;
|
|
1758
|
+
}
|
|
1759
|
+
const behaviorsFile = exportBehaviorsSync(
|
|
1760
|
+
employeeName,
|
|
1761
|
+
path8.basename(spawnCwd),
|
|
1762
|
+
sessionName
|
|
1763
|
+
);
|
|
1764
|
+
if (behaviorsFile) {
|
|
1765
|
+
behaviorsFlag = ` --append-system-prompt-file ${behaviorsFile}`;
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1768
|
+
if (legacyFallbackWarned) {
|
|
1769
|
+
process.stderr.write(
|
|
1770
|
+
`[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.
|
|
1771
|
+
`
|
|
1772
|
+
);
|
|
1773
|
+
}
|
|
1774
|
+
let sessionContextFlag = "";
|
|
1775
|
+
try {
|
|
1776
|
+
const ctxDir = path8.join(os5.homedir(), ".exe-os", "session-cache");
|
|
1777
|
+
mkdirSync4(ctxDir, { recursive: true });
|
|
1778
|
+
const ctxFile = path8.join(ctxDir, `session-context-${sessionName}.md`);
|
|
1779
|
+
const ctxContent = [
|
|
1780
|
+
`## Session Context`,
|
|
1781
|
+
`You are running in tmux session: ${sessionName}.`,
|
|
1782
|
+
`Your parent exe session is ${exeSession}.`,
|
|
1783
|
+
`Your employees (if any) use the -${exeSession} suffix (e.g., tom-${exeSession}).`
|
|
1784
|
+
].join("\n");
|
|
1785
|
+
writeFileSync4(ctxFile, ctxContent);
|
|
1786
|
+
sessionContextFlag = ` --append-system-prompt-file ${ctxFile}`;
|
|
1787
|
+
} catch {
|
|
1788
|
+
}
|
|
1789
|
+
let envPrefix = `EXE_SESSION=${exeSession} EXE_SESSION_NAME=${sessionName}`;
|
|
1790
|
+
if (ccProvider !== DEFAULT_PROVIDER) {
|
|
1791
|
+
const cfg = PROVIDER_TABLE[ccProvider];
|
|
1792
|
+
if (cfg?.apiKeyEnv) {
|
|
1793
|
+
const keyVal = process.env[cfg.apiKeyEnv];
|
|
1794
|
+
if (keyVal) {
|
|
1795
|
+
envPrefix = `${envPrefix} ${cfg.apiKeyEnv}=${keyVal}`;
|
|
1796
|
+
}
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
let spawnCommand;
|
|
1800
|
+
if (useExeAgent) {
|
|
1801
|
+
spawnCommand = `${envPrefix} exe-agent --employee ${employeeName} --model ${opts.model} --provider ${opts.provider}${cleanupSuffix}`;
|
|
1802
|
+
} else if (useBinSymlink) {
|
|
1803
|
+
const binName = `${employeeName}-${ccProvider}`;
|
|
1804
|
+
process.stderr.write(
|
|
1805
|
+
`[tmux-routing] provider cascade: ${ccProvider} \u2192 spawning ${binName}
|
|
1806
|
+
`
|
|
1807
|
+
);
|
|
1808
|
+
spawnCommand = `${envPrefix} ${binName}${cleanupSuffix}`;
|
|
1809
|
+
} else {
|
|
1810
|
+
spawnCommand = `${envPrefix} claude --dangerously-skip-permissions${identityFlag}${behaviorsFlag}${sessionContextFlag}${cleanupSuffix}`;
|
|
1811
|
+
}
|
|
1812
|
+
const spawnResult = transport.spawn(sessionName, {
|
|
1813
|
+
cwd: spawnCwd,
|
|
1814
|
+
command: spawnCommand
|
|
1815
|
+
});
|
|
1816
|
+
if (spawnResult.error) {
|
|
1817
|
+
releaseSpawnLock(sessionName);
|
|
1818
|
+
return { sessionName, error: `tmux new-session failed: ${spawnResult.error}` };
|
|
1819
|
+
}
|
|
1820
|
+
transport.pipeLog(sessionName, logFile);
|
|
1821
|
+
try {
|
|
1822
|
+
const mySession = getMySession();
|
|
1823
|
+
const dispatchInfo = path8.join(SESSION_CACHE, `dispatch-info-${sessionName}.json`);
|
|
1824
|
+
writeFileSync4(dispatchInfo, JSON.stringify({
|
|
1825
|
+
dispatchedBy: mySession,
|
|
1826
|
+
rootExe: exeSession,
|
|
1827
|
+
provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
|
|
1828
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1829
|
+
}));
|
|
1830
|
+
} catch {
|
|
1831
|
+
}
|
|
1832
|
+
let booted = false;
|
|
1833
|
+
for (let i = 0; i < 30; i++) {
|
|
1834
|
+
try {
|
|
1835
|
+
execSync4("sleep 0.5");
|
|
1836
|
+
} catch {
|
|
1837
|
+
}
|
|
1838
|
+
try {
|
|
1839
|
+
const pane = transport.capturePane(sessionName);
|
|
1840
|
+
if (useExeAgent) {
|
|
1841
|
+
if (pane.includes("[exe-agent]") || pane.includes("online")) {
|
|
1842
|
+
booted = true;
|
|
1843
|
+
break;
|
|
1844
|
+
}
|
|
1845
|
+
} else {
|
|
1846
|
+
if (pane.includes("Claude Code") || pane.includes("\u276F")) {
|
|
1847
|
+
booted = true;
|
|
1848
|
+
break;
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
} catch {
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
if (!booted) {
|
|
1855
|
+
releaseSpawnLock(sessionName);
|
|
1856
|
+
return { sessionName, error: `${useExeAgent ? "exe-agent" : "claude"} did not boot within 15s` };
|
|
1857
|
+
}
|
|
1858
|
+
if (!useExeAgent) {
|
|
1859
|
+
try {
|
|
1860
|
+
transport.sendKeys(sessionName, `/exe-call ${employeeName}`);
|
|
1861
|
+
} catch {
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
registerSession({
|
|
1865
|
+
windowName: sessionName,
|
|
1866
|
+
agentId: employeeName,
|
|
1867
|
+
projectDir: spawnCwd,
|
|
1868
|
+
parentExe: exeSession,
|
|
1869
|
+
pid: 0,
|
|
1870
|
+
registeredAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1871
|
+
});
|
|
1872
|
+
releaseSpawnLock(sessionName);
|
|
1873
|
+
return { sessionName };
|
|
1874
|
+
}
|
|
1875
|
+
var SPAWN_LOCK_DIR, SESSION_CACHE, BEHAVIORS_EXPORT_TIMEOUT_MS, VALID_SESSION_NAME, VERIFY_PANE_LINES, INTERCOM_DEBOUNCE_MS, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS, BUSY_PATTERN;
|
|
1876
|
+
var init_tmux_routing = __esm({
|
|
1877
|
+
"src/lib/tmux-routing.ts"() {
|
|
1878
|
+
"use strict";
|
|
1879
|
+
init_session_registry();
|
|
1880
|
+
init_session_key();
|
|
1881
|
+
init_transport();
|
|
1882
|
+
init_cc_agent_support();
|
|
1883
|
+
init_mcp_prefix();
|
|
1884
|
+
init_provider_table();
|
|
1885
|
+
init_intercom_queue();
|
|
1886
|
+
init_plan_limits();
|
|
1887
|
+
SPAWN_LOCK_DIR = path8.join(os5.homedir(), ".exe-os", "spawn-locks");
|
|
1888
|
+
SESSION_CACHE = path8.join(os5.homedir(), ".exe-os", "session-cache");
|
|
1889
|
+
BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
|
|
1890
|
+
VALID_SESSION_NAME = /^[a-z]+-exe\d+$|^[a-z]+\d+-exe\d+$/;
|
|
1891
|
+
VERIFY_PANE_LINES = 200;
|
|
1892
|
+
INTERCOM_DEBOUNCE_MS = 3e4;
|
|
1893
|
+
INTERCOM_LOG2 = path8.join(os5.homedir(), ".exe-os", "intercom.log");
|
|
1894
|
+
DEBOUNCE_FILE = path8.join(SESSION_CACHE, "intercom-debounce.json");
|
|
1895
|
+
DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
|
|
1896
|
+
BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
|
|
1897
|
+
}
|
|
1898
|
+
});
|
|
1899
|
+
|
|
1900
|
+
// src/lib/tasks-crud.ts
|
|
1901
|
+
import crypto3 from "crypto";
|
|
1902
|
+
import path9 from "path";
|
|
1903
|
+
import { execSync as execSync5 } from "child_process";
|
|
1904
|
+
import { mkdir as mkdir3, writeFile as writeFile3, appendFile } from "fs/promises";
|
|
1905
|
+
import { existsSync as existsSync9, readFileSync as readFileSync9 } from "fs";
|
|
1906
|
+
async function writeCheckpoint(input) {
|
|
1907
|
+
const client = getClient();
|
|
1908
|
+
const row = await resolveTask(client, input.taskId);
|
|
1909
|
+
const taskId = String(row.id);
|
|
1910
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1911
|
+
const blockedByIds = [];
|
|
1912
|
+
if (row.blocked_by) {
|
|
1913
|
+
blockedByIds.push(String(row.blocked_by));
|
|
1914
|
+
}
|
|
1915
|
+
const checkpoint = {
|
|
1916
|
+
step: input.step,
|
|
1917
|
+
context_summary: input.contextSummary,
|
|
1918
|
+
files_touched: input.filesTouched ?? [],
|
|
1919
|
+
blocked_by_ids: blockedByIds,
|
|
1920
|
+
last_checkpoint_at: now
|
|
1921
|
+
};
|
|
1922
|
+
const result = await client.execute({
|
|
1923
|
+
sql: `UPDATE tasks SET checkpoint = ?, checkpoint_count = checkpoint_count + 1, updated_at = ? WHERE id = ?`,
|
|
1924
|
+
args: [JSON.stringify(checkpoint), now, taskId]
|
|
1925
|
+
});
|
|
1926
|
+
if (result.rowsAffected === 0) {
|
|
1927
|
+
throw new Error(`Checkpoint write failed: task ${taskId} not found`);
|
|
1928
|
+
}
|
|
1929
|
+
const countResult = await client.execute({
|
|
1930
|
+
sql: "SELECT checkpoint_count FROM tasks WHERE id = ?",
|
|
1931
|
+
args: [taskId]
|
|
1932
|
+
});
|
|
1933
|
+
const checkpointCount = Number(countResult.rows[0]?.checkpoint_count ?? 1);
|
|
1934
|
+
return { checkpointCount };
|
|
1935
|
+
}
|
|
1936
|
+
function extractParentFromContext(contextBody) {
|
|
1937
|
+
if (!contextBody) return null;
|
|
1938
|
+
const match = contextBody.match(
|
|
1939
|
+
/Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
|
|
1940
|
+
);
|
|
1941
|
+
return match ? match[1].toLowerCase() : null;
|
|
1942
|
+
}
|
|
1943
|
+
function slugify(title) {
|
|
1944
|
+
return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
|
|
1945
|
+
}
|
|
1946
|
+
async function resolveTask(client, identifier) {
|
|
1947
|
+
let result = await client.execute({
|
|
1948
|
+
sql: "SELECT * FROM tasks WHERE id = ?",
|
|
1949
|
+
args: [identifier]
|
|
1950
|
+
});
|
|
1951
|
+
if (result.rows.length === 1) return result.rows[0];
|
|
1952
|
+
result = await client.execute({
|
|
1953
|
+
sql: "SELECT * FROM tasks WHERE task_file LIKE ?",
|
|
1954
|
+
args: [`%${identifier}%`]
|
|
1955
|
+
});
|
|
1956
|
+
if (result.rows.length === 1) return result.rows[0];
|
|
1957
|
+
if (result.rows.length > 1) {
|
|
1958
|
+
const exact = result.rows.filter(
|
|
1959
|
+
(r) => String(r.task_file).endsWith(`/${identifier}.md`)
|
|
1960
|
+
);
|
|
1961
|
+
if (exact.length === 1) return exact[0];
|
|
1962
|
+
const candidates = exact.length > 1 ? exact : result.rows;
|
|
1963
|
+
const active = candidates.filter(
|
|
1964
|
+
(r) => !["done", "cancelled"].includes(String(r.status))
|
|
1965
|
+
);
|
|
1966
|
+
if (active.length === 1) return active[0];
|
|
1967
|
+
const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
|
|
1968
|
+
throw new Error(
|
|
1969
|
+
`Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
|
|
1970
|
+
);
|
|
1971
|
+
}
|
|
1972
|
+
result = await client.execute({
|
|
1973
|
+
sql: "SELECT * FROM tasks WHERE title LIKE ?",
|
|
1974
|
+
args: [`%${identifier}%`]
|
|
1975
|
+
});
|
|
1976
|
+
if (result.rows.length === 1) return result.rows[0];
|
|
1977
|
+
if (result.rows.length > 1) {
|
|
1978
|
+
const active = result.rows.filter(
|
|
1979
|
+
(r) => !["done", "cancelled"].includes(String(r.status))
|
|
1980
|
+
);
|
|
1981
|
+
if (active.length === 1) return active[0];
|
|
1982
|
+
const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
|
|
1983
|
+
throw new Error(
|
|
1984
|
+
`Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
|
|
1985
|
+
);
|
|
1986
|
+
}
|
|
1987
|
+
throw new Error(`Task not found: ${identifier}`);
|
|
1988
|
+
}
|
|
1989
|
+
async function createTaskCore(input) {
|
|
1990
|
+
const client = getClient();
|
|
1991
|
+
const id = crypto3.randomUUID();
|
|
1992
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1993
|
+
const slug = slugify(input.title);
|
|
1994
|
+
const taskFile = input.taskFile ?? `exe/${input.assignedTo}/${slug}.md`;
|
|
1995
|
+
let blockedById = null;
|
|
1996
|
+
const initialStatus = input.blockedBy ? "blocked" : "open";
|
|
1997
|
+
if (input.blockedBy) {
|
|
1998
|
+
const blocker = await resolveTask(client, input.blockedBy);
|
|
1999
|
+
blockedById = String(blocker.id);
|
|
2000
|
+
}
|
|
2001
|
+
let parentTaskId = null;
|
|
2002
|
+
let parentRef = input.parentTaskId;
|
|
2003
|
+
if (!parentRef) {
|
|
2004
|
+
const extracted = extractParentFromContext(input.context);
|
|
2005
|
+
if (extracted) {
|
|
2006
|
+
parentRef = extracted;
|
|
2007
|
+
process.stderr.write(
|
|
2008
|
+
"[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
|
|
2009
|
+
);
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
if (parentRef) {
|
|
2013
|
+
try {
|
|
2014
|
+
const parent = await resolveTask(client, parentRef);
|
|
2015
|
+
parentTaskId = String(parent.id);
|
|
2016
|
+
} catch (err) {
|
|
2017
|
+
if (!input.parentTaskId) {
|
|
2018
|
+
throw new Error(
|
|
2019
|
+
`create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
|
|
2020
|
+
);
|
|
2021
|
+
}
|
|
2022
|
+
throw err;
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
let warning;
|
|
2026
|
+
const dupCheck = await client.execute({
|
|
2027
|
+
sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
|
|
2028
|
+
args: [input.title, input.assignedTo]
|
|
2029
|
+
});
|
|
2030
|
+
if (dupCheck.rows.length > 0) {
|
|
2031
|
+
warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
|
|
2032
|
+
}
|
|
2033
|
+
if (input.baseDir) {
|
|
2034
|
+
try {
|
|
2035
|
+
await mkdir3(path9.join(input.baseDir, "exe", "output"), { recursive: true });
|
|
2036
|
+
await mkdir3(path9.join(input.baseDir, "exe", "research"), { recursive: true });
|
|
2037
|
+
await ensureArchitectureDoc(input.baseDir, input.projectName);
|
|
2038
|
+
await ensureGitignoreExe(input.baseDir);
|
|
2039
|
+
} catch {
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
const complexity = input.complexity ?? "standard";
|
|
2043
|
+
let sessionScope = null;
|
|
2044
|
+
try {
|
|
2045
|
+
const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
|
|
2046
|
+
sessionScope = resolveExeSession2();
|
|
2047
|
+
} catch {
|
|
2048
|
+
}
|
|
2049
|
+
await client.execute({
|
|
2050
|
+
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, session_scope, created_at, updated_at)
|
|
2051
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
2052
|
+
args: [
|
|
2053
|
+
id,
|
|
2054
|
+
input.title,
|
|
2055
|
+
input.assignedTo,
|
|
2056
|
+
input.assignedBy,
|
|
2057
|
+
input.projectName,
|
|
2058
|
+
input.priority,
|
|
2059
|
+
initialStatus,
|
|
2060
|
+
taskFile,
|
|
2061
|
+
blockedById,
|
|
2062
|
+
parentTaskId,
|
|
2063
|
+
input.reviewer ?? null,
|
|
2064
|
+
input.context,
|
|
2065
|
+
complexity,
|
|
2066
|
+
input.budgetTokens ?? null,
|
|
2067
|
+
input.budgetFallbackModel ?? null,
|
|
2068
|
+
0,
|
|
2069
|
+
null,
|
|
2070
|
+
sessionScope,
|
|
2071
|
+
now,
|
|
2072
|
+
now
|
|
2073
|
+
]
|
|
2074
|
+
});
|
|
2075
|
+
return {
|
|
2076
|
+
id,
|
|
2077
|
+
title: input.title,
|
|
2078
|
+
assignedTo: input.assignedTo,
|
|
2079
|
+
assignedBy: input.assignedBy,
|
|
2080
|
+
projectName: input.projectName,
|
|
2081
|
+
priority: input.priority,
|
|
2082
|
+
status: initialStatus,
|
|
2083
|
+
taskFile,
|
|
2084
|
+
createdAt: now,
|
|
2085
|
+
updatedAt: now,
|
|
2086
|
+
warning,
|
|
2087
|
+
budgetTokens: input.budgetTokens ?? null,
|
|
2088
|
+
budgetFallbackModel: input.budgetFallbackModel ?? null,
|
|
2089
|
+
tokensUsed: 0,
|
|
2090
|
+
tokensWarnedAt: null
|
|
2091
|
+
};
|
|
2092
|
+
}
|
|
2093
|
+
async function listTasks(input) {
|
|
2094
|
+
const client = getClient();
|
|
2095
|
+
const conditions = [];
|
|
2096
|
+
const args = [];
|
|
2097
|
+
if (input.assignedTo) {
|
|
2098
|
+
conditions.push("assigned_to = ?");
|
|
2099
|
+
args.push(input.assignedTo);
|
|
2100
|
+
}
|
|
2101
|
+
if (input.status) {
|
|
2102
|
+
conditions.push("status = ?");
|
|
2103
|
+
args.push(input.status);
|
|
2104
|
+
} else {
|
|
2105
|
+
conditions.push("status IN ('open', 'in_progress', 'blocked')");
|
|
2106
|
+
}
|
|
2107
|
+
if (input.projectName) {
|
|
2108
|
+
conditions.push("project_name = ?");
|
|
2109
|
+
args.push(input.projectName);
|
|
2110
|
+
}
|
|
2111
|
+
if (input.priority) {
|
|
2112
|
+
conditions.push("priority = ?");
|
|
2113
|
+
args.push(input.priority);
|
|
1279
2114
|
}
|
|
1280
2115
|
try {
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
if (
|
|
1284
|
-
|
|
2116
|
+
const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
|
|
2117
|
+
const session = resolveExeSession2();
|
|
2118
|
+
if (session) {
|
|
2119
|
+
conditions.push("(session_scope IS NULL OR session_scope = ?)");
|
|
2120
|
+
args.push(session);
|
|
1285
2121
|
}
|
|
2122
|
+
} catch {
|
|
1286
2123
|
}
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
2124
|
+
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
2125
|
+
const result = await client.execute({
|
|
2126
|
+
sql: `SELECT * FROM tasks ${where} ORDER BY CASE status WHEN 'blocked' THEN 0 WHEN 'in_progress' THEN 1 WHEN 'open' THEN 2 ELSE 3 END, priority ASC, created_at DESC LIMIT 1000`,
|
|
2127
|
+
args
|
|
2128
|
+
});
|
|
2129
|
+
return result.rows.map((r) => ({
|
|
2130
|
+
id: String(r.id),
|
|
2131
|
+
title: String(r.title),
|
|
2132
|
+
assignedTo: String(r.assigned_to),
|
|
2133
|
+
assignedBy: String(r.assigned_by),
|
|
2134
|
+
projectName: String(r.project_name),
|
|
2135
|
+
priority: String(r.priority),
|
|
2136
|
+
status: String(r.status),
|
|
2137
|
+
taskFile: String(r.task_file),
|
|
2138
|
+
createdAt: String(r.created_at),
|
|
2139
|
+
updatedAt: String(r.updated_at),
|
|
2140
|
+
checkpointCount: Number(r.checkpoint_count ?? 0),
|
|
2141
|
+
budgetTokens: r.budget_tokens !== null ? Number(r.budget_tokens) : null,
|
|
2142
|
+
budgetFallbackModel: r.budget_fallback_model !== null ? String(r.budget_fallback_model) : null,
|
|
2143
|
+
tokensUsed: Number(r.tokens_used ?? 0),
|
|
2144
|
+
tokensWarnedAt: r.tokens_warned_at !== null ? Number(r.tokens_warned_at) : null
|
|
2145
|
+
}));
|
|
2146
|
+
}
|
|
2147
|
+
function checkStaleCompletion(taskContext, taskCreatedAt) {
|
|
2148
|
+
if (!taskContext) return null;
|
|
2149
|
+
if (!DELEGATION_KEYWORDS.test(taskContext)) return null;
|
|
2150
|
+
try {
|
|
2151
|
+
const since = new Date(taskCreatedAt).toISOString();
|
|
2152
|
+
const branch = execSync5(
|
|
2153
|
+
"git rev-parse --abbrev-ref HEAD 2>/dev/null",
|
|
2154
|
+
{ encoding: "utf8", timeout: 3e3 }
|
|
2155
|
+
).trim();
|
|
2156
|
+
const branchArg = branch && branch !== "HEAD" ? branch : "";
|
|
2157
|
+
const commitCount = execSync5(
|
|
2158
|
+
`git log --oneline --since="${since}" ${branchArg} 2>/dev/null | wc -l`,
|
|
2159
|
+
{ encoding: "utf8", timeout: 5e3 }
|
|
2160
|
+
).trim();
|
|
2161
|
+
const count = parseInt(commitCount, 10);
|
|
2162
|
+
if (count === 0) {
|
|
2163
|
+
return "WARNING: task closed with no new commits since creation. Verify work was actually produced.";
|
|
2164
|
+
}
|
|
2165
|
+
return null;
|
|
2166
|
+
} catch {
|
|
2167
|
+
return null;
|
|
1294
2168
|
}
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
2169
|
+
}
|
|
2170
|
+
async function updateTaskStatus(input) {
|
|
2171
|
+
const client = getClient();
|
|
2172
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
2173
|
+
const row = await resolveTask(client, input.taskId);
|
|
2174
|
+
const taskId = String(row.id);
|
|
2175
|
+
const taskFile = String(row.task_file);
|
|
2176
|
+
if (input.status === "done" && String(row.assigned_by) === "system" && taskFile.includes("review-")) {
|
|
2177
|
+
process.stderr.write(
|
|
2178
|
+
`[updateTask] Review task "${String(row.title)}" being marked done (assigned to ${String(row.assigned_to)})
|
|
2179
|
+
`
|
|
1301
2180
|
);
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
2181
|
+
}
|
|
2182
|
+
if (input.status === "done") {
|
|
2183
|
+
const existingRow = await client.execute({
|
|
2184
|
+
sql: "SELECT context, created_at FROM tasks WHERE id = ?",
|
|
2185
|
+
args: [taskId]
|
|
2186
|
+
});
|
|
2187
|
+
if (existingRow.rows.length > 0) {
|
|
2188
|
+
const ctx = existingRow.rows[0];
|
|
2189
|
+
const warning = checkStaleCompletion(ctx.context, ctx.created_at);
|
|
2190
|
+
if (warning) {
|
|
2191
|
+
input.result = input.result ? `\u26A0\uFE0F ${warning}
|
|
2192
|
+
|
|
2193
|
+
${input.result}` : `\u26A0\uFE0F ${warning}`;
|
|
2194
|
+
process.stderr.write(`[tasks] ${warning} (task: ${taskId})
|
|
2195
|
+
`);
|
|
2196
|
+
}
|
|
1308
2197
|
}
|
|
1309
|
-
effectiveInstance = free === 0 ? void 0 : free;
|
|
1310
2198
|
}
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
const
|
|
1314
|
-
|
|
1315
|
-
|
|
2199
|
+
if (input.status === "in_progress") {
|
|
2200
|
+
const tmuxSession = process.env.TMUX_PANE ?? process.env.MY_TMUX_SESSION ?? "unknown";
|
|
2201
|
+
const claim = await client.execute({
|
|
2202
|
+
sql: `UPDATE tasks
|
|
2203
|
+
SET status = 'in_progress', assigned_tmux = ?, updated_at = ?
|
|
2204
|
+
WHERE id = ? AND status = 'open'`,
|
|
2205
|
+
args: [tmuxSession, now, taskId]
|
|
2206
|
+
});
|
|
2207
|
+
if (claim.rowsAffected === 0) {
|
|
2208
|
+
const current = await client.execute({
|
|
2209
|
+
sql: "SELECT status, assigned_tmux FROM tasks WHERE id = ?",
|
|
2210
|
+
args: [taskId]
|
|
2211
|
+
});
|
|
2212
|
+
const cur = current.rows[0];
|
|
2213
|
+
const status = cur?.status ?? "unknown";
|
|
2214
|
+
const claimedBy = cur?.assigned_tmux ? ` (claimed by ${cur.assigned_tmux})` : "";
|
|
2215
|
+
throw new Error(`${TASK_ALREADY_CLAIMED_PREFIX}: task ${taskId} is ${status}${claimedBy}`);
|
|
1316
2216
|
}
|
|
1317
|
-
|
|
1318
|
-
|
|
2217
|
+
try {
|
|
2218
|
+
await writeCheckpoint({
|
|
2219
|
+
taskId,
|
|
2220
|
+
step: "claimed",
|
|
2221
|
+
contextSummary: `Task claimed by session. Transitioning open \u2192 in_progress.`
|
|
2222
|
+
});
|
|
2223
|
+
} catch {
|
|
1319
2224
|
}
|
|
1320
|
-
return {
|
|
2225
|
+
return { row, taskFile, now, taskId };
|
|
1321
2226
|
}
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
const instanceLabel = opts?.instance != null && opts.instance > 0 ? `${employeeName}${opts.instance}` : employeeName;
|
|
1333
|
-
const logDir = path9.join(os5.homedir(), ".exe-os", "session-logs");
|
|
1334
|
-
const logFile = path9.join(logDir, `${instanceLabel}-${Date.now()}.log`);
|
|
1335
|
-
if (!existsSync9(logDir)) {
|
|
1336
|
-
mkdirSync4(logDir, { recursive: true });
|
|
2227
|
+
if (input.result) {
|
|
2228
|
+
await client.execute({
|
|
2229
|
+
sql: "UPDATE tasks SET status = ?, result = ?, updated_at = ? WHERE id = ?",
|
|
2230
|
+
args: [input.status, input.result, now, taskId]
|
|
2231
|
+
});
|
|
2232
|
+
} else {
|
|
2233
|
+
await client.execute({
|
|
2234
|
+
sql: "UPDATE tasks SET status = ?, updated_at = ? WHERE id = ?",
|
|
2235
|
+
args: [input.status, now, taskId]
|
|
2236
|
+
});
|
|
1337
2237
|
}
|
|
1338
|
-
transport.kill(sessionName);
|
|
1339
|
-
let cleanupSuffix = "";
|
|
1340
2238
|
try {
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
}
|
|
2239
|
+
await writeCheckpoint({
|
|
2240
|
+
taskId,
|
|
2241
|
+
step: `status_transition:${input.status}`,
|
|
2242
|
+
contextSummary: input.result ? `Transitioned to ${input.status}. Result: ${input.result.slice(0, 500)}` : `Transitioned to ${input.status}.`
|
|
2243
|
+
});
|
|
1346
2244
|
} catch {
|
|
1347
2245
|
}
|
|
2246
|
+
return { row, taskFile, now, taskId };
|
|
2247
|
+
}
|
|
2248
|
+
async function deleteTaskCore(taskId, _baseDir) {
|
|
2249
|
+
const client = getClient();
|
|
2250
|
+
const row = await resolveTask(client, taskId);
|
|
2251
|
+
const id = String(row.id);
|
|
2252
|
+
const taskFile = String(row.task_file);
|
|
2253
|
+
const assignedTo = String(row.assigned_to);
|
|
2254
|
+
const assignedBy = String(row.assigned_by);
|
|
2255
|
+
await client.execute({ sql: "DELETE FROM tasks WHERE id = ?", args: [id] });
|
|
2256
|
+
const taskSlug = taskFile.split("/").pop()?.replace(".md", "") ?? "";
|
|
2257
|
+
return { taskFile, assignedTo, assignedBy, taskSlug };
|
|
2258
|
+
}
|
|
2259
|
+
async function ensureArchitectureDoc(baseDir, projectName) {
|
|
2260
|
+
const archPath = path9.join(baseDir, "exe", "ARCHITECTURE.md");
|
|
1348
2261
|
try {
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
2262
|
+
if (existsSync9(archPath)) return;
|
|
2263
|
+
const template = [
|
|
2264
|
+
`# ${projectName} \u2014 System Architecture`,
|
|
2265
|
+
"",
|
|
2266
|
+
"> Employees: read this before every task. Update it when you change system structure.",
|
|
2267
|
+
`> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
|
|
2268
|
+
"",
|
|
2269
|
+
"## Overview",
|
|
2270
|
+
"",
|
|
2271
|
+
"<!-- Describe what this system does, its main components, and how they connect. -->",
|
|
2272
|
+
"",
|
|
2273
|
+
"## Key Components",
|
|
2274
|
+
"",
|
|
2275
|
+
"<!-- List the major modules, services, or subsystems. -->",
|
|
2276
|
+
"",
|
|
2277
|
+
"## Data Flow",
|
|
2278
|
+
"",
|
|
2279
|
+
"<!-- How does data move through the system? What writes where? -->",
|
|
2280
|
+
"",
|
|
2281
|
+
"## Invariants",
|
|
2282
|
+
"",
|
|
2283
|
+
"<!-- Rules that must never be violated. What breaks if these are wrong? -->",
|
|
2284
|
+
"",
|
|
2285
|
+
"## Dependencies",
|
|
2286
|
+
"",
|
|
2287
|
+
"<!-- What depends on what? If I change X, what else is affected? -->",
|
|
2288
|
+
""
|
|
2289
|
+
].join("\n");
|
|
2290
|
+
await writeFile3(archPath, template, "utf-8");
|
|
1361
2291
|
} catch {
|
|
1362
2292
|
}
|
|
2293
|
+
}
|
|
2294
|
+
async function ensureGitignoreExe(baseDir) {
|
|
2295
|
+
const gitignorePath = path9.join(baseDir, ".gitignore");
|
|
1363
2296
|
try {
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
settings = JSON.parse(readFileSync9(settingsPath, "utf8"));
|
|
1371
|
-
} catch {
|
|
1372
|
-
}
|
|
1373
|
-
const perms = settings.permissions ?? {};
|
|
1374
|
-
const allow = perms.allow ?? [];
|
|
1375
|
-
const toolNames = [
|
|
1376
|
-
"recall_my_memory",
|
|
1377
|
-
"store_memory",
|
|
1378
|
-
"create_task",
|
|
1379
|
-
"update_task",
|
|
1380
|
-
"list_tasks",
|
|
1381
|
-
"get_task",
|
|
1382
|
-
"ask_team_memory",
|
|
1383
|
-
"store_behavior",
|
|
1384
|
-
"get_identity",
|
|
1385
|
-
"send_message"
|
|
1386
|
-
];
|
|
1387
|
-
const requiredTools = expandDualPrefixTools(toolNames);
|
|
1388
|
-
let changed = false;
|
|
1389
|
-
for (const tool of requiredTools) {
|
|
1390
|
-
if (!allow.includes(tool)) {
|
|
1391
|
-
allow.push(tool);
|
|
1392
|
-
changed = true;
|
|
1393
|
-
}
|
|
1394
|
-
}
|
|
1395
|
-
if (changed) {
|
|
1396
|
-
perms.allow = allow;
|
|
1397
|
-
settings.permissions = perms;
|
|
1398
|
-
mkdirSync4(projSettingsDir, { recursive: true });
|
|
1399
|
-
writeFileSync4(settingsPath, JSON.stringify(settings, null, 2) + "\n");
|
|
2297
|
+
if (existsSync9(gitignorePath)) {
|
|
2298
|
+
const content = readFileSync9(gitignorePath, "utf-8");
|
|
2299
|
+
if (/^\/?exe\/?$/m.test(content)) return;
|
|
2300
|
+
await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
|
|
2301
|
+
} else {
|
|
2302
|
+
await writeFile3(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
|
|
1400
2303
|
}
|
|
1401
2304
|
} catch {
|
|
1402
2305
|
}
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
const identityPath = path9.join(
|
|
1412
|
-
os5.homedir(),
|
|
1413
|
-
".exe-os",
|
|
1414
|
-
"identity",
|
|
1415
|
-
`${employeeName}.md`
|
|
1416
|
-
);
|
|
1417
|
-
_resetCcAgentSupportCache();
|
|
1418
|
-
const hasAgentFlag = claudeSupportsAgentFlag();
|
|
1419
|
-
if (hasAgentFlag) {
|
|
1420
|
-
identityFlag = ` --agent ${employeeName}`;
|
|
1421
|
-
} else if (existsSync9(identityPath)) {
|
|
1422
|
-
identityFlag = ` --append-system-prompt-file ${identityPath}`;
|
|
1423
|
-
legacyFallbackWarned = true;
|
|
1424
|
-
}
|
|
1425
|
-
const behaviorsFile = exportBehaviorsSync(
|
|
1426
|
-
employeeName,
|
|
1427
|
-
path9.basename(spawnCwd),
|
|
1428
|
-
sessionName
|
|
1429
|
-
);
|
|
1430
|
-
if (behaviorsFile) {
|
|
1431
|
-
behaviorsFlag = ` --append-system-prompt-file ${behaviorsFile}`;
|
|
1432
|
-
}
|
|
2306
|
+
}
|
|
2307
|
+
var DELEGATION_KEYWORDS, TASK_ALREADY_CLAIMED_PREFIX;
|
|
2308
|
+
var init_tasks_crud = __esm({
|
|
2309
|
+
"src/lib/tasks-crud.ts"() {
|
|
2310
|
+
"use strict";
|
|
2311
|
+
init_database();
|
|
2312
|
+
DELEGATION_KEYWORDS = /parallel|delegate|wave|tom\d*-exe/i;
|
|
2313
|
+
TASK_ALREADY_CLAIMED_PREFIX = "TASK_ALREADY_CLAIMED";
|
|
1433
2314
|
}
|
|
1434
|
-
|
|
2315
|
+
});
|
|
2316
|
+
|
|
2317
|
+
// src/lib/tasks-review.ts
|
|
2318
|
+
import path10 from "path";
|
|
2319
|
+
import { existsSync as existsSync10, readdirSync as readdirSync2, unlinkSync as unlinkSync3 } from "fs";
|
|
2320
|
+
async function countPendingReviews() {
|
|
2321
|
+
const client = getClient();
|
|
2322
|
+
const result = await client.execute({
|
|
2323
|
+
sql: "SELECT COUNT(*) as cnt FROM tasks WHERE status = 'needs_review'",
|
|
2324
|
+
args: []
|
|
2325
|
+
});
|
|
2326
|
+
return Number(result.rows[0]?.cnt) || 0;
|
|
2327
|
+
}
|
|
2328
|
+
async function countNewPendingReviewsSince(sinceIso) {
|
|
2329
|
+
const client = getClient();
|
|
2330
|
+
const result = await client.execute({
|
|
2331
|
+
sql: `SELECT COUNT(*) as cnt FROM tasks
|
|
2332
|
+
WHERE status = 'needs_review' AND updated_at > ?`,
|
|
2333
|
+
args: [sinceIso]
|
|
2334
|
+
});
|
|
2335
|
+
return Number(result.rows[0]?.cnt) || 0;
|
|
2336
|
+
}
|
|
2337
|
+
async function listPendingReviews(limit) {
|
|
2338
|
+
const client = getClient();
|
|
2339
|
+
const result = await client.execute({
|
|
2340
|
+
sql: `SELECT title, assigned_to, project_name FROM tasks
|
|
2341
|
+
WHERE status = 'needs_review'
|
|
2342
|
+
ORDER BY priority ASC, created_at DESC LIMIT ?`,
|
|
2343
|
+
args: [limit]
|
|
2344
|
+
});
|
|
2345
|
+
return result.rows;
|
|
2346
|
+
}
|
|
2347
|
+
async function cleanupOrphanedReviews() {
|
|
2348
|
+
const client = getClient();
|
|
2349
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
2350
|
+
const r1 = await client.execute({
|
|
2351
|
+
sql: `UPDATE tasks SET status = 'done', updated_at = ?
|
|
2352
|
+
WHERE status = 'needs_review'
|
|
2353
|
+
AND assigned_by = 'system'
|
|
2354
|
+
AND title LIKE 'Review:%'
|
|
2355
|
+
AND parent_task_id IN (SELECT id FROM tasks WHERE status IN ('done', 'cancelled'))`,
|
|
2356
|
+
args: [now]
|
|
2357
|
+
});
|
|
2358
|
+
const staleThreshold = new Date(Date.now() - 60 * 60 * 1e3).toISOString();
|
|
2359
|
+
const r2 = await client.execute({
|
|
2360
|
+
sql: `UPDATE tasks SET status = 'done', updated_at = ?
|
|
2361
|
+
WHERE status = 'needs_review'
|
|
2362
|
+
AND result IS NOT NULL
|
|
2363
|
+
AND updated_at < ?`,
|
|
2364
|
+
args: [now, staleThreshold]
|
|
2365
|
+
});
|
|
2366
|
+
const total = r1.rowsAffected + r2.rowsAffected;
|
|
2367
|
+
if (total > 0) {
|
|
1435
2368
|
process.stderr.write(
|
|
1436
|
-
`[
|
|
2369
|
+
`[cleanup] Closed ${total} orphaned review(s): ${r1.rowsAffected} cascade + ${r2.rowsAffected} stale
|
|
1437
2370
|
`
|
|
1438
2371
|
);
|
|
1439
2372
|
}
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
2373
|
+
return total;
|
|
2374
|
+
}
|
|
2375
|
+
function getReviewChecklist(role, agent, taskSlug) {
|
|
2376
|
+
const roleLower = role.toLowerCase();
|
|
2377
|
+
if (roleLower.includes("engineer") || roleLower === "principal engineer") {
|
|
2378
|
+
return {
|
|
2379
|
+
lens: "Code Quality (Engineer)",
|
|
2380
|
+
checklist: [
|
|
2381
|
+
"1. Do all tests pass? Any new tests needed?",
|
|
2382
|
+
"2. Is the code clean \u2014 no dead code, no TODOs left?",
|
|
2383
|
+
"3. Does it follow existing patterns and conventions in the codebase?",
|
|
2384
|
+
"4. Any regressions in the test suite?"
|
|
2385
|
+
]
|
|
2386
|
+
};
|
|
1454
2387
|
}
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
2388
|
+
if (roleLower === "cto" || roleLower.includes("architect")) {
|
|
2389
|
+
return {
|
|
2390
|
+
lens: "Architecture (CTO)",
|
|
2391
|
+
checklist: [
|
|
2392
|
+
"1. Does this fit the existing architecture? Consistent with ARCHITECTURE.md?",
|
|
2393
|
+
"2. Is it backward compatible? Any breaking changes?",
|
|
2394
|
+
"3. Does it introduce technical debt? Is that debt justified?",
|
|
2395
|
+
"4. Security implications? Any new attack surface?",
|
|
2396
|
+
"5. Does it scale? Performance considerations?",
|
|
2397
|
+
"6. Coordination: does this affect other employees' work or other projects?"
|
|
2398
|
+
]
|
|
2399
|
+
};
|
|
2400
|
+
}
|
|
2401
|
+
if (roleLower === "coo" || roleLower.includes("operations")) {
|
|
2402
|
+
return {
|
|
2403
|
+
lens: "Strategic (COO)",
|
|
2404
|
+
checklist: [
|
|
2405
|
+
"1. Does this serve the project mission?",
|
|
2406
|
+
"2. Is this the right work at the right time?",
|
|
2407
|
+
"3. Does the architectural assessment make sense for the business?",
|
|
2408
|
+
"4. Any cross-project implications?"
|
|
2409
|
+
]
|
|
2410
|
+
};
|
|
2411
|
+
}
|
|
2412
|
+
return {
|
|
2413
|
+
lens: "General",
|
|
2414
|
+
checklist: [
|
|
2415
|
+
"1. Read the original task's acceptance criteria",
|
|
2416
|
+
`2. Check git log for related commits: \`git log --oneline --author-date-order -10\``,
|
|
2417
|
+
"3. Verify code changes match requirements",
|
|
2418
|
+
"4. Check if tests were added/updated",
|
|
2419
|
+
`5. Look for output files in exe/output/${agent}-${taskSlug}*`
|
|
2420
|
+
]
|
|
2421
|
+
};
|
|
2422
|
+
}
|
|
2423
|
+
async function cleanupReviewFile(row, taskFile, _baseDir) {
|
|
2424
|
+
if (String(row.assigned_by) !== "system" || !taskFile.includes("review-")) return;
|
|
2425
|
+
try {
|
|
2426
|
+
const client = getClient();
|
|
2427
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
2428
|
+
const parentId = row.parent_task_id ? String(row.parent_task_id) : null;
|
|
2429
|
+
if (parentId) {
|
|
2430
|
+
const result = await client.execute({
|
|
2431
|
+
sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ? AND status = 'needs_review'",
|
|
2432
|
+
args: [now, parentId]
|
|
2433
|
+
});
|
|
2434
|
+
if (result.rowsAffected > 0) {
|
|
2435
|
+
process.stderr.write(
|
|
2436
|
+
`[review-cleanup] Cascaded original task to done via parent_task_id: ${parentId}
|
|
2437
|
+
`
|
|
2438
|
+
);
|
|
2439
|
+
}
|
|
2440
|
+
} else {
|
|
2441
|
+
const fileName = taskFile.split("/").pop() ?? "";
|
|
2442
|
+
const reviewPrefix = fileName.replace(".md", "");
|
|
2443
|
+
const parts = reviewPrefix.split("-");
|
|
2444
|
+
if (parts.length >= 3 && parts[0] === "review") {
|
|
2445
|
+
const agent = parts[1];
|
|
2446
|
+
const slug = parts.slice(2).join("-");
|
|
2447
|
+
const originalTaskFile = `exe/${agent}/${slug}.md`;
|
|
2448
|
+
const result = await client.execute({
|
|
2449
|
+
sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE task_file = ? AND status = 'needs_review'",
|
|
2450
|
+
args: [now, originalTaskFile]
|
|
2451
|
+
});
|
|
2452
|
+
if (result.rowsAffected > 0) {
|
|
2453
|
+
process.stderr.write(
|
|
2454
|
+
`[review-cleanup] Cascaded original task to done (legacy path): ${originalTaskFile}
|
|
2455
|
+
`
|
|
2456
|
+
);
|
|
2457
|
+
}
|
|
1462
2458
|
}
|
|
1463
2459
|
}
|
|
1464
|
-
}
|
|
1465
|
-
let spawnCommand;
|
|
1466
|
-
if (useExeAgent) {
|
|
1467
|
-
spawnCommand = `${envPrefix} exe-agent --employee ${employeeName} --model ${opts.model} --provider ${opts.provider}${cleanupSuffix}`;
|
|
1468
|
-
} else if (useBinSymlink) {
|
|
1469
|
-
const binName = `${employeeName}-${ccProvider}`;
|
|
2460
|
+
} catch (err) {
|
|
1470
2461
|
process.stderr.write(
|
|
1471
|
-
`[
|
|
2462
|
+
`[review-cleanup] Failed to cascade original task: ${err instanceof Error ? err.message : String(err)}
|
|
1472
2463
|
`
|
|
1473
2464
|
);
|
|
1474
|
-
spawnCommand = `${envPrefix} ${binName}${cleanupSuffix}`;
|
|
1475
|
-
} else {
|
|
1476
|
-
spawnCommand = `${envPrefix} claude --dangerously-skip-permissions${identityFlag}${behaviorsFlag}${sessionContextFlag}${cleanupSuffix}`;
|
|
1477
|
-
}
|
|
1478
|
-
const spawnResult = transport.spawn(sessionName, {
|
|
1479
|
-
cwd: spawnCwd,
|
|
1480
|
-
command: spawnCommand
|
|
1481
|
-
});
|
|
1482
|
-
if (spawnResult.error) {
|
|
1483
|
-
releaseSpawnLock(sessionName);
|
|
1484
|
-
return { sessionName, error: `tmux new-session failed: ${spawnResult.error}` };
|
|
1485
2465
|
}
|
|
1486
|
-
transport.pipeLog(sessionName, logFile);
|
|
1487
2466
|
try {
|
|
1488
|
-
const
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
|
|
1494
|
-
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1495
|
-
}));
|
|
1496
|
-
} catch {
|
|
1497
|
-
}
|
|
1498
|
-
let booted = false;
|
|
1499
|
-
for (let i = 0; i < 30; i++) {
|
|
1500
|
-
try {
|
|
1501
|
-
execSync5("sleep 0.5");
|
|
1502
|
-
} catch {
|
|
1503
|
-
}
|
|
1504
|
-
try {
|
|
1505
|
-
const pane = transport.capturePane(sessionName);
|
|
1506
|
-
if (useExeAgent) {
|
|
1507
|
-
if (pane.includes("[exe-agent]") || pane.includes("online")) {
|
|
1508
|
-
booted = true;
|
|
1509
|
-
break;
|
|
1510
|
-
}
|
|
1511
|
-
} else {
|
|
1512
|
-
if (pane.includes("Claude Code") || pane.includes("\u276F")) {
|
|
1513
|
-
booted = true;
|
|
1514
|
-
break;
|
|
2467
|
+
const cacheDir = path10.join(EXE_AI_DIR, "session-cache");
|
|
2468
|
+
if (existsSync10(cacheDir)) {
|
|
2469
|
+
for (const f of readdirSync2(cacheDir)) {
|
|
2470
|
+
if (f.startsWith("review-notified-")) {
|
|
2471
|
+
unlinkSync3(path10.join(cacheDir, f));
|
|
1515
2472
|
}
|
|
1516
2473
|
}
|
|
1517
|
-
} catch {
|
|
1518
|
-
}
|
|
1519
|
-
}
|
|
1520
|
-
if (!booted) {
|
|
1521
|
-
releaseSpawnLock(sessionName);
|
|
1522
|
-
return { sessionName, error: `${useExeAgent ? "exe-agent" : "claude"} did not boot within 15s` };
|
|
1523
|
-
}
|
|
1524
|
-
if (!useExeAgent) {
|
|
1525
|
-
try {
|
|
1526
|
-
transport.sendKeys(sessionName, `/exe-call ${employeeName}`);
|
|
1527
|
-
} catch {
|
|
1528
2474
|
}
|
|
2475
|
+
} catch {
|
|
1529
2476
|
}
|
|
1530
|
-
registerSession({
|
|
1531
|
-
windowName: sessionName,
|
|
1532
|
-
agentId: employeeName,
|
|
1533
|
-
projectDir: spawnCwd,
|
|
1534
|
-
parentExe: exeSession,
|
|
1535
|
-
pid: 0,
|
|
1536
|
-
registeredAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1537
|
-
});
|
|
1538
|
-
releaseSpawnLock(sessionName);
|
|
1539
|
-
return { sessionName };
|
|
1540
2477
|
}
|
|
1541
|
-
var SPAWN_LOCK_DIR, SESSION_CACHE, BEHAVIORS_EXPORT_TIMEOUT_MS, INTERCOM_DEBOUNCE_MS, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS, BUSY_PATTERN;
|
|
1542
|
-
var init_tmux_routing = __esm({
|
|
1543
|
-
"src/lib/tmux-routing.ts"() {
|
|
1544
|
-
"use strict";
|
|
1545
|
-
init_session_registry();
|
|
1546
|
-
init_session_key();
|
|
1547
|
-
init_transport();
|
|
1548
|
-
init_cc_agent_support();
|
|
1549
|
-
init_mcp_prefix();
|
|
1550
|
-
init_provider_table();
|
|
1551
|
-
init_intercom_queue();
|
|
1552
|
-
init_plan_limits();
|
|
1553
|
-
SPAWN_LOCK_DIR = path9.join(os5.homedir(), ".exe-os", "spawn-locks");
|
|
1554
|
-
SESSION_CACHE = path9.join(os5.homedir(), ".exe-os", "session-cache");
|
|
1555
|
-
BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
|
|
1556
|
-
INTERCOM_DEBOUNCE_MS = 3e4;
|
|
1557
|
-
INTERCOM_LOG2 = path9.join(os5.homedir(), ".exe-os", "intercom.log");
|
|
1558
|
-
DEBOUNCE_FILE = path9.join(SESSION_CACHE, "intercom-debounce.json");
|
|
1559
|
-
DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
|
|
1560
|
-
BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
|
|
1561
|
-
}
|
|
1562
|
-
});
|
|
1563
|
-
|
|
1564
|
-
// src/lib/tasks-review.ts
|
|
1565
|
-
import path10 from "path";
|
|
1566
|
-
import { existsSync as existsSync10, readdirSync as readdirSync2, unlinkSync as unlinkSync3 } from "fs";
|
|
1567
2478
|
var init_tasks_review = __esm({
|
|
1568
2479
|
"src/lib/tasks-review.ts"() {
|
|
1569
2480
|
"use strict";
|
|
@@ -1574,12 +2485,83 @@ var init_tasks_review = __esm({
|
|
|
1574
2485
|
init_tasks_crud();
|
|
1575
2486
|
init_tmux_routing();
|
|
1576
2487
|
init_session_key();
|
|
2488
|
+
init_state_bus();
|
|
1577
2489
|
}
|
|
1578
2490
|
});
|
|
1579
2491
|
|
|
1580
2492
|
// src/lib/tasks-chain.ts
|
|
1581
2493
|
import path11 from "path";
|
|
1582
2494
|
import { readFile as readFile3, writeFile as writeFile4 } from "fs/promises";
|
|
2495
|
+
async function cascadeUnblock(taskId, baseDir, now) {
|
|
2496
|
+
const client = getClient();
|
|
2497
|
+
const unblocked = await client.execute({
|
|
2498
|
+
sql: `UPDATE tasks SET status = 'open', blocked_by = NULL, updated_at = ?
|
|
2499
|
+
WHERE blocked_by = ? AND status = 'blocked'`,
|
|
2500
|
+
args: [now, taskId]
|
|
2501
|
+
});
|
|
2502
|
+
if (baseDir && unblocked.rowsAffected > 0) {
|
|
2503
|
+
const unblockedRows = await client.execute({
|
|
2504
|
+
sql: `SELECT task_file FROM tasks WHERE blocked_by IS NULL AND updated_at = ?`,
|
|
2505
|
+
args: [now]
|
|
2506
|
+
});
|
|
2507
|
+
for (const ur of unblockedRows.rows) {
|
|
2508
|
+
try {
|
|
2509
|
+
const ubFile = path11.join(baseDir, String(ur.task_file));
|
|
2510
|
+
let ubContent = await readFile3(ubFile, "utf-8");
|
|
2511
|
+
ubContent = ubContent.replace(/\*\*Status:\*\* blocked/, "**Status:** open");
|
|
2512
|
+
ubContent = ubContent.replace(/\n\*\*Blocked by:\*\*.*\n/, "\n");
|
|
2513
|
+
await writeFile4(ubFile, ubContent, "utf-8");
|
|
2514
|
+
} catch {
|
|
2515
|
+
}
|
|
2516
|
+
}
|
|
2517
|
+
}
|
|
2518
|
+
}
|
|
2519
|
+
async function findNextTask(assignedTo) {
|
|
2520
|
+
const client = getClient();
|
|
2521
|
+
const nextResult = await client.execute({
|
|
2522
|
+
sql: `SELECT title, task_file, priority FROM tasks
|
|
2523
|
+
WHERE assigned_to = ? AND status = 'open'
|
|
2524
|
+
ORDER BY priority ASC, created_at ASC
|
|
2525
|
+
LIMIT 1`,
|
|
2526
|
+
args: [assignedTo]
|
|
2527
|
+
});
|
|
2528
|
+
if (nextResult.rows.length === 1) {
|
|
2529
|
+
const nr = nextResult.rows[0];
|
|
2530
|
+
return {
|
|
2531
|
+
title: String(nr.title),
|
|
2532
|
+
priority: String(nr.priority),
|
|
2533
|
+
taskFile: String(nr.task_file)
|
|
2534
|
+
};
|
|
2535
|
+
}
|
|
2536
|
+
return void 0;
|
|
2537
|
+
}
|
|
2538
|
+
async function checkSubtaskCompletion(parentTaskId, projectName) {
|
|
2539
|
+
const client = getClient();
|
|
2540
|
+
const remaining = await client.execute({
|
|
2541
|
+
sql: `SELECT COUNT(*) as cnt FROM tasks
|
|
2542
|
+
WHERE parent_task_id = ? AND status NOT IN ('done', 'cancelled')`,
|
|
2543
|
+
args: [parentTaskId]
|
|
2544
|
+
});
|
|
2545
|
+
const cnt = Number(remaining.rows[0]?.cnt ?? 1);
|
|
2546
|
+
if (cnt === 0) {
|
|
2547
|
+
const parentRow = await client.execute({
|
|
2548
|
+
sql: `SELECT assigned_to, title, task_file, project_name FROM tasks WHERE id = ?`,
|
|
2549
|
+
args: [parentTaskId]
|
|
2550
|
+
});
|
|
2551
|
+
if (parentRow.rows.length === 1) {
|
|
2552
|
+
const pr = parentRow.rows[0];
|
|
2553
|
+
const parentProject = pr.project_name == null ? projectName : String(pr.project_name);
|
|
2554
|
+
await writeNotification({
|
|
2555
|
+
agentId: String(pr.assigned_to),
|
|
2556
|
+
agentRole: "system",
|
|
2557
|
+
event: "subtasks_complete",
|
|
2558
|
+
project: parentProject,
|
|
2559
|
+
summary: `All subtasks complete for "${String(pr.title)}" \u2014 ready for rollup review`,
|
|
2560
|
+
taskFile: String(pr.task_file)
|
|
2561
|
+
});
|
|
2562
|
+
}
|
|
2563
|
+
}
|
|
2564
|
+
}
|
|
1583
2565
|
var init_tasks_chain = __esm({
|
|
1584
2566
|
"src/lib/tasks-chain.ts"() {
|
|
1585
2567
|
"use strict";
|
|
@@ -1668,13 +2650,12 @@ function assertSessionScope(actionType, targetProject) {
|
|
|
1668
2650
|
};
|
|
1669
2651
|
}
|
|
1670
2652
|
process.stderr.write(
|
|
1671
|
-
`[session-scope]
|
|
2653
|
+
`[session-scope] BLOCKED cross-project ${actionType}: session project="${currentProject}" \u2260 target project="${targetProject}"
|
|
1672
2654
|
`
|
|
1673
2655
|
);
|
|
1674
2656
|
return {
|
|
1675
|
-
allowed:
|
|
1676
|
-
|
|
1677
|
-
reason: "cross_session_granted",
|
|
2657
|
+
allowed: false,
|
|
2658
|
+
reason: "cross_session_denied",
|
|
1678
2659
|
currentProject,
|
|
1679
2660
|
targetProject,
|
|
1680
2661
|
targetSession: findSessionForProject(targetProject)?.windowName
|
|
@@ -1700,8 +2681,9 @@ async function dispatchTaskToEmployee(input) {
|
|
|
1700
2681
|
try {
|
|
1701
2682
|
const { assertSessionScope: assertSessionScope2 } = (init_session_scope(), __toCommonJS(session_scope_exports));
|
|
1702
2683
|
const check = assertSessionScope2("dispatch_task", input.projectName);
|
|
1703
|
-
if (check.reason === "
|
|
2684
|
+
if (check.reason === "cross_session_denied") {
|
|
1704
2685
|
crossProject = true;
|
|
2686
|
+
return { dispatched: "skipped", crossProject: true };
|
|
1705
2687
|
}
|
|
1706
2688
|
} catch {
|
|
1707
2689
|
}
|
|
@@ -1733,6 +2715,19 @@ async function dispatchTaskToEmployee(input) {
|
|
|
1733
2715
|
return { dispatched: "session_missing" };
|
|
1734
2716
|
}
|
|
1735
2717
|
}
|
|
2718
|
+
function notifyTaskDone() {
|
|
2719
|
+
try {
|
|
2720
|
+
const key = getSessionKey();
|
|
2721
|
+
if (key && !process.env.VITEST) notifyParentExe(key);
|
|
2722
|
+
} catch {
|
|
2723
|
+
}
|
|
2724
|
+
}
|
|
2725
|
+
async function markTaskNotificationsRead(taskFile) {
|
|
2726
|
+
try {
|
|
2727
|
+
await markAsReadByTaskFile(taskFile);
|
|
2728
|
+
} catch {
|
|
2729
|
+
}
|
|
2730
|
+
}
|
|
1736
2731
|
var init_tasks_notify = __esm({
|
|
1737
2732
|
"src/lib/tasks-notify.ts"() {
|
|
1738
2733
|
"use strict";
|
|
@@ -1744,7 +2739,337 @@ var init_tasks_notify = __esm({
|
|
|
1744
2739
|
}
|
|
1745
2740
|
});
|
|
1746
2741
|
|
|
2742
|
+
// src/lib/behaviors.ts
|
|
2743
|
+
import crypto4 from "crypto";
|
|
2744
|
+
async function storeBehavior(opts) {
|
|
2745
|
+
const client = getClient();
|
|
2746
|
+
const id = crypto4.randomUUID();
|
|
2747
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
2748
|
+
await client.execute({
|
|
2749
|
+
sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, priority, content, active, created_at, updated_at)
|
|
2750
|
+
VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)`,
|
|
2751
|
+
args: [id, opts.agentId, opts.projectName ?? null, opts.domain ?? null, opts.priority ?? "p1", opts.content, now, now]
|
|
2752
|
+
});
|
|
2753
|
+
return id;
|
|
2754
|
+
}
|
|
2755
|
+
var init_behaviors = __esm({
|
|
2756
|
+
"src/lib/behaviors.ts"() {
|
|
2757
|
+
"use strict";
|
|
2758
|
+
init_database();
|
|
2759
|
+
}
|
|
2760
|
+
});
|
|
2761
|
+
|
|
2762
|
+
// src/lib/skill-learning.ts
|
|
2763
|
+
var skill_learning_exports = {};
|
|
2764
|
+
__export(skill_learning_exports, {
|
|
2765
|
+
captureAndLearn: () => captureAndLearn,
|
|
2766
|
+
captureTrajectory: () => captureTrajectory,
|
|
2767
|
+
editDistance: () => editDistance,
|
|
2768
|
+
extractSkill: () => extractSkill,
|
|
2769
|
+
extractTrajectory: () => extractTrajectory,
|
|
2770
|
+
findSimilarTrajectories: () => findSimilarTrajectories,
|
|
2771
|
+
hashSignature: () => hashSignature,
|
|
2772
|
+
storeTrajectory: () => storeTrajectory,
|
|
2773
|
+
sweepTrajectories: () => sweepTrajectories
|
|
2774
|
+
});
|
|
2775
|
+
import crypto5 from "crypto";
|
|
2776
|
+
async function extractTrajectory(taskId, agentId) {
|
|
2777
|
+
const client = getClient();
|
|
2778
|
+
const result = await client.execute({
|
|
2779
|
+
sql: `SELECT tool_name, raw_text
|
|
2780
|
+
FROM memories
|
|
2781
|
+
WHERE task_id = ? AND agent_id = ?
|
|
2782
|
+
ORDER BY timestamp ASC`,
|
|
2783
|
+
args: [taskId, agentId]
|
|
2784
|
+
});
|
|
2785
|
+
if (result.rows.length === 0) return [];
|
|
2786
|
+
const rawTools = result.rows.map((r) => {
|
|
2787
|
+
const toolName = String(r.tool_name);
|
|
2788
|
+
if (toolName === "Bash") {
|
|
2789
|
+
const text = String(r.raw_text);
|
|
2790
|
+
const cmdMatch = text.match(/(?:command|Command).*?[:\s]+"?(\w+)/);
|
|
2791
|
+
return cmdMatch ? `Bash:${cmdMatch[1]}` : "Bash";
|
|
2792
|
+
}
|
|
2793
|
+
return toolName;
|
|
2794
|
+
});
|
|
2795
|
+
const signature = [];
|
|
2796
|
+
for (const tool of rawTools) {
|
|
2797
|
+
if (signature.length === 0 || signature[signature.length - 1] !== tool) {
|
|
2798
|
+
signature.push(tool);
|
|
2799
|
+
}
|
|
2800
|
+
}
|
|
2801
|
+
return signature;
|
|
2802
|
+
}
|
|
2803
|
+
function hashSignature(signature) {
|
|
2804
|
+
return crypto5.createHash("sha256").update(signature.join("|")).digest("hex").slice(0, 16);
|
|
2805
|
+
}
|
|
2806
|
+
async function storeTrajectory(opts) {
|
|
2807
|
+
const client = getClient();
|
|
2808
|
+
const id = crypto5.randomUUID();
|
|
2809
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
2810
|
+
const signatureHash = hashSignature(opts.signature);
|
|
2811
|
+
await client.execute({
|
|
2812
|
+
sql: `INSERT INTO trajectories (id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at)
|
|
2813
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
2814
|
+
args: [
|
|
2815
|
+
id,
|
|
2816
|
+
opts.taskId,
|
|
2817
|
+
opts.agentId,
|
|
2818
|
+
opts.projectName,
|
|
2819
|
+
opts.taskTitle,
|
|
2820
|
+
JSON.stringify(opts.signature),
|
|
2821
|
+
signatureHash,
|
|
2822
|
+
opts.signature.length,
|
|
2823
|
+
now
|
|
2824
|
+
]
|
|
2825
|
+
});
|
|
2826
|
+
return id;
|
|
2827
|
+
}
|
|
2828
|
+
async function findSimilarTrajectories(signature, threshold = DEFAULT_SKILL_THRESHOLD) {
|
|
2829
|
+
const client = getClient();
|
|
2830
|
+
const hash = hashSignature(signature);
|
|
2831
|
+
const result = await client.execute({
|
|
2832
|
+
sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
|
|
2833
|
+
FROM trajectories
|
|
2834
|
+
WHERE signature_hash = ?
|
|
2835
|
+
ORDER BY created_at DESC
|
|
2836
|
+
LIMIT 20`,
|
|
2837
|
+
args: [hash]
|
|
2838
|
+
});
|
|
2839
|
+
const mapRow = (r) => ({
|
|
2840
|
+
id: String(r.id),
|
|
2841
|
+
taskId: String(r.task_id),
|
|
2842
|
+
agentId: String(r.agent_id),
|
|
2843
|
+
projectName: String(r.project_name),
|
|
2844
|
+
taskTitle: String(r.task_title),
|
|
2845
|
+
signature: JSON.parse(String(r.signature)),
|
|
2846
|
+
signatureHash: String(r.signature_hash),
|
|
2847
|
+
toolCount: Number(r.tool_count),
|
|
2848
|
+
skillId: r.skill_id ? String(r.skill_id) : null,
|
|
2849
|
+
createdAt: String(r.created_at)
|
|
2850
|
+
});
|
|
2851
|
+
const matches = result.rows.map(mapRow);
|
|
2852
|
+
if (matches.length >= threshold) return matches;
|
|
2853
|
+
const nearResult = await client.execute({
|
|
2854
|
+
sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
|
|
2855
|
+
FROM trajectories
|
|
2856
|
+
WHERE tool_count BETWEEN ? AND ?
|
|
2857
|
+
AND signature_hash != ?
|
|
2858
|
+
ORDER BY created_at DESC
|
|
2859
|
+
LIMIT 50`,
|
|
2860
|
+
args: [
|
|
2861
|
+
Math.max(1, signature.length - 3),
|
|
2862
|
+
signature.length + 3,
|
|
2863
|
+
hash
|
|
2864
|
+
]
|
|
2865
|
+
});
|
|
2866
|
+
for (const r of nearResult.rows) {
|
|
2867
|
+
const candidateSig = JSON.parse(String(r.signature));
|
|
2868
|
+
if (editDistance(signature, candidateSig) <= 2) {
|
|
2869
|
+
matches.push(mapRow(r));
|
|
2870
|
+
}
|
|
2871
|
+
}
|
|
2872
|
+
return matches;
|
|
2873
|
+
}
|
|
2874
|
+
async function captureTrajectory(opts) {
|
|
2875
|
+
const signature = await extractTrajectory(opts.taskId, opts.agentId);
|
|
2876
|
+
if (signature.length < 3) {
|
|
2877
|
+
return { trajectoryId: "", similarCount: 0, similar: [] };
|
|
2878
|
+
}
|
|
2879
|
+
const trajectoryId = await storeTrajectory({
|
|
2880
|
+
taskId: opts.taskId,
|
|
2881
|
+
agentId: opts.agentId,
|
|
2882
|
+
projectName: opts.projectName,
|
|
2883
|
+
taskTitle: opts.taskTitle,
|
|
2884
|
+
signature
|
|
2885
|
+
});
|
|
2886
|
+
const similar = await findSimilarTrajectories(
|
|
2887
|
+
signature,
|
|
2888
|
+
opts.skillThreshold ?? DEFAULT_SKILL_THRESHOLD
|
|
2889
|
+
);
|
|
2890
|
+
return { trajectoryId, similarCount: similar.length, similar };
|
|
2891
|
+
}
|
|
2892
|
+
function buildExtractionPrompt(trajectories) {
|
|
2893
|
+
const items = trajectories.map((t, i) => {
|
|
2894
|
+
const sig = t.signature.join(" \u2192 ");
|
|
2895
|
+
return `Task ${i + 1}: "${t.taskTitle}" (${t.agentId}, ${t.projectName}) \u2014 ${t.toolCount} tool calls
|
|
2896
|
+
Signature: ${sig}`;
|
|
2897
|
+
}).join("\n\n");
|
|
2898
|
+
return `You are analyzing ${trajectories.length} completed tasks that followed similar procedures:
|
|
2899
|
+
|
|
2900
|
+
${items}
|
|
2901
|
+
|
|
2902
|
+
Extract the reusable procedure. Format your response EXACTLY like this:
|
|
2903
|
+
|
|
2904
|
+
SKILL: {name \u2014 short, descriptive}
|
|
2905
|
+
TRIGGER: {when to use this \u2014 one sentence}
|
|
2906
|
+
STEPS:
|
|
2907
|
+
1. ...
|
|
2908
|
+
2. ...
|
|
2909
|
+
PITFALLS: {common mistakes to avoid}
|
|
2910
|
+
|
|
2911
|
+
Be specific and actionable. Include tool names, file patterns, and concrete commands where applicable.`;
|
|
2912
|
+
}
|
|
2913
|
+
async function extractSkill(trajectories, model) {
|
|
2914
|
+
if (trajectories.length === 0) return null;
|
|
2915
|
+
const config = await loadConfig();
|
|
2916
|
+
const skillModel = model ?? config.skillModel;
|
|
2917
|
+
const Anthropic = (await import("@anthropic-ai/sdk")).default;
|
|
2918
|
+
const client = new Anthropic();
|
|
2919
|
+
const prompt = buildExtractionPrompt(trajectories);
|
|
2920
|
+
const response = await client.messages.create({
|
|
2921
|
+
model: skillModel,
|
|
2922
|
+
max_tokens: 500,
|
|
2923
|
+
messages: [{ role: "user", content: prompt }]
|
|
2924
|
+
});
|
|
2925
|
+
const textBlock = response.content.find((b) => b.type === "text");
|
|
2926
|
+
const skillText = textBlock?.text;
|
|
2927
|
+
if (!skillText) return null;
|
|
2928
|
+
const agentId = trajectories[0].agentId;
|
|
2929
|
+
const projectName = trajectories[0].projectName;
|
|
2930
|
+
const skillId = await storeBehavior({
|
|
2931
|
+
agentId,
|
|
2932
|
+
content: skillText,
|
|
2933
|
+
domain: "skill",
|
|
2934
|
+
projectName
|
|
2935
|
+
});
|
|
2936
|
+
const dbClient = getClient();
|
|
2937
|
+
for (const t of trajectories) {
|
|
2938
|
+
await dbClient.execute({
|
|
2939
|
+
sql: "UPDATE trajectories SET skill_id = ? WHERE id = ?",
|
|
2940
|
+
args: [skillId, t.id]
|
|
2941
|
+
});
|
|
2942
|
+
}
|
|
2943
|
+
process.stderr.write(
|
|
2944
|
+
`[skill-learning] Skill extracted from ${trajectories.length} trajectories \u2192 behavior ${skillId}
|
|
2945
|
+
`
|
|
2946
|
+
);
|
|
2947
|
+
return skillId;
|
|
2948
|
+
}
|
|
2949
|
+
async function captureAndLearn(opts) {
|
|
2950
|
+
try {
|
|
2951
|
+
const config = await loadConfig();
|
|
2952
|
+
if (!config.skillLearning) return;
|
|
2953
|
+
const { trajectoryId, similarCount, similar } = await captureTrajectory({
|
|
2954
|
+
...opts,
|
|
2955
|
+
skillThreshold: config.skillThreshold
|
|
2956
|
+
});
|
|
2957
|
+
if (!trajectoryId) return;
|
|
2958
|
+
if (similarCount >= config.skillThreshold) {
|
|
2959
|
+
const unprocessed = similar.filter((t) => !t.skillId);
|
|
2960
|
+
if (unprocessed.length >= config.skillThreshold) {
|
|
2961
|
+
extractSkill(unprocessed, config.skillModel).catch((err) => {
|
|
2962
|
+
process.stderr.write(
|
|
2963
|
+
`[skill-learning] Extraction failed: ${err instanceof Error ? err.message : String(err)}
|
|
2964
|
+
`
|
|
2965
|
+
);
|
|
2966
|
+
});
|
|
2967
|
+
}
|
|
2968
|
+
}
|
|
2969
|
+
} catch (err) {
|
|
2970
|
+
process.stderr.write(
|
|
2971
|
+
`[skill-learning] captureAndLearn failed: ${err instanceof Error ? err.message : String(err)}
|
|
2972
|
+
`
|
|
2973
|
+
);
|
|
2974
|
+
}
|
|
2975
|
+
}
|
|
2976
|
+
async function sweepTrajectories(threshold, model) {
|
|
2977
|
+
const config = await loadConfig();
|
|
2978
|
+
if (!config.skillLearning) return { clustersProcessed: 0, skillsExtracted: 0 };
|
|
2979
|
+
const t = threshold ?? config.skillThreshold;
|
|
2980
|
+
const client = getClient();
|
|
2981
|
+
const result = await client.execute({
|
|
2982
|
+
sql: `SELECT signature_hash, COUNT(*) as cnt
|
|
2983
|
+
FROM trajectories
|
|
2984
|
+
WHERE skill_id IS NULL
|
|
2985
|
+
GROUP BY signature_hash
|
|
2986
|
+
HAVING cnt >= ?
|
|
2987
|
+
ORDER BY cnt DESC
|
|
2988
|
+
LIMIT 10`,
|
|
2989
|
+
args: [t]
|
|
2990
|
+
});
|
|
2991
|
+
let clustersProcessed = 0;
|
|
2992
|
+
let skillsExtracted = 0;
|
|
2993
|
+
for (const row of result.rows) {
|
|
2994
|
+
const hash = String(row.signature_hash);
|
|
2995
|
+
const trajResult = await client.execute({
|
|
2996
|
+
sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at
|
|
2997
|
+
FROM trajectories
|
|
2998
|
+
WHERE signature_hash = ? AND skill_id IS NULL
|
|
2999
|
+
ORDER BY created_at DESC
|
|
3000
|
+
LIMIT 10`,
|
|
3001
|
+
args: [hash]
|
|
3002
|
+
});
|
|
3003
|
+
const trajectories = trajResult.rows.map((r) => ({
|
|
3004
|
+
id: String(r.id),
|
|
3005
|
+
taskId: String(r.task_id),
|
|
3006
|
+
agentId: String(r.agent_id),
|
|
3007
|
+
projectName: String(r.project_name),
|
|
3008
|
+
taskTitle: String(r.task_title),
|
|
3009
|
+
signature: JSON.parse(String(r.signature)),
|
|
3010
|
+
signatureHash: String(r.signature_hash),
|
|
3011
|
+
toolCount: Number(r.tool_count),
|
|
3012
|
+
skillId: null,
|
|
3013
|
+
createdAt: String(r.created_at)
|
|
3014
|
+
}));
|
|
3015
|
+
if (trajectories.length >= t) {
|
|
3016
|
+
clustersProcessed++;
|
|
3017
|
+
const skillId = await extractSkill(trajectories, model ?? config.skillModel);
|
|
3018
|
+
if (skillId) skillsExtracted++;
|
|
3019
|
+
}
|
|
3020
|
+
}
|
|
3021
|
+
return { clustersProcessed, skillsExtracted };
|
|
3022
|
+
}
|
|
3023
|
+
function editDistance(a, b) {
|
|
3024
|
+
const m = a.length;
|
|
3025
|
+
const n = b.length;
|
|
3026
|
+
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
|
|
3027
|
+
for (let i = 0; i <= m; i++) dp[i][0] = i;
|
|
3028
|
+
for (let j = 0; j <= n; j++) dp[0][j] = j;
|
|
3029
|
+
for (let i = 1; i <= m; i++) {
|
|
3030
|
+
for (let j = 1; j <= n; j++) {
|
|
3031
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
3032
|
+
dp[i][j] = Math.min(
|
|
3033
|
+
dp[i - 1][j] + 1,
|
|
3034
|
+
dp[i][j - 1] + 1,
|
|
3035
|
+
dp[i - 1][j - 1] + cost
|
|
3036
|
+
);
|
|
3037
|
+
}
|
|
3038
|
+
}
|
|
3039
|
+
return dp[m][n];
|
|
3040
|
+
}
|
|
3041
|
+
var DEFAULT_SKILL_THRESHOLD;
|
|
3042
|
+
var init_skill_learning = __esm({
|
|
3043
|
+
"src/lib/skill-learning.ts"() {
|
|
3044
|
+
"use strict";
|
|
3045
|
+
init_database();
|
|
3046
|
+
init_behaviors();
|
|
3047
|
+
init_config();
|
|
3048
|
+
DEFAULT_SKILL_THRESHOLD = 3;
|
|
3049
|
+
}
|
|
3050
|
+
});
|
|
3051
|
+
|
|
1747
3052
|
// src/lib/tasks.ts
|
|
3053
|
+
var tasks_exports = {};
|
|
3054
|
+
__export(tasks_exports, {
|
|
3055
|
+
cleanupOrphanedReviews: () => cleanupOrphanedReviews,
|
|
3056
|
+
countNewPendingReviewsSince: () => countNewPendingReviewsSince,
|
|
3057
|
+
countPendingReviews: () => countPendingReviews,
|
|
3058
|
+
createTask: () => createTask,
|
|
3059
|
+
createTaskCore: () => createTaskCore,
|
|
3060
|
+
deleteTask: () => deleteTask,
|
|
3061
|
+
deleteTaskCore: () => deleteTaskCore,
|
|
3062
|
+
ensureArchitectureDoc: () => ensureArchitectureDoc,
|
|
3063
|
+
ensureGitignoreExe: () => ensureGitignoreExe,
|
|
3064
|
+
getReviewChecklist: () => getReviewChecklist,
|
|
3065
|
+
listPendingReviews: () => listPendingReviews,
|
|
3066
|
+
listTasks: () => listTasks,
|
|
3067
|
+
resolveTask: () => resolveTask,
|
|
3068
|
+
slugify: () => slugify,
|
|
3069
|
+
updateTask: () => updateTask,
|
|
3070
|
+
updateTaskStatus: () => updateTaskStatus,
|
|
3071
|
+
writeCheckpoint: () => writeCheckpoint
|
|
3072
|
+
});
|
|
1748
3073
|
import path13 from "path";
|
|
1749
3074
|
import { writeFileSync as writeFileSync5, mkdirSync as mkdirSync5, unlinkSync as unlinkSync4 } from "fs";
|
|
1750
3075
|
async function createTask(input) {
|
|
@@ -1761,12 +3086,141 @@ async function createTask(input) {
|
|
|
1761
3086
|
}
|
|
1762
3087
|
return result;
|
|
1763
3088
|
}
|
|
3089
|
+
async function updateTask(input) {
|
|
3090
|
+
const { row, taskFile, now, taskId } = await updateTaskStatus(input);
|
|
3091
|
+
try {
|
|
3092
|
+
const agent = String(row.assigned_to);
|
|
3093
|
+
const cacheDir = path13.join(EXE_AI_DIR, "session-cache");
|
|
3094
|
+
const cachePath = path13.join(cacheDir, `current-task-${agent}.json`);
|
|
3095
|
+
if (input.status === "in_progress") {
|
|
3096
|
+
mkdirSync5(cacheDir, { recursive: true });
|
|
3097
|
+
writeFileSync5(cachePath, JSON.stringify({ taskId, title: String(row.title) }));
|
|
3098
|
+
} else if (input.status === "done" || input.status === "blocked" || input.status === "cancelled") {
|
|
3099
|
+
try {
|
|
3100
|
+
unlinkSync4(cachePath);
|
|
3101
|
+
} catch {
|
|
3102
|
+
}
|
|
3103
|
+
}
|
|
3104
|
+
} catch {
|
|
3105
|
+
}
|
|
3106
|
+
if (input.status === "done") {
|
|
3107
|
+
await cleanupReviewFile(row, taskFile, input.baseDir);
|
|
3108
|
+
}
|
|
3109
|
+
if (input.status === "done" || input.status === "cancelled") {
|
|
3110
|
+
try {
|
|
3111
|
+
const client = getClient();
|
|
3112
|
+
const taskTitle = String(row.title);
|
|
3113
|
+
const escaped = taskTitle.replace(/%/g, "\\%").replace(/_/g, "\\_");
|
|
3114
|
+
await client.execute({
|
|
3115
|
+
sql: `UPDATE tasks SET status = 'cancelled', updated_at = ?
|
|
3116
|
+
WHERE title LIKE ? ESCAPE '\\' AND status IN ('open', 'in_progress')`,
|
|
3117
|
+
args: [now, `%left '${escaped}' as in\\_progress%`]
|
|
3118
|
+
});
|
|
3119
|
+
} catch {
|
|
3120
|
+
}
|
|
3121
|
+
try {
|
|
3122
|
+
const client = getClient();
|
|
3123
|
+
const cascaded = await client.execute({
|
|
3124
|
+
sql: `UPDATE tasks SET status = 'done', updated_at = ?
|
|
3125
|
+
WHERE parent_task_id = ? AND status = 'needs_review'`,
|
|
3126
|
+
args: [now, taskId]
|
|
3127
|
+
});
|
|
3128
|
+
if (cascaded.rowsAffected > 0) {
|
|
3129
|
+
process.stderr.write(
|
|
3130
|
+
`[cascade] Closed ${cascaded.rowsAffected} orphaned review task(s) for parent ${taskId}
|
|
3131
|
+
`
|
|
3132
|
+
);
|
|
3133
|
+
}
|
|
3134
|
+
} catch {
|
|
3135
|
+
}
|
|
3136
|
+
}
|
|
3137
|
+
const isTerminal = input.status === "done" || input.status === "needs_review";
|
|
3138
|
+
if (isTerminal) {
|
|
3139
|
+
const isExe = String(row.assigned_to) === "exe";
|
|
3140
|
+
if (!isExe) {
|
|
3141
|
+
notifyTaskDone();
|
|
3142
|
+
}
|
|
3143
|
+
await markTaskNotificationsRead(taskFile);
|
|
3144
|
+
if (input.status === "done") {
|
|
3145
|
+
try {
|
|
3146
|
+
await cascadeUnblock(taskId, input.baseDir, now);
|
|
3147
|
+
} catch {
|
|
3148
|
+
}
|
|
3149
|
+
orgBus.emit({
|
|
3150
|
+
type: "task_completed",
|
|
3151
|
+
taskId,
|
|
3152
|
+
employee: String(row.assigned_to),
|
|
3153
|
+
result: input.result ?? "",
|
|
3154
|
+
timestamp: now
|
|
3155
|
+
});
|
|
3156
|
+
if (row.parent_task_id) {
|
|
3157
|
+
try {
|
|
3158
|
+
await checkSubtaskCompletion(String(row.parent_task_id), String(row.project_name));
|
|
3159
|
+
} catch {
|
|
3160
|
+
}
|
|
3161
|
+
}
|
|
3162
|
+
}
|
|
3163
|
+
}
|
|
3164
|
+
if (input.status === "done" && String(row.assigned_to) !== "exe" && !process.env.VITEST) {
|
|
3165
|
+
Promise.resolve().then(() => (init_skill_learning(), skill_learning_exports)).then(
|
|
3166
|
+
({ captureAndLearn: captureAndLearn2 }) => captureAndLearn2({
|
|
3167
|
+
taskId,
|
|
3168
|
+
agentId: String(row.assigned_to),
|
|
3169
|
+
projectName: String(row.project_name),
|
|
3170
|
+
taskTitle: String(row.title)
|
|
3171
|
+
})
|
|
3172
|
+
).catch((err) => {
|
|
3173
|
+
process.stderr.write(
|
|
3174
|
+
`[updateTask] skill learning failed: ${err instanceof Error ? err.message : String(err)}
|
|
3175
|
+
`
|
|
3176
|
+
);
|
|
3177
|
+
});
|
|
3178
|
+
}
|
|
3179
|
+
let nextTask;
|
|
3180
|
+
if (isTerminal && String(row.assigned_to) !== "exe") {
|
|
3181
|
+
try {
|
|
3182
|
+
nextTask = await findNextTask(String(row.assigned_to));
|
|
3183
|
+
} catch {
|
|
3184
|
+
}
|
|
3185
|
+
}
|
|
3186
|
+
return {
|
|
3187
|
+
id: String(row.id),
|
|
3188
|
+
title: String(row.title),
|
|
3189
|
+
assignedTo: String(row.assigned_to),
|
|
3190
|
+
assignedBy: String(row.assigned_by),
|
|
3191
|
+
projectName: String(row.project_name),
|
|
3192
|
+
priority: String(row.priority),
|
|
3193
|
+
status: input.status,
|
|
3194
|
+
taskFile,
|
|
3195
|
+
createdAt: String(row.created_at),
|
|
3196
|
+
updatedAt: now,
|
|
3197
|
+
budgetTokens: row.budget_tokens !== void 0 && row.budget_tokens !== null ? Number(row.budget_tokens) : null,
|
|
3198
|
+
budgetFallbackModel: row.budget_fallback_model !== void 0 && row.budget_fallback_model !== null ? String(row.budget_fallback_model) : null,
|
|
3199
|
+
tokensUsed: Number(row.tokens_used ?? 0),
|
|
3200
|
+
tokensWarnedAt: row.tokens_warned_at !== void 0 && row.tokens_warned_at !== null ? Number(row.tokens_warned_at) : null,
|
|
3201
|
+
nextTask
|
|
3202
|
+
};
|
|
3203
|
+
}
|
|
3204
|
+
async function deleteTask(taskId, baseDir) {
|
|
3205
|
+
const client = getClient();
|
|
3206
|
+
const { taskFile, assignedTo, assignedBy, taskSlug } = await deleteTaskCore(taskId, baseDir);
|
|
3207
|
+
const reviewer = assignedBy || "exe";
|
|
3208
|
+
const reviewSlug = `review-${assignedTo}-${taskSlug}`;
|
|
3209
|
+
const reviewFile = `exe/${reviewer}/${reviewSlug}.md`;
|
|
3210
|
+
await client.execute({
|
|
3211
|
+
sql: "DELETE FROM tasks WHERE task_file = ? OR task_file = ?",
|
|
3212
|
+
args: [reviewFile, `exe/exe/${reviewSlug}.md`]
|
|
3213
|
+
});
|
|
3214
|
+
await markAsReadByTaskFile(taskFile);
|
|
3215
|
+
await markAsReadByTaskFile(reviewFile);
|
|
3216
|
+
}
|
|
1764
3217
|
var init_tasks = __esm({
|
|
1765
3218
|
"src/lib/tasks.ts"() {
|
|
1766
3219
|
"use strict";
|
|
1767
3220
|
init_database();
|
|
1768
3221
|
init_config();
|
|
1769
3222
|
init_notifications();
|
|
3223
|
+
init_state_bus();
|
|
1770
3224
|
init_tasks_crud();
|
|
1771
3225
|
init_tasks_review();
|
|
1772
3226
|
init_tasks_crud();
|