@conveno/cli 0.0.0 → 0.1.1-rc.1
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/LICENSE +202 -0
- package/NOTICE +15 -0
- package/README.md +56 -3
- package/dist/bin.js +4169 -0
- package/dist/daemon.js +995 -0
- package/dist/dist-Do8KKOnN.js +1470 -0
- package/package.json +55 -10
package/dist/daemon.js
ADDED
|
@@ -0,0 +1,995 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { $ as makeResult, B as Message, G as SessionId, H as PROTOCOL_VERSION, I as DeviceId, J as encodeFrame, K as createLineDecoder, L as EVENT_NAMES, M as takeWithinBytes, N as tooManyUnreadMessage, O as readInbox, P as validateRename, Q as makeEventNotification, S as pendingForInjection, T as proofsMatch, U as RpcErrorCode, X as isSocketPathTooLong, Z as makeError, _ as holderAfterDeparture, a as ackEntries, at as socketPathTooLongMessage, b as newAuthNonce, c as clientProof, d as dataPaths, et as newDeviceId, f as detectRepo, g as generateSessionName, i as RESPONSE_BUDGET_BYTES, it as sanitizeLine, j as statusAfterLiveness, k as resolveRecipient, l as daemonProof, m as evaluateLiveness, nt as newSessionId, o as baseName, p as effectiveHolder, q as defaultSocketPath, rt as parseIpcRequest, s as claimOrchestrator, t as ConvenoError, tt as newMessageId, u as dataDir, v as isOnline, y as markDelivered } from "./dist-Do8KKOnN.js";
|
|
4
|
+
import { randomBytes } from "node:crypto";
|
|
5
|
+
import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { connect, createServer } from "node:net";
|
|
7
|
+
import { dirname } from "node:path";
|
|
8
|
+
import { DatabaseSync } from "node:sqlite";
|
|
9
|
+
// ../daemon/src/lifecycle.ts
|
|
10
|
+
/** Thrown when another Conveno daemon already owns the lock file or answers on the socket. */
|
|
11
|
+
var DaemonAlreadyRunningError = class extends Error {
|
|
12
|
+
constructor(detail) {
|
|
13
|
+
super(`The Conveno daemon is already running (${detail}). Run "conveno daemon status" to see it.`);
|
|
14
|
+
this.name = "DaemonAlreadyRunningError";
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
/** `kill(pid, 0)` liveness: EPERM means the process exists but belongs to someone else. */
|
|
18
|
+
function defaultIsAlive(pid) {
|
|
19
|
+
try {
|
|
20
|
+
process.kill(pid, 0);
|
|
21
|
+
return true;
|
|
22
|
+
} catch (e) {
|
|
23
|
+
return e.code === "EPERM";
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** True when something accepts connections on the socket or pipe. */
|
|
27
|
+
function probeSocket(socketPath, timeoutMs = 500) {
|
|
28
|
+
return new Promise((resolve) => {
|
|
29
|
+
const s = connect(socketPath);
|
|
30
|
+
const done = (alive) => {
|
|
31
|
+
clearTimeout(timer);
|
|
32
|
+
s.destroy();
|
|
33
|
+
resolve(alive);
|
|
34
|
+
};
|
|
35
|
+
const timer = setTimeout(() => done(false), timeoutMs);
|
|
36
|
+
s.once("connect", () => done(true));
|
|
37
|
+
s.once("error", () => done(false));
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
/** A lock younger than this is trusted even if the socket does not answer yet (daemon booting). */
|
|
41
|
+
const LOCK_GRACE_MS = 5e3;
|
|
42
|
+
/**
|
|
43
|
+
* Create the lock file exclusively. The lock records the pid and the socket path of its owner.
|
|
44
|
+
* An existing lock is stale unless its pid is alive and either the socket recorded in the lock
|
|
45
|
+
* answers or the lock is brand new. The recorded socket is probed, not the new daemon's own, so
|
|
46
|
+
* a daemon started with a different socket path is still seen as running. Returns a function that
|
|
47
|
+
* releases the lock.
|
|
48
|
+
*/
|
|
49
|
+
async function acquireLock(lockPath, socketPath) {
|
|
50
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
51
|
+
try {
|
|
52
|
+
writeFileSync(lockPath, JSON.stringify({
|
|
53
|
+
pid: process.pid,
|
|
54
|
+
socketPath
|
|
55
|
+
}), {
|
|
56
|
+
flag: "wx",
|
|
57
|
+
mode: 384
|
|
58
|
+
});
|
|
59
|
+
return () => {
|
|
60
|
+
try {
|
|
61
|
+
unlinkSync(lockPath);
|
|
62
|
+
} catch {}
|
|
63
|
+
};
|
|
64
|
+
} catch (e) {
|
|
65
|
+
if (e.code !== "EEXIST") throw e;
|
|
66
|
+
}
|
|
67
|
+
let pid = 0;
|
|
68
|
+
let lockedSocket = socketPath;
|
|
69
|
+
let ageMs = Number.POSITIVE_INFINITY;
|
|
70
|
+
try {
|
|
71
|
+
const lock = JSON.parse(readFileSync(lockPath, "utf8"));
|
|
72
|
+
pid = lock.pid ?? 0;
|
|
73
|
+
if (typeof lock.socketPath === "string" && lock.socketPath !== "") lockedSocket = lock.socketPath;
|
|
74
|
+
ageMs = Date.now() - statSync(lockPath).mtimeMs;
|
|
75
|
+
} catch {}
|
|
76
|
+
if (pid > 0 && defaultIsAlive(pid) && (ageMs < LOCK_GRACE_MS || await probeSocket(lockedSocket))) throw new DaemonAlreadyRunningError(`pid ${pid}`);
|
|
77
|
+
try {
|
|
78
|
+
unlinkSync(lockPath);
|
|
79
|
+
} catch {}
|
|
80
|
+
}
|
|
81
|
+
throw new DaemonAlreadyRunningError("could not take the lock file");
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* POSIX only: remove a leftover socket file, but only after confirming no live daemon answers on it.
|
|
85
|
+
* Named pipes on Windows vanish with their owner, so there is nothing to remove.
|
|
86
|
+
*/
|
|
87
|
+
async function clearStaleSocket(socketPath) {
|
|
88
|
+
if (process.platform === "win32" || socketPath.startsWith("\\\\")) return;
|
|
89
|
+
if (!existsSync(socketPath)) return;
|
|
90
|
+
if (await probeSocket(socketPath)) throw new DaemonAlreadyRunningError(`socket ${socketPath}`);
|
|
91
|
+
try {
|
|
92
|
+
unlinkSync(socketPath);
|
|
93
|
+
} catch (e) {
|
|
94
|
+
if (e.code !== "ENOENT") throw e;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Read the auth token, creating it (32 random bytes, hex) with mode 0600 on first start.
|
|
99
|
+
* On Windows the mode is ignored; the file inherits the ACL of the per-user data directory.
|
|
100
|
+
*/
|
|
101
|
+
function loadOrCreateToken(tokenPath) {
|
|
102
|
+
if (existsSync(tokenPath)) {
|
|
103
|
+
const t = readFileSync(tokenPath, "utf8").trim();
|
|
104
|
+
if (t.length >= 32) {
|
|
105
|
+
if (process.platform !== "win32") chmodSync(tokenPath, 384);
|
|
106
|
+
return t;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
const token = randomBytes(32).toString("hex");
|
|
110
|
+
writeFileSync(tokenPath, `${token}\n`, { mode: 384 });
|
|
111
|
+
if (process.platform !== "win32") chmodSync(tokenPath, 384);
|
|
112
|
+
return token;
|
|
113
|
+
}
|
|
114
|
+
function ensureDir(dir) {
|
|
115
|
+
mkdirSync(dir, {
|
|
116
|
+
recursive: true,
|
|
117
|
+
mode: 448
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
const describeError = (e) => e instanceof Error ? e.stack ?? `${e.name}: ${e.message}` : String(e);
|
|
121
|
+
/**
|
|
122
|
+
* The daemon's own log, for errors it did not expect. One file, readable by the user only, with one
|
|
123
|
+
* older generation kept: when the file reaches `maxBytes` it replaces `<path>.1` and a new file
|
|
124
|
+
* starts. Request parameters are never logged, since they can hold message text.
|
|
125
|
+
*/
|
|
126
|
+
function createDaemonLog(path, opts = {}) {
|
|
127
|
+
const maxBytes = opts.maxBytes ?? 1048576;
|
|
128
|
+
const now = opts.now ?? (() => /* @__PURE__ */ new Date());
|
|
129
|
+
return {
|
|
130
|
+
path,
|
|
131
|
+
error(what, e) {
|
|
132
|
+
try {
|
|
133
|
+
mkdirSync(dirname(path), {
|
|
134
|
+
recursive: true,
|
|
135
|
+
mode: 448
|
|
136
|
+
});
|
|
137
|
+
let size = 0;
|
|
138
|
+
try {
|
|
139
|
+
size = statSync(path).size;
|
|
140
|
+
} catch {}
|
|
141
|
+
if (size >= maxBytes) {
|
|
142
|
+
rmSync(`${path}.1`, { force: true });
|
|
143
|
+
renameSync(path, `${path}.1`);
|
|
144
|
+
}
|
|
145
|
+
appendFileSync(path, `${now().toISOString()} ${what}\n${describeError(e)}\n\n`, { mode: 384 });
|
|
146
|
+
if (process.platform !== "win32") chmodSync(path, 384);
|
|
147
|
+
} catch {}
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
// ../daemon/src/store.ts
|
|
152
|
+
const MIGRATIONS = [{
|
|
153
|
+
name: "001_initial",
|
|
154
|
+
sql: `
|
|
155
|
+
CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
156
|
+
CREATE TABLE sessions (
|
|
157
|
+
id TEXT PRIMARY KEY,
|
|
158
|
+
name TEXT NOT NULL,
|
|
159
|
+
cli TEXT NOT NULL,
|
|
160
|
+
cli_version TEXT,
|
|
161
|
+
device_id TEXT NOT NULL,
|
|
162
|
+
cwd TEXT NOT NULL,
|
|
163
|
+
repo_root TEXT,
|
|
164
|
+
repo_remote_hash TEXT,
|
|
165
|
+
pid INTEGER,
|
|
166
|
+
host_pid INTEGER,
|
|
167
|
+
status TEXT NOT NULL,
|
|
168
|
+
status_text TEXT,
|
|
169
|
+
delivery_tier TEXT NOT NULL,
|
|
170
|
+
spawned_by TEXT,
|
|
171
|
+
spawn_depth INTEGER NOT NULL DEFAULT 0,
|
|
172
|
+
started_at TEXT NOT NULL,
|
|
173
|
+
last_seen_at TEXT NOT NULL
|
|
174
|
+
);
|
|
175
|
+
CREATE INDEX sessions_host_pid ON sessions (host_pid);
|
|
176
|
+
CREATE TABLE messages (
|
|
177
|
+
id TEXT PRIMARY KEY,
|
|
178
|
+
json TEXT NOT NULL
|
|
179
|
+
);
|
|
180
|
+
CREATE TABLE mailbox (
|
|
181
|
+
session_id TEXT NOT NULL,
|
|
182
|
+
message_id TEXT NOT NULL,
|
|
183
|
+
state TEXT NOT NULL,
|
|
184
|
+
queued_at TEXT NOT NULL,
|
|
185
|
+
delivered_at TEXT,
|
|
186
|
+
read_at TEXT,
|
|
187
|
+
acked_at TEXT,
|
|
188
|
+
PRIMARY KEY (session_id, message_id)
|
|
189
|
+
);
|
|
190
|
+
CREATE INDEX mailbox_state ON mailbox (session_id, state);
|
|
191
|
+
CREATE TABLE orchestrator (
|
|
192
|
+
slot INTEGER PRIMARY KEY CHECK (slot = 1),
|
|
193
|
+
session_id TEXT
|
|
194
|
+
);
|
|
195
|
+
INSERT INTO orchestrator (slot, session_id) VALUES (1, NULL);
|
|
196
|
+
`
|
|
197
|
+
}, {
|
|
198
|
+
name: "002_host_pids",
|
|
199
|
+
sql: `
|
|
200
|
+
ALTER TABLE sessions ADD COLUMN host_pids TEXT;
|
|
201
|
+
UPDATE sessions SET host_pids = '[' || host_pid || ']' WHERE host_pid IS NOT NULL;
|
|
202
|
+
`
|
|
203
|
+
}];
|
|
204
|
+
const str = (v) => typeof v === "string" ? v : void 0;
|
|
205
|
+
const num = (v) => typeof v === "number" ? v : void 0;
|
|
206
|
+
function pidList(v) {
|
|
207
|
+
if (typeof v !== "string") return void 0;
|
|
208
|
+
try {
|
|
209
|
+
const list = JSON.parse(v);
|
|
210
|
+
if (!Array.isArray(list)) return void 0;
|
|
211
|
+
const pids = list.filter((p) => Number.isInteger(p) && p > 0);
|
|
212
|
+
return pids.length > 0 ? pids : void 0;
|
|
213
|
+
} catch {
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
function toSessionRow(r) {
|
|
218
|
+
const row = {
|
|
219
|
+
id: r.id,
|
|
220
|
+
name: r.name,
|
|
221
|
+
cli: r.cli,
|
|
222
|
+
deviceId: r.device_id,
|
|
223
|
+
cwd: r.cwd,
|
|
224
|
+
status: r.status,
|
|
225
|
+
deliveryTier: r.delivery_tier,
|
|
226
|
+
spawnDepth: r.spawn_depth,
|
|
227
|
+
startedAt: r.started_at,
|
|
228
|
+
lastSeenAt: r.last_seen_at
|
|
229
|
+
};
|
|
230
|
+
const cliVersion = str(r.cli_version);
|
|
231
|
+
if (cliVersion !== void 0) row.cliVersion = cliVersion;
|
|
232
|
+
const repoRoot = str(r.repo_root);
|
|
233
|
+
if (repoRoot !== void 0) row.repoRoot = repoRoot;
|
|
234
|
+
const hash = str(r.repo_remote_hash);
|
|
235
|
+
if (hash !== void 0) row.repoRemoteUrlHash = hash;
|
|
236
|
+
const pid = num(r.pid);
|
|
237
|
+
if (pid !== void 0) row.pid = pid;
|
|
238
|
+
const hostPid = num(r.host_pid);
|
|
239
|
+
if (hostPid !== void 0) row.hostPid = hostPid;
|
|
240
|
+
const hostPids = pidList(r.host_pids);
|
|
241
|
+
if (hostPids !== void 0) row.hostPids = hostPids;
|
|
242
|
+
const statusText = str(r.status_text);
|
|
243
|
+
if (statusText !== void 0) row.statusText = statusText;
|
|
244
|
+
const spawnedBy = str(r.spawned_by);
|
|
245
|
+
if (spawnedBy !== void 0) row.spawnedBy = spawnedBy;
|
|
246
|
+
return row;
|
|
247
|
+
}
|
|
248
|
+
/** Wire-format session for a stored row. */
|
|
249
|
+
function toSession(row, isOrchestrator) {
|
|
250
|
+
const s = {
|
|
251
|
+
id: row.id,
|
|
252
|
+
name: row.name,
|
|
253
|
+
cli: row.cli,
|
|
254
|
+
deviceId: row.deviceId,
|
|
255
|
+
cwd: row.cwd,
|
|
256
|
+
status: row.status,
|
|
257
|
+
isOrchestrator,
|
|
258
|
+
deliveryTier: row.deliveryTier,
|
|
259
|
+
spawnDepth: row.spawnDepth,
|
|
260
|
+
startedAt: row.startedAt,
|
|
261
|
+
lastSeenAt: row.lastSeenAt
|
|
262
|
+
};
|
|
263
|
+
if (row.cliVersion !== void 0) s.cliVersion = row.cliVersion;
|
|
264
|
+
if (row.repoRoot !== void 0) s.repo = row.repoRemoteUrlHash !== void 0 ? {
|
|
265
|
+
root: row.repoRoot,
|
|
266
|
+
remoteUrlHash: row.repoRemoteUrlHash
|
|
267
|
+
} : { root: row.repoRoot };
|
|
268
|
+
if (row.pid !== void 0) s.pid = row.pid;
|
|
269
|
+
if (row.hostPid !== void 0) s.hostPid = row.hostPid;
|
|
270
|
+
if (row.hostPids !== void 0) s.hostPids = row.hostPids;
|
|
271
|
+
if (row.statusText !== void 0) s.statusText = row.statusText;
|
|
272
|
+
if (row.spawnedBy !== void 0) s.spawnedBy = row.spawnedBy;
|
|
273
|
+
return s;
|
|
274
|
+
}
|
|
275
|
+
function toEntry(r) {
|
|
276
|
+
const entry = {
|
|
277
|
+
message: Message.parse(JSON.parse(r.json)),
|
|
278
|
+
state: r.state,
|
|
279
|
+
queuedAt: r.queued_at
|
|
280
|
+
};
|
|
281
|
+
const d = str(r.delivered_at);
|
|
282
|
+
const rd = str(r.read_at);
|
|
283
|
+
const a = str(r.acked_at);
|
|
284
|
+
if (d) entry.deliveredAt = d;
|
|
285
|
+
if (rd) entry.readAt = rd;
|
|
286
|
+
if (a) entry.ackedAt = a;
|
|
287
|
+
return entry;
|
|
288
|
+
}
|
|
289
|
+
/** SQLite persistence. All methods are synchronous; callers group writes with `tx`. */
|
|
290
|
+
var Store = class {
|
|
291
|
+
db;
|
|
292
|
+
constructor(path) {
|
|
293
|
+
this.db = new DatabaseSync(path);
|
|
294
|
+
this.db.exec("PRAGMA journal_mode = WAL");
|
|
295
|
+
this.db.exec("PRAGMA synchronous = NORMAL");
|
|
296
|
+
this.db.exec("PRAGMA busy_timeout = 5000");
|
|
297
|
+
this.migrate();
|
|
298
|
+
}
|
|
299
|
+
all(sql, ...params) {
|
|
300
|
+
return this.db.prepare(sql).all(...params);
|
|
301
|
+
}
|
|
302
|
+
run(sql, ...params) {
|
|
303
|
+
this.db.prepare(sql).run(...params);
|
|
304
|
+
}
|
|
305
|
+
migrate() {
|
|
306
|
+
this.db.exec("CREATE TABLE IF NOT EXISTS migrations (name TEXT PRIMARY KEY, applied_at TEXT NOT NULL)");
|
|
307
|
+
const done = new Set(this.all("SELECT name FROM migrations").map((r) => r.name));
|
|
308
|
+
for (const m of MIGRATIONS) {
|
|
309
|
+
if (done.has(m.name)) continue;
|
|
310
|
+
this.tx(() => {
|
|
311
|
+
this.db.exec(m.sql);
|
|
312
|
+
this.run("INSERT INTO migrations (name, applied_at) VALUES (?, ?)", m.name, (/* @__PURE__ */ new Date()).toISOString());
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
tx(fn) {
|
|
317
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
318
|
+
try {
|
|
319
|
+
const out = fn();
|
|
320
|
+
this.db.exec("COMMIT");
|
|
321
|
+
return out;
|
|
322
|
+
} catch (e) {
|
|
323
|
+
this.db.exec("ROLLBACK");
|
|
324
|
+
throw e;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
close() {
|
|
328
|
+
this.db.close();
|
|
329
|
+
}
|
|
330
|
+
migrationNames() {
|
|
331
|
+
return this.all("SELECT name FROM migrations ORDER BY name").map((r) => r.name);
|
|
332
|
+
}
|
|
333
|
+
/** The device id of this machine, generated on first start. */
|
|
334
|
+
deviceId() {
|
|
335
|
+
const r = this.all("SELECT value FROM meta WHERE key = 'device_id'")[0];
|
|
336
|
+
if (r) return DeviceId.parse(r.value);
|
|
337
|
+
const id = newDeviceId();
|
|
338
|
+
this.run("INSERT INTO meta (key, value) VALUES ('device_id', ?)", id);
|
|
339
|
+
return id;
|
|
340
|
+
}
|
|
341
|
+
insertSession(s) {
|
|
342
|
+
this.run(`INSERT INTO sessions (id, name, cli, cli_version, device_id, cwd, repo_root, repo_remote_hash,
|
|
343
|
+
pid, host_pid, host_pids, status, status_text, delivery_tier, spawned_by, spawn_depth, started_at, last_seen_at)
|
|
344
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, s.id, s.name, s.cli, s.cliVersion ?? null, s.deviceId, s.cwd, s.repoRoot ?? null, s.repoRemoteUrlHash ?? null, s.pid ?? null, s.hostPid ?? null, s.hostPids ? JSON.stringify(s.hostPids) : null, s.status, s.statusText ?? null, s.deliveryTier, s.spawnedBy ?? null, s.spawnDepth, s.startedAt, s.lastSeenAt);
|
|
345
|
+
}
|
|
346
|
+
getSession(id) {
|
|
347
|
+
const r = this.all("SELECT * FROM sessions WHERE id = ?", id)[0];
|
|
348
|
+
return r ? toSessionRow(r) : void 0;
|
|
349
|
+
}
|
|
350
|
+
/** Every session, oldest first (ids are monotonic ULIDs). */
|
|
351
|
+
allSessions() {
|
|
352
|
+
return this.all("SELECT * FROM sessions ORDER BY started_at, id").map(toSessionRow);
|
|
353
|
+
}
|
|
354
|
+
updateSession(id, fields) {
|
|
355
|
+
const sets = [];
|
|
356
|
+
const vals = [];
|
|
357
|
+
if (fields.name !== void 0) {
|
|
358
|
+
sets.push("name = ?");
|
|
359
|
+
vals.push(fields.name);
|
|
360
|
+
}
|
|
361
|
+
if (fields.status !== void 0) {
|
|
362
|
+
sets.push("status = ?");
|
|
363
|
+
vals.push(fields.status);
|
|
364
|
+
}
|
|
365
|
+
if (fields.statusText !== void 0) {
|
|
366
|
+
sets.push("status_text = ?");
|
|
367
|
+
vals.push(fields.statusText);
|
|
368
|
+
}
|
|
369
|
+
if (fields.lastSeenAt !== void 0) {
|
|
370
|
+
sets.push("last_seen_at = ?");
|
|
371
|
+
vals.push(fields.lastSeenAt);
|
|
372
|
+
}
|
|
373
|
+
if (sets.length === 0) return;
|
|
374
|
+
this.run(`UPDATE sessions SET ${sets.join(", ")} WHERE id = ?`, ...vals, id);
|
|
375
|
+
}
|
|
376
|
+
holder() {
|
|
377
|
+
const r = this.all("SELECT session_id FROM orchestrator WHERE slot = 1")[0];
|
|
378
|
+
return str(r?.session_id) ?? null;
|
|
379
|
+
}
|
|
380
|
+
setHolder(id) {
|
|
381
|
+
this.run("UPDATE orchestrator SET session_id = ? WHERE slot = 1", id);
|
|
382
|
+
}
|
|
383
|
+
insertMessage(message, recipient, at) {
|
|
384
|
+
this.run("INSERT INTO messages (id, json) VALUES (?, ?)", message.id, JSON.stringify(message));
|
|
385
|
+
this.run("INSERT INTO mailbox (session_id, message_id, state, queued_at) VALUES (?, ?, 'queued', ?)", recipient, message.id, at);
|
|
386
|
+
}
|
|
387
|
+
/** Messages queued for a session that no one has been shown yet. */
|
|
388
|
+
unreadCount(sessionId) {
|
|
389
|
+
const r = this.all("SELECT COUNT(*) AS n FROM mailbox WHERE session_id = ? AND state = 'queued'", sessionId)[0];
|
|
390
|
+
return num(r?.n) ?? 0;
|
|
391
|
+
}
|
|
392
|
+
hasMessage(id) {
|
|
393
|
+
return this.all("SELECT 1 AS x FROM messages WHERE id = ?", id).length > 0;
|
|
394
|
+
}
|
|
395
|
+
/** Remove a session, its mailbox, and any message no mailbox refers to any more. */
|
|
396
|
+
deleteSession(id) {
|
|
397
|
+
this.run("DELETE FROM mailbox WHERE session_id = ?", id);
|
|
398
|
+
this.run("DELETE FROM messages WHERE id NOT IN (SELECT message_id FROM mailbox)");
|
|
399
|
+
this.run("DELETE FROM sessions WHERE id = ?", id);
|
|
400
|
+
}
|
|
401
|
+
/** Mailbox entries of one session, optionally limited to the given states or message ids. */
|
|
402
|
+
entries(sessionId, filter = {}) {
|
|
403
|
+
let sql = `SELECT m.json, b.state, b.queued_at, b.delivered_at, b.read_at, b.acked_at
|
|
404
|
+
FROM mailbox b JOIN messages m ON m.id = b.message_id WHERE b.session_id = ?`;
|
|
405
|
+
const params = [sessionId];
|
|
406
|
+
if (filter.states) {
|
|
407
|
+
sql += ` AND b.state IN (${filter.states.map(() => "?").join(",")})`;
|
|
408
|
+
params.push(...filter.states);
|
|
409
|
+
}
|
|
410
|
+
if (filter.ids) {
|
|
411
|
+
sql += ` AND b.message_id IN (${filter.ids.map(() => "?").join(",")})`;
|
|
412
|
+
params.push(...filter.ids);
|
|
413
|
+
}
|
|
414
|
+
return this.all(sql, ...params).map(toEntry);
|
|
415
|
+
}
|
|
416
|
+
saveEntry(sessionId, e) {
|
|
417
|
+
this.run(`UPDATE mailbox SET state = ?, delivered_at = ?, read_at = ?, acked_at = ?
|
|
418
|
+
WHERE session_id = ? AND message_id = ?`, e.state, e.deliveredAt ?? null, e.readAt ?? null, e.ackedAt ?? null, sessionId, e.message.id);
|
|
419
|
+
}
|
|
420
|
+
};
|
|
421
|
+
// ../daemon/src/server.ts
|
|
422
|
+
const DAEMON_VERSION = "0.1.1-rc.1";
|
|
423
|
+
/** A connection that has not finished the handshake by then is closed. */
|
|
424
|
+
const AUTH_TIMEOUT_MS = 5e3;
|
|
425
|
+
/** Unread messages one session may hold. */
|
|
426
|
+
const MAX_UNREAD_PER_SESSION = 1e3;
|
|
427
|
+
/**
|
|
428
|
+
* How long an offline session stays listed (`conveno status --all`) before the sweep deletes it.
|
|
429
|
+
* A closed session does not come back after a day: it returns only while its host process is alive,
|
|
430
|
+
* and a new run of the CLI registers as a new session. 24 h keeps a working day's history visible
|
|
431
|
+
* without piling up months of test sessions. It applies only when nothing is waiting for it.
|
|
432
|
+
*/
|
|
433
|
+
const PRUNE_OFFLINE_AFTER_MS = 864e5;
|
|
434
|
+
/**
|
|
435
|
+
* An offline session that a newer live session has replaced (same name, CLI and repo) is deleted
|
|
436
|
+
* after this grace. It cannot come back: a heartbeat is refused while another live session holds
|
|
437
|
+
* its name.
|
|
438
|
+
*/
|
|
439
|
+
const PRUNE_SUPERSEDED_AFTER_MS = 3e5;
|
|
440
|
+
/**
|
|
441
|
+
* An offline session with unread (queued) messages keeps them this long, whatever the other rules
|
|
442
|
+
* say, so mail sent to a closed session survives a weekend. Then the session and its mailbox go.
|
|
443
|
+
*/
|
|
444
|
+
const PRUNE_UNREAD_AFTER_MS = 6048e5;
|
|
445
|
+
/** Sender id on `system` messages made by the daemon itself (no session sent them). */
|
|
446
|
+
const DAEMON_SENDER_ID = SessionId.parse("0".repeat(26));
|
|
447
|
+
const CLI_TIER = {
|
|
448
|
+
claude: "next_turn",
|
|
449
|
+
codex: "next_turn"
|
|
450
|
+
};
|
|
451
|
+
var Daemon = class {
|
|
452
|
+
store;
|
|
453
|
+
token;
|
|
454
|
+
now;
|
|
455
|
+
isAlive;
|
|
456
|
+
idleExitMs;
|
|
457
|
+
requestIdleExit;
|
|
458
|
+
requestShutdown;
|
|
459
|
+
log;
|
|
460
|
+
authTimeoutMs;
|
|
461
|
+
conns = /* @__PURE__ */ new Set();
|
|
462
|
+
deviceId;
|
|
463
|
+
idleSince;
|
|
464
|
+
startedMs;
|
|
465
|
+
constructor(store, token, now, isAlive, idleExitMs, requestIdleExit, requestShutdown, log, authTimeoutMs = AUTH_TIMEOUT_MS) {
|
|
466
|
+
this.store = store;
|
|
467
|
+
this.token = token;
|
|
468
|
+
this.now = now;
|
|
469
|
+
this.isAlive = isAlive;
|
|
470
|
+
this.idleExitMs = idleExitMs;
|
|
471
|
+
this.requestIdleExit = requestIdleExit;
|
|
472
|
+
this.requestShutdown = requestShutdown;
|
|
473
|
+
this.log = log;
|
|
474
|
+
this.authTimeoutMs = authTimeoutMs;
|
|
475
|
+
this.deviceId = store.deviceId();
|
|
476
|
+
this.startedMs = now().getTime();
|
|
477
|
+
this.idleSince = this.startedMs;
|
|
478
|
+
}
|
|
479
|
+
iso = () => this.now().toISOString();
|
|
480
|
+
attach(socket) {
|
|
481
|
+
const conn = {
|
|
482
|
+
socket,
|
|
483
|
+
authed: false,
|
|
484
|
+
queue: Promise.resolve()
|
|
485
|
+
};
|
|
486
|
+
this.conns.add(conn);
|
|
487
|
+
const authTimer = setTimeout(() => {
|
|
488
|
+
if (!conn.authed) socket.destroy();
|
|
489
|
+
}, this.authTimeoutMs);
|
|
490
|
+
authTimer.unref();
|
|
491
|
+
const decoder = createLineDecoder();
|
|
492
|
+
socket.on("data", (chunk) => {
|
|
493
|
+
for (const frame of decoder.push(chunk)) conn.queue = conn.queue.then(() => this.onFrame(conn, frame));
|
|
494
|
+
});
|
|
495
|
+
socket.on("close", () => {
|
|
496
|
+
clearTimeout(authTimer);
|
|
497
|
+
this.conns.delete(conn);
|
|
498
|
+
});
|
|
499
|
+
socket.on("error", () => socket.destroy());
|
|
500
|
+
}
|
|
501
|
+
send(conn, obj, flushed) {
|
|
502
|
+
if (conn.socket.destroyed) {
|
|
503
|
+
flushed?.();
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
try {
|
|
507
|
+
conn.socket.write(encodeFrame(obj), flushed);
|
|
508
|
+
} catch {
|
|
509
|
+
const id = obj?.id;
|
|
510
|
+
if (typeof id === "string" || typeof id === "number") conn.socket.write(encodeFrame(makeError(id, RpcErrorCode.InternalError, "The response was too large to send.")));
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
async onFrame(conn, frame) {
|
|
514
|
+
if (!frame.ok) {
|
|
515
|
+
if (frame.error.code === "invalid_json") this.send(conn, makeError(null, RpcErrorCode.ParseError, "Parse error: line is not valid JSON."));
|
|
516
|
+
else this.send(conn, makeError(null, RpcErrorCode.InvalidRequest, "Line is longer than 1 MiB. Send smaller requests."));
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
const parsed = parseIpcRequest(frame.value);
|
|
520
|
+
if (!parsed.ok) {
|
|
521
|
+
const method = frame.value?.method;
|
|
522
|
+
const needsAuth = !conn.authed && method !== "hello" && method !== "auth";
|
|
523
|
+
const code = parsed.error.code;
|
|
524
|
+
if (needsAuth && (code === RpcErrorCode.MethodNotFound || code === RpcErrorCode.InvalidParams)) this.send(conn, makeError(parsed.id, RpcErrorCode.Unauthorized, unauthorizedMessage));
|
|
525
|
+
else this.send(conn, makeError(parsed.id, code, parsed.error.message, parsed.error.data));
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
const req = parsed.request;
|
|
529
|
+
if (!conn.authed && req.method !== "hello" && req.method !== "auth") {
|
|
530
|
+
this.send(conn, makeError(req.id, RpcErrorCode.Unauthorized, unauthorizedMessage));
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
try {
|
|
534
|
+
const result = await this.dispatch(conn, req);
|
|
535
|
+
const flushed = req.method === "daemon.shutdown" ? this.requestShutdown : void 0;
|
|
536
|
+
this.send(conn, makeResult(req.id, result), flushed);
|
|
537
|
+
} catch (e) {
|
|
538
|
+
this.sendError(conn, req.id, req.method, e);
|
|
539
|
+
if (req.method === "hello" || req.method === "auth") conn.socket.end();
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
sendError(conn, id, method, e) {
|
|
543
|
+
if (e instanceof ConvenoError) this.send(conn, makeError(id, e.code, e.message));
|
|
544
|
+
else {
|
|
545
|
+
this.log.error(`internal error in ${method}`, e);
|
|
546
|
+
this.send(conn, makeError(id, RpcErrorCode.InternalError, `The Conveno daemon hit an internal error. Check the daemon log at ${this.log.path}, then run "conveno daemon stop" and try again.`));
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
dispatch(conn, req) {
|
|
550
|
+
switch (req.method) {
|
|
551
|
+
case "hello": return this.hello(conn, req.params);
|
|
552
|
+
case "auth": return this.auth(conn, req.params);
|
|
553
|
+
case "session.register": return this.registerAsync(req.params);
|
|
554
|
+
case "session.heartbeat": return this.heartbeat(req.params.sessionId);
|
|
555
|
+
case "session.unregister": return this.unregister(req.params.sessionId);
|
|
556
|
+
case "session.rename": return this.rename(req.params);
|
|
557
|
+
case "session.setStatus": return this.setStatus(req.params);
|
|
558
|
+
case "session.list": return this.list(req.params);
|
|
559
|
+
case "session.byHost": return this.byHost(req.params.pid);
|
|
560
|
+
case "daemon.shutdown": return { ok: true };
|
|
561
|
+
case "orchestrator.claim": return this.claim(req.params.sessionId);
|
|
562
|
+
case "message.send": return this.sendMessage(req.params);
|
|
563
|
+
case "message.inbox": return this.inbox(req.params);
|
|
564
|
+
case "message.deliver": return this.deliver(req.params);
|
|
565
|
+
case "message.ack": return this.ack(req.params);
|
|
566
|
+
case "events.subscribe": return this.subscribe(conn, req.params);
|
|
567
|
+
default: throw new ConvenoError(RpcErrorCode.MethodNotFound, `Method not found: ${req.method}. This version of the Conveno daemon does not support it. Run "conveno daemon status" to see which version is running.`);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
hello(conn, p) {
|
|
571
|
+
if (conn.challenge !== void 0) throw new ConvenoError(RpcErrorCode.Conflict, "The handshake already started on this connection.");
|
|
572
|
+
if (p.protocolVersion !== "conveno/1") throw new ConvenoError(RpcErrorCode.VersionMismatch, `Protocol version "${p.protocolVersion}" is not supported. This daemon speaks "${PROTOCOL_VERSION}". Update the client or the daemon so the versions match.`);
|
|
573
|
+
conn.challenge = newAuthNonce();
|
|
574
|
+
return {
|
|
575
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
576
|
+
daemonVersion: DAEMON_VERSION,
|
|
577
|
+
proof: daemonProof(this.token, p.nonce),
|
|
578
|
+
challenge: conn.challenge
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
auth(conn, p) {
|
|
582
|
+
if (conn.challenge === void 0) throw new ConvenoError(RpcErrorCode.Unauthorized, unauthorizedMessage);
|
|
583
|
+
if (!proofsMatch(p.proof, clientProof(this.token, conn.challenge))) throw new ConvenoError(RpcErrorCode.Unauthorized, "The auth proof is wrong. The client must use the token in daemon.token in the Conveno data directory.");
|
|
584
|
+
conn.authed = true;
|
|
585
|
+
return { ok: true };
|
|
586
|
+
}
|
|
587
|
+
named(rows) {
|
|
588
|
+
return rows.map((r) => ({
|
|
589
|
+
id: r.id,
|
|
590
|
+
name: r.name,
|
|
591
|
+
status: r.status
|
|
592
|
+
}));
|
|
593
|
+
}
|
|
594
|
+
requireSession(id) {
|
|
595
|
+
const row = this.store.getSession(id);
|
|
596
|
+
if (!row) throw new ConvenoError(RpcErrorCode.NotFound, `No session with id ${id}. Register the session again.`);
|
|
597
|
+
return row;
|
|
598
|
+
}
|
|
599
|
+
view(row) {
|
|
600
|
+
return toSession(row, effectiveHolder(this.store.holder(), this.named([row]))?.id === row.id);
|
|
601
|
+
}
|
|
602
|
+
emit(payload, onlyTo) {
|
|
603
|
+
for (const c of this.conns) {
|
|
604
|
+
const sub = c.sub;
|
|
605
|
+
if (!sub?.topics.has(payload.event)) continue;
|
|
606
|
+
if (onlyTo !== void 0 && sub.sessionId !== onlyTo) continue;
|
|
607
|
+
this.send(c, makeEventNotification(payload));
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
emitSession(id, change) {
|
|
611
|
+
const row = this.store.getSession(id);
|
|
612
|
+
if (row) this.emit({
|
|
613
|
+
event: "session.updated",
|
|
614
|
+
data: {
|
|
615
|
+
session: this.view(row),
|
|
616
|
+
change
|
|
617
|
+
}
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
emitMessage(m, recipient) {
|
|
621
|
+
this.emit({
|
|
622
|
+
event: "message.received",
|
|
623
|
+
data: { message: m }
|
|
624
|
+
}, recipient);
|
|
625
|
+
}
|
|
626
|
+
async detect(p) {
|
|
627
|
+
if (p.repo) return p.repo;
|
|
628
|
+
const found = await detectRepo(p.cwd, { exists: (path) => existsSync(path) });
|
|
629
|
+
return found.root ? { root: found.root } : void 0;
|
|
630
|
+
}
|
|
631
|
+
register(p, repo) {
|
|
632
|
+
const id = newSessionId();
|
|
633
|
+
const at = this.iso();
|
|
634
|
+
const row = this.store.tx(() => {
|
|
635
|
+
const named = this.named(this.store.allSessions());
|
|
636
|
+
const base = baseName(repo?.root ?? p.cwd);
|
|
637
|
+
const name = p.name !== void 0 ? validateRename(id, p.name, named) : generateSessionName(p.cli, base, named);
|
|
638
|
+
const parent = p.spawnedBy ? this.store.getSession(p.spawnedBy) : void 0;
|
|
639
|
+
const r = {
|
|
640
|
+
id,
|
|
641
|
+
name,
|
|
642
|
+
cli: p.cli,
|
|
643
|
+
deviceId: this.deviceId,
|
|
644
|
+
cwd: p.cwd,
|
|
645
|
+
status: "idle",
|
|
646
|
+
deliveryTier: CLI_TIER[p.cli] ?? "inbox",
|
|
647
|
+
spawnDepth: parent ? parent.spawnDepth + 1 : 0,
|
|
648
|
+
startedAt: at,
|
|
649
|
+
lastSeenAt: at
|
|
650
|
+
};
|
|
651
|
+
if (p.cliVersion !== void 0) r.cliVersion = p.cliVersion;
|
|
652
|
+
if (repo) {
|
|
653
|
+
r.repoRoot = repo.root;
|
|
654
|
+
if (repo.remoteUrlHash !== void 0) r.repoRemoteUrlHash = repo.remoteUrlHash;
|
|
655
|
+
}
|
|
656
|
+
if (p.pid !== void 0) r.pid = p.pid;
|
|
657
|
+
if (p.hostPid !== void 0) r.hostPid = p.hostPid;
|
|
658
|
+
if (p.hostPids !== void 0) r.hostPids = p.hostPids;
|
|
659
|
+
if (p.spawnedBy !== void 0) r.spawnedBy = p.spawnedBy;
|
|
660
|
+
this.store.insertSession(r);
|
|
661
|
+
return r;
|
|
662
|
+
});
|
|
663
|
+
this.emitSession(row.id, "registered");
|
|
664
|
+
return { session: this.view(row) };
|
|
665
|
+
}
|
|
666
|
+
async registerAsync(p) {
|
|
667
|
+
return this.register(p, await this.detect(p));
|
|
668
|
+
}
|
|
669
|
+
heartbeat(sessionId) {
|
|
670
|
+
const row = this.requireSession(sessionId);
|
|
671
|
+
const at = this.iso();
|
|
672
|
+
if (row.status !== "offline") {
|
|
673
|
+
this.store.updateSession(sessionId, { lastSeenAt: at });
|
|
674
|
+
return { lastSeenAt: at };
|
|
675
|
+
}
|
|
676
|
+
const taken = this.named(this.store.allSessions()).some((s) => s.id !== sessionId && isOnline(s) && s.name === row.name);
|
|
677
|
+
if (row.hostPid !== void 0 && !this.isAlive(row.hostPid) || taken) throw new ConvenoError(RpcErrorCode.NotFound, `Session "${row.name}" is offline and cannot come back. Register the session again.`);
|
|
678
|
+
this.store.updateSession(sessionId, {
|
|
679
|
+
status: "idle",
|
|
680
|
+
lastSeenAt: at
|
|
681
|
+
});
|
|
682
|
+
this.emitSession(sessionId, "updated");
|
|
683
|
+
return { lastSeenAt: at };
|
|
684
|
+
}
|
|
685
|
+
depart(sessionId, change) {
|
|
686
|
+
const before = this.store.holder();
|
|
687
|
+
const after = holderAfterDeparture(before, sessionId);
|
|
688
|
+
this.store.tx(() => {
|
|
689
|
+
this.store.updateSession(sessionId, { status: "offline" });
|
|
690
|
+
if (after !== before) this.store.setHolder(after);
|
|
691
|
+
});
|
|
692
|
+
this.emitSession(sessionId, change);
|
|
693
|
+
if (after !== before) this.emit({
|
|
694
|
+
event: "orchestrator.changed",
|
|
695
|
+
data: {
|
|
696
|
+
orchestrator: after,
|
|
697
|
+
previous: before
|
|
698
|
+
}
|
|
699
|
+
});
|
|
700
|
+
}
|
|
701
|
+
unregister(sessionId) {
|
|
702
|
+
if (this.requireSession(sessionId).status !== "offline") this.depart(sessionId, "unregistered");
|
|
703
|
+
return { ok: true };
|
|
704
|
+
}
|
|
705
|
+
rename(p) {
|
|
706
|
+
const row = this.requireSession(p.sessionId);
|
|
707
|
+
const name = validateRename(p.sessionId, p.name, this.named(this.store.allSessions()));
|
|
708
|
+
if (name !== row.name) {
|
|
709
|
+
this.store.updateSession(p.sessionId, { name });
|
|
710
|
+
this.emitSession(p.sessionId, "updated");
|
|
711
|
+
}
|
|
712
|
+
return { session: this.view(this.requireSession(p.sessionId)) };
|
|
713
|
+
}
|
|
714
|
+
setStatus(p) {
|
|
715
|
+
const row = this.requireSession(p.sessionId);
|
|
716
|
+
if (row.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${row.name}" is offline. Register the session again.`);
|
|
717
|
+
if (p.status === "offline") throw new ConvenoError(RpcErrorCode.InvalidParams, "Status \"offline\" is set by the daemon. Use idle, busy or waiting_on_question, or unregister the session.");
|
|
718
|
+
const fields = {};
|
|
719
|
+
if (p.status !== void 0) fields.status = p.status;
|
|
720
|
+
if (p.statusText !== void 0) {
|
|
721
|
+
const clean = p.statusText === null ? "" : sanitizeLine(p.statusText);
|
|
722
|
+
fields.statusText = clean === "" ? null : clean;
|
|
723
|
+
}
|
|
724
|
+
this.store.updateSession(p.sessionId, fields);
|
|
725
|
+
this.emitSession(p.sessionId, "updated");
|
|
726
|
+
return { session: this.view(this.requireSession(p.sessionId)) };
|
|
727
|
+
}
|
|
728
|
+
list(p) {
|
|
729
|
+
return { sessions: this.store.allSessions().filter((r) => {
|
|
730
|
+
if (!p.includeOffline && r.status === "offline") return false;
|
|
731
|
+
if (p.cli && r.cli !== p.cli) return false;
|
|
732
|
+
if (p.repo && r.repoRoot !== p.repo && baseName(r.repoRoot ?? r.cwd) !== p.repo) return false;
|
|
733
|
+
return true;
|
|
734
|
+
}).map((r) => this.view(r)) };
|
|
735
|
+
}
|
|
736
|
+
/**
|
|
737
|
+
* Find the session a hook belongs to: the one online session whose `hostPid` equals `pid`.
|
|
738
|
+
* Exact equality only, with no walk to farther ancestors, so a hook from a CLI that has no
|
|
739
|
+
* session matches nothing. Two sessions under one CLI process are ambiguous, so the result is
|
|
740
|
+
* null; the daemon never guesses.
|
|
741
|
+
*/
|
|
742
|
+
byHost(pid) {
|
|
743
|
+
const holders = this.store.allSessions().filter((r) => r.status !== "offline" && r.hostPid === pid);
|
|
744
|
+
const only = holders.length === 1 ? holders[0] : void 0;
|
|
745
|
+
return { session: only ? this.view(only) : null };
|
|
746
|
+
}
|
|
747
|
+
claim(sessionId) {
|
|
748
|
+
this.requireSession(sessionId);
|
|
749
|
+
const rows = this.store.allSessions();
|
|
750
|
+
const holder = this.store.holder();
|
|
751
|
+
const res = claimOrchestrator(holder, sessionId, this.named(rows));
|
|
752
|
+
const at = this.iso();
|
|
753
|
+
const sent = [];
|
|
754
|
+
this.store.tx(() => {
|
|
755
|
+
this.store.setHolder(res.orchestrator);
|
|
756
|
+
for (const n of res.notices) {
|
|
757
|
+
const m = {
|
|
758
|
+
id: newMessageId(),
|
|
759
|
+
from: DAEMON_SENDER_ID,
|
|
760
|
+
to: n.to,
|
|
761
|
+
kind: "system",
|
|
762
|
+
body: {
|
|
763
|
+
event: n.event,
|
|
764
|
+
detail: n.detail
|
|
765
|
+
},
|
|
766
|
+
urgent: false,
|
|
767
|
+
createdAt: at
|
|
768
|
+
};
|
|
769
|
+
this.store.insertMessage(m, n.to, at);
|
|
770
|
+
sent.push(m);
|
|
771
|
+
}
|
|
772
|
+
});
|
|
773
|
+
if (res.notices.length > 0) {
|
|
774
|
+
this.emit({
|
|
775
|
+
event: "orchestrator.changed",
|
|
776
|
+
data: {
|
|
777
|
+
orchestrator: res.orchestrator,
|
|
778
|
+
previous: res.previous
|
|
779
|
+
}
|
|
780
|
+
});
|
|
781
|
+
this.emitSession(sessionId, "updated");
|
|
782
|
+
if (res.previous) this.emitSession(res.previous, "updated");
|
|
783
|
+
for (const m of sent) this.emitMessage(m, m.to);
|
|
784
|
+
}
|
|
785
|
+
return {
|
|
786
|
+
orchestrator: res.orchestrator,
|
|
787
|
+
previous: res.previous
|
|
788
|
+
};
|
|
789
|
+
}
|
|
790
|
+
sendMessage(p) {
|
|
791
|
+
const sender = this.requireSession(p.sessionId);
|
|
792
|
+
if (sender.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${sender.name}" is offline. Register the session again before sending.`);
|
|
793
|
+
if (p.kind === "system") throw new ConvenoError(RpcErrorCode.InvalidParams, "Messages of kind \"system\" are made by the Conveno daemon only. Send kind \"text\" instead.");
|
|
794
|
+
if (p.replyTo !== void 0 && !this.store.hasMessage(p.replyTo)) throw new ConvenoError(RpcErrorCode.NotFound, `Message ${p.replyTo} does not exist, so it cannot be replied to. Check the message id.`);
|
|
795
|
+
const rows = this.store.allSessions();
|
|
796
|
+
const target = resolveRecipient(p.to, this.named(rows), this.store.holder());
|
|
797
|
+
const targetRow = rows.find((r) => r.id === target.id);
|
|
798
|
+
if (this.store.unreadCount(targetRow.id) >= 1e3) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(targetRow.name, MAX_UNREAD_PER_SESSION));
|
|
799
|
+
const at = this.iso();
|
|
800
|
+
const message = {
|
|
801
|
+
id: newMessageId(),
|
|
802
|
+
from: sender.id,
|
|
803
|
+
to: p.to,
|
|
804
|
+
kind: p.kind,
|
|
805
|
+
body: p.body,
|
|
806
|
+
urgent: p.urgent,
|
|
807
|
+
createdAt: at,
|
|
808
|
+
fromName: sender.name,
|
|
809
|
+
fromCli: sender.cli,
|
|
810
|
+
...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
|
|
811
|
+
};
|
|
812
|
+
this.store.insertMessage(message, targetRow.id, at);
|
|
813
|
+
this.emitMessage(message, targetRow.id);
|
|
814
|
+
return {
|
|
815
|
+
message,
|
|
816
|
+
delivery: targetRow.deliveryTier,
|
|
817
|
+
deliveredTo: {
|
|
818
|
+
id: targetRow.id,
|
|
819
|
+
name: targetRow.name
|
|
820
|
+
}
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
inbox(p) {
|
|
824
|
+
this.requireSession(p.sessionId);
|
|
825
|
+
const at = this.iso();
|
|
826
|
+
return this.store.tx(() => {
|
|
827
|
+
const entries = this.store.entries(p.sessionId, p.unreadOnly ? { states: ["queued"] } : {});
|
|
828
|
+
const res = readInbox(entries, {
|
|
829
|
+
unreadOnly: p.unreadOnly,
|
|
830
|
+
limit: p.limit,
|
|
831
|
+
maxBytes: RESPONSE_BUDGET_BYTES
|
|
832
|
+
}, at);
|
|
833
|
+
const changed = new Set(res.returned.map((e) => e.message.id));
|
|
834
|
+
for (const e of res.entries) if (changed.has(e.message.id)) this.store.saveEntry(p.sessionId, e);
|
|
835
|
+
return {
|
|
836
|
+
messages: res.returned.map((e) => e.message),
|
|
837
|
+
unreadCount: res.unreadCount
|
|
838
|
+
};
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
deliver(p) {
|
|
842
|
+
this.requireSession(p.sessionId);
|
|
843
|
+
const at = this.iso();
|
|
844
|
+
return this.store.tx(() => {
|
|
845
|
+
const pending = pendingForInjection(this.store.entries(p.sessionId, { states: ["queued"] }));
|
|
846
|
+
const taken = takeWithinBytes(pending.slice(0, p.limit), RESPONSE_BUDGET_BYTES);
|
|
847
|
+
const updated = markDelivered(taken, taken.map((e) => e.message.id), at);
|
|
848
|
+
for (const e of updated) this.store.saveEntry(p.sessionId, e);
|
|
849
|
+
return {
|
|
850
|
+
messages: updated.map((e) => e.message),
|
|
851
|
+
remaining: pending.length - taken.length
|
|
852
|
+
};
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
ack(p) {
|
|
856
|
+
this.requireSession(p.sessionId);
|
|
857
|
+
const at = this.iso();
|
|
858
|
+
return this.store.tx(() => {
|
|
859
|
+
const entries = this.store.entries(p.sessionId, { ids: p.ids });
|
|
860
|
+
const res = ackEntries(entries, p.ids, at);
|
|
861
|
+
for (const e of res.entries) this.store.saveEntry(p.sessionId, e);
|
|
862
|
+
return { acked: res.acked };
|
|
863
|
+
});
|
|
864
|
+
}
|
|
865
|
+
subscribe(conn, p) {
|
|
866
|
+
this.requireSession(p.sessionId);
|
|
867
|
+
const topics = p.topics ?? [...EVENT_NAMES];
|
|
868
|
+
conn.sub = {
|
|
869
|
+
sessionId: p.sessionId,
|
|
870
|
+
topics: new Set(topics)
|
|
871
|
+
};
|
|
872
|
+
return { subscribed: topics };
|
|
873
|
+
}
|
|
874
|
+
/**
|
|
875
|
+
* Prune rules for an offline session, in order:
|
|
876
|
+
* 1. With unread messages waiting, keep it for PRUNE_UNREAD_AFTER_MS, then delete it and its mail.
|
|
877
|
+
* 2. Replaced by a newer live session with the same name, CLI and repo: delete after
|
|
878
|
+
* PRUNE_SUPERSEDED_AFTER_MS.
|
|
879
|
+
* 3. Otherwise delete after PRUNE_OFFLINE_AFTER_MS.
|
|
880
|
+
*/
|
|
881
|
+
shouldPrune(row, all, nowMs) {
|
|
882
|
+
const offlineMs = nowMs - Date.parse(row.lastSeenAt);
|
|
883
|
+
if (this.store.unreadCount(row.id) > 0) return offlineMs >= PRUNE_UNREAD_AFTER_MS;
|
|
884
|
+
const place = (r) => r.repoRoot ?? r.cwd;
|
|
885
|
+
return offlineMs >= (all.some((o) => o.id !== row.id && o.status !== "offline" && o.name === row.name && o.cli === row.cli && place(o) === place(row) && Date.parse(o.startedAt) > Date.parse(row.startedAt)) ? PRUNE_SUPERSEDED_AFTER_MS : PRUNE_OFFLINE_AFTER_MS);
|
|
886
|
+
}
|
|
887
|
+
sweep() {
|
|
888
|
+
const nowMs = this.now().getTime();
|
|
889
|
+
let online = 0;
|
|
890
|
+
const rows = this.store.allSessions();
|
|
891
|
+
for (const row of rows) {
|
|
892
|
+
if (row.status === "offline") {
|
|
893
|
+
if (this.shouldPrune(row, rows, nowMs)) this.store.tx(() => this.store.deleteSession(row.id));
|
|
894
|
+
continue;
|
|
895
|
+
}
|
|
896
|
+
const lastSeenMs = Math.max(Date.parse(row.lastSeenAt), this.startedMs);
|
|
897
|
+
const verdict = evaluateLiveness({
|
|
898
|
+
lastSeenMs,
|
|
899
|
+
hostPid: row.hostPid
|
|
900
|
+
}, nowMs, this.isAlive);
|
|
901
|
+
if (statusAfterLiveness(row.status, verdict) === "offline") this.depart(row.id, "offline");
|
|
902
|
+
else online++;
|
|
903
|
+
}
|
|
904
|
+
if (online > 0) this.idleSince = nowMs;
|
|
905
|
+
else if (nowMs - this.idleSince >= this.idleExitMs) this.requestIdleExit();
|
|
906
|
+
}
|
|
907
|
+
};
|
|
908
|
+
const unauthorizedMessage = "Finish the handshake first: call hello, then auth. Both use the token in daemon.token in the Conveno data directory.";
|
|
909
|
+
/** Start convenod: take the lock, open the database, listen on the socket. */
|
|
910
|
+
async function startDaemon(opts) {
|
|
911
|
+
const platform = process.platform;
|
|
912
|
+
const paths = dataPaths(platform, opts.dataDir);
|
|
913
|
+
const socketPath = opts.socketPath ?? defaultSocketPath(platform, process.env, homedir());
|
|
914
|
+
if (isSocketPathTooLong(socketPath, platform)) throw new Error(socketPathTooLongMessage(socketPath, platform));
|
|
915
|
+
const now = opts.now ?? (() => /* @__PURE__ */ new Date());
|
|
916
|
+
const isAlive = opts.isAlive ?? defaultIsAlive;
|
|
917
|
+
ensureDir(opts.dataDir);
|
|
918
|
+
const releaseLock = await acquireLock(paths.lock, socketPath);
|
|
919
|
+
let store;
|
|
920
|
+
let server;
|
|
921
|
+
try {
|
|
922
|
+
const token = loadOrCreateToken(paths.token);
|
|
923
|
+
store = new Store(paths.database);
|
|
924
|
+
if (platform !== "win32" && !socketPath.startsWith("\\\\")) ensureDir(dirname(socketPath));
|
|
925
|
+
await clearStaleSocket(socketPath);
|
|
926
|
+
let closing;
|
|
927
|
+
let timer;
|
|
928
|
+
const daemon = new Daemon(store, token, now, isAlive, opts.idleExitMs ?? 6e5, () => {
|
|
929
|
+
close().then(() => opts.onIdleExit?.());
|
|
930
|
+
}, () => {
|
|
931
|
+
close().then(() => opts.onShutdown?.());
|
|
932
|
+
}, createDaemonLog(paths.daemonLog, { now }), opts.authTimeoutMs ?? 5e3);
|
|
933
|
+
const srv = createServer((socket) => daemon.attach(socket));
|
|
934
|
+
server = srv;
|
|
935
|
+
await new Promise((resolve, reject) => {
|
|
936
|
+
srv.once("error", (e) => reject(e.code === "EADDRINUSE" ? new DaemonAlreadyRunningError(`socket ${socketPath}`) : e));
|
|
937
|
+
srv.listen(socketPath, () => resolve());
|
|
938
|
+
});
|
|
939
|
+
if (platform !== "win32" && !socketPath.startsWith("\\\\")) chmodSync(socketPath, 384);
|
|
940
|
+
timer = setInterval(() => daemon.sweep(), opts.sweepIntervalMs ?? 15e3);
|
|
941
|
+
timer.unref();
|
|
942
|
+
const liveStore = store;
|
|
943
|
+
function close() {
|
|
944
|
+
closing ??= (async () => {
|
|
945
|
+
if (timer) clearInterval(timer);
|
|
946
|
+
const stopped = new Promise((resolve) => srv.close(() => resolve()));
|
|
947
|
+
for (const c of daemon.conns) c.socket.destroy();
|
|
948
|
+
await stopped;
|
|
949
|
+
liveStore.close();
|
|
950
|
+
if (platform !== "win32" && !socketPath.startsWith("\\\\")) rmSync(socketPath, { force: true });
|
|
951
|
+
releaseLock();
|
|
952
|
+
})();
|
|
953
|
+
return closing;
|
|
954
|
+
}
|
|
955
|
+
return {
|
|
956
|
+
socketPath,
|
|
957
|
+
close,
|
|
958
|
+
sweep: () => daemon.sweep()
|
|
959
|
+
};
|
|
960
|
+
} catch (e) {
|
|
961
|
+
server?.close();
|
|
962
|
+
store?.close();
|
|
963
|
+
releaseLock();
|
|
964
|
+
throw e;
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
// ../daemon/src/bin.ts
|
|
968
|
+
async function main() {
|
|
969
|
+
const handle = await startDaemon({
|
|
970
|
+
dataDir: dataDir(process.platform, process.env, homedir()),
|
|
971
|
+
onIdleExit: () => {
|
|
972
|
+
process.stderr.write("convenod: no sessions for a while, exiting.\n");
|
|
973
|
+
process.exit(0);
|
|
974
|
+
},
|
|
975
|
+
onShutdown: () => process.exit(0)
|
|
976
|
+
});
|
|
977
|
+
process.stderr.write(`convenod: listening on ${handle.socketPath}\n`);
|
|
978
|
+
let stopping = false;
|
|
979
|
+
const stop = () => {
|
|
980
|
+
if (stopping) return;
|
|
981
|
+
stopping = true;
|
|
982
|
+
handle.close().then(() => process.exit(0));
|
|
983
|
+
};
|
|
984
|
+
process.on("SIGINT", stop);
|
|
985
|
+
process.on("SIGTERM", stop);
|
|
986
|
+
}
|
|
987
|
+
main().catch((e) => {
|
|
988
|
+
if (e instanceof DaemonAlreadyRunningError) {
|
|
989
|
+
process.stderr.write(`${e.message}\n`);
|
|
990
|
+
process.exit(0);
|
|
991
|
+
}
|
|
992
|
+
process.stderr.write(`convenod failed to start: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
993
|
+
process.exit(1);
|
|
994
|
+
});
|
|
995
|
+
export {};
|