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