@conveno/cli 0.1.1 → 0.2.0-rc.10
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 +34 -16
- package/dist/acp-TSjX4JP9.js +82 -0
- package/dist/agy-relay-D-OWo85B.js +137 -0
- package/dist/args-B3Cj2Ie4.js +361 -0
- package/dist/bin.js +24 -4383
- package/dist/ctx-tYftvhz_.js +17 -0
- package/dist/daemon.js +2239 -144
- package/dist/daemonError-C05GqdhQ.js +66 -0
- package/dist/dist-BLfduOoT.js +624 -0
- package/dist/dist-BRjg9CLd.js +731 -0
- package/dist/dist-CVdpCNJo.js +793 -0
- package/dist/dist-D_O_JLLq.js +473 -0
- package/dist/dist-DaIpdMke.js +667 -0
- package/dist/dist-MK-cK1JY.js +969 -0
- package/dist/dist-STNJjbNH.js +10084 -0
- package/dist/dist-VOS92iqO.js +645 -0
- package/dist/fmt-C2SsP5Y0.js +96 -0
- package/dist/hook-CDF1A8AY.js +114 -0
- package/dist/hook-entry-C0bPssOy.js +1 -0
- package/dist/hook-entry-CQQU-e_t.js +2500 -0
- package/dist/main-BhKTG0AI.js +650 -0
- package/dist/pick-DLp6w_-z.js +9 -0
- package/dist/run-eCXO1SyO.js +5609 -0
- package/dist/runtime-BGPlr8CI.js +772 -0
- package/dist/toml-patch-DGzVRdd1.js +6756 -0
- package/dist/uninstall-DQlzpv5R.js +2034 -0
- package/dist/watch-D0KIPowJ.js +185 -0
- package/package.json +27 -11
- package/dist/dist-WPVVRVUh.js +0 -1507
package/dist/daemon.js
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { homedir } from "node:os";
|
|
3
|
-
import {
|
|
2
|
+
import { homedir, hostname, userInfo } from "node:os";
|
|
3
|
+
import { t as codexAdapter } from "./dist-MK-cK1JY.js";
|
|
4
|
+
import { An as newSessionId, C as bindAccountDevice, Ct as proofsMatch, D as clientProof, Dn as makeResult, E as clearOrchestrator, En as makeEventNotification, Et as readAncestry, F as dataPaths, Fn as socketPathTooLongMessage, I as decideAutoContinue, J as formatHookContext, L as defaultProcessIo, M as currentAccessToken, Mn as parseRelayFrame, N as daemonProof, Nn as safeParse, On as newDeviceId, Ot as readInbox, P as dataDir, Pn as sanitizeLine, Pt as requeueEntries, Qt as turnHops, R as detectRepo, Rt as resolveRecipient, S as baseName, Sn as encodeFrame, Tn as makeError, Tt as readAccountTokens, U as evaluateLiveness, V as effectiveHolder, X as generateSessionName, Xt as takeWithinChars, Yt as takeWithinBytes, Z as holderAfterDeparture, Zt as tooManyUnreadMessage, b as autoCandidates, bn as createLineDecoder, cn as EVENT_NAMES, ct as markDelivered, dn as Message, gn as RpcErrorCode, gt as pendingForInjection, hn as RelayPayload, j as createWmiWalker, jn as parseIpcRequest, kn as newMessageId, kt as readSettings, l as RESPONSE_BUDGET_BYTES, mn as PROTOCOL_VERSION, n as AccountError, nt as jwtClaim, p as ackEntries, pn as OWNER_SESSION_ID, q as formatContinuation, qt as statusAfterLiveness, r as ConvenoError, sn as DeviceId, tn as validateRename, tt as isOnline, ut as newAuthNonce, w as claimOrchestrator, wn as isSocketPathTooLong, x as autoLimitsFromEnv, xn as defaultSocketPath, xt as planSpawn, yn as SessionId } from "./dist-STNJjbNH.js";
|
|
4
5
|
import { randomBytes } from "node:crypto";
|
|
5
6
|
import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
6
7
|
import { connect, createServer } from "node:net";
|
|
7
|
-
import { dirname } from "node:path";
|
|
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-CVdpCNJo.js";
|
|
10
|
+
import { execFileSync } from "node:child_process";
|
|
8
11
|
import { DatabaseSync } from "node:sqlite";
|
|
9
12
|
// ../daemon/src/lifecycle.ts
|
|
10
13
|
/** Thrown when another Conveno daemon already owns the lock file or answers on the socket. */
|
|
@@ -119,39 +122,1473 @@ function ensureDir(dir) {
|
|
|
119
122
|
}
|
|
120
123
|
const describeError = (e) => e instanceof Error ? e.stack ?? `${e.name}: ${e.message}` : String(e);
|
|
121
124
|
/**
|
|
122
|
-
* The daemon's own log, for errors it did not expect
|
|
123
|
-
*
|
|
124
|
-
* starts. Request parameters are never logged,
|
|
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.
|
|
125
129
|
*/
|
|
126
130
|
function createDaemonLog(path, opts = {}) {
|
|
127
131
|
const maxBytes = opts.maxBytes ?? 1048576;
|
|
128
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
|
+
};
|
|
129
151
|
return {
|
|
130
152
|
path,
|
|
131
153
|
error(what, e) {
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
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;
|
|
138
765
|
try {
|
|
139
|
-
|
|
140
|
-
} catch {
|
|
141
|
-
|
|
142
|
-
rmSync(`${path}.1`, { force: true });
|
|
143
|
-
renameSync(path, `${path}.1`);
|
|
766
|
+
await this.evaluateOnce();
|
|
767
|
+
} catch (e) {
|
|
768
|
+
this.o.host.log.error("relay: state check failed", e);
|
|
144
769
|
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
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);
|
|
148
1381
|
}
|
|
149
|
-
|
|
150
|
-
|
|
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
|
+
};
|
|
151
1587
|
// ../daemon/src/store.ts
|
|
152
|
-
const MIGRATIONS = [
|
|
153
|
-
|
|
154
|
-
|
|
1588
|
+
const MIGRATIONS = [
|
|
1589
|
+
{
|
|
1590
|
+
name: "001_initial",
|
|
1591
|
+
sql: `
|
|
155
1592
|
CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
156
1593
|
CREATE TABLE sessions (
|
|
157
1594
|
id TEXT PRIMARY KEY,
|
|
@@ -194,13 +1631,68 @@ const MIGRATIONS = [{
|
|
|
194
1631
|
);
|
|
195
1632
|
INSERT INTO orchestrator (slot, session_id) VALUES (1, NULL);
|
|
196
1633
|
`
|
|
197
|
-
},
|
|
198
|
-
|
|
199
|
-
|
|
1634
|
+
},
|
|
1635
|
+
{
|
|
1636
|
+
name: "002_host_pids",
|
|
1637
|
+
sql: `
|
|
200
1638
|
ALTER TABLE sessions ADD COLUMN host_pids TEXT;
|
|
201
1639
|
UPDATE sessions SET host_pids = '[' || host_pid || ']' WHERE host_pid IS NOT NULL;
|
|
202
1640
|
`
|
|
203
|
-
}
|
|
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
|
+
];
|
|
204
1696
|
const str = (v) => typeof v === "string" ? v : void 0;
|
|
205
1697
|
const num = (v) => typeof v === "number" ? v : void 0;
|
|
206
1698
|
function pidList(v) {
|
|
@@ -214,6 +1706,15 @@ function pidList(v) {
|
|
|
214
1706
|
return;
|
|
215
1707
|
}
|
|
216
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
|
+
}
|
|
217
1718
|
function toSessionRow(r) {
|
|
218
1719
|
const row = {
|
|
219
1720
|
id: r.id,
|
|
@@ -223,7 +1724,10 @@ function toSessionRow(r) {
|
|
|
223
1724
|
cwd: r.cwd,
|
|
224
1725
|
status: r.status,
|
|
225
1726
|
deliveryTier: r.delivery_tier,
|
|
1727
|
+
spawned: r.spawned === 1,
|
|
226
1728
|
spawnDepth: r.spawn_depth,
|
|
1729
|
+
autoRuns: isoList(r.auto_runs),
|
|
1730
|
+
turnHops: num(r.turn_hops) ?? 0,
|
|
227
1731
|
startedAt: r.started_at,
|
|
228
1732
|
lastSeenAt: r.last_seen_at
|
|
229
1733
|
};
|
|
@@ -243,10 +1747,12 @@ function toSessionRow(r) {
|
|
|
243
1747
|
if (statusText !== void 0) row.statusText = statusText;
|
|
244
1748
|
const spawnedBy = str(r.spawned_by);
|
|
245
1749
|
if (spawnedBy !== void 0) row.spawnedBy = spawnedBy;
|
|
1750
|
+
const nativeId = str(r.native_id);
|
|
1751
|
+
if (nativeId !== void 0) row.nativeId = nativeId;
|
|
246
1752
|
return row;
|
|
247
1753
|
}
|
|
248
1754
|
/** Wire-format session for a stored row. */
|
|
249
|
-
function toSession(row, isOrchestrator) {
|
|
1755
|
+
function toSession(row, isOrchestrator, unreadCount) {
|
|
250
1756
|
const s = {
|
|
251
1757
|
id: row.id,
|
|
252
1758
|
name: row.name,
|
|
@@ -256,10 +1762,12 @@ function toSession(row, isOrchestrator) {
|
|
|
256
1762
|
status: row.status,
|
|
257
1763
|
isOrchestrator,
|
|
258
1764
|
deliveryTier: row.deliveryTier,
|
|
1765
|
+
spawned: row.spawned,
|
|
259
1766
|
spawnDepth: row.spawnDepth,
|
|
260
1767
|
startedAt: row.startedAt,
|
|
261
1768
|
lastSeenAt: row.lastSeenAt
|
|
262
1769
|
};
|
|
1770
|
+
if (unreadCount !== void 0) s.unreadCount = unreadCount;
|
|
263
1771
|
if (row.cliVersion !== void 0) s.cliVersion = row.cliVersion;
|
|
264
1772
|
if (row.repoRoot !== void 0) s.repo = row.repoRemoteUrlHash !== void 0 ? {
|
|
265
1773
|
root: row.repoRoot,
|
|
@@ -270,6 +1778,7 @@ function toSession(row, isOrchestrator) {
|
|
|
270
1778
|
if (row.hostPids !== void 0) s.hostPids = row.hostPids;
|
|
271
1779
|
if (row.statusText !== void 0) s.statusText = row.statusText;
|
|
272
1780
|
if (row.spawnedBy !== void 0) s.spawnedBy = row.spawnedBy;
|
|
1781
|
+
if (row.nativeId !== void 0) s.nativeId = row.nativeId;
|
|
273
1782
|
return s;
|
|
274
1783
|
}
|
|
275
1784
|
function toEntry(r) {
|
|
@@ -284,6 +1793,8 @@ function toEntry(r) {
|
|
|
284
1793
|
if (d) entry.deliveredAt = d;
|
|
285
1794
|
if (rd) entry.readAt = rd;
|
|
286
1795
|
if (a) entry.ackedAt = a;
|
|
1796
|
+
const hops = num(r.hops);
|
|
1797
|
+
if (hops !== void 0 && hops > 0) entry.hops = hops;
|
|
287
1798
|
return entry;
|
|
288
1799
|
}
|
|
289
1800
|
/** SQLite persistence. All methods are synchronous; callers group writes with `tx`. */
|
|
@@ -340,8 +1851,9 @@ var Store = class {
|
|
|
340
1851
|
}
|
|
341
1852
|
insertSession(s) {
|
|
342
1853
|
this.run(`INSERT INTO sessions (id, name, cli, cli_version, device_id, cwd, repo_root, repo_remote_hash,
|
|
343
|
-
pid, host_pid, host_pids, status, status_text, delivery_tier, spawned_by,
|
|
344
|
-
|
|
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);
|
|
345
1857
|
}
|
|
346
1858
|
getSession(id) {
|
|
347
1859
|
const r = this.all("SELECT * FROM sessions WHERE id = ?", id)[0];
|
|
@@ -354,6 +1866,18 @@ var Store = class {
|
|
|
354
1866
|
updateSession(id, fields) {
|
|
355
1867
|
const sets = [];
|
|
356
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
|
+
}
|
|
357
1881
|
if (fields.name !== void 0) {
|
|
358
1882
|
sets.push("name = ?");
|
|
359
1883
|
vals.push(fields.name);
|
|
@@ -380,9 +1904,10 @@ var Store = class {
|
|
|
380
1904
|
setHolder(id) {
|
|
381
1905
|
this.run("UPDATE orchestrator SET session_id = ? WHERE slot = 1", id);
|
|
382
1906
|
}
|
|
383
|
-
|
|
1907
|
+
/** `hops`: automatic turns behind the message (the wake limit counts them). */
|
|
1908
|
+
insertMessage(message, recipient, at, hops = 0) {
|
|
384
1909
|
this.run("INSERT INTO messages (id, json) VALUES (?, ?)", message.id, JSON.stringify(message));
|
|
385
|
-
this.run("INSERT INTO mailbox (session_id, message_id, state, queued_at) VALUES (?, ?, 'queued', ?)", recipient, message.id, at);
|
|
1910
|
+
this.run("INSERT INTO mailbox (session_id, message_id, state, queued_at, hops) VALUES (?, ?, 'queued', ?, ?)", recipient, message.id, at, hops);
|
|
386
1911
|
}
|
|
387
1912
|
/** Messages queued for a session that no one has been shown yet. */
|
|
388
1913
|
unreadCount(sessionId) {
|
|
@@ -400,7 +1925,7 @@ var Store = class {
|
|
|
400
1925
|
}
|
|
401
1926
|
/** Mailbox entries of one session, optionally limited to the given states or message ids. */
|
|
402
1927
|
entries(sessionId, filter = {}) {
|
|
403
|
-
let sql = `SELECT m.json, b.state, b.queued_at, b.delivered_at, b.read_at, b.acked_at
|
|
1928
|
+
let sql = `SELECT m.json, b.state, b.queued_at, b.delivered_at, b.read_at, b.acked_at, b.hops
|
|
404
1929
|
FROM mailbox b JOIN messages m ON m.id = b.message_id WHERE b.session_id = ?`;
|
|
405
1930
|
const params = [sessionId];
|
|
406
1931
|
if (filter.states) {
|
|
@@ -419,34 +1944,34 @@ var Store = class {
|
|
|
419
1944
|
}
|
|
420
1945
|
};
|
|
421
1946
|
// ../daemon/src/server.ts
|
|
422
|
-
const DAEMON_VERSION = "0.
|
|
1947
|
+
const DAEMON_VERSION = "0.2.0-rc.10";
|
|
423
1948
|
/** A connection that has not finished the handshake by then is closed. */
|
|
424
1949
|
const AUTH_TIMEOUT_MS = 5e3;
|
|
425
1950
|
/** Unread messages one session may hold. */
|
|
426
1951
|
const MAX_UNREAD_PER_SESSION = 1e3;
|
|
427
1952
|
/**
|
|
428
|
-
*
|
|
429
|
-
*
|
|
430
|
-
*
|
|
431
|
-
* without piling up months of test sessions. It applies only when nothing is waiting for it.
|
|
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.
|
|
432
1956
|
*/
|
|
433
|
-
const
|
|
434
|
-
/**
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
*/
|
|
439
|
-
const
|
|
440
|
-
/**
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
*/
|
|
444
|
-
const PRUNE_UNREAD_AFTER_MS = 6048e5;
|
|
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;
|
|
445
1967
|
/** Sender id on `system` messages made by the daemon itself (no session sent them). */
|
|
446
1968
|
const DAEMON_SENDER_ID = SessionId.parse("0".repeat(26));
|
|
447
1969
|
const CLI_TIER = {
|
|
448
1970
|
claude: "next_turn",
|
|
449
|
-
codex: "next_turn"
|
|
1971
|
+
codex: "next_turn",
|
|
1972
|
+
cursor: "next_turn",
|
|
1973
|
+
copilot: "next_turn",
|
|
1974
|
+
antigravity: "next_turn"
|
|
450
1975
|
};
|
|
451
1976
|
var Daemon = class {
|
|
452
1977
|
store;
|
|
@@ -458,12 +1983,44 @@ var Daemon = class {
|
|
|
458
1983
|
requestShutdown;
|
|
459
1984
|
log;
|
|
460
1985
|
authTimeoutMs;
|
|
461
|
-
|
|
1986
|
+
autoLimits;
|
|
1987
|
+
processIo;
|
|
1988
|
+
platform;
|
|
1989
|
+
wakers;
|
|
1990
|
+
settingsPath;
|
|
462
1991
|
conns = /* @__PURE__ */ new Set();
|
|
1992
|
+
/** Reaches the owner's other devices; set by startDaemon unless disabled. */
|
|
1993
|
+
relay;
|
|
463
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();
|
|
464
2019
|
idleSince;
|
|
465
2020
|
startedMs;
|
|
466
|
-
|
|
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) {
|
|
467
2024
|
this.store = store;
|
|
468
2025
|
this.token = token;
|
|
469
2026
|
this.now = now;
|
|
@@ -473,7 +2030,11 @@ var Daemon = class {
|
|
|
473
2030
|
this.requestShutdown = requestShutdown;
|
|
474
2031
|
this.log = log;
|
|
475
2032
|
this.authTimeoutMs = authTimeoutMs;
|
|
476
|
-
this.
|
|
2033
|
+
this.autoLimits = autoLimits;
|
|
2034
|
+
this.processIo = processIo;
|
|
2035
|
+
this.platform = platform;
|
|
2036
|
+
this.wakers = wakers;
|
|
2037
|
+
this.settingsPath = settingsPath;
|
|
477
2038
|
this.deviceId = store.deviceId();
|
|
478
2039
|
this.startedMs = now().getTime();
|
|
479
2040
|
this.idleSince = this.startedMs;
|
|
@@ -497,6 +2058,7 @@ var Daemon = class {
|
|
|
497
2058
|
socket.on("close", () => {
|
|
498
2059
|
clearTimeout(authTimer);
|
|
499
2060
|
this.conns.delete(conn);
|
|
2061
|
+
this.listenerGone(conn);
|
|
500
2062
|
});
|
|
501
2063
|
socket.on("error", () => socket.destroy());
|
|
502
2064
|
}
|
|
@@ -558,22 +2120,40 @@ var Daemon = class {
|
|
|
558
2120
|
case "session.rename": return this.rename(req.params);
|
|
559
2121
|
case "session.setStatus": return this.setStatus(req.params);
|
|
560
2122
|
case "session.list": return this.list(req.params);
|
|
561
|
-
case "session.byHost": return this.byHost(req.params
|
|
562
|
-
case "session.
|
|
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);
|
|
563
2129
|
case "daemon.shutdown": return { ok: true };
|
|
564
2130
|
case "orchestrator.claim": return this.claim(req.params.sessionId);
|
|
2131
|
+
case "orchestrator.clear": return this.clearLead(conn);
|
|
565
2132
|
case "message.send": return this.sendMessage(req.params);
|
|
2133
|
+
case "owner.send": return this.ownerSend(conn, req.params);
|
|
566
2134
|
case "message.inbox": return this.inbox(req.params);
|
|
567
2135
|
case "message.deliver": return this.deliver(req.params);
|
|
568
2136
|
case "message.ack": return this.ack(req.params);
|
|
2137
|
+
case "message.requeue": return this.requeue(req.params);
|
|
569
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);
|
|
570
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.`);
|
|
571
2149
|
}
|
|
572
2150
|
}
|
|
573
2151
|
hello(conn, p) {
|
|
574
2152
|
if (conn.challenge !== void 0) throw new ConvenoError(RpcErrorCode.Conflict, "The handshake already started on this connection.");
|
|
575
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;
|
|
576
2155
|
conn.challenge = newAuthNonce();
|
|
2156
|
+
conn.client = p.client;
|
|
577
2157
|
return {
|
|
578
2158
|
protocolVersion: PROTOCOL_VERSION,
|
|
579
2159
|
daemonVersion: DAEMON_VERSION,
|
|
@@ -599,14 +2179,29 @@ var Daemon = class {
|
|
|
599
2179
|
if (!row) throw new ConvenoError(RpcErrorCode.NotFound, `No session with id ${id}. Register the session again.`);
|
|
600
2180
|
return row;
|
|
601
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`). */
|
|
602
2188
|
view(row) {
|
|
603
|
-
|
|
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;
|
|
604
2198
|
}
|
|
605
2199
|
emit(payload, onlyTo) {
|
|
2200
|
+
const only = onlyTo === void 0 || Array.isArray(onlyTo) ? onlyTo : [onlyTo];
|
|
606
2201
|
for (const c of this.conns) {
|
|
607
2202
|
const sub = c.sub;
|
|
608
2203
|
if (!sub?.topics.has(payload.event)) continue;
|
|
609
|
-
if (
|
|
2204
|
+
if (only !== void 0 && sub.sessionId !== void 0 && !only.includes(sub.sessionId)) continue;
|
|
610
2205
|
this.send(c, makeEventNotification(payload));
|
|
611
2206
|
}
|
|
612
2207
|
}
|
|
@@ -619,12 +2214,15 @@ var Daemon = class {
|
|
|
619
2214
|
change
|
|
620
2215
|
}
|
|
621
2216
|
});
|
|
2217
|
+
this.relay?.sessionsChanged();
|
|
622
2218
|
}
|
|
2219
|
+
/** Every message that lands in a local mailbox goes through here. */
|
|
623
2220
|
emitMessage(m, recipient) {
|
|
624
2221
|
this.emit({
|
|
625
2222
|
event: "message.received",
|
|
626
2223
|
data: { message: m }
|
|
627
2224
|
}, recipient);
|
|
2225
|
+
this.daemonWake(recipient);
|
|
628
2226
|
}
|
|
629
2227
|
async detect(p) {
|
|
630
2228
|
if (p.repo) return p.repo;
|
|
@@ -646,8 +2244,11 @@ var Daemon = class {
|
|
|
646
2244
|
deviceId: this.deviceId,
|
|
647
2245
|
cwd: p.cwd,
|
|
648
2246
|
status: "idle",
|
|
649
|
-
deliveryTier: CLI_TIER[p.cli] ?? "inbox",
|
|
2247
|
+
deliveryTier: p.acp ? "acp" : CLI_TIER[p.cli] ?? "inbox",
|
|
2248
|
+
spawned: p.spawned,
|
|
650
2249
|
spawnDepth: parent ? parent.spawnDepth + 1 : 0,
|
|
2250
|
+
autoRuns: [],
|
|
2251
|
+
turnHops: 0,
|
|
651
2252
|
startedAt: at,
|
|
652
2253
|
lastSeenAt: at
|
|
653
2254
|
};
|
|
@@ -664,7 +2265,18 @@ var Daemon = class {
|
|
|
664
2265
|
return r;
|
|
665
2266
|
});
|
|
666
2267
|
this.emitSession(row.id, "registered");
|
|
667
|
-
|
|
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);
|
|
668
2280
|
}
|
|
669
2281
|
async registerAsync(p) {
|
|
670
2282
|
return this.register(p, await this.detect(p));
|
|
@@ -682,6 +2294,7 @@ var Daemon = class {
|
|
|
682
2294
|
status: "idle",
|
|
683
2295
|
lastSeenAt: at
|
|
684
2296
|
});
|
|
2297
|
+
this.offlineSince.delete(sessionId);
|
|
685
2298
|
this.emitSession(sessionId, "updated");
|
|
686
2299
|
return { lastSeenAt: at };
|
|
687
2300
|
}
|
|
@@ -692,6 +2305,9 @@ var Daemon = class {
|
|
|
692
2305
|
this.store.updateSession(sessionId, { status: "offline" });
|
|
693
2306
|
if (after !== before) this.store.setHolder(after);
|
|
694
2307
|
});
|
|
2308
|
+
this.listeners.delete(sessionId);
|
|
2309
|
+
this.woken.delete(sessionId);
|
|
2310
|
+
this.offlineSince.set(sessionId, this.now().getTime());
|
|
695
2311
|
this.emitSession(sessionId, change);
|
|
696
2312
|
if (after !== before) this.emit({
|
|
697
2313
|
event: "orchestrator.changed",
|
|
@@ -729,70 +2345,110 @@ var Daemon = class {
|
|
|
729
2345
|
return { session: this.view(this.requireSession(p.sessionId)) };
|
|
730
2346
|
}
|
|
731
2347
|
list(p) {
|
|
732
|
-
|
|
733
|
-
if (
|
|
2348
|
+
const rows = this.store.allSessions().filter((r) => {
|
|
2349
|
+
if (r.status === "offline" && !p.includeOffline) return false;
|
|
734
2350
|
if (p.cli && r.cli !== p.cli) return false;
|
|
735
2351
|
if (p.repo && r.repoRoot !== p.repo && baseName(r.repoRoot ?? r.cwd) !== p.repo) return false;
|
|
736
2352
|
return true;
|
|
737
|
-
})
|
|
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] };
|
|
738
2359
|
}
|
|
739
2360
|
/**
|
|
740
2361
|
* Find the session a hook belongs to: the one online session whose `hostPid` equals `pid`.
|
|
741
2362
|
* Exact equality only, with no walk to farther ancestors, so a hook from a CLI that has no
|
|
742
2363
|
* session matches nothing. Two sessions under one CLI process are ambiguous, so the result is
|
|
743
|
-
* null; the daemon never guesses.
|
|
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.
|
|
744
2368
|
*/
|
|
745
|
-
byHost(
|
|
746
|
-
const
|
|
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);
|
|
747
2385
|
const only = holders.length === 1 ? holders[0] : void 0;
|
|
748
2386
|
return { session: only ? this.view(only) : null };
|
|
749
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
|
+
}
|
|
750
2392
|
/**
|
|
751
|
-
*
|
|
752
|
-
*
|
|
753
|
-
*
|
|
754
|
-
*
|
|
755
|
-
*
|
|
756
|
-
* mailbox with it, in one transaction.
|
|
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.
|
|
757
2398
|
*/
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
const
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
id: r.id,
|
|
769
|
-
name: r.name
|
|
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
|
|
770
2409
|
});
|
|
771
|
-
const offline = matched.filter((r) => r.status === "offline");
|
|
772
|
-
const skippedOnline = explicit ? matched.filter((r) => r.status !== "offline") : [];
|
|
773
|
-
if (!p.dryRun) this.forgetRows(offline);
|
|
774
2410
|
return {
|
|
775
|
-
|
|
776
|
-
|
|
2411
|
+
online: true,
|
|
2412
|
+
complete: a.complete,
|
|
2413
|
+
...a.complete && a.hostPid !== void 0 ? { hostPid: a.hostPid } : {}
|
|
777
2414
|
};
|
|
778
2415
|
}
|
|
779
|
-
|
|
780
|
-
|
|
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);
|
|
781
2424
|
this.store.tx(() => {
|
|
782
|
-
for (const
|
|
2425
|
+
for (const o of others) this.store.updateSession(o.id, { nativeId: null });
|
|
2426
|
+
this.store.updateSession(row.id, { nativeId: p.nativeId });
|
|
783
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)) };
|
|
784
2432
|
}
|
|
785
|
-
/**
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
if (
|
|
794
|
-
|
|
795
|
-
|
|
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
|
+
}
|
|
796
2452
|
}
|
|
797
2453
|
claim(sessionId) {
|
|
798
2454
|
this.requireSession(sessionId);
|
|
@@ -837,51 +2493,384 @@ var Daemon = class {
|
|
|
837
2493
|
previous: res.previous
|
|
838
2494
|
};
|
|
839
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
|
+
}
|
|
840
2534
|
sendMessage(p) {
|
|
841
2535
|
const sender = this.requireSession(p.sessionId);
|
|
842
2536
|
if (sender.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${sender.name}" is offline. Register the session again before sending.`);
|
|
843
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) {
|
|
844
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.`);
|
|
845
|
-
const rows = this.store.allSessions();
|
|
846
|
-
const target = resolveRecipient(p.to, this.named(rows), this.store.holder());
|
|
847
|
-
const targetRow = rows.find((r) => r.id === target.id);
|
|
848
|
-
if (this.store.unreadCount(targetRow.id) >= 1e3) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(targetRow.name, MAX_UNREAD_PER_SESSION));
|
|
849
2555
|
const at = this.iso();
|
|
850
|
-
const
|
|
2556
|
+
const rows = this.store.allSessions();
|
|
2557
|
+
const make = (to) => ({
|
|
851
2558
|
id: newMessageId(),
|
|
852
2559
|
from: sender.id,
|
|
853
|
-
to
|
|
2560
|
+
to,
|
|
854
2561
|
kind: p.kind,
|
|
855
2562
|
body: p.body,
|
|
856
2563
|
urgent: p.urgent,
|
|
857
2564
|
createdAt: at,
|
|
858
2565
|
fromName: sender.name,
|
|
859
|
-
fromCli: sender.cli,
|
|
2566
|
+
...sender.cli !== void 0 ? { fromCli: sender.cli } : {},
|
|
860
2567
|
...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
|
|
861
|
-
};
|
|
862
|
-
this.
|
|
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);
|
|
863
2582
|
this.emitMessage(message, targetRow.id);
|
|
864
2583
|
return {
|
|
865
2584
|
message,
|
|
866
|
-
delivery: targetRow
|
|
2585
|
+
delivery: this.tierFor(targetRow),
|
|
867
2586
|
deliveredTo: {
|
|
868
2587
|
id: targetRow.id,
|
|
869
2588
|
name: targetRow.name
|
|
870
2589
|
}
|
|
871
2590
|
};
|
|
872
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
|
+
}
|
|
873
2858
|
inbox(p) {
|
|
874
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) {
|
|
875
2864
|
const at = this.iso();
|
|
876
2865
|
return this.store.tx(() => {
|
|
877
|
-
const entries = this.store.entries(
|
|
2866
|
+
const entries = this.store.entries(id, unreadOnly ? { states: ["queued"] } : {});
|
|
878
2867
|
const res = readInbox(entries, {
|
|
879
|
-
unreadOnly
|
|
880
|
-
limit
|
|
2868
|
+
unreadOnly,
|
|
2869
|
+
limit,
|
|
881
2870
|
maxBytes: RESPONSE_BUDGET_BYTES
|
|
882
2871
|
}, at);
|
|
883
2872
|
const changed = new Set(res.returned.map((e) => e.message.id));
|
|
884
|
-
for (const e of res.entries) if (changed.has(e.message.id)) this.store.saveEntry(
|
|
2873
|
+
for (const e of res.entries) if (changed.has(e.message.id)) this.store.saveEntry(id, e);
|
|
885
2874
|
return {
|
|
886
2875
|
messages: res.returned.map((e) => e.message),
|
|
887
2876
|
unreadCount: res.unreadCount
|
|
@@ -893,9 +2882,14 @@ var Daemon = class {
|
|
|
893
2882
|
const at = this.iso();
|
|
894
2883
|
return this.store.tx(() => {
|
|
895
2884
|
const pending = pendingForInjection(this.store.entries(p.sessionId, { states: ["queued"] }));
|
|
896
|
-
const
|
|
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));
|
|
897
2887
|
const updated = markDelivered(taken, taken.map((e) => e.message.id), at);
|
|
898
2888
|
for (const e of updated) this.store.saveEntry(p.sessionId, e);
|
|
2889
|
+
if (preview) return {
|
|
2890
|
+
messages: [preview],
|
|
2891
|
+
remaining: pending.length
|
|
2892
|
+
};
|
|
899
2893
|
return {
|
|
900
2894
|
messages: updated.map((e) => e.message),
|
|
901
2895
|
remaining: pending.length - taken.length
|
|
@@ -904,46 +2898,104 @@ var Daemon = class {
|
|
|
904
2898
|
}
|
|
905
2899
|
ack(p) {
|
|
906
2900
|
this.requireSession(p.sessionId);
|
|
2901
|
+
return this.ackFor(p.sessionId, p.ids);
|
|
2902
|
+
}
|
|
2903
|
+
ackFor(id, ids) {
|
|
907
2904
|
const at = this.iso();
|
|
908
2905
|
return this.store.tx(() => {
|
|
909
|
-
const entries = this.store.entries(
|
|
910
|
-
const res = ackEntries(entries,
|
|
911
|
-
for (const e of res.entries) this.store.saveEntry(
|
|
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);
|
|
912
2909
|
return { acked: res.acked };
|
|
913
2910
|
});
|
|
914
2911
|
}
|
|
915
2912
|
subscribe(conn, p) {
|
|
916
|
-
|
|
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);
|
|
917
2916
|
const topics = p.topics ?? [...EVENT_NAMES];
|
|
918
2917
|
conn.sub = {
|
|
919
|
-
sessionId: p.sessionId,
|
|
2918
|
+
...p.sessionId !== void 0 ? { sessionId: p.sessionId } : {},
|
|
920
2919
|
topics: new Set(topics)
|
|
921
2920
|
};
|
|
922
2921
|
return { subscribed: topics };
|
|
923
2922
|
}
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
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);
|
|
937
2990
|
}
|
|
938
2991
|
sweep() {
|
|
939
2992
|
const nowMs = this.now().getTime();
|
|
2993
|
+
this.removeOffline(OFFLINE_GRACE_MS);
|
|
2994
|
+
this.retryDaemonWakes(nowMs);
|
|
940
2995
|
let online = 0;
|
|
941
2996
|
const rows = this.store.allSessions();
|
|
942
2997
|
for (const row of rows) {
|
|
943
|
-
if (row.status === "offline")
|
|
944
|
-
if (this.shouldPrune(row, rows, nowMs) || this.workspaceGone(row, nowMs)) this.forgetRows([row]);
|
|
945
|
-
continue;
|
|
946
|
-
}
|
|
2998
|
+
if (row.status === "offline") continue;
|
|
947
2999
|
const lastSeenMs = Math.max(Date.parse(row.lastSeenAt), this.startedMs);
|
|
948
3000
|
const verdict = evaluateLiveness({
|
|
949
3001
|
lastSeenMs,
|
|
@@ -956,7 +3008,29 @@ var Daemon = class {
|
|
|
956
3008
|
else if (nowMs - this.idleSince >= this.idleExitMs) this.requestIdleExit();
|
|
957
3009
|
}
|
|
958
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
|
+
}
|
|
959
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
|
+
}
|
|
960
3034
|
/** Start convenod: take the lock, open the database, listen on the socket. */
|
|
961
3035
|
async function startDaemon(opts) {
|
|
962
3036
|
const platform = process.platform;
|
|
@@ -965,6 +3039,11 @@ async function startDaemon(opts) {
|
|
|
965
3039
|
if (isSocketPathTooLong(socketPath, platform)) throw new Error(socketPathTooLongMessage(socketPath, platform));
|
|
966
3040
|
const now = opts.now ?? (() => /* @__PURE__ */ new Date());
|
|
967
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);
|
|
968
3047
|
ensureDir(opts.dataDir);
|
|
969
3048
|
const releaseLock = await acquireLock(paths.lock, socketPath);
|
|
970
3049
|
let store;
|
|
@@ -976,11 +3055,13 @@ async function startDaemon(opts) {
|
|
|
976
3055
|
await clearStaleSocket(socketPath);
|
|
977
3056
|
let closing;
|
|
978
3057
|
let timer;
|
|
3058
|
+
const daemonLog = createDaemonLog(paths.daemonLog, { now });
|
|
979
3059
|
const daemon = new Daemon(store, token, now, isAlive, opts.idleExitMs ?? 6e5, () => {
|
|
980
3060
|
close().then(() => opts.onIdleExit?.());
|
|
981
3061
|
}, () => {
|
|
982
3062
|
close().then(() => opts.onShutdown?.());
|
|
983
|
-
},
|
|
3063
|
+
}, daemonLog, opts.authTimeoutMs ?? 5e3, opts.autoLimits ?? autoLimitsFromEnv(process.env), processIo, opts.platform, opts.wakers ?? {}, paths.settings);
|
|
3064
|
+
daemon.removeAllOffline();
|
|
984
3065
|
const srv = createServer((socket) => daemon.attach(socket));
|
|
985
3066
|
server = srv;
|
|
986
3067
|
await new Promise((resolve, reject) => {
|
|
@@ -988,12 +3069,16 @@ async function startDaemon(opts) {
|
|
|
988
3069
|
srv.listen(socketPath, () => resolve());
|
|
989
3070
|
});
|
|
990
3071
|
if (platform !== "win32" && !socketPath.startsWith("\\\\")) chmodSync(socketPath, 384);
|
|
3072
|
+
if (opts.relay !== false) startRelay(daemon, opts, opts.relay ?? {});
|
|
991
3073
|
timer = setInterval(() => daemon.sweep(), opts.sweepIntervalMs ?? 15e3);
|
|
992
3074
|
timer.unref();
|
|
993
3075
|
const liveStore = store;
|
|
994
3076
|
function close() {
|
|
995
3077
|
closing ??= (async () => {
|
|
996
3078
|
if (timer) clearInterval(timer);
|
|
3079
|
+
daemon.stopping = true;
|
|
3080
|
+
walker?.close();
|
|
3081
|
+
daemon.relay?.stop();
|
|
997
3082
|
const stopped = new Promise((resolve) => srv.close(() => resolve()));
|
|
998
3083
|
for (const c of daemon.conns) c.socket.destroy();
|
|
999
3084
|
await stopped;
|
|
@@ -1006,7 +3091,16 @@ async function startDaemon(opts) {
|
|
|
1006
3091
|
return {
|
|
1007
3092
|
socketPath,
|
|
1008
3093
|
close,
|
|
1009
|
-
sweep: () => daemon.sweep()
|
|
3094
|
+
sweep: () => daemon.sweep(),
|
|
3095
|
+
testRelay: {
|
|
3096
|
+
host: () => daemon.relayHost(),
|
|
3097
|
+
set: (relay) => {
|
|
3098
|
+
daemon.relay = relay && {
|
|
3099
|
+
sessionsChanged: () => {},
|
|
3100
|
+
...relay
|
|
3101
|
+
};
|
|
3102
|
+
}
|
|
3103
|
+
}
|
|
1010
3104
|
};
|
|
1011
3105
|
} catch (e) {
|
|
1012
3106
|
server?.close();
|
|
@@ -1019,6 +3113,7 @@ async function startDaemon(opts) {
|
|
|
1019
3113
|
async function main() {
|
|
1020
3114
|
const handle = await startDaemon({
|
|
1021
3115
|
dataDir: dataDir(process.platform, process.env, homedir()),
|
|
3116
|
+
wakers: { codex: codexAdapter.daemonWake },
|
|
1022
3117
|
onIdleExit: () => {
|
|
1023
3118
|
process.stderr.write("convenod: no sessions for a while, exiting.\n");
|
|
1024
3119
|
process.exit(0);
|