@conveno/cli 0.2.0-rc.8 → 0.2.0
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 +3 -5
- package/dist/{acp-YHhVx0Ya.js → acp-BUddItzP.js} +39 -7
- package/dist/{agy-relay-BS2NeFlh.js → agy-relay-BZ3d_-FS.js} +4 -2
- package/dist/{args-CGL-AmNd.js → args-CtyKPZuN.js} +29 -8
- package/dist/bin.js +16 -2
- package/dist/daemon.js +4 -3139
- package/dist/{daemonError-DJ-P55nH.js → daemonError-CDgEtvy7.js} +1 -1
- package/dist/dist-BNhTPp5p.js +4509 -0
- package/dist/{dist-BRjg9CLd.js → dist-BOwFdixw.js} +23 -50
- package/dist/{dist-CcoTmwrf.js → dist-CFsDqevs.js} +94 -56
- package/dist/dist-CNdqmI3E.js +1065 -0
- package/dist/{dist-BBdba94T.js → dist-CSSvrcKr.js} +1752 -708
- package/dist/{dist-B6Sm0MRT.js → dist-D6Xoip5W.js} +203 -62
- package/dist/{dist-WTkKRM39.js → dist-DAVtixeC.js} +19 -5
- package/dist/dist-DTMnNySx.js +989 -0
- package/dist/hook-BA-tI6Oc.js +208 -0
- package/dist/hook-entry-BwzBtAnd.js +1346 -0
- package/dist/hook-entry-Cgt5ZH1s.js +1 -0
- package/dist/{main-DrzHsV5y.js → main-kKnLA7Hj.js} +58 -21
- package/dist/{pick-Bi1yJDh6.js → pick-BsMvXuDo.js} +1 -1
- package/dist/run-PQBzaHv1.js +8193 -0
- package/dist/{runtime-Db_YT5Xg.js → runtime-0FMqklYn.js} +233 -122
- package/dist/{uninstall-D9rW_j7H.js → uninstall-DcxkIDpk.js} +556 -82
- package/dist/{watch-BrTWYf3Y.js → watch-BIepRTXJ.js} +29 -7
- package/package.json +14 -15
- package/dist/dist-B1EVHdIM.js +0 -504
- package/dist/dist-BlWWt5gx.js +0 -624
- package/dist/dist-C6cMQ00I.js +0 -793
- package/dist/hook-DxjJDCjz.js +0 -94
- package/dist/hook-entry-CrpZz5QW.js +0 -1
- package/dist/hook-entry-pHJioNgN.js +0 -2494
- package/dist/run-C32oP2c_.js +0 -5550
package/dist/daemon.js
CHANGED
|
@@ -1,3141 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
7
|
-
import { connect, createServer } from "node:net";
|
|
8
|
-
import { dirname, join, posix, win32 } from "node:path";
|
|
9
|
-
import { _ as sasMatches, a as JoinerPairing, b as signRelayHello, c as decodePairMessage, d as forkPoint, f as generateIdentity, g as publicRecord, h as parseIdentity, i as InviterPairing, l as deviceFingerprint, m as openEnvelope, n as ENVELOPE_MAX_AGE_MS, o as appendRevoke, p as headMatches, r as ENVELOPE_MAX_FUTURE_MS, s as chainHead, t as CryptoError, u as encodePairMessage, v as sealEnvelope, x as verifyChain, y as serializeIdentity } from "./dist-C6cMQ00I.js";
|
|
10
|
-
import { execFileSync } from "node:child_process";
|
|
11
|
-
import { DatabaseSync } from "node:sqlite";
|
|
12
|
-
// ../daemon/src/lifecycle.ts
|
|
13
|
-
/** Thrown when another Conveno daemon already owns the lock file or answers on the socket. */
|
|
14
|
-
var DaemonAlreadyRunningError = class extends Error {
|
|
15
|
-
constructor(detail) {
|
|
16
|
-
super(`The Conveno daemon is already running (${detail}). Run "conveno daemon status" to see it.`);
|
|
17
|
-
this.name = "DaemonAlreadyRunningError";
|
|
18
|
-
}
|
|
19
|
-
};
|
|
20
|
-
/** `kill(pid, 0)` liveness: EPERM means the process exists but belongs to someone else. */
|
|
21
|
-
function defaultIsAlive(pid) {
|
|
22
|
-
try {
|
|
23
|
-
process.kill(pid, 0);
|
|
24
|
-
return true;
|
|
25
|
-
} catch (e) {
|
|
26
|
-
return e.code === "EPERM";
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
/** True when something accepts connections on the socket or pipe. */
|
|
30
|
-
function probeSocket(socketPath, timeoutMs = 500) {
|
|
31
|
-
return new Promise((resolve) => {
|
|
32
|
-
const s = connect(socketPath);
|
|
33
|
-
const done = (alive) => {
|
|
34
|
-
clearTimeout(timer);
|
|
35
|
-
s.destroy();
|
|
36
|
-
resolve(alive);
|
|
37
|
-
};
|
|
38
|
-
const timer = setTimeout(() => done(false), timeoutMs);
|
|
39
|
-
s.once("connect", () => done(true));
|
|
40
|
-
s.once("error", () => done(false));
|
|
41
|
-
});
|
|
42
|
-
}
|
|
43
|
-
/** A lock younger than this is trusted even if the socket does not answer yet (daemon booting). */
|
|
44
|
-
const LOCK_GRACE_MS = 5e3;
|
|
45
|
-
/**
|
|
46
|
-
* Create the lock file exclusively. The lock records the pid and the socket path of its owner.
|
|
47
|
-
* An existing lock is stale unless its pid is alive and either the socket recorded in the lock
|
|
48
|
-
* answers or the lock is brand new. The recorded socket is probed, not the new daemon's own, so
|
|
49
|
-
* a daemon started with a different socket path is still seen as running. Returns a function that
|
|
50
|
-
* releases the lock.
|
|
51
|
-
*/
|
|
52
|
-
async function acquireLock(lockPath, socketPath) {
|
|
53
|
-
for (let attempt = 0; attempt < 3; attempt++) {
|
|
54
|
-
try {
|
|
55
|
-
writeFileSync(lockPath, JSON.stringify({
|
|
56
|
-
pid: process.pid,
|
|
57
|
-
socketPath
|
|
58
|
-
}), {
|
|
59
|
-
flag: "wx",
|
|
60
|
-
mode: 384
|
|
61
|
-
});
|
|
62
|
-
return () => {
|
|
63
|
-
try {
|
|
64
|
-
unlinkSync(lockPath);
|
|
65
|
-
} catch {}
|
|
66
|
-
};
|
|
67
|
-
} catch (e) {
|
|
68
|
-
if (e.code !== "EEXIST") throw e;
|
|
69
|
-
}
|
|
70
|
-
let pid = 0;
|
|
71
|
-
let lockedSocket = socketPath;
|
|
72
|
-
let ageMs = Number.POSITIVE_INFINITY;
|
|
73
|
-
try {
|
|
74
|
-
const lock = JSON.parse(readFileSync(lockPath, "utf8"));
|
|
75
|
-
pid = lock.pid ?? 0;
|
|
76
|
-
if (typeof lock.socketPath === "string" && lock.socketPath !== "") lockedSocket = lock.socketPath;
|
|
77
|
-
ageMs = Date.now() - statSync(lockPath).mtimeMs;
|
|
78
|
-
} catch {}
|
|
79
|
-
if (pid > 0 && defaultIsAlive(pid) && (ageMs < LOCK_GRACE_MS || await probeSocket(lockedSocket))) throw new DaemonAlreadyRunningError(`pid ${pid}`);
|
|
80
|
-
try {
|
|
81
|
-
unlinkSync(lockPath);
|
|
82
|
-
} catch {}
|
|
83
|
-
}
|
|
84
|
-
throw new DaemonAlreadyRunningError("could not take the lock file");
|
|
85
|
-
}
|
|
86
|
-
/**
|
|
87
|
-
* POSIX only: remove a leftover socket file, but only after confirming no live daemon answers on it.
|
|
88
|
-
* Named pipes on Windows vanish with their owner, so there is nothing to remove.
|
|
89
|
-
*/
|
|
90
|
-
async function clearStaleSocket(socketPath) {
|
|
91
|
-
if (process.platform === "win32" || socketPath.startsWith("\\\\")) return;
|
|
92
|
-
if (!existsSync(socketPath)) return;
|
|
93
|
-
if (await probeSocket(socketPath)) throw new DaemonAlreadyRunningError(`socket ${socketPath}`);
|
|
94
|
-
try {
|
|
95
|
-
unlinkSync(socketPath);
|
|
96
|
-
} catch (e) {
|
|
97
|
-
if (e.code !== "ENOENT") throw e;
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
/**
|
|
101
|
-
* Read the auth token, creating it (32 random bytes, hex) with mode 0600 on first start.
|
|
102
|
-
* On Windows the mode is ignored; the file inherits the ACL of the per-user data directory.
|
|
103
|
-
*/
|
|
104
|
-
function loadOrCreateToken(tokenPath) {
|
|
105
|
-
if (existsSync(tokenPath)) {
|
|
106
|
-
const t = readFileSync(tokenPath, "utf8").trim();
|
|
107
|
-
if (t.length >= 32) {
|
|
108
|
-
if (process.platform !== "win32") chmodSync(tokenPath, 384);
|
|
109
|
-
return t;
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
const token = randomBytes(32).toString("hex");
|
|
113
|
-
writeFileSync(tokenPath, `${token}\n`, { mode: 384 });
|
|
114
|
-
if (process.platform !== "win32") chmodSync(tokenPath, 384);
|
|
115
|
-
return token;
|
|
116
|
-
}
|
|
117
|
-
function ensureDir(dir) {
|
|
118
|
-
mkdirSync(dir, {
|
|
119
|
-
recursive: true,
|
|
120
|
-
mode: 448
|
|
121
|
-
});
|
|
122
|
-
}
|
|
123
|
-
const describeError = (e) => e instanceof Error ? e.stack ?? `${e.name}: ${e.message}` : String(e);
|
|
124
|
-
/**
|
|
125
|
-
* The daemon's own log, for errors it did not expect and for events the owner should be able to
|
|
126
|
-
* see. One file, readable by the user only, with one older generation kept: when the file reaches
|
|
127
|
-
* `maxBytes` it replaces `<path>.1` and a new file starts. Request parameters are never logged,
|
|
128
|
-
* since they can hold message text.
|
|
129
|
-
*/
|
|
130
|
-
function createDaemonLog(path, opts = {}) {
|
|
131
|
-
const maxBytes = opts.maxBytes ?? 1048576;
|
|
132
|
-
const now = opts.now ?? (() => /* @__PURE__ */ new Date());
|
|
133
|
-
const append = (text) => {
|
|
134
|
-
try {
|
|
135
|
-
mkdirSync(dirname(path), {
|
|
136
|
-
recursive: true,
|
|
137
|
-
mode: 448
|
|
138
|
-
});
|
|
139
|
-
let size = 0;
|
|
140
|
-
try {
|
|
141
|
-
size = statSync(path).size;
|
|
142
|
-
} catch {}
|
|
143
|
-
if (size >= maxBytes) {
|
|
144
|
-
rmSync(`${path}.1`, { force: true });
|
|
145
|
-
renameSync(path, `${path}.1`);
|
|
146
|
-
}
|
|
147
|
-
appendFileSync(path, text, { mode: 384 });
|
|
148
|
-
if (process.platform !== "win32") chmodSync(path, 384);
|
|
149
|
-
} catch {}
|
|
150
|
-
};
|
|
151
|
-
return {
|
|
152
|
-
path,
|
|
153
|
-
error(what, e) {
|
|
154
|
-
append(`${now().toISOString()} ${what}\n${describeError(e)}\n\n`);
|
|
155
|
-
},
|
|
156
|
-
note(line) {
|
|
157
|
-
append(`${now().toISOString()} ${line.replace(/[\r\n]+/g, " ")}\n`);
|
|
158
|
-
}
|
|
159
|
-
};
|
|
160
|
-
}
|
|
161
|
-
const HANDSHAKE_TIMEOUT_MS = 15e3;
|
|
162
|
-
/**
|
|
163
|
-
* One WebSocket to the relay: challenge, signed hello, then frames. It does not reconnect by
|
|
164
|
-
* itself; the hub decides when to try again. The access token goes in the Authorization header
|
|
165
|
-
* of the upgrade request, never in the URL, so it does not end up in access logs.
|
|
166
|
-
*/
|
|
167
|
-
var RelayConnection = class {
|
|
168
|
-
o;
|
|
169
|
-
ws;
|
|
170
|
-
pinger;
|
|
171
|
-
handshake;
|
|
172
|
-
stateValue = "idle";
|
|
173
|
-
stopped = false;
|
|
174
|
-
explaining = false;
|
|
175
|
-
constructor(o) {
|
|
176
|
-
this.o = o;
|
|
177
|
-
}
|
|
178
|
-
get state() {
|
|
179
|
-
return this.stateValue;
|
|
180
|
-
}
|
|
181
|
-
start() {
|
|
182
|
-
this.stateValue = "connecting";
|
|
183
|
-
const ws = new WebSocket(this.o.url, { headers: { Authorization: `Bearer ${this.o.token}` } });
|
|
184
|
-
this.ws = ws;
|
|
185
|
-
this.handshake = setTimeout(() => this.fail("The relay did not answer in time."), HANDSHAKE_TIMEOUT_MS);
|
|
186
|
-
this.handshake.unref();
|
|
187
|
-
ws.addEventListener("message", (e) => this.onMessage(e.data));
|
|
188
|
-
ws.addEventListener("error", () => {
|
|
189
|
-
if (this.stateValue === "connecting") {
|
|
190
|
-
this.explaining = true;
|
|
191
|
-
this.explainFailure();
|
|
192
|
-
} else this.fail("The connection to the relay failed.");
|
|
193
|
-
});
|
|
194
|
-
ws.addEventListener("close", (e) => {
|
|
195
|
-
if (!this.explaining) this.fail(`The relay closed the connection (${e.code} ${e.reason}).`);
|
|
196
|
-
});
|
|
197
|
-
}
|
|
198
|
-
/** Close for good; no `down` event. */
|
|
199
|
-
stop() {
|
|
200
|
-
this.stopped = true;
|
|
201
|
-
this.cleanup();
|
|
202
|
-
}
|
|
203
|
-
/** Send a frame if the connection is ready. Returns false when it is not. */
|
|
204
|
-
send(frame) {
|
|
205
|
-
if (this.stateValue !== "ready" || !this.ws) return false;
|
|
206
|
-
try {
|
|
207
|
-
this.ws.send(JSON.stringify(frame));
|
|
208
|
-
return true;
|
|
209
|
-
} catch {
|
|
210
|
-
return false;
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
onMessage(data) {
|
|
214
|
-
if (typeof data !== "string" || data === "pong") return;
|
|
215
|
-
let json;
|
|
216
|
-
try {
|
|
217
|
-
json = JSON.parse(data);
|
|
218
|
-
} catch {
|
|
219
|
-
return;
|
|
220
|
-
}
|
|
221
|
-
const r = parseRelayFrame(json);
|
|
222
|
-
if (!r.ok) return;
|
|
223
|
-
const f = r.value;
|
|
224
|
-
if (this.stateValue === "connecting") {
|
|
225
|
-
if (f.t === "challenge") this.ws?.send(JSON.stringify(signRelayHello(this.o.identity, f.nonce)));
|
|
226
|
-
else if (f.t === "ready") {
|
|
227
|
-
if (this.handshake) clearTimeout(this.handshake);
|
|
228
|
-
this.stateValue = "ready";
|
|
229
|
-
this.pinger = setInterval(() => {
|
|
230
|
-
try {
|
|
231
|
-
this.ws?.send("ping");
|
|
232
|
-
} catch {}
|
|
233
|
-
}, this.o.pingMs ?? 3e4);
|
|
234
|
-
this.pinger.unref();
|
|
235
|
-
this.o.events.ready(f.online);
|
|
236
|
-
} else if (f.t === "error") this.fail(f.message, f.code);
|
|
237
|
-
return;
|
|
238
|
-
}
|
|
239
|
-
this.o.events.frame(f);
|
|
240
|
-
}
|
|
241
|
-
async explainFailure() {
|
|
242
|
-
const httpUrl = this.o.url.replace(/^ws/, "http");
|
|
243
|
-
try {
|
|
244
|
-
const res = await (this.o.fetchImpl ?? fetch)(httpUrl, {
|
|
245
|
-
headers: { Authorization: `Bearer ${this.o.token}` },
|
|
246
|
-
signal: AbortSignal.timeout(1e4)
|
|
247
|
-
});
|
|
248
|
-
const body = await res.json().catch(() => ({}));
|
|
249
|
-
if (res.status === 401 || res.status === 403) return this.fail(body.error?.message ?? "The relay refused the access token.", body.error?.code);
|
|
250
|
-
this.fail(`The relay could not be reached (HTTP ${res.status}).`);
|
|
251
|
-
} catch {
|
|
252
|
-
this.fail("The relay could not be reached.");
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
fail(detail, code) {
|
|
256
|
-
if (this.stopped || this.stateValue === "disconnected") return;
|
|
257
|
-
this.stateValue = "disconnected";
|
|
258
|
-
this.cleanup();
|
|
259
|
-
this.o.events.down(detail, code);
|
|
260
|
-
}
|
|
261
|
-
cleanup() {
|
|
262
|
-
if (this.handshake) clearTimeout(this.handshake);
|
|
263
|
-
if (this.pinger) clearInterval(this.pinger);
|
|
264
|
-
try {
|
|
265
|
-
this.ws?.close();
|
|
266
|
-
} catch {}
|
|
267
|
-
}
|
|
268
|
-
};
|
|
269
|
-
// ../daemon/src/relay/state.ts
|
|
270
|
-
/** Files the relay client keeps in the data directory. */
|
|
271
|
-
function relayPaths(join, dataDir) {
|
|
272
|
-
return {
|
|
273
|
-
/** This device's secret keys. Mode 0600. */
|
|
274
|
-
identity: join(dataDir, "device-key.json"),
|
|
275
|
-
/** Device list, device name and seen envelope ids. Mode 0600. */
|
|
276
|
-
database: join(dataDir, "relay.db")
|
|
277
|
-
};
|
|
278
|
-
}
|
|
279
|
-
/**
|
|
280
|
-
* The icacls command that leaves only the current user with access to `path`: inherited entries
|
|
281
|
-
* removed (`/inheritance:r`), full control granted to the user, replacing any earlier grant
|
|
282
|
-
* (`/grant:r`). For a directory, `inherit` makes the grant apply to files and folders created in
|
|
283
|
-
* it (`(OI)(CI)`), so they are user-only from the moment they exist.
|
|
284
|
-
* See https://learn.microsoft.com/windows-server/administration/windows-commands/icacls.
|
|
285
|
-
* icacls is run from System32 by absolute path, never looked up on PATH.
|
|
286
|
-
*/
|
|
287
|
-
function userOnlyAclPlan(path, env, user, isFile, inherit = false) {
|
|
288
|
-
const systemRoot = env.SystemRoot ?? env.SYSTEMROOT ?? "C:\\Windows";
|
|
289
|
-
const icacls = win32.join(systemRoot, "System32", "icacls.exe");
|
|
290
|
-
const domain = env.USERDOMAIN;
|
|
291
|
-
const grant = `${domain ? `${domain}\\${user}` : user}:${inherit ? "(OI)(CI)" : ""}F`;
|
|
292
|
-
return planSpawn(icacls, [
|
|
293
|
-
path,
|
|
294
|
-
"/inheritance:r",
|
|
295
|
-
"/grant:r",
|
|
296
|
-
grant
|
|
297
|
-
], {
|
|
298
|
-
platform: "win32",
|
|
299
|
-
env,
|
|
300
|
-
...isFile ? { isFile } : {}
|
|
301
|
-
});
|
|
302
|
-
}
|
|
303
|
-
/**
|
|
304
|
-
* Make a file readable by the current user only: mode 0600 on POSIX, a user-only ACL on Windows
|
|
305
|
-
* (where the mode is ignored).
|
|
306
|
-
*/
|
|
307
|
-
function restrictToUser(path, platform = process.platform, directory = false) {
|
|
308
|
-
if (platform !== "win32") {
|
|
309
|
-
chmodSync(path, directory ? 448 : 384);
|
|
310
|
-
return;
|
|
311
|
-
}
|
|
312
|
-
const plan = userOnlyAclPlan(path, process.env, userInfo().username, void 0, directory);
|
|
313
|
-
execFileSync(plan.file, plan.args, {
|
|
314
|
-
stdio: "ignore",
|
|
315
|
-
windowsHide: true,
|
|
316
|
-
...plan.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
|
|
317
|
-
});
|
|
318
|
-
}
|
|
319
|
-
const restrictIfPresent = (path) => {
|
|
320
|
-
if (process.platform !== "win32" && existsSync(path)) chmodSync(path, 384);
|
|
321
|
-
};
|
|
322
|
-
/**
|
|
323
|
-
* Rename, retrying for a few seconds while Windows reports the file busy: a virus scanner often
|
|
324
|
-
* holds a file that was just written (graceful-fs retries renames for the same reason).
|
|
325
|
-
*/
|
|
326
|
-
function renameRetrying(from, to) {
|
|
327
|
-
const wait = new Int32Array(new SharedArrayBuffer(4));
|
|
328
|
-
for (let attempt = 0;; attempt++) try {
|
|
329
|
-
renameSync(from, to);
|
|
330
|
-
return;
|
|
331
|
-
} catch (e) {
|
|
332
|
-
const code = e.code;
|
|
333
|
-
if (attempt >= 30 || code !== "EPERM" && code !== "EACCES" && code !== "EBUSY") throw e;
|
|
334
|
-
Atomics.wait(wait, 0, 0, Math.min(25 * (attempt + 1), 200));
|
|
335
|
-
}
|
|
336
|
-
}
|
|
337
|
-
/**
|
|
338
|
-
* The user-only directory new key files are written in before they are renamed into place, so a
|
|
339
|
-
* key file never exists with the data folder's own, possibly broader, permissions. Made private
|
|
340
|
-
* once; a marker file inside it records that on Windows, where icacls is slow.
|
|
341
|
-
*/
|
|
342
|
-
function keyStagingDir(path, o, platform) {
|
|
343
|
-
const dir = join(dirname(path), ".key-staging");
|
|
344
|
-
const restrictDir = o.restrictDir ?? ((d) => restrictToUser(d, platform, true));
|
|
345
|
-
mkdirSync(dir, {
|
|
346
|
-
recursive: true,
|
|
347
|
-
mode: 448
|
|
348
|
-
});
|
|
349
|
-
const marker = join(dir, ".acl");
|
|
350
|
-
if (platform !== "win32") restrictDir(dir);
|
|
351
|
-
else if (!existsSync(marker)) {
|
|
352
|
-
restrictDir(dir);
|
|
353
|
-
writeFileSync(marker, "user-only ACL set\n");
|
|
354
|
-
}
|
|
355
|
-
return dir;
|
|
356
|
-
}
|
|
357
|
-
/** The identity stored at `path`, or undefined. Upgrades an old Windows key file's ACL once. */
|
|
358
|
-
function loadIdentity(path, o = {}) {
|
|
359
|
-
if (!existsSync(path)) return void 0;
|
|
360
|
-
const platform = o.platform ?? process.platform;
|
|
361
|
-
const restrict = o.restrict ?? ((f) => restrictToUser(f, platform));
|
|
362
|
-
const marker = `${path}.acl`;
|
|
363
|
-
const id = parseIdentity(JSON.parse(readFileSync(path, "utf8")));
|
|
364
|
-
if (platform === "win32") {
|
|
365
|
-
if (!existsSync(marker)) {
|
|
366
|
-
restrict(path);
|
|
367
|
-
writeFileSync(marker, "user-only ACL set\n");
|
|
368
|
-
}
|
|
369
|
-
} else restrict(path);
|
|
370
|
-
return id;
|
|
371
|
-
}
|
|
372
|
-
/**
|
|
373
|
-
* Write a new identity: a temporary file in the user-only staging directory, restricted to the
|
|
374
|
-
* user itself as well, then renamed into place (a rename on one volume keeps the file's ACL).
|
|
375
|
-
*/
|
|
376
|
-
function saveNewIdentity(path, id, o = {}) {
|
|
377
|
-
const platform = o.platform ?? process.platform;
|
|
378
|
-
const restrict = o.restrict ?? ((f) => restrictToUser(f, platform));
|
|
379
|
-
const tmp = join(keyStagingDir(path, o, platform), `${randomBytes(6).toString("hex")}.tmp`);
|
|
380
|
-
try {
|
|
381
|
-
writeFileSync(tmp, `${JSON.stringify(serializeIdentity(id))}\n`, {
|
|
382
|
-
mode: 384,
|
|
383
|
-
flag: "wx"
|
|
384
|
-
});
|
|
385
|
-
restrict(tmp);
|
|
386
|
-
renameRetrying(tmp, path);
|
|
387
|
-
} catch (e) {
|
|
388
|
-
rmSync(tmp, { force: true });
|
|
389
|
-
throw e;
|
|
390
|
-
}
|
|
391
|
-
if (platform === "win32") writeFileSync(`${path}.acl`, "user-only ACL set\n");
|
|
392
|
-
}
|
|
393
|
-
/** SQLite state of the relay client, in its own file so it never touches the session store. */
|
|
394
|
-
var RelayState = class {
|
|
395
|
-
path;
|
|
396
|
-
handle;
|
|
397
|
-
/**
|
|
398
|
-
* The file is created only when there is something to keep. Creating it (WAL mode and the
|
|
399
|
-
* schema) costs tens of milliseconds of disk syncs, which a daemon that never uses the relay
|
|
400
|
-
* should not pay at every start.
|
|
401
|
-
*/
|
|
402
|
-
constructor(path) {
|
|
403
|
-
this.path = path;
|
|
404
|
-
}
|
|
405
|
-
/** The open database, created on first write. */
|
|
406
|
-
get db() {
|
|
407
|
-
return this.handle ?? this.open();
|
|
408
|
-
}
|
|
409
|
-
/** The database for a read: undefined while the file does not exist, which reads as empty. */
|
|
410
|
-
get reader() {
|
|
411
|
-
return this.handle ?? (existsSync(this.path) ? this.open() : void 0);
|
|
412
|
-
}
|
|
413
|
-
open() {
|
|
414
|
-
const path = this.path;
|
|
415
|
-
const db = new DatabaseSync(path);
|
|
416
|
-
db.exec("PRAGMA journal_mode = WAL");
|
|
417
|
-
db.exec("PRAGMA synchronous = NORMAL");
|
|
418
|
-
db.exec("PRAGMA busy_timeout = 5000");
|
|
419
|
-
db.exec(`
|
|
420
|
-
BEGIN;
|
|
421
|
-
CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
422
|
-
CREATE TABLE IF NOT EXISTS seen (id TEXT PRIMARY KEY, ts INTEGER NOT NULL);
|
|
423
|
-
CREATE INDEX IF NOT EXISTS seen_ts ON seen (ts);
|
|
424
|
-
-- Messages from another device that arrived before its session list. Stored before the
|
|
425
|
-
-- envelope is acknowledged, so a restart or a flood cannot lose them.
|
|
426
|
-
CREATE TABLE IF NOT EXISTS held (
|
|
427
|
-
id TEXT PRIMARY KEY,
|
|
428
|
-
from_device TEXT NOT NULL,
|
|
429
|
-
payload TEXT NOT NULL,
|
|
430
|
-
since INTEGER NOT NULL
|
|
431
|
-
);
|
|
432
|
-
-- Local ids for sessions on other devices, so they can never collide with local ones.
|
|
433
|
-
CREATE TABLE IF NOT EXISTS alias (
|
|
434
|
-
alias TEXT PRIMARY KEY,
|
|
435
|
-
device_id TEXT NOT NULL,
|
|
436
|
-
remote_id TEXT NOT NULL,
|
|
437
|
-
UNIQUE (device_id, remote_id)
|
|
438
|
-
);
|
|
439
|
-
COMMIT;
|
|
440
|
-
`);
|
|
441
|
-
for (const f of [
|
|
442
|
-
path,
|
|
443
|
-
`${path}-wal`,
|
|
444
|
-
`${path}-shm`
|
|
445
|
-
]) restrictIfPresent(f);
|
|
446
|
-
this.handle = db;
|
|
447
|
-
return db;
|
|
448
|
-
}
|
|
449
|
-
close() {
|
|
450
|
-
this.handle?.close();
|
|
451
|
-
this.handle = void 0;
|
|
452
|
-
}
|
|
453
|
-
get(key) {
|
|
454
|
-
return (this.reader?.prepare("SELECT value FROM kv WHERE key = ?").get(key))?.value;
|
|
455
|
-
}
|
|
456
|
-
set(key, value) {
|
|
457
|
-
if (value === void 0) this.reader?.prepare("DELETE FROM kv WHERE key = ?").run(key);
|
|
458
|
-
else this.db.prepare("INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = ?").run(key, value, value);
|
|
459
|
-
}
|
|
460
|
-
/** The device list, or undefined when this device has none yet. Verified by the caller. */
|
|
461
|
-
chain() {
|
|
462
|
-
const raw = this.get("chain");
|
|
463
|
-
return raw === void 0 ? void 0 : JSON.parse(raw);
|
|
464
|
-
}
|
|
465
|
-
setChain(chain) {
|
|
466
|
-
this.set("chain", chain === void 0 ? void 0 : JSON.stringify(chain));
|
|
467
|
-
}
|
|
468
|
-
/** An unresolved disagreement about the device list, until the owner accepts a head. */
|
|
469
|
-
conflict() {
|
|
470
|
-
const raw = this.get("conflict");
|
|
471
|
-
return raw === void 0 ? void 0 : JSON.parse(raw);
|
|
472
|
-
}
|
|
473
|
-
setConflict(c) {
|
|
474
|
-
this.set("conflict", c === void 0 ? void 0 : JSON.stringify(c));
|
|
475
|
-
}
|
|
476
|
-
hold(id, from, payload, since) {
|
|
477
|
-
this.db.prepare("INSERT OR IGNORE INTO held (id, from_device, payload, since) VALUES (?, ?, ?, ?)").run(id, from, JSON.stringify(payload), since);
|
|
478
|
-
}
|
|
479
|
-
heldCount(from) {
|
|
480
|
-
return (this.reader?.prepare("SELECT COUNT(*) AS n FROM held WHERE from_device = ?").get(from))?.n ?? 0;
|
|
481
|
-
}
|
|
482
|
-
/** Held messages, oldest first; from one device, or all. */
|
|
483
|
-
held(from) {
|
|
484
|
-
const db = this.reader;
|
|
485
|
-
if (!db) return [];
|
|
486
|
-
return (from === void 0 ? db.prepare("SELECT * FROM held ORDER BY since, id").all() : db.prepare("SELECT * FROM held WHERE from_device = ? ORDER BY since, id").all(from)).map((r) => ({
|
|
487
|
-
id: r.id,
|
|
488
|
-
from: r.from_device,
|
|
489
|
-
payload: JSON.parse(r.payload),
|
|
490
|
-
since: r.since
|
|
491
|
-
}));
|
|
492
|
-
}
|
|
493
|
-
unhold(id) {
|
|
494
|
-
this.reader?.prepare("DELETE FROM held WHERE id = ?").run(id);
|
|
495
|
-
}
|
|
496
|
-
/** The local id for a session on another device, made on first use. */
|
|
497
|
-
alias(device, remote) {
|
|
498
|
-
const row = this.db.prepare("SELECT alias FROM alias WHERE device_id = ? AND remote_id = ?").get(device, remote);
|
|
499
|
-
if (row) return row.alias;
|
|
500
|
-
const id = newSessionId();
|
|
501
|
-
this.db.prepare("INSERT INTO alias (alias, device_id, remote_id) VALUES (?, ?, ?)").run(id, device, remote);
|
|
502
|
-
return id;
|
|
503
|
-
}
|
|
504
|
-
/** The device and remote id behind a local alias. */
|
|
505
|
-
unalias(alias) {
|
|
506
|
-
const row = this.reader?.prepare("SELECT device_id, remote_id FROM alias WHERE alias = ?").get(alias);
|
|
507
|
-
return row ? {
|
|
508
|
-
device: row.device_id,
|
|
509
|
-
remote: row.remote_id
|
|
510
|
-
} : void 0;
|
|
511
|
-
}
|
|
512
|
-
deviceName() {
|
|
513
|
-
return this.get("device_name");
|
|
514
|
-
}
|
|
515
|
-
setDeviceName(name) {
|
|
516
|
-
this.set("device_name", name);
|
|
517
|
-
}
|
|
518
|
-
/** Run `f` in one SQLite transaction: all of its writes happen, or none. */
|
|
519
|
-
atomically(f) {
|
|
520
|
-
this.db.exec("BEGIN IMMEDIATE");
|
|
521
|
-
try {
|
|
522
|
-
f();
|
|
523
|
-
this.db.exec("COMMIT");
|
|
524
|
-
} catch (e) {
|
|
525
|
-
this.db.exec("ROLLBACK");
|
|
526
|
-
throw e;
|
|
527
|
-
}
|
|
528
|
-
}
|
|
529
|
-
has(id) {
|
|
530
|
-
return this.reader?.prepare("SELECT 1 AS x FROM seen WHERE id = ?").get(id) !== void 0;
|
|
531
|
-
}
|
|
532
|
-
add(id, ts) {
|
|
533
|
-
this.db.prepare("INSERT OR IGNORE INTO seen (id, ts) VALUES (?, ?)").run(id, ts);
|
|
534
|
-
}
|
|
535
|
-
/** Forget ids that are too old to be accepted again anyway. */
|
|
536
|
-
pruneSeen(nowMs) {
|
|
537
|
-
const before = nowMs - ENVELOPE_MAX_AGE_MS - ENVELOPE_MAX_FUTURE_MS;
|
|
538
|
-
this.reader?.prepare("DELETE FROM seen WHERE ts < ?").run(before);
|
|
539
|
-
}
|
|
540
|
-
};
|
|
541
|
-
// ../daemon/src/relay/hub.ts
|
|
542
|
-
/** Remote sessions not republished for this many publish periods are dropped. */
|
|
543
|
-
const REMOTE_EXPIRY_PERIODS = 3;
|
|
544
|
-
const PAIRING_TIMEOUT_MS = 3e5;
|
|
545
|
-
/** Wrong codes the owner may type before the pairing fails. */
|
|
546
|
-
const PAIR_CODE_ATTEMPTS = 3;
|
|
547
|
-
const MAX_BACKOFF_MS = 6e4;
|
|
548
|
-
/**
|
|
549
|
-
* Relay error codes after which retrying soon cannot help. `token_expired` is not one: the next
|
|
550
|
-
* attempt renews the token.
|
|
551
|
-
*/
|
|
552
|
-
const AUTH_CODES = /* @__PURE__ */ new Set([
|
|
553
|
-
"unauthorized",
|
|
554
|
-
"plan_required",
|
|
555
|
-
"device_key_mismatch",
|
|
556
|
-
"device_mismatch",
|
|
557
|
-
"device_revoked"
|
|
558
|
-
]);
|
|
559
|
-
/** Messages that arrive before the sending device's session list wait this long for it. */
|
|
560
|
-
const HELD_MESSAGES_PER_DEVICE = 50;
|
|
561
|
-
const HELD_MESSAGE_MS = 12e4;
|
|
562
|
-
/** Ids of messages sent to other devices, so only a bounce for one of them is accepted. */
|
|
563
|
-
const SENT_MAX = 1e3;
|
|
564
|
-
const SENT_MS = 864e5;
|
|
565
|
-
/** What the sender shows for each bounce reason. Peers send only the code. */
|
|
566
|
-
const BOUNCE_TEXT = {
|
|
567
|
-
session_gone: "the session no longer exists",
|
|
568
|
-
session_offline: "the session is offline",
|
|
569
|
-
mailbox_full: "the session has too many unread messages",
|
|
570
|
-
unknown_sender: "the receiving device did not recognize the sending session",
|
|
571
|
-
not_allowed: "this kind of message is not carried between devices"
|
|
572
|
-
};
|
|
573
|
-
/** A device name as the first part of a remote session name: `[a-z0-9][a-z0-9._-]{0,23}`. */
|
|
574
|
-
const deviceSlug = (s) => s.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[^a-z0-9]+/, "").slice(0, 24) || "device";
|
|
575
|
-
/**
|
|
576
|
-
* How a session on another device is named here: `<device>:<name>`. Local session names cannot
|
|
577
|
-
* contain `:`, so the two never collide, and no remote session can pose as a local one or as a
|
|
578
|
-
* reserved sender such as `conveno`.
|
|
579
|
-
*/
|
|
580
|
-
function remoteSessionName(session, device) {
|
|
581
|
-
return `${deviceSlug(device)}:${session}`;
|
|
582
|
-
}
|
|
583
|
-
const NOT_PRO = "The relay is part of Conveno Pro. This account is on the free plan.";
|
|
584
|
-
const sanitizeName = (n) => n.replace(/[^\p{L}\p{N}._ -]/gu, "").trim().slice(0, 64) || "device";
|
|
585
|
-
/**
|
|
586
|
-
* The relay client inside the daemon. It keeps the device identity and its copy of the signed
|
|
587
|
-
* device list, holds the WebSocket to the relay while this device is paired (or pairing),
|
|
588
|
-
* publishes the local sessions to the other devices, keeps theirs, and carries messages between
|
|
589
|
-
* them.
|
|
590
|
-
*
|
|
591
|
-
* The relay holds the account's device list and only accepts strict extensions of it, so the
|
|
592
|
-
* list is linear. This device adopts a list only from the relay, and only one that extends its
|
|
593
|
-
* own copy; changes it makes (a pairing, a revocation) count only once the relay accepted them.
|
|
594
|
-
* When the relay's list is not an extension of this device's, or another device's envelope
|
|
595
|
-
* carries a list head that does not fit this device's list, the hub records a conflict, warns, and
|
|
596
|
-
* sends nothing until the owner accepts the relay's head (`devices.accept`).
|
|
597
|
-
*/
|
|
598
|
-
var RelayHub = class {
|
|
599
|
-
o;
|
|
600
|
-
identity;
|
|
601
|
-
/** Where the identity is kept, and whether it is there yet. */
|
|
602
|
-
identityPath;
|
|
603
|
-
identitySaved;
|
|
604
|
-
state;
|
|
605
|
-
now;
|
|
606
|
-
url;
|
|
607
|
-
accessToken;
|
|
608
|
-
evaluating;
|
|
609
|
-
evaluateAgain = false;
|
|
610
|
-
connectImpl;
|
|
611
|
-
publishMs;
|
|
612
|
-
pairResendMs;
|
|
613
|
-
listTimeoutMs;
|
|
614
|
-
chain;
|
|
615
|
-
chainState;
|
|
616
|
-
/** The list the relay last sent, verified. */
|
|
617
|
-
relayChain;
|
|
618
|
-
/**
|
|
619
|
-
* Head and length of the relay's list. The relay sends the whole list only to its members; any
|
|
620
|
-
* other device, such as one being paired, gets just this.
|
|
621
|
-
*/
|
|
622
|
-
relayHead;
|
|
623
|
-
/** The relay's list has arrived since the connection became ready. */
|
|
624
|
-
listReceived = false;
|
|
625
|
-
conflict;
|
|
626
|
-
pendingList;
|
|
627
|
-
/** The relay refused this device because its list revokes it. */
|
|
628
|
-
relayRevoked = false;
|
|
629
|
-
sent = /* @__PURE__ */ new Map();
|
|
630
|
-
sessionSeq = /* @__PURE__ */ new Map();
|
|
631
|
-
publishSeq = 0;
|
|
632
|
-
link;
|
|
633
|
-
linkReady = false;
|
|
634
|
-
connState = "logged_out";
|
|
635
|
-
detail;
|
|
636
|
-
failures = 0;
|
|
637
|
-
/** The code of the last `error` frame, for the close that usually follows it. */
|
|
638
|
-
lastErrorCode;
|
|
639
|
-
online = /* @__PURE__ */ new Set();
|
|
640
|
-
remote = /* @__PURE__ */ new Map();
|
|
641
|
-
pairing;
|
|
642
|
-
timers = [];
|
|
643
|
-
retryTimer;
|
|
644
|
-
publishTimer;
|
|
645
|
-
stopped = false;
|
|
646
|
-
constructor(o) {
|
|
647
|
-
this.o = o;
|
|
648
|
-
const platform = o.platform ?? process.platform;
|
|
649
|
-
const paths = relayPaths((platform === "win32" ? win32 : posix).join, o.dataDir);
|
|
650
|
-
this.identityPath = paths.identity;
|
|
651
|
-
const stored = loadIdentity(paths.identity);
|
|
652
|
-
this.identity = stored ?? generateIdentity(newDeviceId());
|
|
653
|
-
this.identitySaved = stored !== void 0;
|
|
654
|
-
this.state = new RelayState(paths.database);
|
|
655
|
-
this.now = o.now ?? (() => /* @__PURE__ */ new Date());
|
|
656
|
-
this.url = o.relayUrl ?? process.env.CONVENO_RELAY_URL ?? "wss://relay.conveno.dev/v1/connect";
|
|
657
|
-
const accountFile = dataPaths(platform, o.dataDir).account;
|
|
658
|
-
this.accessToken = o.accessToken ?? (async (refresh, deviceId) => {
|
|
659
|
-
if (!refresh) return (await readAccountTokens(accountFile))?.accessToken ?? null;
|
|
660
|
-
const token = await currentAccessToken(accountFile);
|
|
661
|
-
if (token === null || jwtClaim(token, "did") === deviceId) return token;
|
|
662
|
-
return bindAccountDevice(accountFile, deviceId);
|
|
663
|
-
});
|
|
664
|
-
this.connectImpl = o.connect ?? ((c) => new RelayConnection(c));
|
|
665
|
-
this.publishMs = o.publishIntervalMs ?? 6e4;
|
|
666
|
-
this.pairResendMs = o.pairResendMs ?? 2e3;
|
|
667
|
-
this.listTimeoutMs = o.listTimeoutMs ?? 15e3;
|
|
668
|
-
this.conflict = this.state.conflict();
|
|
669
|
-
this.loadChain(this.state.chain());
|
|
670
|
-
this.state.pruneSeen(this.ms());
|
|
671
|
-
}
|
|
672
|
-
ms() {
|
|
673
|
-
return this.now().getTime();
|
|
674
|
-
}
|
|
675
|
-
deviceName() {
|
|
676
|
-
return this.state.deviceName() ?? sanitizeName(hostname());
|
|
677
|
-
}
|
|
678
|
-
record() {
|
|
679
|
-
return publicRecord(this.identity, this.deviceName());
|
|
680
|
-
}
|
|
681
|
-
loadChain(chain) {
|
|
682
|
-
if (!chain) {
|
|
683
|
-
this.chain = void 0;
|
|
684
|
-
this.chainState = void 0;
|
|
685
|
-
return;
|
|
686
|
-
}
|
|
687
|
-
try {
|
|
688
|
-
this.chainState = verifyChain(chain);
|
|
689
|
-
this.chain = chain;
|
|
690
|
-
} catch (e) {
|
|
691
|
-
this.o.host.log.error("relay: the stored device list does not verify", e);
|
|
692
|
-
this.chain = void 0;
|
|
693
|
-
this.chainState = void 0;
|
|
694
|
-
}
|
|
695
|
-
}
|
|
696
|
-
setChain(chain) {
|
|
697
|
-
this.state.setChain(chain);
|
|
698
|
-
this.loadChain(chain);
|
|
699
|
-
for (const id of [...this.remote.keys()]) if (!this.member(id)) this.remote.delete(id);
|
|
700
|
-
}
|
|
701
|
-
/**
|
|
702
|
-
* An active device of the list other than this one. While there is a conflict about the list,
|
|
703
|
-
* none is: nothing is sent and nothing is accepted.
|
|
704
|
-
*/
|
|
705
|
-
member(deviceId) {
|
|
706
|
-
if (deviceId === this.identity.deviceId || this.conflict) return void 0;
|
|
707
|
-
return this.chainState?.members.get(deviceId);
|
|
708
|
-
}
|
|
709
|
-
isRevoked() {
|
|
710
|
-
return this.relayRevoked || (this.chainState?.revoked.has(this.identity.deviceId) ?? false);
|
|
711
|
-
}
|
|
712
|
-
paired() {
|
|
713
|
-
const s = this.chainState;
|
|
714
|
-
return !!s && s.members.has(this.identity.deviceId) && s.members.size > 1;
|
|
715
|
-
}
|
|
716
|
-
setConflict(kind, detail, peer) {
|
|
717
|
-
if (this.conflict) return;
|
|
718
|
-
const c = {
|
|
719
|
-
kind,
|
|
720
|
-
detail,
|
|
721
|
-
at: this.now().toISOString()
|
|
722
|
-
};
|
|
723
|
-
if (this.chain) c.local = chainHead(this.chain);
|
|
724
|
-
if (this.relayHead) c.relay = this.relayHead;
|
|
725
|
-
if (peer) c.peer = peer;
|
|
726
|
-
this.conflict = c;
|
|
727
|
-
this.state.setConflict(c);
|
|
728
|
-
this.remote.clear();
|
|
729
|
-
this.o.host.log.error("relay: device list conflict, nothing is sent until it is resolved", detail);
|
|
730
|
-
}
|
|
731
|
-
start() {
|
|
732
|
-
this.evaluate();
|
|
733
|
-
const t = setInterval(() => {
|
|
734
|
-
this.evaluate();
|
|
735
|
-
if (this.linkReady) this.publishAll();
|
|
736
|
-
this.expireRemote();
|
|
737
|
-
this.expireHeld();
|
|
738
|
-
}, this.publishMs);
|
|
739
|
-
t.unref();
|
|
740
|
-
this.timers.push(t);
|
|
741
|
-
const prune = setInterval(() => this.state.pruneSeen(this.ms()), 36e5);
|
|
742
|
-
prune.unref();
|
|
743
|
-
this.timers.push(prune);
|
|
744
|
-
}
|
|
745
|
-
stop() {
|
|
746
|
-
this.stopped = true;
|
|
747
|
-
for (const t of this.timers) clearInterval(t);
|
|
748
|
-
if (this.retryTimer) clearTimeout(this.retryTimer);
|
|
749
|
-
if (this.publishTimer) clearTimeout(this.publishTimer);
|
|
750
|
-
this.disconnect();
|
|
751
|
-
this.state.close();
|
|
752
|
-
}
|
|
753
|
-
/**
|
|
754
|
-
* Decide whether to be connected, and connect or disconnect. Called often; runs one check at a
|
|
755
|
-
* time and once more if asked meanwhile. The returned promise settles when the check is done.
|
|
756
|
-
*/
|
|
757
|
-
evaluate() {
|
|
758
|
-
if (this.evaluating) {
|
|
759
|
-
this.evaluateAgain = true;
|
|
760
|
-
return this.evaluating;
|
|
761
|
-
}
|
|
762
|
-
this.evaluating = (async () => {
|
|
763
|
-
do {
|
|
764
|
-
this.evaluateAgain = false;
|
|
765
|
-
try {
|
|
766
|
-
await this.evaluateOnce();
|
|
767
|
-
} catch (e) {
|
|
768
|
-
this.o.host.log.error("relay: state check failed", e);
|
|
769
|
-
}
|
|
770
|
-
} while (this.evaluateAgain && !this.stopped);
|
|
771
|
-
})().finally(() => {
|
|
772
|
-
this.evaluating = void 0;
|
|
773
|
-
});
|
|
774
|
-
return this.evaluating;
|
|
775
|
-
}
|
|
776
|
-
async evaluateOnce() {
|
|
777
|
-
if (this.stopped) return;
|
|
778
|
-
if (this.isRevoked()) return this.idle("revoked", "This device was removed from the device list.");
|
|
779
|
-
const want = this.paired() || this.pairingActive();
|
|
780
|
-
const self = this.identity.deviceId;
|
|
781
|
-
if (!want) {
|
|
782
|
-
const stored = await this.accessToken(false, self);
|
|
783
|
-
if (!stored) return this.idle("logged_out", "Not logged in. Run \"conveno login\".");
|
|
784
|
-
if (jwtClaim(stored, "plan") !== "pro") return this.idle("not_pro", NOT_PRO);
|
|
785
|
-
return this.idle("unpaired", "Pair this device first: \"conveno devices pair\".");
|
|
786
|
-
}
|
|
787
|
-
let token;
|
|
788
|
-
try {
|
|
789
|
-
token = await this.accessToken(true, self);
|
|
790
|
-
} catch (e) {
|
|
791
|
-
if (e instanceof AccountError && e.code === "session_expired") return this.idle("logged_out", `${e.message} Run "conveno login" again.`);
|
|
792
|
-
if (!this.link) {
|
|
793
|
-
this.connState = "disconnected";
|
|
794
|
-
this.detail = "Could not renew the access token. Retrying.";
|
|
795
|
-
}
|
|
796
|
-
return;
|
|
797
|
-
}
|
|
798
|
-
if (this.stopped) return;
|
|
799
|
-
if (!token) return this.idle("logged_out", "Not logged in. Run \"conveno login\".");
|
|
800
|
-
if (jwtClaim(token, "plan") !== "pro") return this.idle("not_pro", NOT_PRO);
|
|
801
|
-
if (this.link || this.retryTimer) return;
|
|
802
|
-
this.saveIdentity();
|
|
803
|
-
this.connState = "connecting";
|
|
804
|
-
this.detail = void 0;
|
|
805
|
-
const events = {
|
|
806
|
-
ready: (online) => this.onReady(online),
|
|
807
|
-
frame: (f) => this.onFrame(f),
|
|
808
|
-
down: (detail, code) => this.onDown(detail, code)
|
|
809
|
-
};
|
|
810
|
-
this.link = this.connectImpl({
|
|
811
|
-
url: this.url,
|
|
812
|
-
identity: this.identity,
|
|
813
|
-
token,
|
|
814
|
-
events
|
|
815
|
-
});
|
|
816
|
-
this.link.start();
|
|
817
|
-
}
|
|
818
|
-
saveIdentity() {
|
|
819
|
-
if (this.identitySaved) return;
|
|
820
|
-
saveNewIdentity(this.identityPath, this.identity);
|
|
821
|
-
this.identitySaved = true;
|
|
822
|
-
}
|
|
823
|
-
idle(state, detail) {
|
|
824
|
-
this.connState = state;
|
|
825
|
-
this.detail = detail;
|
|
826
|
-
this.disconnect();
|
|
827
|
-
}
|
|
828
|
-
disconnect() {
|
|
829
|
-
this.link?.stop();
|
|
830
|
-
this.link = void 0;
|
|
831
|
-
this.linkReady = false;
|
|
832
|
-
this.listReceived = false;
|
|
833
|
-
this.online.clear();
|
|
834
|
-
this.remote.clear();
|
|
835
|
-
this.failPendingList("The relay connection closed.");
|
|
836
|
-
}
|
|
837
|
-
onReady(online) {
|
|
838
|
-
this.linkReady = true;
|
|
839
|
-
this.listReceived = false;
|
|
840
|
-
this.failures = 0;
|
|
841
|
-
this.connState = "connected";
|
|
842
|
-
this.detail = void 0;
|
|
843
|
-
this.online.clear();
|
|
844
|
-
for (const d of online) this.online.add(d);
|
|
845
|
-
this.pairingTick();
|
|
846
|
-
}
|
|
847
|
-
onDown(detail, frameCode) {
|
|
848
|
-
const code = frameCode ?? this.lastErrorCode;
|
|
849
|
-
this.lastErrorCode = void 0;
|
|
850
|
-
this.link = void 0;
|
|
851
|
-
this.linkReady = false;
|
|
852
|
-
this.listReceived = false;
|
|
853
|
-
this.online.clear();
|
|
854
|
-
this.remote.clear();
|
|
855
|
-
this.failPendingList("The relay connection closed.");
|
|
856
|
-
if (this.stopped) return;
|
|
857
|
-
if (code === "device_revoked") {
|
|
858
|
-
this.relayRevoked = true;
|
|
859
|
-
this.idle("revoked", "The relay says the device list revokes this device.");
|
|
860
|
-
return;
|
|
861
|
-
}
|
|
862
|
-
this.connState = "disconnected";
|
|
863
|
-
this.detail = detail;
|
|
864
|
-
this.failures++;
|
|
865
|
-
const backoff = code !== void 0 && AUTH_CODES.has(code) ? MAX_BACKOFF_MS : Math.min(MAX_BACKOFF_MS, 1e3 * 2 ** Math.min(this.failures - 1, 6));
|
|
866
|
-
const delay = Math.round(backoff * (.5 + Math.random() / 2));
|
|
867
|
-
this.retryTimer = setTimeout(() => {
|
|
868
|
-
this.retryTimer = void 0;
|
|
869
|
-
this.evaluate();
|
|
870
|
-
}, delay);
|
|
871
|
-
this.retryTimer.unref();
|
|
872
|
-
}
|
|
873
|
-
onFrame(f) {
|
|
874
|
-
switch (f.t) {
|
|
875
|
-
case "list":
|
|
876
|
-
this.onRelayList(f.chain, f.head !== void 0 && f.length !== void 0 ? {
|
|
877
|
-
head: f.head,
|
|
878
|
-
length: f.length
|
|
879
|
-
} : void 0);
|
|
880
|
-
return;
|
|
881
|
-
case "envelope":
|
|
882
|
-
this.onEnvelope(f);
|
|
883
|
-
return;
|
|
884
|
-
case "presence":
|
|
885
|
-
if (f.online) {
|
|
886
|
-
this.online.add(f.deviceId);
|
|
887
|
-
if (this.listReceived) this.greet(f.deviceId);
|
|
888
|
-
} else {
|
|
889
|
-
this.online.delete(f.deviceId);
|
|
890
|
-
this.remote.delete(f.deviceId);
|
|
891
|
-
}
|
|
892
|
-
return;
|
|
893
|
-
case "pair":
|
|
894
|
-
this.onPair(f.fromDevice, f.toDevice, f.data);
|
|
895
|
-
return;
|
|
896
|
-
case "error":
|
|
897
|
-
this.detail = `The relay reported: ${f.message}`;
|
|
898
|
-
this.lastErrorCode = f.code;
|
|
899
|
-
if (f.code === "list_rejected") this.failPendingList(f.message);
|
|
900
|
-
return;
|
|
901
|
-
default: return;
|
|
902
|
-
}
|
|
903
|
-
}
|
|
904
|
-
/**
|
|
905
|
-
* The relay's list, after `ready` and whenever it changes. Adopted when it extends this
|
|
906
|
-
* device's list; anything else is a conflict. `headOnly` is what a device that is not a member
|
|
907
|
-
* of the relay's list gets instead of the list.
|
|
908
|
-
*/
|
|
909
|
-
onRelayList(raw, headOnly) {
|
|
910
|
-
let relay;
|
|
911
|
-
if (raw.length > 0) try {
|
|
912
|
-
verifyChain(raw);
|
|
913
|
-
relay = raw;
|
|
914
|
-
} catch {
|
|
915
|
-
this.setConflict("not_prefix", "The relay sent a device list that does not verify.");
|
|
916
|
-
}
|
|
917
|
-
this.relayChain = relay;
|
|
918
|
-
this.relayHead = relay ? chainHead(relay) : headOnly;
|
|
919
|
-
if (!relay && headOnly && this.chain && !this.conflict) this.setConflict("not_prefix", "The relay holds a device list that does not include this device.");
|
|
920
|
-
const pending = this.pendingList;
|
|
921
|
-
if (relay && pending && chainHead(relay).head === pending.head) {
|
|
922
|
-
this.setChain(relay);
|
|
923
|
-
this.pendingList = void 0;
|
|
924
|
-
clearTimeout(pending.timer);
|
|
925
|
-
pending.resolve();
|
|
926
|
-
} else if (this.chain && !this.conflict && !headOnly) {
|
|
927
|
-
const at = relay ? forkPoint(this.chain, relay) : 0;
|
|
928
|
-
if (!relay || at >= 0 || relay.length < this.chain.length) this.setConflict("not_prefix", relay ? "The relay holds a device list that this device's list is not part of." : "The relay holds no device list, but this device has one.");
|
|
929
|
-
else if (relay.length > this.chain.length) this.setChain(relay);
|
|
930
|
-
}
|
|
931
|
-
if (this.isRevoked()) {
|
|
932
|
-
this.evaluate();
|
|
933
|
-
return;
|
|
934
|
-
}
|
|
935
|
-
const first = !this.listReceived;
|
|
936
|
-
this.listReceived = true;
|
|
937
|
-
if (first) for (const d of this.online) this.greet(d);
|
|
938
|
-
}
|
|
939
|
-
/**
|
|
940
|
-
* Ask the relay to store a new version of the list. Resolves once the relay accepted it (and
|
|
941
|
-
* this device adopted it); rejects when the relay refuses it, does not answer, or the
|
|
942
|
-
* connection drops.
|
|
943
|
-
*/
|
|
944
|
-
publishList(chain) {
|
|
945
|
-
if (!this.link || !this.linkReady || !this.listReceived) return Promise.reject(/* @__PURE__ */ new Error("The relay is not connected."));
|
|
946
|
-
if (this.pendingList) return Promise.reject(/* @__PURE__ */ new Error("Another device list change is waiting for the relay."));
|
|
947
|
-
const { head } = chainHead(chain);
|
|
948
|
-
return new Promise((resolve, reject) => {
|
|
949
|
-
const timer = setTimeout(() => this.failPendingList("The relay did not answer."), this.listTimeoutMs);
|
|
950
|
-
timer.unref();
|
|
951
|
-
this.pendingList = {
|
|
952
|
-
head,
|
|
953
|
-
resolve,
|
|
954
|
-
reject,
|
|
955
|
-
timer
|
|
956
|
-
};
|
|
957
|
-
this.link?.send({
|
|
958
|
-
t: "list",
|
|
959
|
-
v: 1,
|
|
960
|
-
chain
|
|
961
|
-
});
|
|
962
|
-
});
|
|
963
|
-
}
|
|
964
|
-
failPendingList(why) {
|
|
965
|
-
const p = this.pendingList;
|
|
966
|
-
if (!p) return;
|
|
967
|
-
this.pendingList = void 0;
|
|
968
|
-
clearTimeout(p.timer);
|
|
969
|
-
p.reject(new Error(why));
|
|
970
|
-
}
|
|
971
|
-
/** A device came online: send it our sessions. */
|
|
972
|
-
greet(deviceId) {
|
|
973
|
-
if (!this.member(deviceId)) return;
|
|
974
|
-
this.publishTo(deviceId);
|
|
975
|
-
}
|
|
976
|
-
sendPayload(to, payload) {
|
|
977
|
-
const recipient = this.member(to);
|
|
978
|
-
if (!recipient || !this.chain || !this.link || !this.linkReady || !this.listReceived) return false;
|
|
979
|
-
const env = sealEnvelope({
|
|
980
|
-
sender: this.identity,
|
|
981
|
-
recipient,
|
|
982
|
-
id: newMessageId(),
|
|
983
|
-
plaintext: new TextEncoder().encode(JSON.stringify(payload)),
|
|
984
|
-
ts: this.ms(),
|
|
985
|
-
list: chainHead(this.chain)
|
|
986
|
-
});
|
|
987
|
-
return this.link.send(env);
|
|
988
|
-
}
|
|
989
|
-
/**
|
|
990
|
-
* An envelope from another device. It is acknowledged to the relay only after it was handled:
|
|
991
|
-
* a message is in a local mailbox, or stored in relay.db to wait for its sender's session list.
|
|
992
|
-
*/
|
|
993
|
-
onEnvelope(env) {
|
|
994
|
-
let pt;
|
|
995
|
-
try {
|
|
996
|
-
pt = openEnvelope(env, {
|
|
997
|
-
self: this.identity,
|
|
998
|
-
sender: (d) => this.member(d),
|
|
999
|
-
replay: this.state,
|
|
1000
|
-
now: this.ms(),
|
|
1001
|
-
record: false
|
|
1002
|
-
});
|
|
1003
|
-
} catch {
|
|
1004
|
-
this.ack(env);
|
|
1005
|
-
return;
|
|
1006
|
-
}
|
|
1007
|
-
if (this.chain && !headMatches(this.chain, env.head, env.len)) {
|
|
1008
|
-
const name = this.chainState?.members.get(env.fromDevice)?.name ?? "another device";
|
|
1009
|
-
this.setConflict("split_view", `${name} holds a device list (length ${env.len}) that does not match this device's.`, {
|
|
1010
|
-
deviceId: env.fromDevice,
|
|
1011
|
-
name,
|
|
1012
|
-
head: env.head,
|
|
1013
|
-
length: env.len
|
|
1014
|
-
});
|
|
1015
|
-
this.state.add(env.id, env.ts);
|
|
1016
|
-
this.ack(env);
|
|
1017
|
-
return;
|
|
1018
|
-
}
|
|
1019
|
-
try {
|
|
1020
|
-
const json = JSON.parse(new TextDecoder().decode(pt));
|
|
1021
|
-
const r = safeParse(RelayPayload, json);
|
|
1022
|
-
this.state.atomically(() => {
|
|
1023
|
-
if (r.ok) this.onPayload(env.fromDevice, r.value, env.id);
|
|
1024
|
-
this.state.add(env.id, env.ts);
|
|
1025
|
-
});
|
|
1026
|
-
} catch (e) {
|
|
1027
|
-
this.o.host.log.error("relay: an envelope could not be handled", e);
|
|
1028
|
-
}
|
|
1029
|
-
this.ack(env);
|
|
1030
|
-
}
|
|
1031
|
-
ack(env) {
|
|
1032
|
-
this.link?.send({
|
|
1033
|
-
t: "ack",
|
|
1034
|
-
id: env.id
|
|
1035
|
-
});
|
|
1036
|
-
}
|
|
1037
|
-
onPayload(from, p, envelopeId) {
|
|
1038
|
-
switch (p.type) {
|
|
1039
|
-
case "sessions": {
|
|
1040
|
-
const last = this.sessionSeq.get(from);
|
|
1041
|
-
if (last !== void 0 && p.seq <= last) return;
|
|
1042
|
-
this.sessionSeq.set(from, p.seq);
|
|
1043
|
-
this.remote.set(from, {
|
|
1044
|
-
deviceName: p.deviceName,
|
|
1045
|
-
sessions: p.sessions.map((s) => ({
|
|
1046
|
-
...s,
|
|
1047
|
-
deviceId: from
|
|
1048
|
-
})),
|
|
1049
|
-
receivedAt: this.ms()
|
|
1050
|
-
});
|
|
1051
|
-
for (const h of this.state.held(from)) {
|
|
1052
|
-
this.state.unhold(h.id);
|
|
1053
|
-
const r = safeParse(RelayPayload, h.payload);
|
|
1054
|
-
if (r.ok && r.value.type === "message") this.onMessage(from, r.value, h.id, h.since);
|
|
1055
|
-
}
|
|
1056
|
-
return;
|
|
1057
|
-
}
|
|
1058
|
-
case "message":
|
|
1059
|
-
this.onMessage(from, p, envelopeId);
|
|
1060
|
-
return;
|
|
1061
|
-
case "bounce": {
|
|
1062
|
-
const sent = this.sent.get(p.messageId);
|
|
1063
|
-
if (!sent || sent.toDevice !== from || sent.toSession !== p.toSession || sent.fromSession !== p.fromSession) return;
|
|
1064
|
-
this.sent.delete(p.messageId);
|
|
1065
|
-
const device = this.chainState?.members.get(from)?.name ?? "another device";
|
|
1066
|
-
this.o.host.notify(sent.fromSession, "message.bounced", `Message ${p.messageId} to session "${sent.toName}" on ${device} was not delivered: ${BOUNCE_TEXT[p.reason]}.`);
|
|
1067
|
-
return;
|
|
1068
|
-
}
|
|
1069
|
-
}
|
|
1070
|
-
}
|
|
1071
|
-
/**
|
|
1072
|
-
* A message from a session on another device. It is delivered only when `from` is one of the
|
|
1073
|
-
* sessions that device publishes, and it is shown with a local alias id and the name
|
|
1074
|
-
* `<device>:<session>`, with the device name from the signed list, whatever the sender put in
|
|
1075
|
-
* the message. One that arrives before the device's session list is stored durably and waits.
|
|
1076
|
-
*/
|
|
1077
|
-
onMessage(from, p, id, since = this.ms()) {
|
|
1078
|
-
const r = this.remote.get(from);
|
|
1079
|
-
if (!r) {
|
|
1080
|
-
if (this.state.heldCount(from) >= HELD_MESSAGES_PER_DEVICE) {
|
|
1081
|
-
this.bounce(from, p, "unknown_sender");
|
|
1082
|
-
return;
|
|
1083
|
-
}
|
|
1084
|
-
this.state.hold(id, from, p, since);
|
|
1085
|
-
return;
|
|
1086
|
-
}
|
|
1087
|
-
const isOwner = p.message.from === OWNER_SESSION_ID;
|
|
1088
|
-
const sender = isOwner ? void 0 : r.sessions.find((s) => s.id === p.message.from);
|
|
1089
|
-
if (!isOwner && !sender) {
|
|
1090
|
-
this.bounce(from, p, "unknown_sender");
|
|
1091
|
-
return;
|
|
1092
|
-
}
|
|
1093
|
-
if (p.message.kind === "system") {
|
|
1094
|
-
this.bounce(from, p, "not_allowed");
|
|
1095
|
-
return;
|
|
1096
|
-
}
|
|
1097
|
-
const device = this.chainState?.members.get(from)?.name ?? r.deviceName;
|
|
1098
|
-
const { fromCli: _c, ...rest } = p.message;
|
|
1099
|
-
const message = sender ? {
|
|
1100
|
-
...p.message,
|
|
1101
|
-
from: this.state.alias(from, sender.id),
|
|
1102
|
-
to: p.toSession,
|
|
1103
|
-
fromName: remoteSessionName(sender.name, device),
|
|
1104
|
-
fromCli: sender.cli
|
|
1105
|
-
} : {
|
|
1106
|
-
...rest,
|
|
1107
|
-
from: OWNER_SESSION_ID,
|
|
1108
|
-
to: p.toSession,
|
|
1109
|
-
fromName: "you"
|
|
1110
|
-
};
|
|
1111
|
-
const reason = this.o.host.deliverLocal(message, p.toSession, p.hops ?? 0);
|
|
1112
|
-
if (reason !== void 0) this.bounce(from, p, reason);
|
|
1113
|
-
}
|
|
1114
|
-
bounce(to, p, reason) {
|
|
1115
|
-
this.sendPayload(to, {
|
|
1116
|
-
type: "bounce",
|
|
1117
|
-
messageId: p.message.id,
|
|
1118
|
-
toSession: p.toSession,
|
|
1119
|
-
fromSession: p.message.from,
|
|
1120
|
-
reason
|
|
1121
|
-
});
|
|
1122
|
-
}
|
|
1123
|
-
expireHeld() {
|
|
1124
|
-
const now = this.ms();
|
|
1125
|
-
for (const h of this.state.held()) {
|
|
1126
|
-
if (now - h.since <= HELD_MESSAGE_MS) continue;
|
|
1127
|
-
this.state.unhold(h.id);
|
|
1128
|
-
const r = safeParse(RelayPayload, h.payload);
|
|
1129
|
-
if (r.ok && r.value.type === "message") this.bounce(h.from, r.value, "unknown_sender");
|
|
1130
|
-
}
|
|
1131
|
-
for (const [id, m] of this.sent) if (now - m.at > SENT_MS) this.sent.delete(id);
|
|
1132
|
-
}
|
|
1133
|
-
/** Called by the daemon whenever a local session changed. Publishes shortly after. */
|
|
1134
|
-
sessionsChanged() {
|
|
1135
|
-
if (!this.linkReady || this.publishTimer) return;
|
|
1136
|
-
this.publishTimer = setTimeout(() => {
|
|
1137
|
-
this.publishTimer = void 0;
|
|
1138
|
-
this.publishAll();
|
|
1139
|
-
}, 300);
|
|
1140
|
-
this.publishTimer.unref();
|
|
1141
|
-
}
|
|
1142
|
-
publishTo(deviceId) {
|
|
1143
|
-
const sessions = this.o.host.localSessions().filter((s) => !s.remote).map((s) => {
|
|
1144
|
-
const { pid: _p, hostPid: _h, hostPids: _hs, remote: _r, deviceName: _d, ...rest } = s;
|
|
1145
|
-
return {
|
|
1146
|
-
...rest,
|
|
1147
|
-
deviceId: this.identity.deviceId
|
|
1148
|
-
};
|
|
1149
|
-
});
|
|
1150
|
-
this.publishSeq = Math.max(this.publishSeq + 1, this.ms());
|
|
1151
|
-
this.sendPayload(deviceId, {
|
|
1152
|
-
type: "sessions",
|
|
1153
|
-
deviceName: this.deviceName(),
|
|
1154
|
-
seq: this.publishSeq,
|
|
1155
|
-
sessions
|
|
1156
|
-
});
|
|
1157
|
-
}
|
|
1158
|
-
publishAll() {
|
|
1159
|
-
if (!this.listReceived) return;
|
|
1160
|
-
for (const d of this.online) this.publishTo(d);
|
|
1161
|
-
}
|
|
1162
|
-
expireRemote() {
|
|
1163
|
-
const cutoff = this.ms() - REMOTE_EXPIRY_PERIODS * this.publishMs;
|
|
1164
|
-
for (const [id, r] of this.remote) if (r.receivedAt < cutoff) this.remote.delete(id);
|
|
1165
|
-
}
|
|
1166
|
-
/**
|
|
1167
|
-
* Sessions on the other devices, as `session.list` shows them: a local alias id and the name
|
|
1168
|
-
* `<device>:<name>`, so none can collide with a local session.
|
|
1169
|
-
*/
|
|
1170
|
-
remoteSessions(filter = {}) {
|
|
1171
|
-
const out = [];
|
|
1172
|
-
for (const [deviceId, r] of this.remote) {
|
|
1173
|
-
if (!this.member(deviceId)) continue;
|
|
1174
|
-
const device = this.chainState?.members.get(deviceId)?.name ?? r.deviceName;
|
|
1175
|
-
for (const s of r.sessions) {
|
|
1176
|
-
if (filter.cli && s.cli !== filter.cli) continue;
|
|
1177
|
-
const root = s.repo?.root;
|
|
1178
|
-
if (filter.repo && root !== filter.repo && baseName(root ?? s.cwd) !== filter.repo) continue;
|
|
1179
|
-
out.push({
|
|
1180
|
-
...s,
|
|
1181
|
-
id: this.state.alias(deviceId, s.id),
|
|
1182
|
-
name: remoteSessionName(s.name, device),
|
|
1183
|
-
deviceId,
|
|
1184
|
-
remote: true,
|
|
1185
|
-
deviceName: device
|
|
1186
|
-
});
|
|
1187
|
-
}
|
|
1188
|
-
}
|
|
1189
|
-
return out;
|
|
1190
|
-
}
|
|
1191
|
-
/** A remote session by its local alias id or its full `<device>:<name>`. */
|
|
1192
|
-
resolveRemote(to) {
|
|
1193
|
-
const all = this.remoteSessions().filter((s) => s.status !== "offline");
|
|
1194
|
-
return all.find((s) => s.id === to) ?? all.find((s) => s.name === to);
|
|
1195
|
-
}
|
|
1196
|
-
/** Send a message to a session on another device. Throws when that cannot be done now. */
|
|
1197
|
-
sendRemote(target, message, hops = 0) {
|
|
1198
|
-
if (this.conflict) throw new ConvenoError(RpcErrorCode.Conflict, "The device list has a conflict, so nothing is sent to other devices. Run \"conveno devices\".");
|
|
1199
|
-
const real = this.state.unalias(target.id);
|
|
1200
|
-
if (!real) throw new ConvenoError(RpcErrorCode.NotFound, `No session "${target.name}".`);
|
|
1201
|
-
if (!this.sendPayload(real.device, {
|
|
1202
|
-
type: "message",
|
|
1203
|
-
toSession: real.remote,
|
|
1204
|
-
message,
|
|
1205
|
-
...hops > 0 ? { hops } : {}
|
|
1206
|
-
})) throw new ConvenoError(RpcErrorCode.NotFound, `Session "${target.name}" is on ${target.deviceName ?? "another device"}, and the relay is not connected. Run "conveno relay status".`);
|
|
1207
|
-
this.sent.set(message.id, {
|
|
1208
|
-
fromSession: message.from,
|
|
1209
|
-
toDevice: real.device,
|
|
1210
|
-
toSession: real.remote,
|
|
1211
|
-
toName: target.name,
|
|
1212
|
-
at: this.ms()
|
|
1213
|
-
});
|
|
1214
|
-
if (this.sent.size > SENT_MAX) {
|
|
1215
|
-
const oldest = this.sent.keys().next().value;
|
|
1216
|
-
if (oldest !== void 0) this.sent.delete(oldest);
|
|
1217
|
-
}
|
|
1218
|
-
}
|
|
1219
|
-
async status() {
|
|
1220
|
-
await this.evaluating;
|
|
1221
|
-
const self = this.record();
|
|
1222
|
-
const out = {
|
|
1223
|
-
state: this.connState,
|
|
1224
|
-
relayUrl: this.url,
|
|
1225
|
-
device: {
|
|
1226
|
-
deviceId: self.deviceId,
|
|
1227
|
-
name: self.name,
|
|
1228
|
-
fingerprint: deviceFingerprint(self)
|
|
1229
|
-
},
|
|
1230
|
-
peers: this.deviceInfos().filter((d) => !d.self)
|
|
1231
|
-
};
|
|
1232
|
-
if (this.detail !== void 0) out.detail = this.detail;
|
|
1233
|
-
if (this.chain) out.list = chainHead(this.chain);
|
|
1234
|
-
if (this.conflict) out.conflict = this.conflict;
|
|
1235
|
-
return out;
|
|
1236
|
-
}
|
|
1237
|
-
deviceInfos() {
|
|
1238
|
-
const s = this.chainState;
|
|
1239
|
-
if (!s?.members.has(this.identity.deviceId)) {
|
|
1240
|
-
const self = this.record();
|
|
1241
|
-
return [{
|
|
1242
|
-
deviceId: self.deviceId,
|
|
1243
|
-
name: self.name,
|
|
1244
|
-
fingerprint: deviceFingerprint(self),
|
|
1245
|
-
self: true,
|
|
1246
|
-
online: this.linkReady,
|
|
1247
|
-
sessions: 0
|
|
1248
|
-
}];
|
|
1249
|
-
}
|
|
1250
|
-
return [...s.members.values()].map((m) => {
|
|
1251
|
-
const self = m.deviceId === this.identity.deviceId;
|
|
1252
|
-
return {
|
|
1253
|
-
deviceId: m.deviceId,
|
|
1254
|
-
name: m.name,
|
|
1255
|
-
fingerprint: deviceFingerprint(m),
|
|
1256
|
-
self,
|
|
1257
|
-
online: self ? this.linkReady : this.online.has(m.deviceId),
|
|
1258
|
-
sessions: self ? 0 : this.remote.get(m.deviceId)?.sessions.length ?? 0,
|
|
1259
|
-
addedAt: new Date(m.addedAt).toISOString(),
|
|
1260
|
-
addedBy: m.addedBy
|
|
1261
|
-
};
|
|
1262
|
-
});
|
|
1263
|
-
}
|
|
1264
|
-
devices() {
|
|
1265
|
-
const revoked = [...this.chainState?.revoked.entries() ?? []].map(([id, r]) => ({
|
|
1266
|
-
deviceId: id,
|
|
1267
|
-
name: r.device.name,
|
|
1268
|
-
revokedAt: new Date(r.revokedAt).toISOString(),
|
|
1269
|
-
revokedBy: r.by
|
|
1270
|
-
}));
|
|
1271
|
-
const out = {
|
|
1272
|
-
devices: this.deviceInfos(),
|
|
1273
|
-
revoked
|
|
1274
|
-
};
|
|
1275
|
-
if (this.chain) out.list = chainHead(this.chain);
|
|
1276
|
-
if (this.conflict) out.conflict = this.conflict;
|
|
1277
|
-
return out;
|
|
1278
|
-
}
|
|
1279
|
-
/**
|
|
1280
|
-
* Recover from a conflict: adopt the relay's list, but only if its head is the one the owner
|
|
1281
|
-
* read on a device that is a member of it.
|
|
1282
|
-
*/
|
|
1283
|
-
accept(p) {
|
|
1284
|
-
if (!this.conflict) throw new ConvenoError(RpcErrorCode.Conflict, "The device list has no conflict.");
|
|
1285
|
-
const relay = this.relayChain;
|
|
1286
|
-
if (!relay?.length) throw new ConvenoError(RpcErrorCode.NotFound, this.relayHead ? "The relay's device list does not include this device. Run \"conveno devices reset\", then pair it again." : "The relay holds no device list (the devices were reset). Run \"conveno devices reset\", then pair again.");
|
|
1287
|
-
const head = chainHead(relay);
|
|
1288
|
-
if (head.head !== p.head) throw new ConvenoError(RpcErrorCode.Conflict, `The relay's device list has head ${head.head.slice(0, 16)}, not ${p.head.slice(0, 16)}. Nothing was changed.`);
|
|
1289
|
-
this.conflict = void 0;
|
|
1290
|
-
this.state.setConflict(void 0);
|
|
1291
|
-
this.setChain(relay);
|
|
1292
|
-
const member = this.chainState?.members.has(this.identity.deviceId) ?? false;
|
|
1293
|
-
if (this.linkReady && this.listReceived) for (const d of this.online) this.greet(d);
|
|
1294
|
-
this.evaluate();
|
|
1295
|
-
return {
|
|
1296
|
-
list: head,
|
|
1297
|
-
member
|
|
1298
|
-
};
|
|
1299
|
-
}
|
|
1300
|
-
rename(p) {
|
|
1301
|
-
const name = sanitizeName(p.name);
|
|
1302
|
-
this.state.setDeviceName(name);
|
|
1303
|
-
return { name };
|
|
1304
|
-
}
|
|
1305
|
-
/**
|
|
1306
|
-
* Revoke a device: append the revocation, and once the relay has accepted it (which also cuts
|
|
1307
|
-
* the device off at the relay), tell the account service to end the device's sessions.
|
|
1308
|
-
*/
|
|
1309
|
-
async revoke(p) {
|
|
1310
|
-
if (this.conflict) throw new ConvenoError(RpcErrorCode.Conflict, "The device list has a conflict. Run \"conveno devices\" to resolve it first.");
|
|
1311
|
-
const s = this.chainState;
|
|
1312
|
-
if (!this.chain || !s?.members.has(this.identity.deviceId)) throw new ConvenoError(RpcErrorCode.NotFound, "This device has no device list yet.");
|
|
1313
|
-
const byId = s.members.get(p.device);
|
|
1314
|
-
const byName = [...s.members.values()].filter((m) => m.name === p.device);
|
|
1315
|
-
if (!byId && byName.length > 1) throw new ConvenoError(RpcErrorCode.Conflict, `Several devices are named "${p.device}". Revoke by device id instead.`);
|
|
1316
|
-
const target = byId ?? byName[0];
|
|
1317
|
-
if (!target) throw new ConvenoError(RpcErrorCode.NotFound, `No active device "${p.device}". Run "conveno devices" to list them.`);
|
|
1318
|
-
let next;
|
|
1319
|
-
try {
|
|
1320
|
-
next = appendRevoke(this.chain, this.identity, target.deviceId, this.ms());
|
|
1321
|
-
} catch (e) {
|
|
1322
|
-
throw new ConvenoError(RpcErrorCode.InvalidParams, e.message);
|
|
1323
|
-
}
|
|
1324
|
-
try {
|
|
1325
|
-
await this.publishList(next);
|
|
1326
|
-
} catch (e) {
|
|
1327
|
-
throw new ConvenoError(RpcErrorCode.Conflict, `The relay did not accept the revocation: ${e.message} Nothing was changed.`);
|
|
1328
|
-
}
|
|
1329
|
-
this.remote.delete(target.deviceId);
|
|
1330
|
-
return { revoked: {
|
|
1331
|
-
deviceId: target.deviceId,
|
|
1332
|
-
name: target.name
|
|
1333
|
-
} };
|
|
1334
|
-
}
|
|
1335
|
-
/**
|
|
1336
|
-
* Forget this device's copy of the list after the owner reset the account's devices, or when
|
|
1337
|
-
* the relay's list no longer includes it. The device is then unpaired and can pair again.
|
|
1338
|
-
*/
|
|
1339
|
-
reset() {
|
|
1340
|
-
if (!this.conflict && !this.isRevoked()) throw new ConvenoError(RpcErrorCode.Conflict, "The device list has no conflict and this device is not revoked, so there is nothing to reset.");
|
|
1341
|
-
this.conflict = void 0;
|
|
1342
|
-
this.state.setConflict(void 0);
|
|
1343
|
-
this.state.setChain(void 0);
|
|
1344
|
-
this.loadChain(void 0);
|
|
1345
|
-
this.relayRevoked = false;
|
|
1346
|
-
this.remote.clear();
|
|
1347
|
-
this.disconnect();
|
|
1348
|
-
this.evaluate();
|
|
1349
|
-
return { reset: true };
|
|
1350
|
-
}
|
|
1351
|
-
pairingActive() {
|
|
1352
|
-
const p = this.pairing;
|
|
1353
|
-
return !!p && p.state !== "done" && p.state !== "failed";
|
|
1354
|
-
}
|
|
1355
|
-
async pairStart(p) {
|
|
1356
|
-
if (this.isRevoked()) throw new ConvenoError(RpcErrorCode.Conflict, "This device was removed from the device list.");
|
|
1357
|
-
if (p.role === "join" && this.paired()) throw new ConvenoError(RpcErrorCode.Conflict, "This device is already paired. Run \"conveno devices pair\" here to add another device instead.");
|
|
1358
|
-
if (this.conflict) throw new ConvenoError(RpcErrorCode.Conflict, "The device list has a conflict. Run \"conveno devices\" and resolve it first.");
|
|
1359
|
-
if (p.role === "invite" && this.chainState && !this.chainState.members.has(this.identity.deviceId)) throw new ConvenoError(RpcErrorCode.Conflict, "This device is not in its own device list.");
|
|
1360
|
-
if (this.pairingActive()) this.failPairing("Replaced by a new pairing.");
|
|
1361
|
-
this.saveIdentity();
|
|
1362
|
-
const record = this.record();
|
|
1363
|
-
const pairing = {
|
|
1364
|
-
id: newMessageId(),
|
|
1365
|
-
role: p.role,
|
|
1366
|
-
state: "waiting",
|
|
1367
|
-
localConfirmed: false,
|
|
1368
|
-
createdAt: this.ms(),
|
|
1369
|
-
wrongCodes: 0
|
|
1370
|
-
};
|
|
1371
|
-
if (p.role === "join") {
|
|
1372
|
-
pairing.joiner = new JoinerPairing(this.identity, record);
|
|
1373
|
-
pairing.resend = { message: pairing.joiner.commit() };
|
|
1374
|
-
} else pairing.inviter = new InviterPairing(this.identity, record);
|
|
1375
|
-
this.pairing = pairing;
|
|
1376
|
-
await this.evaluate();
|
|
1377
|
-
if (this.connState === "logged_out" || this.connState === "not_pro") {
|
|
1378
|
-
const detail = this.detail ?? "Cannot pair now.";
|
|
1379
|
-
this.failPairing(detail, false);
|
|
1380
|
-
throw new ConvenoError(RpcErrorCode.PermissionRequired, detail);
|
|
1381
|
-
}
|
|
1382
|
-
const tick = setInterval(() => this.pairingTick(), this.pairResendMs);
|
|
1383
|
-
tick.unref();
|
|
1384
|
-
this.timers.push(tick);
|
|
1385
|
-
this.pairingTick();
|
|
1386
|
-
return this.pairStatus({ pairingId: pairing.id });
|
|
1387
|
-
}
|
|
1388
|
-
pairingTick() {
|
|
1389
|
-
const p = this.pairing;
|
|
1390
|
-
if (!p || !this.pairingActive()) return;
|
|
1391
|
-
if (this.ms() - p.createdAt > PAIRING_TIMEOUT_MS) {
|
|
1392
|
-
this.failPairing("Pairing timed out. Start it again on both devices.");
|
|
1393
|
-
return;
|
|
1394
|
-
}
|
|
1395
|
-
if (p.resend) this.sendPair(p.resend.message, p.resend.to);
|
|
1396
|
-
}
|
|
1397
|
-
sendPair(m, to) {
|
|
1398
|
-
if (!this.link || !this.linkReady) return;
|
|
1399
|
-
this.link.send({
|
|
1400
|
-
t: "pair",
|
|
1401
|
-
v: 1,
|
|
1402
|
-
fromDevice: this.identity.deviceId,
|
|
1403
|
-
...to ? { toDevice: to } : {},
|
|
1404
|
-
data: encodePairMessage(m)
|
|
1405
|
-
});
|
|
1406
|
-
}
|
|
1407
|
-
failPairing(error, notify = true) {
|
|
1408
|
-
const p = this.pairing;
|
|
1409
|
-
if (!p) return;
|
|
1410
|
-
const pairingId = p.joiner?.pairingId ?? p.inviter?.pairingId;
|
|
1411
|
-
if (notify && p.peerDevice && pairingId) this.sendPair({
|
|
1412
|
-
type: "abort",
|
|
1413
|
-
pairingId,
|
|
1414
|
-
reason: error.slice(0, 200)
|
|
1415
|
-
}, p.peerDevice);
|
|
1416
|
-
p.state = "failed";
|
|
1417
|
-
p.error = error;
|
|
1418
|
-
p.resend = void 0;
|
|
1419
|
-
this.evaluate();
|
|
1420
|
-
}
|
|
1421
|
-
onPair(from, to, data) {
|
|
1422
|
-
const p = this.pairing;
|
|
1423
|
-
if (!p) return;
|
|
1424
|
-
if (to !== void 0 && to !== this.identity.deviceId) return;
|
|
1425
|
-
let m;
|
|
1426
|
-
try {
|
|
1427
|
-
m = decodePairMessage(data);
|
|
1428
|
-
} catch {
|
|
1429
|
-
return;
|
|
1430
|
-
}
|
|
1431
|
-
if (m.type === "abort") {
|
|
1432
|
-
if (from === p.peerDevice && p.state !== "done") this.failPairing(`The other device stopped: ${m.reason}`, false);
|
|
1433
|
-
return;
|
|
1434
|
-
}
|
|
1435
|
-
try {
|
|
1436
|
-
if (p.inviter) this.onPairAsInviter(p, p.inviter, from, m);
|
|
1437
|
-
else if (p.joiner) this.onPairAsJoiner(p, p.joiner, from, m);
|
|
1438
|
-
} catch (e) {
|
|
1439
|
-
if (p.state === "done") return;
|
|
1440
|
-
this.failPairing(e instanceof CryptoError ? e.message : "Pairing failed.");
|
|
1441
|
-
}
|
|
1442
|
-
}
|
|
1443
|
-
onPairAsInviter(p, inv, from, m) {
|
|
1444
|
-
if (m.type === "commit") {
|
|
1445
|
-
if (this.chainState?.members.has(from) || this.chainState?.revoked.has(from) || !this.online.has(from)) return;
|
|
1446
|
-
if (inv.pairingId === void 0 && p.state === "waiting") {
|
|
1447
|
-
p.offer = inv.onCommit(m);
|
|
1448
|
-
p.peerDevice = from;
|
|
1449
|
-
this.sendPair(p.offer, from);
|
|
1450
|
-
} else if (m.pairingId === inv.pairingId && from === p.peerDevice && p.offer) this.sendPair(p.offer, from);
|
|
1451
|
-
return;
|
|
1452
|
-
}
|
|
1453
|
-
if (from !== p.peerDevice || m.pairingId !== inv.pairingId) return;
|
|
1454
|
-
if (m.type === "reveal") {
|
|
1455
|
-
const key = JSON.stringify(m);
|
|
1456
|
-
if (p.lastReveal === key) return;
|
|
1457
|
-
inv.onReveal(m);
|
|
1458
|
-
p.lastReveal = key;
|
|
1459
|
-
if (p.state === "waiting") p.state = "confirm";
|
|
1460
|
-
} else if (m.type === "confirm") {
|
|
1461
|
-
if (p.state === "done" && p.welcome) {
|
|
1462
|
-
this.sendPair(p.welcome, from);
|
|
1463
|
-
return;
|
|
1464
|
-
}
|
|
1465
|
-
if (inv.joinerHasConfirmed) return;
|
|
1466
|
-
inv.onConfirm(m);
|
|
1467
|
-
if (p.localConfirmed) this.finishInvite(p, inv);
|
|
1468
|
-
}
|
|
1469
|
-
}
|
|
1470
|
-
onPairAsJoiner(p, j, from, m) {
|
|
1471
|
-
if (m.pairingId !== j.pairingId) return;
|
|
1472
|
-
if (m.type === "offer") {
|
|
1473
|
-
if (p.peerDevice !== void 0) return;
|
|
1474
|
-
const reveal = j.onOffer(m);
|
|
1475
|
-
p.peerDevice = from;
|
|
1476
|
-
p.state = "confirm";
|
|
1477
|
-
p.resend = {
|
|
1478
|
-
to: from,
|
|
1479
|
-
message: reveal
|
|
1480
|
-
};
|
|
1481
|
-
this.sendPair(reveal, from);
|
|
1482
|
-
} else if (m.type === "welcome" && from === p.peerDevice && p.localConfirmed) {
|
|
1483
|
-
if (p.state === "done") return;
|
|
1484
|
-
const { chain } = j.onWelcome(m);
|
|
1485
|
-
const relay = this.relayChain;
|
|
1486
|
-
const { head, length } = chainHead(chain);
|
|
1487
|
-
let adopt;
|
|
1488
|
-
if (relay) {
|
|
1489
|
-
if (headMatches(relay, head, length)) adopt = relay;
|
|
1490
|
-
} else if (this.relayHead?.head === head && this.relayHead.length === length) adopt = chain;
|
|
1491
|
-
if (!adopt) {
|
|
1492
|
-
this.failPairing("The relay does not hold the device list the other device sent.");
|
|
1493
|
-
return;
|
|
1494
|
-
}
|
|
1495
|
-
if (!verifyChain(adopt).members.has(this.identity.deviceId)) {
|
|
1496
|
-
this.failPairing("The relay's device list does not include this device.");
|
|
1497
|
-
return;
|
|
1498
|
-
}
|
|
1499
|
-
this.setChain(adopt);
|
|
1500
|
-
p.state = "done";
|
|
1501
|
-
p.resend = void 0;
|
|
1502
|
-
this.evaluate();
|
|
1503
|
-
for (const d of this.online) this.greet(d);
|
|
1504
|
-
}
|
|
1505
|
-
}
|
|
1506
|
-
/**
|
|
1507
|
-
* Both owners typed the right codes: add the joiner to the list, and once the relay has
|
|
1508
|
-
* accepted the new list, send the joiner its welcome.
|
|
1509
|
-
*/
|
|
1510
|
-
async finishInvite(p, inv) {
|
|
1511
|
-
if (p.finishing || p.state === "done") return;
|
|
1512
|
-
p.finishing = true;
|
|
1513
|
-
p.state = "waiting_peer";
|
|
1514
|
-
try {
|
|
1515
|
-
const { chain, message } = inv.welcome(this.chain, this.ms());
|
|
1516
|
-
await this.publishList(chain);
|
|
1517
|
-
p.welcome = message;
|
|
1518
|
-
p.state = "done";
|
|
1519
|
-
p.resend = void 0;
|
|
1520
|
-
if (p.peerDevice) this.sendPair(message, p.peerDevice);
|
|
1521
|
-
if (p.peerDevice && this.online.has(p.peerDevice)) this.publishTo(p.peerDevice);
|
|
1522
|
-
this.evaluate();
|
|
1523
|
-
} catch (e) {
|
|
1524
|
-
this.failPairing(e instanceof CryptoError ? e.message : `The relay did not accept the new device list: ${e.message}`);
|
|
1525
|
-
} finally {
|
|
1526
|
-
p.finishing = false;
|
|
1527
|
-
}
|
|
1528
|
-
}
|
|
1529
|
-
pairStatus(q) {
|
|
1530
|
-
const p = this.pairing;
|
|
1531
|
-
if (!p || p.id !== q.pairingId) throw new ConvenoError(RpcErrorCode.NotFound, "No pairing with that id. Start one again.");
|
|
1532
|
-
const flow = p.inviter ?? p.joiner;
|
|
1533
|
-
const out = {
|
|
1534
|
-
pairingId: p.id,
|
|
1535
|
-
role: p.role,
|
|
1536
|
-
state: p.state
|
|
1537
|
-
};
|
|
1538
|
-
const sas = flow?.sas;
|
|
1539
|
-
if (sas !== void 0 && p.state !== "failed") out.sas = sas;
|
|
1540
|
-
const peer = flow?.peer;
|
|
1541
|
-
if (peer) out.peer = {
|
|
1542
|
-
deviceId: peer.deviceId,
|
|
1543
|
-
name: peer.name,
|
|
1544
|
-
fingerprint: deviceFingerprint(peer)
|
|
1545
|
-
};
|
|
1546
|
-
if (p.error !== void 0) out.error = p.error;
|
|
1547
|
-
if (p.state === "waiting" && this.connState !== "connected") out.error = this.detail ?? "Connecting to the relay.";
|
|
1548
|
-
return out;
|
|
1549
|
-
}
|
|
1550
|
-
pairConfirm(q) {
|
|
1551
|
-
const p = this.pairing;
|
|
1552
|
-
if (!p || p.id !== q.pairingId) throw new ConvenoError(RpcErrorCode.NotFound, "No pairing with that id. Start one again.");
|
|
1553
|
-
if (p.state !== "confirm") throw new ConvenoError(RpcErrorCode.Conflict, `The pairing is "${p.state}", not waiting for a confirmation.`);
|
|
1554
|
-
if (!q.accept) {
|
|
1555
|
-
this.failPairing("The owner stopped the pairing.");
|
|
1556
|
-
return this.pairStatus(q);
|
|
1557
|
-
}
|
|
1558
|
-
const expected = (p.inviter ?? p.joiner)?.peerSas;
|
|
1559
|
-
if (!expected || q.code === void 0 || !sasMatches(expected, q.code)) {
|
|
1560
|
-
p.wrongCodes++;
|
|
1561
|
-
if (p.wrongCodes >= PAIR_CODE_ATTEMPTS) {
|
|
1562
|
-
this.failPairing("The code did not match the other device's. Someone may be in between: do not retry on this network until you know why.");
|
|
1563
|
-
return this.pairStatus(q);
|
|
1564
|
-
}
|
|
1565
|
-
const left = PAIR_CODE_ATTEMPTS - p.wrongCodes;
|
|
1566
|
-
return {
|
|
1567
|
-
...this.pairStatus(q),
|
|
1568
|
-
error: `That is not the code the other device shows. ${left} ${left === 1 ? "try" : "tries"} left.`
|
|
1569
|
-
};
|
|
1570
|
-
}
|
|
1571
|
-
p.localConfirmed = true;
|
|
1572
|
-
if (p.inviter) {
|
|
1573
|
-
if (p.inviter.joinerHasConfirmed) this.finishInvite(p, p.inviter);
|
|
1574
|
-
else p.state = "waiting_peer";
|
|
1575
|
-
} else if (p.joiner && p.peerDevice) {
|
|
1576
|
-
const confirm = p.joiner.confirm();
|
|
1577
|
-
p.state = "waiting_peer";
|
|
1578
|
-
p.resend = {
|
|
1579
|
-
to: p.peerDevice,
|
|
1580
|
-
message: confirm
|
|
1581
|
-
};
|
|
1582
|
-
this.sendPair(confirm, p.peerDevice);
|
|
1583
|
-
}
|
|
1584
|
-
return this.pairStatus(q);
|
|
1585
|
-
}
|
|
1586
|
-
};
|
|
1587
|
-
// ../daemon/src/store.ts
|
|
1588
|
-
const MIGRATIONS = [
|
|
1589
|
-
{
|
|
1590
|
-
name: "001_initial",
|
|
1591
|
-
sql: `
|
|
1592
|
-
CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
1593
|
-
CREATE TABLE sessions (
|
|
1594
|
-
id TEXT PRIMARY KEY,
|
|
1595
|
-
name TEXT NOT NULL,
|
|
1596
|
-
cli TEXT NOT NULL,
|
|
1597
|
-
cli_version TEXT,
|
|
1598
|
-
device_id TEXT NOT NULL,
|
|
1599
|
-
cwd TEXT NOT NULL,
|
|
1600
|
-
repo_root TEXT,
|
|
1601
|
-
repo_remote_hash TEXT,
|
|
1602
|
-
pid INTEGER,
|
|
1603
|
-
host_pid INTEGER,
|
|
1604
|
-
status TEXT NOT NULL,
|
|
1605
|
-
status_text TEXT,
|
|
1606
|
-
delivery_tier TEXT NOT NULL,
|
|
1607
|
-
spawned_by TEXT,
|
|
1608
|
-
spawn_depth INTEGER NOT NULL DEFAULT 0,
|
|
1609
|
-
started_at TEXT NOT NULL,
|
|
1610
|
-
last_seen_at TEXT NOT NULL
|
|
1611
|
-
);
|
|
1612
|
-
CREATE INDEX sessions_host_pid ON sessions (host_pid);
|
|
1613
|
-
CREATE TABLE messages (
|
|
1614
|
-
id TEXT PRIMARY KEY,
|
|
1615
|
-
json TEXT NOT NULL
|
|
1616
|
-
);
|
|
1617
|
-
CREATE TABLE mailbox (
|
|
1618
|
-
session_id TEXT NOT NULL,
|
|
1619
|
-
message_id TEXT NOT NULL,
|
|
1620
|
-
state TEXT NOT NULL,
|
|
1621
|
-
queued_at TEXT NOT NULL,
|
|
1622
|
-
delivered_at TEXT,
|
|
1623
|
-
read_at TEXT,
|
|
1624
|
-
acked_at TEXT,
|
|
1625
|
-
PRIMARY KEY (session_id, message_id)
|
|
1626
|
-
);
|
|
1627
|
-
CREATE INDEX mailbox_state ON mailbox (session_id, state);
|
|
1628
|
-
CREATE TABLE orchestrator (
|
|
1629
|
-
slot INTEGER PRIMARY KEY CHECK (slot = 1),
|
|
1630
|
-
session_id TEXT
|
|
1631
|
-
);
|
|
1632
|
-
INSERT INTO orchestrator (slot, session_id) VALUES (1, NULL);
|
|
1633
|
-
`
|
|
1634
|
-
},
|
|
1635
|
-
{
|
|
1636
|
-
name: "002_host_pids",
|
|
1637
|
-
sql: `
|
|
1638
|
-
ALTER TABLE sessions ADD COLUMN host_pids TEXT;
|
|
1639
|
-
UPDATE sessions SET host_pids = '[' || host_pid || ']' WHERE host_pid IS NOT NULL;
|
|
1640
|
-
`
|
|
1641
|
-
},
|
|
1642
|
-
{
|
|
1643
|
-
name: "003_spawned",
|
|
1644
|
-
sql: `
|
|
1645
|
-
ALTER TABLE sessions ADD COLUMN spawned INTEGER NOT NULL DEFAULT 0;
|
|
1646
|
-
`
|
|
1647
|
-
},
|
|
1648
|
-
{
|
|
1649
|
-
name: "004_auto_mode",
|
|
1650
|
-
sql: `
|
|
1651
|
-
ALTER TABLE sessions ADD COLUMN auto INTEGER NOT NULL DEFAULT 0;
|
|
1652
|
-
ALTER TABLE sessions ADD COLUMN auto_explicit INTEGER NOT NULL DEFAULT 0;
|
|
1653
|
-
ALTER TABLE sessions ADD COLUMN auto_paused_at TEXT;
|
|
1654
|
-
ALTER TABLE sessions ADD COLUMN auto_paused_by TEXT;
|
|
1655
|
-
ALTER TABLE sessions ADD COLUMN auto_limit INTEGER;
|
|
1656
|
-
ALTER TABLE sessions ADD COLUMN auto_orch_resumed_at TEXT;
|
|
1657
|
-
ALTER TABLE sessions ADD COLUMN auto_runs TEXT NOT NULL DEFAULT '[]';
|
|
1658
|
-
ALTER TABLE sessions ADD COLUMN turn_hops INTEGER NOT NULL DEFAULT 0;
|
|
1659
|
-
ALTER TABLE mailbox ADD COLUMN hops INTEGER NOT NULL DEFAULT 0;
|
|
1660
|
-
`
|
|
1661
|
-
},
|
|
1662
|
-
{
|
|
1663
|
-
name: "005_peek_metadata",
|
|
1664
|
-
sql: `
|
|
1665
|
-
ALTER TABLE sessions ADD COLUMN cli_session_id TEXT;
|
|
1666
|
-
ALTER TABLE sessions ADD COLUMN transcript_path TEXT;
|
|
1667
|
-
ALTER TABLE sessions ADD COLUMN peekable INTEGER NOT NULL DEFAULT 1;
|
|
1668
|
-
`
|
|
1669
|
-
},
|
|
1670
|
-
{
|
|
1671
|
-
name: "006_cleanup",
|
|
1672
|
-
sql: `
|
|
1673
|
-
DROP TABLE IF EXISTS tickets;
|
|
1674
|
-
DROP TABLE IF EXISTS permission_relay;
|
|
1675
|
-
DELETE FROM mailbox WHERE session_id = '${OWNER_SESSION_ID}';
|
|
1676
|
-
DELETE FROM messages WHERE id NOT IN (SELECT message_id FROM mailbox);
|
|
1677
|
-
ALTER TABLE sessions DROP COLUMN auto;
|
|
1678
|
-
ALTER TABLE sessions DROP COLUMN auto_explicit;
|
|
1679
|
-
ALTER TABLE sessions DROP COLUMN auto_paused_at;
|
|
1680
|
-
ALTER TABLE sessions DROP COLUMN auto_paused_by;
|
|
1681
|
-
ALTER TABLE sessions DROP COLUMN auto_limit;
|
|
1682
|
-
ALTER TABLE sessions DROP COLUMN auto_orch_resumed_at;
|
|
1683
|
-
ALTER TABLE sessions DROP COLUMN peekable;
|
|
1684
|
-
ALTER TABLE sessions DROP COLUMN cli_session_id;
|
|
1685
|
-
ALTER TABLE sessions DROP COLUMN transcript_path;
|
|
1686
|
-
`
|
|
1687
|
-
},
|
|
1688
|
-
{
|
|
1689
|
-
name: "007_native_id",
|
|
1690
|
-
sql: `
|
|
1691
|
-
ALTER TABLE sessions ADD COLUMN native_id TEXT;
|
|
1692
|
-
CREATE INDEX sessions_native_id ON sessions (native_id);
|
|
1693
|
-
`
|
|
1694
|
-
}
|
|
1695
|
-
];
|
|
1696
|
-
const str = (v) => typeof v === "string" ? v : void 0;
|
|
1697
|
-
const num = (v) => typeof v === "number" ? v : void 0;
|
|
1698
|
-
function pidList(v) {
|
|
1699
|
-
if (typeof v !== "string") return void 0;
|
|
1700
|
-
try {
|
|
1701
|
-
const list = JSON.parse(v);
|
|
1702
|
-
if (!Array.isArray(list)) return void 0;
|
|
1703
|
-
const pids = list.filter((p) => Number.isInteger(p) && p > 0);
|
|
1704
|
-
return pids.length > 0 ? pids : void 0;
|
|
1705
|
-
} catch {
|
|
1706
|
-
return;
|
|
1707
|
-
}
|
|
1708
|
-
}
|
|
1709
|
-
function isoList(v) {
|
|
1710
|
-
if (typeof v !== "string") return [];
|
|
1711
|
-
try {
|
|
1712
|
-
const list = JSON.parse(v);
|
|
1713
|
-
return Array.isArray(list) ? list.filter((t) => typeof t === "string") : [];
|
|
1714
|
-
} catch {
|
|
1715
|
-
return [];
|
|
1716
|
-
}
|
|
1717
|
-
}
|
|
1718
|
-
function toSessionRow(r) {
|
|
1719
|
-
const row = {
|
|
1720
|
-
id: r.id,
|
|
1721
|
-
name: r.name,
|
|
1722
|
-
cli: r.cli,
|
|
1723
|
-
deviceId: r.device_id,
|
|
1724
|
-
cwd: r.cwd,
|
|
1725
|
-
status: r.status,
|
|
1726
|
-
deliveryTier: r.delivery_tier,
|
|
1727
|
-
spawned: r.spawned === 1,
|
|
1728
|
-
spawnDepth: r.spawn_depth,
|
|
1729
|
-
autoRuns: isoList(r.auto_runs),
|
|
1730
|
-
turnHops: num(r.turn_hops) ?? 0,
|
|
1731
|
-
startedAt: r.started_at,
|
|
1732
|
-
lastSeenAt: r.last_seen_at
|
|
1733
|
-
};
|
|
1734
|
-
const cliVersion = str(r.cli_version);
|
|
1735
|
-
if (cliVersion !== void 0) row.cliVersion = cliVersion;
|
|
1736
|
-
const repoRoot = str(r.repo_root);
|
|
1737
|
-
if (repoRoot !== void 0) row.repoRoot = repoRoot;
|
|
1738
|
-
const hash = str(r.repo_remote_hash);
|
|
1739
|
-
if (hash !== void 0) row.repoRemoteUrlHash = hash;
|
|
1740
|
-
const pid = num(r.pid);
|
|
1741
|
-
if (pid !== void 0) row.pid = pid;
|
|
1742
|
-
const hostPid = num(r.host_pid);
|
|
1743
|
-
if (hostPid !== void 0) row.hostPid = hostPid;
|
|
1744
|
-
const hostPids = pidList(r.host_pids);
|
|
1745
|
-
if (hostPids !== void 0) row.hostPids = hostPids;
|
|
1746
|
-
const statusText = str(r.status_text);
|
|
1747
|
-
if (statusText !== void 0) row.statusText = statusText;
|
|
1748
|
-
const spawnedBy = str(r.spawned_by);
|
|
1749
|
-
if (spawnedBy !== void 0) row.spawnedBy = spawnedBy;
|
|
1750
|
-
const nativeId = str(r.native_id);
|
|
1751
|
-
if (nativeId !== void 0) row.nativeId = nativeId;
|
|
1752
|
-
return row;
|
|
1753
|
-
}
|
|
1754
|
-
/** Wire-format session for a stored row. */
|
|
1755
|
-
function toSession(row, isOrchestrator, unreadCount) {
|
|
1756
|
-
const s = {
|
|
1757
|
-
id: row.id,
|
|
1758
|
-
name: row.name,
|
|
1759
|
-
cli: row.cli,
|
|
1760
|
-
deviceId: row.deviceId,
|
|
1761
|
-
cwd: row.cwd,
|
|
1762
|
-
status: row.status,
|
|
1763
|
-
isOrchestrator,
|
|
1764
|
-
deliveryTier: row.deliveryTier,
|
|
1765
|
-
spawned: row.spawned,
|
|
1766
|
-
spawnDepth: row.spawnDepth,
|
|
1767
|
-
startedAt: row.startedAt,
|
|
1768
|
-
lastSeenAt: row.lastSeenAt
|
|
1769
|
-
};
|
|
1770
|
-
if (unreadCount !== void 0) s.unreadCount = unreadCount;
|
|
1771
|
-
if (row.cliVersion !== void 0) s.cliVersion = row.cliVersion;
|
|
1772
|
-
if (row.repoRoot !== void 0) s.repo = row.repoRemoteUrlHash !== void 0 ? {
|
|
1773
|
-
root: row.repoRoot,
|
|
1774
|
-
remoteUrlHash: row.repoRemoteUrlHash
|
|
1775
|
-
} : { root: row.repoRoot };
|
|
1776
|
-
if (row.pid !== void 0) s.pid = row.pid;
|
|
1777
|
-
if (row.hostPid !== void 0) s.hostPid = row.hostPid;
|
|
1778
|
-
if (row.hostPids !== void 0) s.hostPids = row.hostPids;
|
|
1779
|
-
if (row.statusText !== void 0) s.statusText = row.statusText;
|
|
1780
|
-
if (row.spawnedBy !== void 0) s.spawnedBy = row.spawnedBy;
|
|
1781
|
-
if (row.nativeId !== void 0) s.nativeId = row.nativeId;
|
|
1782
|
-
return s;
|
|
1783
|
-
}
|
|
1784
|
-
function toEntry(r) {
|
|
1785
|
-
const entry = {
|
|
1786
|
-
message: Message.parse(JSON.parse(r.json)),
|
|
1787
|
-
state: r.state,
|
|
1788
|
-
queuedAt: r.queued_at
|
|
1789
|
-
};
|
|
1790
|
-
const d = str(r.delivered_at);
|
|
1791
|
-
const rd = str(r.read_at);
|
|
1792
|
-
const a = str(r.acked_at);
|
|
1793
|
-
if (d) entry.deliveredAt = d;
|
|
1794
|
-
if (rd) entry.readAt = rd;
|
|
1795
|
-
if (a) entry.ackedAt = a;
|
|
1796
|
-
const hops = num(r.hops);
|
|
1797
|
-
if (hops !== void 0 && hops > 0) entry.hops = hops;
|
|
1798
|
-
return entry;
|
|
1799
|
-
}
|
|
1800
|
-
/** SQLite persistence. All methods are synchronous; callers group writes with `tx`. */
|
|
1801
|
-
var Store = class {
|
|
1802
|
-
db;
|
|
1803
|
-
constructor(path) {
|
|
1804
|
-
this.db = new DatabaseSync(path);
|
|
1805
|
-
this.db.exec("PRAGMA journal_mode = WAL");
|
|
1806
|
-
this.db.exec("PRAGMA synchronous = NORMAL");
|
|
1807
|
-
this.db.exec("PRAGMA busy_timeout = 5000");
|
|
1808
|
-
this.migrate();
|
|
1809
|
-
}
|
|
1810
|
-
all(sql, ...params) {
|
|
1811
|
-
return this.db.prepare(sql).all(...params);
|
|
1812
|
-
}
|
|
1813
|
-
run(sql, ...params) {
|
|
1814
|
-
this.db.prepare(sql).run(...params);
|
|
1815
|
-
}
|
|
1816
|
-
migrate() {
|
|
1817
|
-
this.db.exec("CREATE TABLE IF NOT EXISTS migrations (name TEXT PRIMARY KEY, applied_at TEXT NOT NULL)");
|
|
1818
|
-
const done = new Set(this.all("SELECT name FROM migrations").map((r) => r.name));
|
|
1819
|
-
for (const m of MIGRATIONS) {
|
|
1820
|
-
if (done.has(m.name)) continue;
|
|
1821
|
-
this.tx(() => {
|
|
1822
|
-
this.db.exec(m.sql);
|
|
1823
|
-
this.run("INSERT INTO migrations (name, applied_at) VALUES (?, ?)", m.name, (/* @__PURE__ */ new Date()).toISOString());
|
|
1824
|
-
});
|
|
1825
|
-
}
|
|
1826
|
-
}
|
|
1827
|
-
tx(fn) {
|
|
1828
|
-
this.db.exec("BEGIN IMMEDIATE");
|
|
1829
|
-
try {
|
|
1830
|
-
const out = fn();
|
|
1831
|
-
this.db.exec("COMMIT");
|
|
1832
|
-
return out;
|
|
1833
|
-
} catch (e) {
|
|
1834
|
-
this.db.exec("ROLLBACK");
|
|
1835
|
-
throw e;
|
|
1836
|
-
}
|
|
1837
|
-
}
|
|
1838
|
-
close() {
|
|
1839
|
-
this.db.close();
|
|
1840
|
-
}
|
|
1841
|
-
migrationNames() {
|
|
1842
|
-
return this.all("SELECT name FROM migrations ORDER BY name").map((r) => r.name);
|
|
1843
|
-
}
|
|
1844
|
-
/** The device id of this machine, generated on first start. */
|
|
1845
|
-
deviceId() {
|
|
1846
|
-
const r = this.all("SELECT value FROM meta WHERE key = 'device_id'")[0];
|
|
1847
|
-
if (r) return DeviceId.parse(r.value);
|
|
1848
|
-
const id = newDeviceId();
|
|
1849
|
-
this.run("INSERT INTO meta (key, value) VALUES ('device_id', ?)", id);
|
|
1850
|
-
return id;
|
|
1851
|
-
}
|
|
1852
|
-
insertSession(s) {
|
|
1853
|
-
this.run(`INSERT INTO sessions (id, name, cli, cli_version, device_id, cwd, repo_root, repo_remote_hash,
|
|
1854
|
-
pid, host_pid, host_pids, status, status_text, delivery_tier, spawned_by, spawned, spawn_depth,
|
|
1855
|
-
auto_runs, turn_hops, started_at, last_seen_at)
|
|
1856
|
-
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.spawned ? 1 : 0, s.spawnDepth, JSON.stringify(s.autoRuns), s.turnHops, s.startedAt, s.lastSeenAt);
|
|
1857
|
-
}
|
|
1858
|
-
getSession(id) {
|
|
1859
|
-
const r = this.all("SELECT * FROM sessions WHERE id = ?", id)[0];
|
|
1860
|
-
return r ? toSessionRow(r) : void 0;
|
|
1861
|
-
}
|
|
1862
|
-
/** Every session, oldest first (ids are monotonic ULIDs). */
|
|
1863
|
-
allSessions() {
|
|
1864
|
-
return this.all("SELECT * FROM sessions ORDER BY started_at, id").map(toSessionRow);
|
|
1865
|
-
}
|
|
1866
|
-
updateSession(id, fields) {
|
|
1867
|
-
const sets = [];
|
|
1868
|
-
const vals = [];
|
|
1869
|
-
if (fields.nativeId !== void 0) {
|
|
1870
|
-
sets.push("native_id = ?");
|
|
1871
|
-
vals.push(fields.nativeId);
|
|
1872
|
-
}
|
|
1873
|
-
if (fields.turnHops !== void 0) {
|
|
1874
|
-
sets.push("turn_hops = ?");
|
|
1875
|
-
vals.push(fields.turnHops);
|
|
1876
|
-
}
|
|
1877
|
-
if (fields.autoRuns !== void 0) {
|
|
1878
|
-
sets.push("auto_runs = ?");
|
|
1879
|
-
vals.push(JSON.stringify(fields.autoRuns));
|
|
1880
|
-
}
|
|
1881
|
-
if (fields.name !== void 0) {
|
|
1882
|
-
sets.push("name = ?");
|
|
1883
|
-
vals.push(fields.name);
|
|
1884
|
-
}
|
|
1885
|
-
if (fields.status !== void 0) {
|
|
1886
|
-
sets.push("status = ?");
|
|
1887
|
-
vals.push(fields.status);
|
|
1888
|
-
}
|
|
1889
|
-
if (fields.statusText !== void 0) {
|
|
1890
|
-
sets.push("status_text = ?");
|
|
1891
|
-
vals.push(fields.statusText);
|
|
1892
|
-
}
|
|
1893
|
-
if (fields.lastSeenAt !== void 0) {
|
|
1894
|
-
sets.push("last_seen_at = ?");
|
|
1895
|
-
vals.push(fields.lastSeenAt);
|
|
1896
|
-
}
|
|
1897
|
-
if (sets.length === 0) return;
|
|
1898
|
-
this.run(`UPDATE sessions SET ${sets.join(", ")} WHERE id = ?`, ...vals, id);
|
|
1899
|
-
}
|
|
1900
|
-
holder() {
|
|
1901
|
-
const r = this.all("SELECT session_id FROM orchestrator WHERE slot = 1")[0];
|
|
1902
|
-
return str(r?.session_id) ?? null;
|
|
1903
|
-
}
|
|
1904
|
-
setHolder(id) {
|
|
1905
|
-
this.run("UPDATE orchestrator SET session_id = ? WHERE slot = 1", id);
|
|
1906
|
-
}
|
|
1907
|
-
/** `hops`: automatic turns behind the message (the wake limit counts them). */
|
|
1908
|
-
insertMessage(message, recipient, at, hops = 0) {
|
|
1909
|
-
this.run("INSERT INTO messages (id, json) VALUES (?, ?)", message.id, JSON.stringify(message));
|
|
1910
|
-
this.run("INSERT INTO mailbox (session_id, message_id, state, queued_at, hops) VALUES (?, ?, 'queued', ?, ?)", recipient, message.id, at, hops);
|
|
1911
|
-
}
|
|
1912
|
-
/** Messages queued for a session that no one has been shown yet. */
|
|
1913
|
-
unreadCount(sessionId) {
|
|
1914
|
-
const r = this.all("SELECT COUNT(*) AS n FROM mailbox WHERE session_id = ? AND state = 'queued'", sessionId)[0];
|
|
1915
|
-
return num(r?.n) ?? 0;
|
|
1916
|
-
}
|
|
1917
|
-
hasMessage(id) {
|
|
1918
|
-
return this.all("SELECT 1 AS x FROM messages WHERE id = ?", id).length > 0;
|
|
1919
|
-
}
|
|
1920
|
-
/** Remove a session, its mailbox, and any message no mailbox refers to any more. */
|
|
1921
|
-
deleteSession(id) {
|
|
1922
|
-
this.run("DELETE FROM mailbox WHERE session_id = ?", id);
|
|
1923
|
-
this.run("DELETE FROM messages WHERE id NOT IN (SELECT message_id FROM mailbox)");
|
|
1924
|
-
this.run("DELETE FROM sessions WHERE id = ?", id);
|
|
1925
|
-
}
|
|
1926
|
-
/** Mailbox entries of one session, optionally limited to the given states or message ids. */
|
|
1927
|
-
entries(sessionId, filter = {}) {
|
|
1928
|
-
let sql = `SELECT m.json, b.state, b.queued_at, b.delivered_at, b.read_at, b.acked_at, b.hops
|
|
1929
|
-
FROM mailbox b JOIN messages m ON m.id = b.message_id WHERE b.session_id = ?`;
|
|
1930
|
-
const params = [sessionId];
|
|
1931
|
-
if (filter.states) {
|
|
1932
|
-
sql += ` AND b.state IN (${filter.states.map(() => "?").join(",")})`;
|
|
1933
|
-
params.push(...filter.states);
|
|
1934
|
-
}
|
|
1935
|
-
if (filter.ids) {
|
|
1936
|
-
sql += ` AND b.message_id IN (${filter.ids.map(() => "?").join(",")})`;
|
|
1937
|
-
params.push(...filter.ids);
|
|
1938
|
-
}
|
|
1939
|
-
return this.all(sql, ...params).map(toEntry);
|
|
1940
|
-
}
|
|
1941
|
-
saveEntry(sessionId, e) {
|
|
1942
|
-
this.run(`UPDATE mailbox SET state = ?, delivered_at = ?, read_at = ?, acked_at = ?
|
|
1943
|
-
WHERE session_id = ? AND message_id = ?`, e.state, e.deliveredAt ?? null, e.readAt ?? null, e.ackedAt ?? null, sessionId, e.message.id);
|
|
1944
|
-
}
|
|
1945
|
-
};
|
|
1946
|
-
// ../daemon/src/server.ts
|
|
1947
|
-
const DAEMON_VERSION = "0.2.0-rc.8";
|
|
1948
|
-
/** A connection that has not finished the handshake by then is closed. */
|
|
1949
|
-
const AUTH_TIMEOUT_MS = 5e3;
|
|
1950
|
-
/** Unread messages one session may hold. */
|
|
1951
|
-
const MAX_UNREAD_PER_SESSION = 1e3;
|
|
1952
|
-
/**
|
|
1953
|
-
* An offline session is removed this long after it went offline. The grace lets a session whose
|
|
1954
|
-
* host process is still alive come back with a heartbeat. Sessions already offline when the daemon
|
|
1955
|
-
* starts are removed at once.
|
|
1956
|
-
*/
|
|
1957
|
-
const OFFLINE_GRACE_MS = 6e4;
|
|
1958
|
-
/** Time the daemon spends reading the process table for one `session.hostOf`. */
|
|
1959
|
-
const HOST_OF_TIMEOUT_MS = 1500;
|
|
1960
|
-
/** Message bytes one daemon wake hands over: the text goes on a command line (\`codex queue\`). */
|
|
1961
|
-
const DAEMON_WAKE_BYTES = 16e3;
|
|
1962
|
-
/** First wait before a daemon wake is tried again; doubles up to the max. */
|
|
1963
|
-
const WAKE_RETRY_MS = 15e3;
|
|
1964
|
-
/** A wake still not a turn after this long counts as unread in status (see `stalledWoken`). */
|
|
1965
|
-
const WOKEN_STALL_MS = 3e4;
|
|
1966
|
-
const WAKE_RETRY_MAX_MS = 3e5;
|
|
1967
|
-
/** Sender id on `system` messages made by the daemon itself (no session sent them). */
|
|
1968
|
-
const DAEMON_SENDER_ID = SessionId.parse("0".repeat(26));
|
|
1969
|
-
const CLI_TIER = {
|
|
1970
|
-
claude: "next_turn",
|
|
1971
|
-
codex: "next_turn",
|
|
1972
|
-
cursor: "next_turn",
|
|
1973
|
-
copilot: "next_turn",
|
|
1974
|
-
antigravity: "next_turn"
|
|
1975
|
-
};
|
|
1976
|
-
var Daemon = class {
|
|
1977
|
-
store;
|
|
1978
|
-
token;
|
|
1979
|
-
now;
|
|
1980
|
-
isAlive;
|
|
1981
|
-
idleExitMs;
|
|
1982
|
-
requestIdleExit;
|
|
1983
|
-
requestShutdown;
|
|
1984
|
-
log;
|
|
1985
|
-
authTimeoutMs;
|
|
1986
|
-
autoLimits;
|
|
1987
|
-
processIo;
|
|
1988
|
-
platform;
|
|
1989
|
-
wakers;
|
|
1990
|
-
settingsPath;
|
|
1991
|
-
conns = /* @__PURE__ */ new Set();
|
|
1992
|
-
/** Reaches the owner's other devices; set by startDaemon unless disabled. */
|
|
1993
|
-
relay;
|
|
1994
|
-
deviceId;
|
|
1995
|
-
/**
|
|
1996
|
-
* The newest idle-wake listener of each session, the ids it replaced, and the connection it
|
|
1997
|
-
* asked on. The session counts as wakeable while that connection is open. In memory only.
|
|
1998
|
-
*/
|
|
1999
|
-
listeners = /* @__PURE__ */ new Map();
|
|
2000
|
-
/**
|
|
2001
|
-
* Messages the last wake handed each session, until its turn starts or ends. A requeue of
|
|
2002
|
-
* these makes the session idle again. In memory only.
|
|
2003
|
-
*/
|
|
2004
|
-
woken = /* @__PURE__ */ new Map();
|
|
2005
|
-
/** Sessions a daemon waker is working on, so one session gets one wake at a time. */
|
|
2006
|
-
daemonWaking = /* @__PURE__ */ new Set();
|
|
2007
|
-
/** Daemon wakes to try again (after \`failed\` or the wake limit), by session. In memory only. */
|
|
2008
|
-
wakeRetry = /* @__PURE__ */ new Map();
|
|
2009
|
-
/** Set when the daemon shuts down: closing connections must not touch the store any more. */
|
|
2010
|
-
stopping = false;
|
|
2011
|
-
/**
|
|
2012
|
-
* Sessions whose daemon waker answered \`unsupported\` (no \`queue\` in that binary, an ephemeral
|
|
2013
|
-
* thread): not asked again for them while the daemon runs, so a new daemon checks afresh. Other
|
|
2014
|
-
* sessions of the same CLI are still woken.
|
|
2015
|
-
*/
|
|
2016
|
-
wakersOff = /* @__PURE__ */ new Set();
|
|
2017
|
-
/** When each session's last daemon wake was handed over, to tell a wake that never became a turn. */
|
|
2018
|
-
wokenAt = /* @__PURE__ */ new Map();
|
|
2019
|
-
idleSince;
|
|
2020
|
-
startedMs;
|
|
2021
|
-
/** When each session went offline, for the removal grace. In memory only. */
|
|
2022
|
-
offlineSince = /* @__PURE__ */ new Map();
|
|
2023
|
-
constructor(store, token, now, isAlive, idleExitMs, requestIdleExit, requestShutdown, log, authTimeoutMs = AUTH_TIMEOUT_MS, autoLimits = autoLimitsFromEnv({}), processIo = defaultProcessIo, platform = process.platform, wakers = {}, settingsPath) {
|
|
2024
|
-
this.store = store;
|
|
2025
|
-
this.token = token;
|
|
2026
|
-
this.now = now;
|
|
2027
|
-
this.isAlive = isAlive;
|
|
2028
|
-
this.idleExitMs = idleExitMs;
|
|
2029
|
-
this.requestIdleExit = requestIdleExit;
|
|
2030
|
-
this.requestShutdown = requestShutdown;
|
|
2031
|
-
this.log = log;
|
|
2032
|
-
this.authTimeoutMs = authTimeoutMs;
|
|
2033
|
-
this.autoLimits = autoLimits;
|
|
2034
|
-
this.processIo = processIo;
|
|
2035
|
-
this.platform = platform;
|
|
2036
|
-
this.wakers = wakers;
|
|
2037
|
-
this.settingsPath = settingsPath;
|
|
2038
|
-
this.deviceId = store.deviceId();
|
|
2039
|
-
this.startedMs = now().getTime();
|
|
2040
|
-
this.idleSince = this.startedMs;
|
|
2041
|
-
}
|
|
2042
|
-
iso = () => this.now().toISOString();
|
|
2043
|
-
attach(socket) {
|
|
2044
|
-
const conn = {
|
|
2045
|
-
socket,
|
|
2046
|
-
authed: false,
|
|
2047
|
-
queue: Promise.resolve()
|
|
2048
|
-
};
|
|
2049
|
-
this.conns.add(conn);
|
|
2050
|
-
const authTimer = setTimeout(() => {
|
|
2051
|
-
if (!conn.authed) socket.destroy();
|
|
2052
|
-
}, this.authTimeoutMs);
|
|
2053
|
-
authTimer.unref();
|
|
2054
|
-
const decoder = createLineDecoder();
|
|
2055
|
-
socket.on("data", (chunk) => {
|
|
2056
|
-
for (const frame of decoder.push(chunk)) conn.queue = conn.queue.then(() => this.onFrame(conn, frame));
|
|
2057
|
-
});
|
|
2058
|
-
socket.on("close", () => {
|
|
2059
|
-
clearTimeout(authTimer);
|
|
2060
|
-
this.conns.delete(conn);
|
|
2061
|
-
this.listenerGone(conn);
|
|
2062
|
-
});
|
|
2063
|
-
socket.on("error", () => socket.destroy());
|
|
2064
|
-
}
|
|
2065
|
-
send(conn, obj, flushed) {
|
|
2066
|
-
if (conn.socket.destroyed) {
|
|
2067
|
-
flushed?.();
|
|
2068
|
-
return;
|
|
2069
|
-
}
|
|
2070
|
-
try {
|
|
2071
|
-
conn.socket.write(encodeFrame(obj), flushed);
|
|
2072
|
-
} catch {
|
|
2073
|
-
const id = obj?.id;
|
|
2074
|
-
if (typeof id === "string" || typeof id === "number") conn.socket.write(encodeFrame(makeError(id, RpcErrorCode.InternalError, "The response was too large to send.")));
|
|
2075
|
-
}
|
|
2076
|
-
}
|
|
2077
|
-
async onFrame(conn, frame) {
|
|
2078
|
-
if (!frame.ok) {
|
|
2079
|
-
if (frame.error.code === "invalid_json") this.send(conn, makeError(null, RpcErrorCode.ParseError, "Parse error: line is not valid JSON."));
|
|
2080
|
-
else this.send(conn, makeError(null, RpcErrorCode.InvalidRequest, "Line is longer than 1 MiB. Send smaller requests."));
|
|
2081
|
-
return;
|
|
2082
|
-
}
|
|
2083
|
-
const parsed = parseIpcRequest(frame.value);
|
|
2084
|
-
if (!parsed.ok) {
|
|
2085
|
-
const method = frame.value?.method;
|
|
2086
|
-
const needsAuth = !conn.authed && method !== "hello" && method !== "auth";
|
|
2087
|
-
const code = parsed.error.code;
|
|
2088
|
-
if (needsAuth && (code === RpcErrorCode.MethodNotFound || code === RpcErrorCode.InvalidParams)) this.send(conn, makeError(parsed.id, RpcErrorCode.Unauthorized, unauthorizedMessage));
|
|
2089
|
-
else this.send(conn, makeError(parsed.id, code, parsed.error.message, parsed.error.data));
|
|
2090
|
-
return;
|
|
2091
|
-
}
|
|
2092
|
-
const req = parsed.request;
|
|
2093
|
-
if (!conn.authed && req.method !== "hello" && req.method !== "auth") {
|
|
2094
|
-
this.send(conn, makeError(req.id, RpcErrorCode.Unauthorized, unauthorizedMessage));
|
|
2095
|
-
return;
|
|
2096
|
-
}
|
|
2097
|
-
try {
|
|
2098
|
-
const result = await this.dispatch(conn, req);
|
|
2099
|
-
const flushed = req.method === "daemon.shutdown" ? this.requestShutdown : void 0;
|
|
2100
|
-
this.send(conn, makeResult(req.id, result), flushed);
|
|
2101
|
-
} catch (e) {
|
|
2102
|
-
this.sendError(conn, req.id, req.method, e);
|
|
2103
|
-
if (req.method === "hello" || req.method === "auth") conn.socket.end();
|
|
2104
|
-
}
|
|
2105
|
-
}
|
|
2106
|
-
sendError(conn, id, method, e) {
|
|
2107
|
-
if (e instanceof ConvenoError) this.send(conn, makeError(id, e.code, e.message));
|
|
2108
|
-
else {
|
|
2109
|
-
this.log.error(`internal error in ${method}`, e);
|
|
2110
|
-
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.`));
|
|
2111
|
-
}
|
|
2112
|
-
}
|
|
2113
|
-
dispatch(conn, req) {
|
|
2114
|
-
switch (req.method) {
|
|
2115
|
-
case "hello": return this.hello(conn, req.params);
|
|
2116
|
-
case "auth": return this.auth(conn, req.params);
|
|
2117
|
-
case "session.register": return this.registerAsync(req.params);
|
|
2118
|
-
case "session.heartbeat": return this.heartbeat(req.params.sessionId);
|
|
2119
|
-
case "session.unregister": return this.unregister(req.params.sessionId);
|
|
2120
|
-
case "session.rename": return this.rename(req.params);
|
|
2121
|
-
case "session.setStatus": return this.setStatus(req.params);
|
|
2122
|
-
case "session.list": return this.list(req.params);
|
|
2123
|
-
case "session.byHost": return this.byHost(req.params);
|
|
2124
|
-
case "session.hostOf": return this.hostOf(req.params);
|
|
2125
|
-
case "session.setNative": return this.setNative(req.params);
|
|
2126
|
-
case "turn.start": return this.turnStart(req.params.sessionId);
|
|
2127
|
-
case "turn.end": return this.turnEnd(req.params);
|
|
2128
|
-
case "turn.wake": return this.turnWake(conn, req.params);
|
|
2129
|
-
case "daemon.shutdown": return { ok: true };
|
|
2130
|
-
case "orchestrator.claim": return this.claim(req.params.sessionId);
|
|
2131
|
-
case "orchestrator.clear": return this.clearLead(conn);
|
|
2132
|
-
case "message.send": return this.sendMessage(req.params);
|
|
2133
|
-
case "owner.send": return this.ownerSend(conn, req.params);
|
|
2134
|
-
case "message.inbox": return this.inbox(req.params);
|
|
2135
|
-
case "message.deliver": return this.deliver(req.params);
|
|
2136
|
-
case "message.ack": return this.ack(req.params);
|
|
2137
|
-
case "message.requeue": return this.requeue(req.params);
|
|
2138
|
-
case "events.subscribe": return this.subscribe(conn, req.params);
|
|
2139
|
-
case "relay.status":
|
|
2140
|
-
case "devices.list":
|
|
2141
|
-
case "devices.pair":
|
|
2142
|
-
case "devices.pairStatus":
|
|
2143
|
-
case "devices.pairConfirm":
|
|
2144
|
-
case "devices.revoke":
|
|
2145
|
-
case "devices.rename":
|
|
2146
|
-
case "devices.accept":
|
|
2147
|
-
case "devices.reset": return this.relayCall(req);
|
|
2148
|
-
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.`);
|
|
2149
|
-
}
|
|
2150
|
-
}
|
|
2151
|
-
hello(conn, p) {
|
|
2152
|
-
if (conn.challenge !== void 0) throw new ConvenoError(RpcErrorCode.Conflict, "The handshake already started on this connection.");
|
|
2153
|
-
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.`);
|
|
2154
|
-
conn.kind = p.client;
|
|
2155
|
-
conn.challenge = newAuthNonce();
|
|
2156
|
-
conn.client = p.client;
|
|
2157
|
-
return {
|
|
2158
|
-
protocolVersion: PROTOCOL_VERSION,
|
|
2159
|
-
daemonVersion: DAEMON_VERSION,
|
|
2160
|
-
proof: daemonProof(this.token, p.nonce),
|
|
2161
|
-
challenge: conn.challenge
|
|
2162
|
-
};
|
|
2163
|
-
}
|
|
2164
|
-
auth(conn, p) {
|
|
2165
|
-
if (conn.challenge === void 0) throw new ConvenoError(RpcErrorCode.Unauthorized, unauthorizedMessage);
|
|
2166
|
-
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.");
|
|
2167
|
-
conn.authed = true;
|
|
2168
|
-
return { ok: true };
|
|
2169
|
-
}
|
|
2170
|
-
named(rows) {
|
|
2171
|
-
return rows.map((r) => ({
|
|
2172
|
-
id: r.id,
|
|
2173
|
-
name: r.name,
|
|
2174
|
-
status: r.status
|
|
2175
|
-
}));
|
|
2176
|
-
}
|
|
2177
|
-
requireSession(id) {
|
|
2178
|
-
const row = this.store.getSession(id);
|
|
2179
|
-
if (!row) throw new ConvenoError(RpcErrorCode.NotFound, `No session with id ${id}. Register the session again.`);
|
|
2180
|
-
return row;
|
|
2181
|
-
}
|
|
2182
|
-
requireOnline(id) {
|
|
2183
|
-
const row = this.requireSession(id);
|
|
2184
|
-
if (row.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${row.name}" is offline. Register the session again.`);
|
|
2185
|
-
return row;
|
|
2186
|
-
}
|
|
2187
|
-
/** The wire view of a session. Its `deliveryTier` is the live one (`tierFor`). */
|
|
2188
|
-
view(row) {
|
|
2189
|
-
const holder = effectiveHolder(this.store.holder(), this.named([row]));
|
|
2190
|
-
return toSession({
|
|
2191
|
-
...row,
|
|
2192
|
-
deliveryTier: this.tierFor(row)
|
|
2193
|
-
}, holder?.id === row.id, this.store.unreadCount(row.id) + this.stalledWoken(row.id));
|
|
2194
|
-
}
|
|
2195
|
-
/** The orchestrator as routing sees it: the holder, if it is online. */
|
|
2196
|
-
orchestratorNow() {
|
|
2197
|
-
return effectiveHolder(this.store.holder(), this.named(this.store.allSessions()))?.id ?? null;
|
|
2198
|
-
}
|
|
2199
|
-
emit(payload, onlyTo) {
|
|
2200
|
-
const only = onlyTo === void 0 || Array.isArray(onlyTo) ? onlyTo : [onlyTo];
|
|
2201
|
-
for (const c of this.conns) {
|
|
2202
|
-
const sub = c.sub;
|
|
2203
|
-
if (!sub?.topics.has(payload.event)) continue;
|
|
2204
|
-
if (only !== void 0 && sub.sessionId !== void 0 && !only.includes(sub.sessionId)) continue;
|
|
2205
|
-
this.send(c, makeEventNotification(payload));
|
|
2206
|
-
}
|
|
2207
|
-
}
|
|
2208
|
-
emitSession(id, change) {
|
|
2209
|
-
const row = this.store.getSession(id);
|
|
2210
|
-
if (row) this.emit({
|
|
2211
|
-
event: "session.updated",
|
|
2212
|
-
data: {
|
|
2213
|
-
session: this.view(row),
|
|
2214
|
-
change
|
|
2215
|
-
}
|
|
2216
|
-
});
|
|
2217
|
-
this.relay?.sessionsChanged();
|
|
2218
|
-
}
|
|
2219
|
-
/** Every message that lands in a local mailbox goes through here. */
|
|
2220
|
-
emitMessage(m, recipient) {
|
|
2221
|
-
this.emit({
|
|
2222
|
-
event: "message.received",
|
|
2223
|
-
data: { message: m }
|
|
2224
|
-
}, recipient);
|
|
2225
|
-
this.daemonWake(recipient);
|
|
2226
|
-
}
|
|
2227
|
-
async detect(p) {
|
|
2228
|
-
if (p.repo) return p.repo;
|
|
2229
|
-
const found = await detectRepo(p.cwd, { exists: (path) => existsSync(path) });
|
|
2230
|
-
return found.root ? { root: found.root } : void 0;
|
|
2231
|
-
}
|
|
2232
|
-
register(p, repo) {
|
|
2233
|
-
const id = newSessionId();
|
|
2234
|
-
const at = this.iso();
|
|
2235
|
-
const row = this.store.tx(() => {
|
|
2236
|
-
const named = this.named(this.store.allSessions());
|
|
2237
|
-
const base = baseName(repo?.root ?? p.cwd);
|
|
2238
|
-
const name = p.name !== void 0 ? validateRename(id, p.name, named) : generateSessionName(p.cli, base, named);
|
|
2239
|
-
const parent = p.spawnedBy ? this.store.getSession(p.spawnedBy) : void 0;
|
|
2240
|
-
const r = {
|
|
2241
|
-
id,
|
|
2242
|
-
name,
|
|
2243
|
-
cli: p.cli,
|
|
2244
|
-
deviceId: this.deviceId,
|
|
2245
|
-
cwd: p.cwd,
|
|
2246
|
-
status: "idle",
|
|
2247
|
-
deliveryTier: p.acp ? "acp" : CLI_TIER[p.cli] ?? "inbox",
|
|
2248
|
-
spawned: p.spawned,
|
|
2249
|
-
spawnDepth: parent ? parent.spawnDepth + 1 : 0,
|
|
2250
|
-
autoRuns: [],
|
|
2251
|
-
turnHops: 0,
|
|
2252
|
-
startedAt: at,
|
|
2253
|
-
lastSeenAt: at
|
|
2254
|
-
};
|
|
2255
|
-
if (p.cliVersion !== void 0) r.cliVersion = p.cliVersion;
|
|
2256
|
-
if (repo) {
|
|
2257
|
-
r.repoRoot = repo.root;
|
|
2258
|
-
if (repo.remoteUrlHash !== void 0) r.repoRemoteUrlHash = repo.remoteUrlHash;
|
|
2259
|
-
}
|
|
2260
|
-
if (p.pid !== void 0) r.pid = p.pid;
|
|
2261
|
-
if (p.hostPid !== void 0) r.hostPid = p.hostPid;
|
|
2262
|
-
if (p.hostPids !== void 0) r.hostPids = p.hostPids;
|
|
2263
|
-
if (p.spawnedBy !== void 0) r.spawnedBy = p.spawnedBy;
|
|
2264
|
-
this.store.insertSession(r);
|
|
2265
|
-
return r;
|
|
2266
|
-
});
|
|
2267
|
-
this.emitSession(row.id, "registered");
|
|
2268
|
-
this.claimPreferredLead(row);
|
|
2269
|
-
return { session: this.view(this.store.getSession(row.id) ?? row) };
|
|
2270
|
-
}
|
|
2271
|
-
/**
|
|
2272
|
-
* The saved preferred lead CLI takes the lead when it registers and nobody online leads. The
|
|
2273
|
-
* settings are read on each register, so a change needs no restart. It is the normal claim.
|
|
2274
|
-
*/
|
|
2275
|
-
claimPreferredLead(row) {
|
|
2276
|
-
if (this.settingsPath === void 0) return;
|
|
2277
|
-
if (readSettings(this.settingsPath).leadCli !== row.cli) return;
|
|
2278
|
-
if (this.orchestratorNow() !== null) return;
|
|
2279
|
-
this.claim(row.id);
|
|
2280
|
-
}
|
|
2281
|
-
async registerAsync(p) {
|
|
2282
|
-
return this.register(p, await this.detect(p));
|
|
2283
|
-
}
|
|
2284
|
-
heartbeat(sessionId) {
|
|
2285
|
-
const row = this.requireSession(sessionId);
|
|
2286
|
-
const at = this.iso();
|
|
2287
|
-
if (row.status !== "offline") {
|
|
2288
|
-
this.store.updateSession(sessionId, { lastSeenAt: at });
|
|
2289
|
-
return { lastSeenAt: at };
|
|
2290
|
-
}
|
|
2291
|
-
const taken = this.named(this.store.allSessions()).some((s) => s.id !== sessionId && isOnline(s) && s.name === row.name);
|
|
2292
|
-
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.`);
|
|
2293
|
-
this.store.updateSession(sessionId, {
|
|
2294
|
-
status: "idle",
|
|
2295
|
-
lastSeenAt: at
|
|
2296
|
-
});
|
|
2297
|
-
this.offlineSince.delete(sessionId);
|
|
2298
|
-
this.emitSession(sessionId, "updated");
|
|
2299
|
-
return { lastSeenAt: at };
|
|
2300
|
-
}
|
|
2301
|
-
depart(sessionId, change) {
|
|
2302
|
-
const before = this.store.holder();
|
|
2303
|
-
const after = holderAfterDeparture(before, sessionId);
|
|
2304
|
-
this.store.tx(() => {
|
|
2305
|
-
this.store.updateSession(sessionId, { status: "offline" });
|
|
2306
|
-
if (after !== before) this.store.setHolder(after);
|
|
2307
|
-
});
|
|
2308
|
-
this.listeners.delete(sessionId);
|
|
2309
|
-
this.woken.delete(sessionId);
|
|
2310
|
-
this.offlineSince.set(sessionId, this.now().getTime());
|
|
2311
|
-
this.emitSession(sessionId, change);
|
|
2312
|
-
if (after !== before) this.emit({
|
|
2313
|
-
event: "orchestrator.changed",
|
|
2314
|
-
data: {
|
|
2315
|
-
orchestrator: after,
|
|
2316
|
-
previous: before
|
|
2317
|
-
}
|
|
2318
|
-
});
|
|
2319
|
-
}
|
|
2320
|
-
unregister(sessionId) {
|
|
2321
|
-
if (this.requireSession(sessionId).status !== "offline") this.depart(sessionId, "unregistered");
|
|
2322
|
-
return { ok: true };
|
|
2323
|
-
}
|
|
2324
|
-
rename(p) {
|
|
2325
|
-
const row = this.requireSession(p.sessionId);
|
|
2326
|
-
const name = validateRename(p.sessionId, p.name, this.named(this.store.allSessions()));
|
|
2327
|
-
if (name !== row.name) {
|
|
2328
|
-
this.store.updateSession(p.sessionId, { name });
|
|
2329
|
-
this.emitSession(p.sessionId, "updated");
|
|
2330
|
-
}
|
|
2331
|
-
return { session: this.view(this.requireSession(p.sessionId)) };
|
|
2332
|
-
}
|
|
2333
|
-
setStatus(p) {
|
|
2334
|
-
const row = this.requireSession(p.sessionId);
|
|
2335
|
-
if (row.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${row.name}" is offline. Register the session again.`);
|
|
2336
|
-
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.");
|
|
2337
|
-
const fields = {};
|
|
2338
|
-
if (p.status !== void 0) fields.status = p.status;
|
|
2339
|
-
if (p.statusText !== void 0) {
|
|
2340
|
-
const clean = p.statusText === null ? "" : sanitizeLine(p.statusText);
|
|
2341
|
-
fields.statusText = clean === "" ? null : clean;
|
|
2342
|
-
}
|
|
2343
|
-
this.store.updateSession(p.sessionId, fields);
|
|
2344
|
-
this.emitSession(p.sessionId, "updated");
|
|
2345
|
-
return { session: this.view(this.requireSession(p.sessionId)) };
|
|
2346
|
-
}
|
|
2347
|
-
list(p) {
|
|
2348
|
-
const rows = this.store.allSessions().filter((r) => {
|
|
2349
|
-
if (r.status === "offline" && !p.includeOffline) return false;
|
|
2350
|
-
if (p.cli && r.cli !== p.cli) return false;
|
|
2351
|
-
if (p.repo && r.repoRoot !== p.repo && baseName(r.repoRoot ?? r.cwd) !== p.repo) return false;
|
|
2352
|
-
return true;
|
|
2353
|
-
});
|
|
2354
|
-
const remote = this.relay?.remoteSessions({
|
|
2355
|
-
cli: p.cli,
|
|
2356
|
-
repo: p.repo
|
|
2357
|
-
}) ?? [];
|
|
2358
|
-
return { sessions: [...rows.map((r) => this.view(r)), ...remote] };
|
|
2359
|
-
}
|
|
2360
|
-
/**
|
|
2361
|
-
* Find the session a hook belongs to: the one online session whose `hostPid` equals `pid`.
|
|
2362
|
-
* Exact equality only, with no walk to farther ancestors, so a hook from a CLI that has no
|
|
2363
|
-
* session matches nothing. Two sessions under one CLI process are ambiguous, so the result is
|
|
2364
|
-
* null; the daemon never guesses. With `cwd`, the sessions that share the pid are narrowed to
|
|
2365
|
-
* those registered in the same folder (separators, trailing slash, case
|
|
2366
|
-
* on Windows), so several folders on one OpenCode 2.x server stay apart. Two sessions in one
|
|
2367
|
-
* folder still match nothing.
|
|
2368
|
-
*/
|
|
2369
|
-
byHost(p) {
|
|
2370
|
-
const { pid, cwd, nativeId } = p;
|
|
2371
|
-
const rows = this.store.allSessions().filter((r) => p.includeOffline || r.status !== "offline");
|
|
2372
|
-
const live = (list) => {
|
|
2373
|
-
const online = list.filter((r) => r.status !== "offline");
|
|
2374
|
-
return online.length > 0 ? online : list;
|
|
2375
|
-
};
|
|
2376
|
-
if (nativeId !== void 0) {
|
|
2377
|
-
const own = live(rows.filter((r) => r.nativeId === nativeId))[0];
|
|
2378
|
-
if (!own) return { session: null };
|
|
2379
|
-
const pids = [...own.hostPid === void 0 ? [] : [own.hostPid], ...own.hostPids ?? []];
|
|
2380
|
-
if (pids.length === 0 || pids.includes(pid)) return { session: this.view(own) };
|
|
2381
|
-
const mine = this.pidHolders(rows, pid, cwd, live);
|
|
2382
|
-
return { session: this.view(mine.length === 1 ? mine[0] : own) };
|
|
2383
|
-
}
|
|
2384
|
-
const holders = this.pidHolders(rows, pid, cwd, live);
|
|
2385
|
-
const only = holders.length === 1 ? holders[0] : void 0;
|
|
2386
|
-
return { session: only ? this.view(only) : null };
|
|
2387
|
-
}
|
|
2388
|
-
/** Sessions whose host is `pid` (in `cwd`, when given), online ones first. */
|
|
2389
|
-
pidHolders(rows, pid, cwd, live) {
|
|
2390
|
-
return live(rows.filter((r) => r.hostPid === pid && (cwd === void 0 || samePath(r.cwd, cwd, this.platform))));
|
|
2391
|
-
}
|
|
2392
|
-
/**
|
|
2393
|
-
* Walk up from a hook's parent pid to its host CLI, for a hook that would otherwise read the
|
|
2394
|
-
* process table itself. With no online session of the hook's CLI there is nothing the hook could
|
|
2395
|
-
* deliver to, so it answers `online: false` without reading anything. The answer is only the
|
|
2396
|
-
* pid: the hook still goes through `byHost`, which decides whether a session owns it.
|
|
2397
|
-
* `complete: false` means the table could not be read here and the hook should read it itself.
|
|
2398
|
-
*/
|
|
2399
|
-
async hostOf(p) {
|
|
2400
|
-
if (!this.store.allSessions().some((r) => r.status !== "offline" && r.cli === p.cli)) return {
|
|
2401
|
-
online: false,
|
|
2402
|
-
complete: true
|
|
2403
|
-
};
|
|
2404
|
-
const a = await readAncestry({
|
|
2405
|
-
ppid: p.ppid,
|
|
2406
|
-
timeoutMs: HOST_OF_TIMEOUT_MS,
|
|
2407
|
-
launcherPaths: p.launcherPaths ?? [],
|
|
2408
|
-
io: this.processIo
|
|
2409
|
-
});
|
|
2410
|
-
return {
|
|
2411
|
-
online: true,
|
|
2412
|
-
complete: a.complete,
|
|
2413
|
-
...a.complete && a.hostPid !== void 0 ? { hostPid: a.hostPid } : {}
|
|
2414
|
-
};
|
|
2415
|
-
}
|
|
2416
|
-
/**
|
|
2417
|
-
* A hook records the CLI's own id for its session. One online session holds an id at a time,
|
|
2418
|
-
* so a CLI that reuses an id for a new session (a resumed thread) moves it there.
|
|
2419
|
-
*/
|
|
2420
|
-
setNative(p) {
|
|
2421
|
-
const row = this.requireOnline(p.sessionId);
|
|
2422
|
-
if (row.nativeId === p.nativeId) return { session: this.view(row) };
|
|
2423
|
-
const others = this.store.allSessions().filter((r) => r.id !== row.id && r.nativeId === p.nativeId);
|
|
2424
|
-
this.store.tx(() => {
|
|
2425
|
-
for (const o of others) this.store.updateSession(o.id, { nativeId: null });
|
|
2426
|
-
this.store.updateSession(row.id, { nativeId: p.nativeId });
|
|
2427
|
-
});
|
|
2428
|
-
for (const o of others) this.emitSession(o.id, "updated");
|
|
2429
|
-
this.emitSession(row.id, "updated");
|
|
2430
|
-
this.daemonWake(row.id);
|
|
2431
|
-
return { session: this.view(this.requireSession(row.id)) };
|
|
2432
|
-
}
|
|
2433
|
-
/** Delete offline sessions and their mail. \`graceMs\` 0 removes every one at once. */
|
|
2434
|
-
removeOffline(graceMs) {
|
|
2435
|
-
const nowMs = this.now().getTime();
|
|
2436
|
-
const gone = this.store.allSessions().filter((r) => {
|
|
2437
|
-
if (r.status !== "offline") return false;
|
|
2438
|
-
const since = this.offlineSince.get(r.id) ?? Date.parse(r.lastSeenAt);
|
|
2439
|
-
return nowMs - since >= graceMs;
|
|
2440
|
-
});
|
|
2441
|
-
if (gone.length === 0) return;
|
|
2442
|
-
this.store.tx(() => {
|
|
2443
|
-
for (const r of gone) this.store.deleteSession(r.id);
|
|
2444
|
-
});
|
|
2445
|
-
for (const r of gone) {
|
|
2446
|
-
this.listeners.delete(r.id);
|
|
2447
|
-
this.woken.delete(r.id);
|
|
2448
|
-
this.wokenAt.delete(r.id);
|
|
2449
|
-
this.wakersOff.delete(r.id);
|
|
2450
|
-
this.offlineSince.delete(r.id);
|
|
2451
|
-
}
|
|
2452
|
-
}
|
|
2453
|
-
claim(sessionId) {
|
|
2454
|
-
this.requireSession(sessionId);
|
|
2455
|
-
const rows = this.store.allSessions();
|
|
2456
|
-
const holder = this.store.holder();
|
|
2457
|
-
const res = claimOrchestrator(holder, sessionId, this.named(rows));
|
|
2458
|
-
const at = this.iso();
|
|
2459
|
-
const sent = [];
|
|
2460
|
-
this.store.tx(() => {
|
|
2461
|
-
this.store.setHolder(res.orchestrator);
|
|
2462
|
-
for (const n of res.notices) {
|
|
2463
|
-
const m = {
|
|
2464
|
-
id: newMessageId(),
|
|
2465
|
-
from: DAEMON_SENDER_ID,
|
|
2466
|
-
to: n.to,
|
|
2467
|
-
kind: "system",
|
|
2468
|
-
body: {
|
|
2469
|
-
event: n.event,
|
|
2470
|
-
detail: n.detail
|
|
2471
|
-
},
|
|
2472
|
-
urgent: false,
|
|
2473
|
-
createdAt: at
|
|
2474
|
-
};
|
|
2475
|
-
this.store.insertMessage(m, n.to, at);
|
|
2476
|
-
sent.push(m);
|
|
2477
|
-
}
|
|
2478
|
-
});
|
|
2479
|
-
if (res.notices.length > 0) {
|
|
2480
|
-
this.emit({
|
|
2481
|
-
event: "orchestrator.changed",
|
|
2482
|
-
data: {
|
|
2483
|
-
orchestrator: res.orchestrator,
|
|
2484
|
-
previous: res.previous
|
|
2485
|
-
}
|
|
2486
|
-
});
|
|
2487
|
-
this.emitSession(sessionId, "updated");
|
|
2488
|
-
if (res.previous) this.emitSession(res.previous, "updated");
|
|
2489
|
-
for (const m of sent) this.emitMessage(m, m.to);
|
|
2490
|
-
}
|
|
2491
|
-
return {
|
|
2492
|
-
orchestrator: res.orchestrator,
|
|
2493
|
-
previous: res.previous
|
|
2494
|
-
};
|
|
2495
|
-
}
|
|
2496
|
-
clearLead(conn) {
|
|
2497
|
-
this.requireCli(conn, "clear the lead");
|
|
2498
|
-
const holder = this.store.holder();
|
|
2499
|
-
const res = clearOrchestrator(holder, this.named(this.store.allSessions()));
|
|
2500
|
-
const at = this.iso();
|
|
2501
|
-
const sent = [];
|
|
2502
|
-
this.store.tx(() => {
|
|
2503
|
-
this.store.setHolder(null);
|
|
2504
|
-
for (const n of res.notices) {
|
|
2505
|
-
const m = {
|
|
2506
|
-
id: newMessageId(),
|
|
2507
|
-
from: DAEMON_SENDER_ID,
|
|
2508
|
-
to: n.to,
|
|
2509
|
-
kind: "system",
|
|
2510
|
-
body: {
|
|
2511
|
-
event: n.event,
|
|
2512
|
-
detail: n.detail
|
|
2513
|
-
},
|
|
2514
|
-
urgent: false,
|
|
2515
|
-
createdAt: at
|
|
2516
|
-
};
|
|
2517
|
-
this.store.insertMessage(m, n.to, at);
|
|
2518
|
-
sent.push(m);
|
|
2519
|
-
}
|
|
2520
|
-
});
|
|
2521
|
-
if (holder !== null) {
|
|
2522
|
-
this.emit({
|
|
2523
|
-
event: "orchestrator.changed",
|
|
2524
|
-
data: {
|
|
2525
|
-
orchestrator: null,
|
|
2526
|
-
previous: holder
|
|
2527
|
-
}
|
|
2528
|
-
});
|
|
2529
|
-
if (res.previous) this.emitSession(res.previous, "updated");
|
|
2530
|
-
for (const m of sent) this.emitMessage(m, m.to);
|
|
2531
|
-
}
|
|
2532
|
-
return { previous: res.previous };
|
|
2533
|
-
}
|
|
2534
|
-
sendMessage(p) {
|
|
2535
|
-
const sender = this.requireSession(p.sessionId);
|
|
2536
|
-
if (sender.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${sender.name}" is offline. Register the session again before sending.`);
|
|
2537
|
-
if (p.kind === "system") throw new ConvenoError(RpcErrorCode.InvalidParams, "Messages of kind \"system\" are made by the Conveno daemon only. Send kind \"text\" instead.");
|
|
2538
|
-
return this.deliverFrom({
|
|
2539
|
-
id: sender.id,
|
|
2540
|
-
name: sender.name,
|
|
2541
|
-
cli: sender.cli,
|
|
2542
|
-
hops: sender.status === "busy" ? sender.turnHops : 0
|
|
2543
|
-
}, p);
|
|
2544
|
-
}
|
|
2545
|
-
/** The recipient names the owner: `you`, or the id of a message the owner sent. */
|
|
2546
|
-
isOwnerRecipient(to) {
|
|
2547
|
-
return to === "you" || to === OWNER_SESSION_ID;
|
|
2548
|
-
}
|
|
2549
|
-
/**
|
|
2550
|
-
* Route one message from \`sender\` (a session, or the owner) to a session, or to a session on
|
|
2551
|
-
* another device. The owner is not a session and has no inbox: a session cannot message \`you\`.
|
|
2552
|
-
*/
|
|
2553
|
-
deliverFrom(sender, p) {
|
|
2554
|
-
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.`);
|
|
2555
|
-
const at = this.iso();
|
|
2556
|
-
const rows = this.store.allSessions();
|
|
2557
|
-
const make = (to) => ({
|
|
2558
|
-
id: newMessageId(),
|
|
2559
|
-
from: sender.id,
|
|
2560
|
-
to,
|
|
2561
|
-
kind: p.kind,
|
|
2562
|
-
body: p.body,
|
|
2563
|
-
urgent: p.urgent,
|
|
2564
|
-
createdAt: at,
|
|
2565
|
-
fromName: sender.name,
|
|
2566
|
-
...sender.cli !== void 0 ? { fromCli: sender.cli } : {},
|
|
2567
|
-
...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
|
|
2568
|
-
});
|
|
2569
|
-
if (this.isOwnerRecipient(p.to)) throw new ConvenoError(RpcErrorCode.InvalidParams, sender.id === OWNER_SESSION_ID ? "You cannot send a message to yourself." : "The user reads your replies in this session. Answer there instead of sending a message.");
|
|
2570
|
-
let target;
|
|
2571
|
-
try {
|
|
2572
|
-
target = resolveRecipient(p.to, this.named(rows), this.store.holder());
|
|
2573
|
-
} catch (e) {
|
|
2574
|
-
const remote = e instanceof ConvenoError && e.code === RpcErrorCode.NotFound ? this.relay?.resolveRemote(p.to) : void 0;
|
|
2575
|
-
if (!remote) throw e;
|
|
2576
|
-
return this.sendToRemote(make(p.to), remote, sender.hops);
|
|
2577
|
-
}
|
|
2578
|
-
const targetRow = rows.find((r) => r.id === target.id);
|
|
2579
|
-
if (this.store.unreadCount(targetRow.id) >= 1e3) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(targetRow.name, MAX_UNREAD_PER_SESSION));
|
|
2580
|
-
const message = make(p.to);
|
|
2581
|
-
this.store.insertMessage(message, targetRow.id, at, sender.hops);
|
|
2582
|
-
this.emitMessage(message, targetRow.id);
|
|
2583
|
-
return {
|
|
2584
|
-
message,
|
|
2585
|
-
delivery: this.tierFor(targetRow),
|
|
2586
|
-
deliveredTo: {
|
|
2587
|
-
id: targetRow.id,
|
|
2588
|
-
name: targetRow.name
|
|
2589
|
-
}
|
|
2590
|
-
};
|
|
2591
|
-
}
|
|
2592
|
-
requireCli(conn, what) {
|
|
2593
|
-
if (conn.client !== "cli") throw new ConvenoError(RpcErrorCode.Unauthorized, `Only the conveno command and app can ${what}. A session cannot act as the owner.`);
|
|
2594
|
-
}
|
|
2595
|
-
ownerSend(conn, p) {
|
|
2596
|
-
this.requireCli(conn, "send as the owner");
|
|
2597
|
-
return this.deliverFrom({
|
|
2598
|
-
id: OWNER_SESSION_ID,
|
|
2599
|
-
name: "you",
|
|
2600
|
-
hops: 0
|
|
2601
|
-
}, {
|
|
2602
|
-
to: p.to,
|
|
2603
|
-
kind: "text",
|
|
2604
|
-
body: { text: p.text },
|
|
2605
|
-
urgent: p.urgent,
|
|
2606
|
-
...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
|
|
2607
|
-
});
|
|
2608
|
-
}
|
|
2609
|
-
/**
|
|
2610
|
-
* \`acp\` for an ACP host. \`live\` while something can wake the session: a listener's connection
|
|
2611
|
-
* is open, or the session is busy in a turn a listener's CLI ends with its own hook (it continues
|
|
2612
|
-
* with what waits, then arms a new listener), or a daemon waker can reach it. Otherwise the CLI's
|
|
2613
|
-
* own tier.
|
|
2614
|
-
*/
|
|
2615
|
-
tierFor(row) {
|
|
2616
|
-
if (row.deliveryTier === "acp") return "acp";
|
|
2617
|
-
if (this.listenerConnected(row.id)) return "live";
|
|
2618
|
-
if (row.status === "busy" && this.listeners.has(row.id)) return "live";
|
|
2619
|
-
if (this.daemonWakerFor(row)) return "live";
|
|
2620
|
-
return row.deliveryTier;
|
|
2621
|
-
}
|
|
2622
|
-
listenerConnected(id) {
|
|
2623
|
-
const conn = this.listeners.get(id)?.conn;
|
|
2624
|
-
return conn !== void 0 && this.conns.has(conn) && !conn.socket.destroyed;
|
|
2625
|
-
}
|
|
2626
|
-
/** A connection closed: a listener that asked on it no longer makes its session wakeable. */
|
|
2627
|
-
listenerGone(conn) {
|
|
2628
|
-
if (this.stopping) return;
|
|
2629
|
-
for (const [id, rec] of this.listeners) {
|
|
2630
|
-
if (rec.conn !== conn) continue;
|
|
2631
|
-
rec.conn = void 0;
|
|
2632
|
-
this.emitSession(id, "updated");
|
|
2633
|
-
}
|
|
2634
|
-
}
|
|
2635
|
-
daemonWakerFor(row) {
|
|
2636
|
-
if (row.nativeId === void 0 || this.wakersOff.has(row.id)) return void 0;
|
|
2637
|
-
return this.wakers[row.cli];
|
|
2638
|
-
}
|
|
2639
|
-
/**
|
|
2640
|
-
* A message landed for \`id\`. When its CLI has a daemon waker, no listener is connected and the
|
|
2641
|
-
* session is idle, hand the waiting messages to the waker (under the wake limit, like
|
|
2642
|
-
* \`turn.wake\`, and under \`DAEMON_WAKE_BYTES\`, since they go on a command line). \`queued\`
|
|
2643
|
-
* and \`unknown\` keep them delivered (a wake that timed out may have landed: a requeue could
|
|
2644
|
-
* deliver them twice). \`failed\` and \`unsupported\` put them back; after \`failed\` or the wake
|
|
2645
|
-
* limit, the sweep tries again with a growing delay. One wake per session at a time.
|
|
2646
|
-
*/
|
|
2647
|
-
daemonWake(id) {
|
|
2648
|
-
if (this.daemonWaking.has(id)) return;
|
|
2649
|
-
const row = this.store.getSession(id);
|
|
2650
|
-
const wake = row?.status === "idle" && !this.listenerConnected(id) && this.daemonWakerFor(row);
|
|
2651
|
-
if (!row || !wake) {
|
|
2652
|
-
this.wakeRetry.delete(id);
|
|
2653
|
-
return;
|
|
2654
|
-
}
|
|
2655
|
-
const d = this.continueWith(row, true, false, DAEMON_WAKE_BYTES);
|
|
2656
|
-
if (d.messages.length === 0) {
|
|
2657
|
-
const queued = this.store.entries(id, { states: ["queued"] });
|
|
2658
|
-
if (autoCandidates(queued, id).length > 0) this.scheduleWakeRetry(id);
|
|
2659
|
-
else this.wakeRetry.delete(id);
|
|
2660
|
-
return;
|
|
2661
|
-
}
|
|
2662
|
-
this.markWoken(id, d.messages);
|
|
2663
|
-
this.daemonWaking.add(id);
|
|
2664
|
-
const text = formatContinuation(d.messages, d.orchestrator, d.remaining);
|
|
2665
|
-
const session = this.view(this.requireSession(id));
|
|
2666
|
-
(async () => {
|
|
2667
|
-
let outcome;
|
|
2668
|
-
try {
|
|
2669
|
-
outcome = await wake({
|
|
2670
|
-
session,
|
|
2671
|
-
text,
|
|
2672
|
-
messages: d.messages,
|
|
2673
|
-
...row.nativeId !== void 0 ? { nativeId: row.nativeId } : {}
|
|
2674
|
-
});
|
|
2675
|
-
} catch (e) {
|
|
2676
|
-
this.log.error(`${row.cli} waker failed`, e);
|
|
2677
|
-
outcome = "failed";
|
|
2678
|
-
}
|
|
2679
|
-
this.daemonWaking.delete(id);
|
|
2680
|
-
if (outcome === "queued" || outcome === "unknown" || this.stopping) {
|
|
2681
|
-
this.wakeRetry.delete(id);
|
|
2682
|
-
return;
|
|
2683
|
-
}
|
|
2684
|
-
if (outcome === "unsupported") {
|
|
2685
|
-
this.wakeRetry.delete(id);
|
|
2686
|
-
this.wakersOff.add(row.id);
|
|
2687
|
-
this.relay?.sessionsChanged();
|
|
2688
|
-
}
|
|
2689
|
-
if (this.store.getSession(id)?.status === "offline") {
|
|
2690
|
-
this.wakeRetry.delete(id);
|
|
2691
|
-
return;
|
|
2692
|
-
}
|
|
2693
|
-
this.requeueFor(id, d.messages.map((m) => m.id));
|
|
2694
|
-
if (outcome === "failed") this.scheduleWakeRetry(id);
|
|
2695
|
-
})();
|
|
2696
|
-
}
|
|
2697
|
-
/** Try a daemon wake of \`id\` again later, each time waiting twice as long, up to a cap. */
|
|
2698
|
-
scheduleWakeRetry(id) {
|
|
2699
|
-
const delayMs = Math.min((this.wakeRetry.get(id)?.delayMs ?? 0) * 2 || WAKE_RETRY_MS, WAKE_RETRY_MAX_MS);
|
|
2700
|
-
this.wakeRetry.set(id, {
|
|
2701
|
-
atMs: this.now().getTime() + delayMs,
|
|
2702
|
-
delayMs
|
|
2703
|
-
});
|
|
2704
|
-
}
|
|
2705
|
-
/** Run the daemon wakes whose retry is due. Called by the sweep. */
|
|
2706
|
-
retryDaemonWakes(nowMs) {
|
|
2707
|
-
for (const [id, r] of [...this.wakeRetry]) if (r.atMs <= nowMs) this.daemonWake(id);
|
|
2708
|
-
}
|
|
2709
|
-
markWoken(id, messages) {
|
|
2710
|
-
this.woken.set(id, new Set(messages.map((m) => m.id)));
|
|
2711
|
-
this.wokenAt.set(id, this.now().getTime());
|
|
2712
|
-
}
|
|
2713
|
-
/**
|
|
2714
|
-
* Messages a wake handed over that no turn took up: the CLI accepted them but the turn never
|
|
2715
|
-
* started (Codex keeps queued input while a turn is interrupted). Counted as unread so status
|
|
2716
|
-
* shows them. A turn start or end clears \`woken\`.
|
|
2717
|
-
*/
|
|
2718
|
-
stalledWoken(id) {
|
|
2719
|
-
const at = this.wokenAt.get(id);
|
|
2720
|
-
if (at === void 0 || this.now().getTime() - at < WOKEN_STALL_MS) return 0;
|
|
2721
|
-
return this.woken.get(id)?.size ?? 0;
|
|
2722
|
-
}
|
|
2723
|
-
/**
|
|
2724
|
-
* Delivered messages go back to queued. When they are from the last wake and that wake made the
|
|
2725
|
-
* session busy, the wake never became a turn: the session is idle again and the wake does not
|
|
2726
|
-
* count against the limit.
|
|
2727
|
-
*/
|
|
2728
|
-
requeue(p) {
|
|
2729
|
-
this.requireSession(p.sessionId);
|
|
2730
|
-
return this.requeueFor(p.sessionId, p.ids);
|
|
2731
|
-
}
|
|
2732
|
-
requeueFor(id, ids) {
|
|
2733
|
-
const woken = this.woken.get(id);
|
|
2734
|
-
const fromWake = woken !== void 0 && ids.some((m) => woken.has(m));
|
|
2735
|
-
const res = this.store.tx(() => {
|
|
2736
|
-
const r = requeueEntries(this.store.entries(id, { ids: [...ids] }), ids);
|
|
2737
|
-
for (const e of r.changed) this.store.saveEntry(id, e);
|
|
2738
|
-
const row = this.requireSession(id);
|
|
2739
|
-
const idle = fromWake && r.changed.length > 0 && row.status === "busy";
|
|
2740
|
-
if (idle) this.store.updateSession(id, {
|
|
2741
|
-
status: "idle",
|
|
2742
|
-
turnHops: 0,
|
|
2743
|
-
autoRuns: row.autoRuns.slice(0, -1)
|
|
2744
|
-
});
|
|
2745
|
-
return {
|
|
2746
|
-
requeued: r.changed.length,
|
|
2747
|
-
idle
|
|
2748
|
-
};
|
|
2749
|
-
});
|
|
2750
|
-
if (fromWake) this.woken.delete(id);
|
|
2751
|
-
if (res.idle) this.emitSession(id, "updated");
|
|
2752
|
-
return { requeued: res.requeued };
|
|
2753
|
-
}
|
|
2754
|
-
/**
|
|
2755
|
-
* The user typed a prompt: the session is busy, and messages it sends start a new chain (0 hops).
|
|
2756
|
-
*/
|
|
2757
|
-
turnStart(sessionId) {
|
|
2758
|
-
const row = this.requireOnline(sessionId);
|
|
2759
|
-
const fromWake = this.woken.has(sessionId) && row.status === "busy";
|
|
2760
|
-
this.woken.delete(sessionId);
|
|
2761
|
-
this.store.updateSession(sessionId, fromWake ? { status: "busy" } : {
|
|
2762
|
-
status: "busy",
|
|
2763
|
-
turnHops: 0
|
|
2764
|
-
});
|
|
2765
|
-
this.emitSession(sessionId, "updated");
|
|
2766
|
-
return { session: this.view(this.requireSession(sessionId)) };
|
|
2767
|
-
}
|
|
2768
|
-
/**
|
|
2769
|
-
* Hand the session its waiting messages to continue with, if the wake limit allows it.
|
|
2770
|
-
* On a hand-over the session is busy and its turn carries the hops. With `endOfTurn`, nothing
|
|
2771
|
-
* handed over means the session is now idle. One transaction.
|
|
2772
|
-
*/
|
|
2773
|
-
continueWith(row, allow, endOfTurn, maxBytes = RESPONSE_BUDGET_BYTES, maxChars) {
|
|
2774
|
-
const nowMs = this.now().getTime();
|
|
2775
|
-
const at = this.iso();
|
|
2776
|
-
const orchestrator = this.orchestratorNow();
|
|
2777
|
-
const res = this.store.tx(() => {
|
|
2778
|
-
const queued = this.store.entries(row.id, { states: ["queued"] });
|
|
2779
|
-
const candidates = allow ? autoCandidates(queued, row.id) : [];
|
|
2780
|
-
const decision = decideAutoContinue({ runs: row.autoRuns }, candidates, nowMs, this.autoLimits);
|
|
2781
|
-
if (decision.continue) {
|
|
2782
|
-
const fit = takeWithinBytes(candidates.slice(0, 20), maxBytes);
|
|
2783
|
-
const { taken, preview } = maxChars === void 0 ? { taken: fit } : takeWithinChars(fit, maxChars, (ms, cut) => formatContinuation(ms, orchestrator, queued.length - (cut ? 0 : ms.length)));
|
|
2784
|
-
const updated = markDelivered(taken, taken.map((e) => e.message.id), at);
|
|
2785
|
-
for (const e of updated) this.store.saveEntry(row.id, e);
|
|
2786
|
-
this.store.updateSession(row.id, {
|
|
2787
|
-
status: "busy",
|
|
2788
|
-
autoRuns: decision.runs,
|
|
2789
|
-
turnHops: turnHops(preview ? fit.slice(0, 1) : taken)
|
|
2790
|
-
});
|
|
2791
|
-
if (preview) return {
|
|
2792
|
-
messages: [preview],
|
|
2793
|
-
remaining: queued.length
|
|
2794
|
-
};
|
|
2795
|
-
return {
|
|
2796
|
-
messages: updated.map((e) => e.message),
|
|
2797
|
-
remaining: queued.length - taken.length
|
|
2798
|
-
};
|
|
2799
|
-
}
|
|
2800
|
-
if (endOfTurn) this.store.updateSession(row.id, {
|
|
2801
|
-
status: "idle",
|
|
2802
|
-
turnHops: 0
|
|
2803
|
-
});
|
|
2804
|
-
return {
|
|
2805
|
-
messages: [],
|
|
2806
|
-
remaining: queued.length
|
|
2807
|
-
};
|
|
2808
|
-
});
|
|
2809
|
-
if (res.messages.length > 0 ? row.status !== "busy" : endOfTurn && row.status !== "idle") this.emitSession(row.id, "updated");
|
|
2810
|
-
return {
|
|
2811
|
-
...res,
|
|
2812
|
-
orchestrator
|
|
2813
|
-
};
|
|
2814
|
-
}
|
|
2815
|
-
turnEnd(p) {
|
|
2816
|
-
const row = this.requireOnline(p.sessionId);
|
|
2817
|
-
this.woken.delete(p.sessionId);
|
|
2818
|
-
if (row.status === "waiting_on_question") return this.continueWith(row, false, false);
|
|
2819
|
-
return this.continueWith(row, p.allowContinue, true, RESPONSE_BUDGET_BYTES, p.maxChars);
|
|
2820
|
-
}
|
|
2821
|
-
/**
|
|
2822
|
-
* An idle-wake listener asks for work. The newest listener of a session wins: an older one gets
|
|
2823
|
-
* `superseded` and stops. A busy session is not woken; its messages wait for the end of the turn.
|
|
2824
|
-
*/
|
|
2825
|
-
turnWake(conn, p) {
|
|
2826
|
-
const row = this.requireOnline(p.sessionId);
|
|
2827
|
-
const known = this.listeners.get(row.id);
|
|
2828
|
-
if (known?.retired.includes(p.listenerId)) return {
|
|
2829
|
-
messages: [],
|
|
2830
|
-
remaining: this.store.unreadCount(row.id),
|
|
2831
|
-
orchestrator: this.orchestratorNow(),
|
|
2832
|
-
superseded: true
|
|
2833
|
-
};
|
|
2834
|
-
const wasConnected = this.listenerConnected(row.id);
|
|
2835
|
-
if (known?.current !== p.listenerId) {
|
|
2836
|
-
const retired = known ? [...known.retired, known.current].slice(-64) : [];
|
|
2837
|
-
this.listeners.set(row.id, {
|
|
2838
|
-
current: p.listenerId,
|
|
2839
|
-
retired,
|
|
2840
|
-
conn
|
|
2841
|
-
});
|
|
2842
|
-
if (known) this.emit({
|
|
2843
|
-
event: "session.updated",
|
|
2844
|
-
data: {
|
|
2845
|
-
session: this.view(row),
|
|
2846
|
-
change: "updated"
|
|
2847
|
-
}
|
|
2848
|
-
}, row.id);
|
|
2849
|
-
} else known.conn = conn;
|
|
2850
|
-
if (!wasConnected) this.relay?.sessionsChanged();
|
|
2851
|
-
const d = this.continueWith(row, row.status === "idle", false, RESPONSE_BUDGET_BYTES, p.maxChars);
|
|
2852
|
-
if (d.messages.length > 0) this.markWoken(row.id, d.messages);
|
|
2853
|
-
return {
|
|
2854
|
-
...d,
|
|
2855
|
-
superseded: false
|
|
2856
|
-
};
|
|
2857
|
-
}
|
|
2858
|
-
inbox(p) {
|
|
2859
|
-
this.requireSession(p.sessionId);
|
|
2860
|
-
return this.readInboxOf(p.sessionId, p.unreadOnly, p.limit);
|
|
2861
|
-
}
|
|
2862
|
-
/** A mailbox's messages, oldest first, marked read. */
|
|
2863
|
-
readInboxOf(id, unreadOnly, limit) {
|
|
2864
|
-
const at = this.iso();
|
|
2865
|
-
return this.store.tx(() => {
|
|
2866
|
-
const entries = this.store.entries(id, unreadOnly ? { states: ["queued"] } : {});
|
|
2867
|
-
const res = readInbox(entries, {
|
|
2868
|
-
unreadOnly,
|
|
2869
|
-
limit,
|
|
2870
|
-
maxBytes: RESPONSE_BUDGET_BYTES
|
|
2871
|
-
}, at);
|
|
2872
|
-
const changed = new Set(res.returned.map((e) => e.message.id));
|
|
2873
|
-
for (const e of res.entries) if (changed.has(e.message.id)) this.store.saveEntry(id, e);
|
|
2874
|
-
return {
|
|
2875
|
-
messages: res.returned.map((e) => e.message),
|
|
2876
|
-
unreadCount: res.unreadCount
|
|
2877
|
-
};
|
|
2878
|
-
});
|
|
2879
|
-
}
|
|
2880
|
-
deliver(p) {
|
|
2881
|
-
this.requireSession(p.sessionId);
|
|
2882
|
-
const at = this.iso();
|
|
2883
|
-
return this.store.tx(() => {
|
|
2884
|
-
const pending = pendingForInjection(this.store.entries(p.sessionId, { states: ["queued"] }));
|
|
2885
|
-
const fit = takeWithinBytes(pending.slice(0, p.limit), RESPONSE_BUDGET_BYTES);
|
|
2886
|
-
const { taken, preview } = p.maxChars === void 0 ? { taken: fit } : takeWithinChars(fit, p.maxChars, (ms) => formatHookContext(ms));
|
|
2887
|
-
const updated = markDelivered(taken, taken.map((e) => e.message.id), at);
|
|
2888
|
-
for (const e of updated) this.store.saveEntry(p.sessionId, e);
|
|
2889
|
-
if (preview) return {
|
|
2890
|
-
messages: [preview],
|
|
2891
|
-
remaining: pending.length
|
|
2892
|
-
};
|
|
2893
|
-
return {
|
|
2894
|
-
messages: updated.map((e) => e.message),
|
|
2895
|
-
remaining: pending.length - taken.length
|
|
2896
|
-
};
|
|
2897
|
-
});
|
|
2898
|
-
}
|
|
2899
|
-
ack(p) {
|
|
2900
|
-
this.requireSession(p.sessionId);
|
|
2901
|
-
return this.ackFor(p.sessionId, p.ids);
|
|
2902
|
-
}
|
|
2903
|
-
ackFor(id, ids) {
|
|
2904
|
-
const at = this.iso();
|
|
2905
|
-
return this.store.tx(() => {
|
|
2906
|
-
const entries = this.store.entries(id, { ids });
|
|
2907
|
-
const res = ackEntries(entries, ids, at);
|
|
2908
|
-
for (const e of res.entries) this.store.saveEntry(id, e);
|
|
2909
|
-
return { acked: res.acked };
|
|
2910
|
-
});
|
|
2911
|
-
}
|
|
2912
|
-
subscribe(conn, p) {
|
|
2913
|
-
if (p.sessionId === void 0) {
|
|
2914
|
-
if (conn.client !== "cli") throw new ConvenoError(RpcErrorCode.Unauthorized, "Pass sessionId to subscribe. Only the conveno command and app can subscribe to every event.");
|
|
2915
|
-
} else this.requireSession(p.sessionId);
|
|
2916
|
-
const topics = p.topics ?? [...EVENT_NAMES];
|
|
2917
|
-
conn.sub = {
|
|
2918
|
-
...p.sessionId !== void 0 ? { sessionId: p.sessionId } : {},
|
|
2919
|
-
topics: new Set(topics)
|
|
2920
|
-
};
|
|
2921
|
-
return { subscribed: topics };
|
|
2922
|
-
}
|
|
2923
|
-
relayCall(req) {
|
|
2924
|
-
const relay = this.relay;
|
|
2925
|
-
if (!relay) throw new ConvenoError(RpcErrorCode.MethodNotFound, "The relay is disabled in this daemon.");
|
|
2926
|
-
switch (req.method) {
|
|
2927
|
-
case "relay.status": return relay.status();
|
|
2928
|
-
case "devices.list": return relay.devices();
|
|
2929
|
-
case "devices.pair": return relay.pairStart(req.params);
|
|
2930
|
-
case "devices.pairStatus": return relay.pairStatus(req.params);
|
|
2931
|
-
case "devices.pairConfirm": return relay.pairConfirm(req.params);
|
|
2932
|
-
case "devices.revoke": return relay.revoke(req.params);
|
|
2933
|
-
case "devices.rename": return relay.rename(req.params);
|
|
2934
|
-
case "devices.accept": return relay.accept(req.params);
|
|
2935
|
-
case "devices.reset": return relay.reset();
|
|
2936
|
-
default: throw new ConvenoError(RpcErrorCode.MethodNotFound, `Method not found: ${req.method}`);
|
|
2937
|
-
}
|
|
2938
|
-
}
|
|
2939
|
-
sendToRemote(message, target, hops) {
|
|
2940
|
-
this.relay.sendRemote(target, message, hops);
|
|
2941
|
-
return {
|
|
2942
|
-
message,
|
|
2943
|
-
delivery: target.deliveryTier,
|
|
2944
|
-
deliveredTo: {
|
|
2945
|
-
id: target.id,
|
|
2946
|
-
name: target.name
|
|
2947
|
-
}
|
|
2948
|
-
};
|
|
2949
|
-
}
|
|
2950
|
-
/** The daemon side of the relay: local sessions out, remote messages in. */
|
|
2951
|
-
relayHost() {
|
|
2952
|
-
return {
|
|
2953
|
-
log: this.log,
|
|
2954
|
-
localSessions: () => this.store.allSessions().filter((r) => r.status !== "offline").map((r) => {
|
|
2955
|
-
const { nativeId: _n, ...s } = this.view(r);
|
|
2956
|
-
return s;
|
|
2957
|
-
}),
|
|
2958
|
-
deliverLocal: (m, to, hops = 0) => {
|
|
2959
|
-
if (m.kind === "system") return "not_allowed";
|
|
2960
|
-
const row = this.store.getSession(to);
|
|
2961
|
-
if (!row) return "session_gone";
|
|
2962
|
-
if (row.status === "offline") return "session_offline";
|
|
2963
|
-
if (this.store.hasMessage(m.id)) return void 0;
|
|
2964
|
-
if (this.store.unreadCount(row.id) >= 1e3) return "mailbox_full";
|
|
2965
|
-
this.store.insertMessage(m, row.id, this.iso(), hops);
|
|
2966
|
-
this.emitMessage(m, row.id);
|
|
2967
|
-
},
|
|
2968
|
-
notify: (to, event, detail) => {
|
|
2969
|
-
if (!this.store.getSession(to)) return;
|
|
2970
|
-
const m = {
|
|
2971
|
-
id: newMessageId(),
|
|
2972
|
-
from: DAEMON_SENDER_ID,
|
|
2973
|
-
to,
|
|
2974
|
-
kind: "system",
|
|
2975
|
-
body: {
|
|
2976
|
-
event,
|
|
2977
|
-
detail: detail.slice(0, 2e3)
|
|
2978
|
-
},
|
|
2979
|
-
urgent: false,
|
|
2980
|
-
createdAt: this.iso()
|
|
2981
|
-
};
|
|
2982
|
-
this.store.insertMessage(m, to, this.iso());
|
|
2983
|
-
this.emitMessage(m, to);
|
|
2984
|
-
}
|
|
2985
|
-
};
|
|
2986
|
-
}
|
|
2987
|
-
/** Remove every offline session at once. The daemon does this when it starts. */
|
|
2988
|
-
removeAllOffline() {
|
|
2989
|
-
this.removeOffline(0);
|
|
2990
|
-
}
|
|
2991
|
-
sweep() {
|
|
2992
|
-
const nowMs = this.now().getTime();
|
|
2993
|
-
this.removeOffline(OFFLINE_GRACE_MS);
|
|
2994
|
-
this.retryDaemonWakes(nowMs);
|
|
2995
|
-
let online = 0;
|
|
2996
|
-
const rows = this.store.allSessions();
|
|
2997
|
-
for (const row of rows) {
|
|
2998
|
-
if (row.status === "offline") continue;
|
|
2999
|
-
const lastSeenMs = Math.max(Date.parse(row.lastSeenAt), this.startedMs);
|
|
3000
|
-
const verdict = evaluateLiveness({
|
|
3001
|
-
lastSeenMs,
|
|
3002
|
-
hostPid: row.hostPid
|
|
3003
|
-
}, nowMs, this.isAlive);
|
|
3004
|
-
if (statusAfterLiveness(row.status, verdict) === "offline") this.depart(row.id, "offline");
|
|
3005
|
-
else online++;
|
|
3006
|
-
}
|
|
3007
|
-
if (online > 0) this.idleSince = nowMs;
|
|
3008
|
-
else if (nowMs - this.idleSince >= this.idleExitMs) this.requestIdleExit();
|
|
3009
|
-
}
|
|
3010
|
-
};
|
|
3011
|
-
/** Do two directory paths name the same place, ignoring trailing separators (and case on Windows)? */
|
|
3012
|
-
function samePath(a, b, platform) {
|
|
3013
|
-
const norm = (p) => {
|
|
3014
|
-
const s = p.replace(/[\\/]+$/, "");
|
|
3015
|
-
return platform === "win32" ? s.replace(/\\/g, "/").toLowerCase() : s;
|
|
3016
|
-
};
|
|
3017
|
-
return norm(a) === norm(b);
|
|
3018
|
-
}
|
|
3019
|
-
const unauthorizedMessage = "Finish the handshake first: call hello, then auth. Both use the token in daemon.token in the Conveno data directory.";
|
|
3020
|
-
/** Start the relay client. A broken relay state is logged and leaves the daemon local-only. */
|
|
3021
|
-
function startRelay(daemon, opts, relayOpts) {
|
|
3022
|
-
try {
|
|
3023
|
-
const hub = new RelayHub({
|
|
3024
|
-
...relayOpts,
|
|
3025
|
-
dataDir: opts.dataDir,
|
|
3026
|
-
host: daemon.relayHost()
|
|
3027
|
-
});
|
|
3028
|
-
hub.start();
|
|
3029
|
-
daemon.relay = hub;
|
|
3030
|
-
} catch (e) {
|
|
3031
|
-
daemon.relayHost().log.error("relay: could not start; the daemon runs local-only", e);
|
|
3032
|
-
}
|
|
3033
|
-
}
|
|
3034
|
-
/** Start convenod: take the lock, open the database, listen on the socket. */
|
|
3035
|
-
async function startDaemon(opts) {
|
|
3036
|
-
const platform = process.platform;
|
|
3037
|
-
const paths = dataPaths(platform, opts.dataDir);
|
|
3038
|
-
const socketPath = opts.socketPath ?? defaultSocketPath(platform, process.env, homedir());
|
|
3039
|
-
if (isSocketPathTooLong(socketPath, platform)) throw new Error(socketPathTooLongMessage(socketPath, platform));
|
|
3040
|
-
const now = opts.now ?? (() => /* @__PURE__ */ new Date());
|
|
3041
|
-
const isAlive = opts.isAlive ?? defaultIsAlive;
|
|
3042
|
-
const walker = opts.processIo === void 0 && platform === "win32" ? createWmiWalker({ scriptPath: join(opts.dataDir, "wmi-walk.js") }) : void 0;
|
|
3043
|
-
const processIo = opts.processIo ?? (walker ? {
|
|
3044
|
-
...defaultProcessIo,
|
|
3045
|
-
walk: walker.walk
|
|
3046
|
-
} : defaultProcessIo);
|
|
3047
|
-
ensureDir(opts.dataDir);
|
|
3048
|
-
const releaseLock = await acquireLock(paths.lock, socketPath);
|
|
3049
|
-
let store;
|
|
3050
|
-
let server;
|
|
3051
|
-
try {
|
|
3052
|
-
const token = loadOrCreateToken(paths.token);
|
|
3053
|
-
store = new Store(paths.database);
|
|
3054
|
-
if (platform !== "win32" && !socketPath.startsWith("\\\\")) ensureDir(dirname(socketPath));
|
|
3055
|
-
await clearStaleSocket(socketPath);
|
|
3056
|
-
let closing;
|
|
3057
|
-
let timer;
|
|
3058
|
-
const daemonLog = createDaemonLog(paths.daemonLog, { now });
|
|
3059
|
-
const daemon = new Daemon(store, token, now, isAlive, opts.idleExitMs ?? 6e5, () => {
|
|
3060
|
-
close().then(() => opts.onIdleExit?.());
|
|
3061
|
-
}, () => {
|
|
3062
|
-
close().then(() => opts.onShutdown?.());
|
|
3063
|
-
}, daemonLog, opts.authTimeoutMs ?? 5e3, opts.autoLimits ?? autoLimitsFromEnv(process.env), processIo, opts.platform, opts.wakers ?? {}, paths.settings);
|
|
3064
|
-
daemon.removeAllOffline();
|
|
3065
|
-
const srv = createServer((socket) => daemon.attach(socket));
|
|
3066
|
-
server = srv;
|
|
3067
|
-
await new Promise((resolve, reject) => {
|
|
3068
|
-
srv.once("error", (e) => reject(e.code === "EADDRINUSE" ? new DaemonAlreadyRunningError(`socket ${socketPath}`) : e));
|
|
3069
|
-
srv.listen(socketPath, () => resolve());
|
|
3070
|
-
});
|
|
3071
|
-
if (platform !== "win32" && !socketPath.startsWith("\\\\")) chmodSync(socketPath, 384);
|
|
3072
|
-
if (opts.relay !== false) startRelay(daemon, opts, opts.relay ?? {});
|
|
3073
|
-
timer = setInterval(() => daemon.sweep(), opts.sweepIntervalMs ?? 15e3);
|
|
3074
|
-
timer.unref();
|
|
3075
|
-
const liveStore = store;
|
|
3076
|
-
function close() {
|
|
3077
|
-
closing ??= (async () => {
|
|
3078
|
-
if (timer) clearInterval(timer);
|
|
3079
|
-
daemon.stopping = true;
|
|
3080
|
-
walker?.close();
|
|
3081
|
-
daemon.relay?.stop();
|
|
3082
|
-
const stopped = new Promise((resolve) => srv.close(() => resolve()));
|
|
3083
|
-
for (const c of daemon.conns) c.socket.destroy();
|
|
3084
|
-
await stopped;
|
|
3085
|
-
liveStore.close();
|
|
3086
|
-
if (platform !== "win32" && !socketPath.startsWith("\\\\")) rmSync(socketPath, { force: true });
|
|
3087
|
-
releaseLock();
|
|
3088
|
-
})();
|
|
3089
|
-
return closing;
|
|
3090
|
-
}
|
|
3091
|
-
return {
|
|
3092
|
-
socketPath,
|
|
3093
|
-
close,
|
|
3094
|
-
sweep: () => daemon.sweep(),
|
|
3095
|
-
testRelay: {
|
|
3096
|
-
host: () => daemon.relayHost(),
|
|
3097
|
-
set: (relay) => {
|
|
3098
|
-
daemon.relay = relay && {
|
|
3099
|
-
sessionsChanged: () => {},
|
|
3100
|
-
...relay
|
|
3101
|
-
};
|
|
3102
|
-
}
|
|
3103
|
-
}
|
|
3104
|
-
};
|
|
3105
|
-
} catch (e) {
|
|
3106
|
-
server?.close();
|
|
3107
|
-
store?.close();
|
|
3108
|
-
releaseLock();
|
|
3109
|
-
throw e;
|
|
3110
|
-
}
|
|
3111
|
-
}
|
|
3112
|
-
// ../daemon/src/bin.ts
|
|
3113
|
-
async function main() {
|
|
3114
|
-
const handle = await startDaemon({
|
|
3115
|
-
dataDir: dataDir(process.platform, process.env, homedir()),
|
|
3116
|
-
wakers: { codex: codexAdapter.daemonWake },
|
|
3117
|
-
onIdleExit: () => {
|
|
3118
|
-
process.stderr.write("convenod: no sessions for a while, exiting.\n");
|
|
3119
|
-
process.exit(0);
|
|
3120
|
-
},
|
|
3121
|
-
onShutdown: () => process.exit(0)
|
|
3122
|
-
});
|
|
3123
|
-
process.stderr.write(`convenod: listening on ${handle.socketPath}\n`);
|
|
3124
|
-
let stopping = false;
|
|
3125
|
-
const stop = () => {
|
|
3126
|
-
if (stopping) return;
|
|
3127
|
-
stopping = true;
|
|
3128
|
-
handle.close().then(() => process.exit(0));
|
|
3129
|
-
};
|
|
3130
|
-
process.on("SIGINT", stop);
|
|
3131
|
-
process.on("SIGTERM", stop);
|
|
3132
|
-
}
|
|
3133
|
-
main().catch((e) => {
|
|
3134
|
-
if (e instanceof DaemonAlreadyRunningError) {
|
|
3135
|
-
process.stderr.write(`${e.message}\n`);
|
|
3136
|
-
process.exit(0);
|
|
3137
|
-
}
|
|
3138
|
-
process.stderr.write(`convenod failed to start: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
3139
|
-
process.exit(1);
|
|
3140
|
-
});
|
|
2
|
+
import { t as codexAdapter } from "./dist-DTMnNySx.js";
|
|
3
|
+
import { n as runConvenod } from "./dist-BNhTPp5p.js";
|
|
4
|
+
// src/daemon-entry.ts
|
|
5
|
+
runConvenod({ wakers: { codex: codexAdapter.daemonWake } });
|
|
3141
6
|
export {};
|