@conveno/cli 0.1.1 → 0.2.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -5
- package/dist/acp-BlKK0v-B.js +871 -0
- package/dist/args-DHkLY6_f.js +513 -0
- package/dist/bin.js +24 -4383
- package/dist/daemon.js +2804 -48
- package/dist/dist-CWvQqhPj.js +793 -0
- package/dist/dist-D8gPpZKN.js +8625 -0
- package/dist/dist-DcmKjrmu.js +271 -0
- package/dist/dist-DsRTUePN.js +481 -0
- package/dist/dist-_qrCNXUP.js +10497 -0
- package/dist/hook-bfp9_AVT.js +105 -0
- package/dist/hook-entry-Daxws9EC.js +1 -0
- package/dist/hook-entry-RlH2cG3S.js +1289 -0
- package/dist/main-sIWDc4jt.js +2899 -0
- package/dist/runtime-5nEur1P5.js +1505 -0
- package/package.json +19 -10
- package/dist/dist-WPVVRVUh.js +0 -1507
package/dist/daemon.js
CHANGED
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { homedir } from "node:os";
|
|
3
|
-
import { $ as
|
|
2
|
+
import { homedir, hostname, userInfo } from "node:os";
|
|
3
|
+
import { $t as turnHops, A as currentAccessToken, An as encodeFrame, B as effectiveHolder, Bn as parseIpcRequest, C as claimOrchestrator, Ct as proofsMatch, E as clientProof, En as Ticket, Et as readAncestry, F as defaultProcessIo, Fn as makeResult, H as entriesNewestFirst, Hn as safeParse, Ht as samePath, I as describeToolCall, In as newDeviceId, Jt as tailJsonl, Kt as statusAfterLiveness, L as detectRepo, Ln as newMessageId, M as dataDir, Mn as isSocketPathTooLong, N as dataPaths, Nn as makeError, On as createLineDecoder, Ot as readHeadLine, P as decideAutoContinue, Pn as makeEventNotification, Q as holderAfterDeparture, Qt as tooManyUnreadMessage, Rn as newSessionId, Rt as resolveRecipient, S as bindAccountDevice, T as classifyPermission, Tt as readAccountTokens, U as evaluateLiveness, Un as sanitizeLine, Vn as parseRelayFrame, Wn as socketPathTooLongMessage, Xt as takeWithinBytes, Z as generateSessionName, Zt as toIso, _ as asString, _n as PROTOCOL_VERSION, _t as pendingForInjection, at as jwtClaim, b as autoLimitsFromEnv, cn as DeviceId, ct as markDelivered, d as ackEntries, dt as notFound, en as unsupportedTranscript, fn as HUMAN_ANSWERER, gn as PERMISSION_ANSWERS, gt as pauseLabel, hn as ORCHESTRATOR_ALIAS, j as daemonProof, k as createWmiWalker, kn as defaultSocketPath, kt as readInbox, ln as EVENT_NAMES, lt as nameMatchesPattern, n as AccountError, nn as validateRename, p as acpTranscript, pn as Message, r as ConvenoError, rt as isRecord, s as RESPONSE_BUDGET_BYTES, tt as isOnline, ut as newAuthNonce, vn as RelayPayload, x as baseName, xn as SessionId, xt as planSpawn, y as autoCandidates, yn as RpcErrorCode, zn as newTicketId } from "./dist-_qrCNXUP.js";
|
|
4
4
|
import { randomBytes } from "node:crypto";
|
|
5
5
|
import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
6
6
|
import { connect, createServer } from "node:net";
|
|
7
|
-
import { dirname } from "node:path";
|
|
7
|
+
import { dirname, join, posix, win32 } from "node:path";
|
|
8
|
+
import { n as redactWithReport } from "./dist-DcmKjrmu.js";
|
|
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-CWvQqhPj.js";
|
|
10
|
+
import { execFileSync } from "node:child_process";
|
|
8
11
|
import { DatabaseSync } from "node:sqlite";
|
|
12
|
+
import { c as claudeTranscript, i as codexTranscript, t as openCodeTranscript } from "./dist-D8gPpZKN.js";
|
|
13
|
+
import { readFile, readdir, stat } from "node:fs/promises";
|
|
9
14
|
// ../daemon/src/lifecycle.ts
|
|
10
15
|
/** Thrown when another Conveno daemon already owns the lock file or answers on the socket. */
|
|
11
16
|
var DaemonAlreadyRunningError = class extends Error {
|
|
@@ -119,39 +124,1671 @@ function ensureDir(dir) {
|
|
|
119
124
|
}
|
|
120
125
|
const describeError = (e) => e instanceof Error ? e.stack ?? `${e.name}: ${e.message}` : String(e);
|
|
121
126
|
/**
|
|
122
|
-
* The daemon's own log, for errors it did not expect
|
|
123
|
-
*
|
|
124
|
-
* starts. Request parameters are never logged,
|
|
127
|
+
* The daemon's own log, for errors it did not expect and for events the owner should be able to
|
|
128
|
+
* see. One file, readable by the user only, with one older generation kept: when the file reaches
|
|
129
|
+
* `maxBytes` it replaces `<path>.1` and a new file starts. Request parameters are never logged,
|
|
130
|
+
* since they can hold message text.
|
|
125
131
|
*/
|
|
126
132
|
function createDaemonLog(path, opts = {}) {
|
|
127
133
|
const maxBytes = opts.maxBytes ?? 1048576;
|
|
128
134
|
const now = opts.now ?? (() => /* @__PURE__ */ new Date());
|
|
135
|
+
const append = (text) => {
|
|
136
|
+
try {
|
|
137
|
+
mkdirSync(dirname(path), {
|
|
138
|
+
recursive: true,
|
|
139
|
+
mode: 448
|
|
140
|
+
});
|
|
141
|
+
let size = 0;
|
|
142
|
+
try {
|
|
143
|
+
size = statSync(path).size;
|
|
144
|
+
} catch {}
|
|
145
|
+
if (size >= maxBytes) {
|
|
146
|
+
rmSync(`${path}.1`, { force: true });
|
|
147
|
+
renameSync(path, `${path}.1`);
|
|
148
|
+
}
|
|
149
|
+
appendFileSync(path, text, { mode: 384 });
|
|
150
|
+
if (process.platform !== "win32") chmodSync(path, 384);
|
|
151
|
+
} catch {}
|
|
152
|
+
};
|
|
129
153
|
return {
|
|
130
154
|
path,
|
|
131
155
|
error(what, e) {
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
156
|
+
append(`${now().toISOString()} ${what}\n${describeError(e)}\n\n`);
|
|
157
|
+
},
|
|
158
|
+
note(line) {
|
|
159
|
+
append(`${now().toISOString()} ${line.replace(/[\r\n]+/g, " ")}\n`);
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
// ../daemon/src/peek.ts
|
|
164
|
+
/** Longest text of one turn that is returned. A tool output is cut to this. */
|
|
165
|
+
const PEEK_TURN_MAX_CHARS = 4e3;
|
|
166
|
+
/**
|
|
167
|
+
* Longest text of one turn that is redacted. A larger one is cut first, at a word boundary, so the
|
|
168
|
+
* redaction pass stays fast. The cut can only remove the end of a secret, never expose more.
|
|
169
|
+
*/
|
|
170
|
+
const PEEK_REDACT_INPUT_MAX = 2e5;
|
|
171
|
+
const CLIP = "\n[clipped]";
|
|
172
|
+
/** Cut `text` to at most `max` characters, at a word boundary when one is near. */
|
|
173
|
+
function clip$1(text, max, marker = CLIP) {
|
|
174
|
+
if (text.length <= max) return text;
|
|
175
|
+
const room = Math.max(0, max - marker.length);
|
|
176
|
+
let cut = text.slice(0, room);
|
|
177
|
+
const space = cut.search(/\s\S*$/);
|
|
178
|
+
if (space > room - 80 && space > 0) cut = cut.slice(0, space);
|
|
179
|
+
return cut + marker;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Drop control characters other than tab and newline, and invisible direction and zero-width
|
|
183
|
+
* characters: a transcript can carry terminal escapes, and the reader may show this text.
|
|
184
|
+
*/
|
|
185
|
+
function stripControl(text) {
|
|
186
|
+
let out = "";
|
|
187
|
+
for (const ch of text) {
|
|
188
|
+
const c = ch.codePointAt(0);
|
|
189
|
+
if (!(c < 32 && c !== 9 && c !== 10 || c >= 127 && c <= 159 || c >= 8203 && c <= 8207 || c >= 8232 && c <= 8238 || c >= 8294 && c <= 8297 || c === 65279)) out += ch;
|
|
190
|
+
}
|
|
191
|
+
return out;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Turn what a reader returned into the wire result: redact every turn (always), clip each turn,
|
|
195
|
+
* then keep the newest turns that fit in `maxChars`. Redaction runs on the whole turn text before
|
|
196
|
+
* it is clipped, so a secret is never cut in the middle and left half visible.
|
|
197
|
+
*/
|
|
198
|
+
function preparePeek(entries, more, maxChars) {
|
|
199
|
+
let redactions = 0;
|
|
200
|
+
let truncated = more;
|
|
201
|
+
const perTurn = Math.min(PEEK_TURN_MAX_CHARS, maxChars);
|
|
202
|
+
const prepared = entries.map((e) => {
|
|
203
|
+
const raw = stripControl(e.text);
|
|
204
|
+
const input = clip$1(raw, PEEK_REDACT_INPUT_MAX, "");
|
|
205
|
+
const { text, findings } = redactWithReport(input);
|
|
206
|
+
for (const n of Object.values(findings)) redactions += n;
|
|
207
|
+
const clipped = clip$1(text, perTurn);
|
|
208
|
+
if (clipped !== text || input !== raw) truncated = true;
|
|
209
|
+
return {
|
|
210
|
+
role: e.role,
|
|
211
|
+
text: clipped,
|
|
212
|
+
...e.at ? { at: e.at } : {}
|
|
213
|
+
};
|
|
214
|
+
});
|
|
215
|
+
const kept = [];
|
|
216
|
+
let total = 0;
|
|
217
|
+
for (let i = prepared.length - 1; i >= 0; i--) {
|
|
218
|
+
const t = prepared[i];
|
|
219
|
+
if (total + t.text.length > maxChars) {
|
|
220
|
+
truncated = true;
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
total += t.text.length;
|
|
224
|
+
kept.unshift(t);
|
|
225
|
+
}
|
|
226
|
+
return {
|
|
227
|
+
turns: kept,
|
|
228
|
+
truncated,
|
|
229
|
+
redactions
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
const HANDSHAKE_TIMEOUT_MS = 15e3;
|
|
233
|
+
/**
|
|
234
|
+
* One WebSocket to the relay: challenge, signed hello, then frames. It does not reconnect by
|
|
235
|
+
* itself; the hub decides when to try again. The access token goes in the Authorization header
|
|
236
|
+
* of the upgrade request, never in the URL, so it does not end up in access logs.
|
|
237
|
+
*/
|
|
238
|
+
var RelayConnection = class {
|
|
239
|
+
o;
|
|
240
|
+
ws;
|
|
241
|
+
pinger;
|
|
242
|
+
handshake;
|
|
243
|
+
stateValue = "idle";
|
|
244
|
+
stopped = false;
|
|
245
|
+
explaining = false;
|
|
246
|
+
constructor(o) {
|
|
247
|
+
this.o = o;
|
|
248
|
+
}
|
|
249
|
+
get state() {
|
|
250
|
+
return this.stateValue;
|
|
251
|
+
}
|
|
252
|
+
start() {
|
|
253
|
+
this.stateValue = "connecting";
|
|
254
|
+
const ws = new WebSocket(this.o.url, { headers: { Authorization: `Bearer ${this.o.token}` } });
|
|
255
|
+
this.ws = ws;
|
|
256
|
+
this.handshake = setTimeout(() => this.fail("The relay did not answer in time."), HANDSHAKE_TIMEOUT_MS);
|
|
257
|
+
this.handshake.unref();
|
|
258
|
+
ws.addEventListener("message", (e) => this.onMessage(e.data));
|
|
259
|
+
ws.addEventListener("error", () => {
|
|
260
|
+
if (this.stateValue === "connecting") {
|
|
261
|
+
this.explaining = true;
|
|
262
|
+
this.explainFailure();
|
|
263
|
+
} else this.fail("The connection to the relay failed.");
|
|
264
|
+
});
|
|
265
|
+
ws.addEventListener("close", (e) => {
|
|
266
|
+
if (!this.explaining) this.fail(`The relay closed the connection (${e.code} ${e.reason}).`);
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
/** Close for good; no `down` event. */
|
|
270
|
+
stop() {
|
|
271
|
+
this.stopped = true;
|
|
272
|
+
this.cleanup();
|
|
273
|
+
}
|
|
274
|
+
/** Send a frame if the connection is ready. Returns false when it is not. */
|
|
275
|
+
send(frame) {
|
|
276
|
+
if (this.stateValue !== "ready" || !this.ws) return false;
|
|
277
|
+
try {
|
|
278
|
+
this.ws.send(JSON.stringify(frame));
|
|
279
|
+
return true;
|
|
280
|
+
} catch {
|
|
281
|
+
return false;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
onMessage(data) {
|
|
285
|
+
if (typeof data !== "string" || data === "pong") return;
|
|
286
|
+
let json;
|
|
287
|
+
try {
|
|
288
|
+
json = JSON.parse(data);
|
|
289
|
+
} catch {
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
const r = parseRelayFrame(json);
|
|
293
|
+
if (!r.ok) return;
|
|
294
|
+
const f = r.value;
|
|
295
|
+
if (this.stateValue === "connecting") {
|
|
296
|
+
if (f.t === "challenge") this.ws?.send(JSON.stringify(signRelayHello(this.o.identity, f.nonce)));
|
|
297
|
+
else if (f.t === "ready") {
|
|
298
|
+
if (this.handshake) clearTimeout(this.handshake);
|
|
299
|
+
this.stateValue = "ready";
|
|
300
|
+
this.pinger = setInterval(() => {
|
|
301
|
+
try {
|
|
302
|
+
this.ws?.send("ping");
|
|
303
|
+
} catch {}
|
|
304
|
+
}, this.o.pingMs ?? 3e4);
|
|
305
|
+
this.pinger.unref();
|
|
306
|
+
this.o.events.ready(f.online);
|
|
307
|
+
} else if (f.t === "error") this.fail(f.message, f.code);
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
this.o.events.frame(f);
|
|
311
|
+
}
|
|
312
|
+
async explainFailure() {
|
|
313
|
+
const httpUrl = this.o.url.replace(/^ws/, "http");
|
|
314
|
+
try {
|
|
315
|
+
const res = await (this.o.fetchImpl ?? fetch)(httpUrl, {
|
|
316
|
+
headers: { Authorization: `Bearer ${this.o.token}` },
|
|
317
|
+
signal: AbortSignal.timeout(1e4)
|
|
318
|
+
});
|
|
319
|
+
const body = await res.json().catch(() => ({}));
|
|
320
|
+
if (res.status === 401 || res.status === 403) return this.fail(body.error?.message ?? "The relay refused the access token.", body.error?.code);
|
|
321
|
+
this.fail(`The relay could not be reached (HTTP ${res.status}).`);
|
|
322
|
+
} catch {
|
|
323
|
+
this.fail("The relay could not be reached.");
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
fail(detail, code) {
|
|
327
|
+
if (this.stopped || this.stateValue === "disconnected") return;
|
|
328
|
+
this.stateValue = "disconnected";
|
|
329
|
+
this.cleanup();
|
|
330
|
+
this.o.events.down(detail, code);
|
|
331
|
+
}
|
|
332
|
+
cleanup() {
|
|
333
|
+
if (this.handshake) clearTimeout(this.handshake);
|
|
334
|
+
if (this.pinger) clearInterval(this.pinger);
|
|
335
|
+
try {
|
|
336
|
+
this.ws?.close();
|
|
337
|
+
} catch {}
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
// ../daemon/src/relay/state.ts
|
|
341
|
+
/** Files the relay client keeps in the data directory. */
|
|
342
|
+
function relayPaths(join, dataDir) {
|
|
343
|
+
return {
|
|
344
|
+
/** This device's secret keys. Mode 0600. */
|
|
345
|
+
identity: join(dataDir, "device-key.json"),
|
|
346
|
+
/** Device list, device name and seen envelope ids. Mode 0600. */
|
|
347
|
+
database: join(dataDir, "relay.db")
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* The icacls command that leaves only the current user with access to `path`: inherited entries
|
|
352
|
+
* removed (`/inheritance:r`), full control granted to the user, replacing any earlier grant
|
|
353
|
+
* (`/grant:r`). For a directory, `inherit` makes the grant apply to files and folders created in
|
|
354
|
+
* it (`(OI)(CI)`), so they are user-only from the moment they exist.
|
|
355
|
+
* See https://learn.microsoft.com/windows-server/administration/windows-commands/icacls.
|
|
356
|
+
* icacls is run from System32 by absolute path, never looked up on PATH.
|
|
357
|
+
*/
|
|
358
|
+
function userOnlyAclPlan(path, env, user, isFile, inherit = false) {
|
|
359
|
+
const systemRoot = env.SystemRoot ?? env.SYSTEMROOT ?? "C:\\Windows";
|
|
360
|
+
const icacls = win32.join(systemRoot, "System32", "icacls.exe");
|
|
361
|
+
const domain = env.USERDOMAIN;
|
|
362
|
+
const grant = `${domain ? `${domain}\\${user}` : user}:${inherit ? "(OI)(CI)" : ""}F`;
|
|
363
|
+
return planSpawn(icacls, [
|
|
364
|
+
path,
|
|
365
|
+
"/inheritance:r",
|
|
366
|
+
"/grant:r",
|
|
367
|
+
grant
|
|
368
|
+
], {
|
|
369
|
+
platform: "win32",
|
|
370
|
+
env,
|
|
371
|
+
...isFile ? { isFile } : {}
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Make a file readable by the current user only: mode 0600 on POSIX, a user-only ACL on Windows
|
|
376
|
+
* (where the mode is ignored).
|
|
377
|
+
*/
|
|
378
|
+
function restrictToUser(path, platform = process.platform, directory = false) {
|
|
379
|
+
if (platform !== "win32") {
|
|
380
|
+
chmodSync(path, directory ? 448 : 384);
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
const plan = userOnlyAclPlan(path, process.env, userInfo().username, void 0, directory);
|
|
384
|
+
execFileSync(plan.file, plan.args, {
|
|
385
|
+
stdio: "ignore",
|
|
386
|
+
windowsHide: true,
|
|
387
|
+
...plan.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
const restrictIfPresent = (path) => {
|
|
391
|
+
if (process.platform !== "win32" && existsSync(path)) chmodSync(path, 384);
|
|
392
|
+
};
|
|
393
|
+
/**
|
|
394
|
+
* Rename, retrying for a few seconds while Windows reports the file busy: a virus scanner often
|
|
395
|
+
* holds a file that was just written (graceful-fs retries renames for the same reason).
|
|
396
|
+
*/
|
|
397
|
+
function renameRetrying(from, to) {
|
|
398
|
+
const wait = new Int32Array(new SharedArrayBuffer(4));
|
|
399
|
+
for (let attempt = 0;; attempt++) try {
|
|
400
|
+
renameSync(from, to);
|
|
401
|
+
return;
|
|
402
|
+
} catch (e) {
|
|
403
|
+
const code = e.code;
|
|
404
|
+
if (attempt >= 30 || code !== "EPERM" && code !== "EACCES" && code !== "EBUSY") throw e;
|
|
405
|
+
Atomics.wait(wait, 0, 0, Math.min(25 * (attempt + 1), 200));
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* The user-only directory new key files are written in before they are renamed into place, so a
|
|
410
|
+
* key file never exists with the data folder's own, possibly broader, permissions. Made private
|
|
411
|
+
* once; a marker file inside it records that on Windows, where icacls is slow.
|
|
412
|
+
*/
|
|
413
|
+
function keyStagingDir(path, o, platform) {
|
|
414
|
+
const dir = join(dirname(path), ".key-staging");
|
|
415
|
+
const restrictDir = o.restrictDir ?? ((d) => restrictToUser(d, platform, true));
|
|
416
|
+
mkdirSync(dir, {
|
|
417
|
+
recursive: true,
|
|
418
|
+
mode: 448
|
|
419
|
+
});
|
|
420
|
+
const marker = join(dir, ".acl");
|
|
421
|
+
if (platform !== "win32") restrictDir(dir);
|
|
422
|
+
else if (!existsSync(marker)) {
|
|
423
|
+
restrictDir(dir);
|
|
424
|
+
writeFileSync(marker, "user-only ACL set\n");
|
|
425
|
+
}
|
|
426
|
+
return dir;
|
|
427
|
+
}
|
|
428
|
+
/** The identity stored at `path`, or undefined. Upgrades an old Windows key file's ACL once. */
|
|
429
|
+
function loadIdentity(path, o = {}) {
|
|
430
|
+
if (!existsSync(path)) return void 0;
|
|
431
|
+
const platform = o.platform ?? process.platform;
|
|
432
|
+
const restrict = o.restrict ?? ((f) => restrictToUser(f, platform));
|
|
433
|
+
const marker = `${path}.acl`;
|
|
434
|
+
const id = parseIdentity(JSON.parse(readFileSync(path, "utf8")));
|
|
435
|
+
if (platform === "win32") {
|
|
436
|
+
if (!existsSync(marker)) {
|
|
437
|
+
restrict(path);
|
|
438
|
+
writeFileSync(marker, "user-only ACL set\n");
|
|
439
|
+
}
|
|
440
|
+
} else restrict(path);
|
|
441
|
+
return id;
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* Write a new identity: a temporary file in the user-only staging directory, restricted to the
|
|
445
|
+
* user itself as well, then renamed into place (a rename on one volume keeps the file's ACL).
|
|
446
|
+
*/
|
|
447
|
+
function saveNewIdentity(path, id, o = {}) {
|
|
448
|
+
const platform = o.platform ?? process.platform;
|
|
449
|
+
const restrict = o.restrict ?? ((f) => restrictToUser(f, platform));
|
|
450
|
+
const tmp = join(keyStagingDir(path, o, platform), `${randomBytes(6).toString("hex")}.tmp`);
|
|
451
|
+
try {
|
|
452
|
+
writeFileSync(tmp, `${JSON.stringify(serializeIdentity(id))}\n`, {
|
|
453
|
+
mode: 384,
|
|
454
|
+
flag: "wx"
|
|
455
|
+
});
|
|
456
|
+
restrict(tmp);
|
|
457
|
+
renameRetrying(tmp, path);
|
|
458
|
+
} catch (e) {
|
|
459
|
+
rmSync(tmp, { force: true });
|
|
460
|
+
throw e;
|
|
461
|
+
}
|
|
462
|
+
if (platform === "win32") writeFileSync(`${path}.acl`, "user-only ACL set\n");
|
|
463
|
+
}
|
|
464
|
+
/** SQLite state of the relay client, in its own file so it never touches the session store. */
|
|
465
|
+
var RelayState = class {
|
|
466
|
+
path;
|
|
467
|
+
handle;
|
|
468
|
+
/**
|
|
469
|
+
* The file is created only when there is something to keep. Creating it (WAL mode and the
|
|
470
|
+
* schema) costs tens of milliseconds of disk syncs, which a daemon that never uses the relay
|
|
471
|
+
* should not pay at every start.
|
|
472
|
+
*/
|
|
473
|
+
constructor(path) {
|
|
474
|
+
this.path = path;
|
|
475
|
+
}
|
|
476
|
+
/** The open database, created on first write. */
|
|
477
|
+
get db() {
|
|
478
|
+
return this.handle ?? this.open();
|
|
479
|
+
}
|
|
480
|
+
/** The database for a read: undefined while the file does not exist, which reads as empty. */
|
|
481
|
+
get reader() {
|
|
482
|
+
return this.handle ?? (existsSync(this.path) ? this.open() : void 0);
|
|
483
|
+
}
|
|
484
|
+
open() {
|
|
485
|
+
const path = this.path;
|
|
486
|
+
const db = new DatabaseSync(path);
|
|
487
|
+
db.exec("PRAGMA journal_mode = WAL");
|
|
488
|
+
db.exec("PRAGMA synchronous = NORMAL");
|
|
489
|
+
db.exec("PRAGMA busy_timeout = 5000");
|
|
490
|
+
db.exec(`
|
|
491
|
+
BEGIN;
|
|
492
|
+
CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
493
|
+
CREATE TABLE IF NOT EXISTS seen (id TEXT PRIMARY KEY, ts INTEGER NOT NULL);
|
|
494
|
+
CREATE INDEX IF NOT EXISTS seen_ts ON seen (ts);
|
|
495
|
+
-- Messages from another device that arrived before its session list. Stored before the
|
|
496
|
+
-- envelope is acknowledged, so a restart or a flood cannot lose them.
|
|
497
|
+
CREATE TABLE IF NOT EXISTS held (
|
|
498
|
+
id TEXT PRIMARY KEY,
|
|
499
|
+
from_device TEXT NOT NULL,
|
|
500
|
+
payload TEXT NOT NULL,
|
|
501
|
+
since INTEGER NOT NULL
|
|
502
|
+
);
|
|
503
|
+
-- Local ids for sessions on other devices, so they can never collide with local ones.
|
|
504
|
+
CREATE TABLE IF NOT EXISTS alias (
|
|
505
|
+
alias TEXT PRIMARY KEY,
|
|
506
|
+
device_id TEXT NOT NULL,
|
|
507
|
+
remote_id TEXT NOT NULL,
|
|
508
|
+
UNIQUE (device_id, remote_id)
|
|
509
|
+
);
|
|
510
|
+
COMMIT;
|
|
511
|
+
`);
|
|
512
|
+
for (const f of [
|
|
513
|
+
path,
|
|
514
|
+
`${path}-wal`,
|
|
515
|
+
`${path}-shm`
|
|
516
|
+
]) restrictIfPresent(f);
|
|
517
|
+
this.handle = db;
|
|
518
|
+
return db;
|
|
519
|
+
}
|
|
520
|
+
close() {
|
|
521
|
+
this.handle?.close();
|
|
522
|
+
this.handle = void 0;
|
|
523
|
+
}
|
|
524
|
+
get(key) {
|
|
525
|
+
return (this.reader?.prepare("SELECT value FROM kv WHERE key = ?").get(key))?.value;
|
|
526
|
+
}
|
|
527
|
+
set(key, value) {
|
|
528
|
+
if (value === void 0) this.reader?.prepare("DELETE FROM kv WHERE key = ?").run(key);
|
|
529
|
+
else this.db.prepare("INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = ?").run(key, value, value);
|
|
530
|
+
}
|
|
531
|
+
/** The device list, or undefined when this device has none yet. Verified by the caller. */
|
|
532
|
+
chain() {
|
|
533
|
+
const raw = this.get("chain");
|
|
534
|
+
return raw === void 0 ? void 0 : JSON.parse(raw);
|
|
535
|
+
}
|
|
536
|
+
setChain(chain) {
|
|
537
|
+
this.set("chain", chain === void 0 ? void 0 : JSON.stringify(chain));
|
|
538
|
+
}
|
|
539
|
+
/** An unresolved disagreement about the device list, until the owner accepts a head. */
|
|
540
|
+
conflict() {
|
|
541
|
+
const raw = this.get("conflict");
|
|
542
|
+
return raw === void 0 ? void 0 : JSON.parse(raw);
|
|
543
|
+
}
|
|
544
|
+
setConflict(c) {
|
|
545
|
+
this.set("conflict", c === void 0 ? void 0 : JSON.stringify(c));
|
|
546
|
+
}
|
|
547
|
+
hold(id, from, payload, since) {
|
|
548
|
+
this.db.prepare("INSERT OR IGNORE INTO held (id, from_device, payload, since) VALUES (?, ?, ?, ?)").run(id, from, JSON.stringify(payload), since);
|
|
549
|
+
}
|
|
550
|
+
heldCount(from) {
|
|
551
|
+
return (this.reader?.prepare("SELECT COUNT(*) AS n FROM held WHERE from_device = ?").get(from))?.n ?? 0;
|
|
552
|
+
}
|
|
553
|
+
/** Held messages, oldest first; from one device, or all. */
|
|
554
|
+
held(from) {
|
|
555
|
+
const db = this.reader;
|
|
556
|
+
if (!db) return [];
|
|
557
|
+
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) => ({
|
|
558
|
+
id: r.id,
|
|
559
|
+
from: r.from_device,
|
|
560
|
+
payload: JSON.parse(r.payload),
|
|
561
|
+
since: r.since
|
|
562
|
+
}));
|
|
563
|
+
}
|
|
564
|
+
unhold(id) {
|
|
565
|
+
this.reader?.prepare("DELETE FROM held WHERE id = ?").run(id);
|
|
566
|
+
}
|
|
567
|
+
/** The local id for a session on another device, made on first use. */
|
|
568
|
+
alias(device, remote) {
|
|
569
|
+
const row = this.db.prepare("SELECT alias FROM alias WHERE device_id = ? AND remote_id = ?").get(device, remote);
|
|
570
|
+
if (row) return row.alias;
|
|
571
|
+
const id = newSessionId();
|
|
572
|
+
this.db.prepare("INSERT INTO alias (alias, device_id, remote_id) VALUES (?, ?, ?)").run(id, device, remote);
|
|
573
|
+
return id;
|
|
574
|
+
}
|
|
575
|
+
/** The device and remote id behind a local alias. */
|
|
576
|
+
unalias(alias) {
|
|
577
|
+
const row = this.reader?.prepare("SELECT device_id, remote_id FROM alias WHERE alias = ?").get(alias);
|
|
578
|
+
return row ? {
|
|
579
|
+
device: row.device_id,
|
|
580
|
+
remote: row.remote_id
|
|
581
|
+
} : void 0;
|
|
582
|
+
}
|
|
583
|
+
deviceName() {
|
|
584
|
+
return this.get("device_name");
|
|
585
|
+
}
|
|
586
|
+
setDeviceName(name) {
|
|
587
|
+
this.set("device_name", name);
|
|
588
|
+
}
|
|
589
|
+
/** Run `f` in one SQLite transaction: all of its writes happen, or none. */
|
|
590
|
+
atomically(f) {
|
|
591
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
592
|
+
try {
|
|
593
|
+
f();
|
|
594
|
+
this.db.exec("COMMIT");
|
|
595
|
+
} catch (e) {
|
|
596
|
+
this.db.exec("ROLLBACK");
|
|
597
|
+
throw e;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
has(id) {
|
|
601
|
+
return this.reader?.prepare("SELECT 1 AS x FROM seen WHERE id = ?").get(id) !== void 0;
|
|
602
|
+
}
|
|
603
|
+
add(id, ts) {
|
|
604
|
+
this.db.prepare("INSERT OR IGNORE INTO seen (id, ts) VALUES (?, ?)").run(id, ts);
|
|
605
|
+
}
|
|
606
|
+
/** Forget ids that are too old to be accepted again anyway. */
|
|
607
|
+
pruneSeen(nowMs) {
|
|
608
|
+
const before = nowMs - ENVELOPE_MAX_AGE_MS - ENVELOPE_MAX_FUTURE_MS;
|
|
609
|
+
this.reader?.prepare("DELETE FROM seen WHERE ts < ?").run(before);
|
|
610
|
+
}
|
|
611
|
+
};
|
|
612
|
+
// ../daemon/src/relay/hub.ts
|
|
613
|
+
/** Remote sessions not republished for this many publish periods are dropped. */
|
|
614
|
+
const REMOTE_EXPIRY_PERIODS = 3;
|
|
615
|
+
const PAIRING_TIMEOUT_MS = 3e5;
|
|
616
|
+
/** Wrong codes the owner may type before the pairing fails. */
|
|
617
|
+
const PAIR_CODE_ATTEMPTS = 3;
|
|
618
|
+
const MAX_BACKOFF_MS = 6e4;
|
|
619
|
+
/**
|
|
620
|
+
* Relay error codes after which retrying soon cannot help. `token_expired` is not one: the next
|
|
621
|
+
* attempt renews the token.
|
|
622
|
+
*/
|
|
623
|
+
const AUTH_CODES = /* @__PURE__ */ new Set([
|
|
624
|
+
"unauthorized",
|
|
625
|
+
"plan_required",
|
|
626
|
+
"device_key_mismatch",
|
|
627
|
+
"device_mismatch",
|
|
628
|
+
"device_revoked"
|
|
629
|
+
]);
|
|
630
|
+
/** Messages that arrive before the sending device's session list wait this long for it. */
|
|
631
|
+
const HELD_MESSAGES_PER_DEVICE = 50;
|
|
632
|
+
const HELD_MESSAGE_MS = 12e4;
|
|
633
|
+
/** Ids of messages sent to other devices, so only a bounce for one of them is accepted. */
|
|
634
|
+
const SENT_MAX = 1e3;
|
|
635
|
+
const SENT_MS = 864e5;
|
|
636
|
+
/** What the sender shows for each bounce reason. Peers send only the code. */
|
|
637
|
+
const BOUNCE_TEXT = {
|
|
638
|
+
session_gone: "the session no longer exists",
|
|
639
|
+
session_offline: "the session is offline",
|
|
640
|
+
mailbox_full: "the session has too many unread messages",
|
|
641
|
+
unknown_sender: "the receiving device did not recognize the sending session",
|
|
642
|
+
not_allowed: "this kind of message is not carried between devices"
|
|
643
|
+
};
|
|
644
|
+
/** A device name as the first part of a remote session name: `[a-z0-9][a-z0-9._-]{0,23}`. */
|
|
645
|
+
const deviceSlug = (s) => s.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[^a-z0-9]+/, "").slice(0, 24) || "device";
|
|
646
|
+
/**
|
|
647
|
+
* How a session on another device is named here: `<device>:<name>`. Local session names cannot
|
|
648
|
+
* contain `:`, so the two never collide, and no remote session can pose as a local one or as a
|
|
649
|
+
* reserved sender such as `conveno`.
|
|
650
|
+
*/
|
|
651
|
+
function remoteSessionName(session, device) {
|
|
652
|
+
return `${deviceSlug(device)}:${session}`;
|
|
653
|
+
}
|
|
654
|
+
const NOT_PRO = "The relay is part of Conveno Pro. This account is on the free plan.";
|
|
655
|
+
const sanitizeName = (n) => n.replace(/[^\p{L}\p{N}._ -]/gu, "").trim().slice(0, 64) || "device";
|
|
656
|
+
/**
|
|
657
|
+
* The relay client inside the daemon. It keeps the device identity and its copy of the signed
|
|
658
|
+
* device list, holds the WebSocket to the relay while this device is paired (or pairing),
|
|
659
|
+
* publishes the local sessions to the other devices, keeps theirs, and carries messages between
|
|
660
|
+
* them.
|
|
661
|
+
*
|
|
662
|
+
* The relay holds the account's device list and only accepts strict extensions of it, so the
|
|
663
|
+
* list is linear. This device adopts a list only from the relay, and only one that extends its
|
|
664
|
+
* own copy; changes it makes (a pairing, a revocation) count only once the relay accepted them.
|
|
665
|
+
* When the relay's list is not an extension of this device's, or another device's envelope
|
|
666
|
+
* carries a list head that does not fit this device's list, the hub records a conflict, warns, and
|
|
667
|
+
* sends nothing until the owner accepts the relay's head (`devices.accept`).
|
|
668
|
+
*/
|
|
669
|
+
var RelayHub = class {
|
|
670
|
+
o;
|
|
671
|
+
identity;
|
|
672
|
+
/** Where the identity is kept, and whether it is there yet. */
|
|
673
|
+
identityPath;
|
|
674
|
+
identitySaved;
|
|
675
|
+
state;
|
|
676
|
+
now;
|
|
677
|
+
url;
|
|
678
|
+
accessToken;
|
|
679
|
+
evaluating;
|
|
680
|
+
evaluateAgain = false;
|
|
681
|
+
connectImpl;
|
|
682
|
+
publishMs;
|
|
683
|
+
pairResendMs;
|
|
684
|
+
listTimeoutMs;
|
|
685
|
+
chain;
|
|
686
|
+
chainState;
|
|
687
|
+
/** The list the relay last sent, verified. */
|
|
688
|
+
relayChain;
|
|
689
|
+
/**
|
|
690
|
+
* Head and length of the relay's list. The relay sends the whole list only to its members; any
|
|
691
|
+
* other device, such as one being paired, gets just this.
|
|
692
|
+
*/
|
|
693
|
+
relayHead;
|
|
694
|
+
/** The relay's list has arrived since the connection became ready. */
|
|
695
|
+
listReceived = false;
|
|
696
|
+
conflict;
|
|
697
|
+
pendingList;
|
|
698
|
+
/** The relay refused this device because its list revokes it. */
|
|
699
|
+
relayRevoked = false;
|
|
700
|
+
sent = /* @__PURE__ */ new Map();
|
|
701
|
+
sessionSeq = /* @__PURE__ */ new Map();
|
|
702
|
+
publishSeq = 0;
|
|
703
|
+
link;
|
|
704
|
+
linkReady = false;
|
|
705
|
+
connState = "logged_out";
|
|
706
|
+
detail;
|
|
707
|
+
failures = 0;
|
|
708
|
+
/** The code of the last `error` frame, for the close that usually follows it. */
|
|
709
|
+
lastErrorCode;
|
|
710
|
+
online = /* @__PURE__ */ new Set();
|
|
711
|
+
remote = /* @__PURE__ */ new Map();
|
|
712
|
+
pairing;
|
|
713
|
+
timers = [];
|
|
714
|
+
retryTimer;
|
|
715
|
+
publishTimer;
|
|
716
|
+
stopped = false;
|
|
717
|
+
constructor(o) {
|
|
718
|
+
this.o = o;
|
|
719
|
+
const platform = o.platform ?? process.platform;
|
|
720
|
+
const paths = relayPaths((platform === "win32" ? win32 : posix).join, o.dataDir);
|
|
721
|
+
this.identityPath = paths.identity;
|
|
722
|
+
const stored = loadIdentity(paths.identity);
|
|
723
|
+
this.identity = stored ?? generateIdentity(newDeviceId());
|
|
724
|
+
this.identitySaved = stored !== void 0;
|
|
725
|
+
this.state = new RelayState(paths.database);
|
|
726
|
+
this.now = o.now ?? (() => /* @__PURE__ */ new Date());
|
|
727
|
+
this.url = o.relayUrl ?? process.env.CONVENO_RELAY_URL ?? "wss://relay.conveno.dev/v1/connect";
|
|
728
|
+
const accountFile = dataPaths(platform, o.dataDir).account;
|
|
729
|
+
this.accessToken = o.accessToken ?? (async (refresh, deviceId) => {
|
|
730
|
+
if (!refresh) return (await readAccountTokens(accountFile))?.accessToken ?? null;
|
|
731
|
+
const token = await currentAccessToken(accountFile);
|
|
732
|
+
if (token === null || jwtClaim(token, "did") === deviceId) return token;
|
|
733
|
+
return bindAccountDevice(accountFile, deviceId);
|
|
734
|
+
});
|
|
735
|
+
this.connectImpl = o.connect ?? ((c) => new RelayConnection(c));
|
|
736
|
+
this.publishMs = o.publishIntervalMs ?? 6e4;
|
|
737
|
+
this.pairResendMs = o.pairResendMs ?? 2e3;
|
|
738
|
+
this.listTimeoutMs = o.listTimeoutMs ?? 15e3;
|
|
739
|
+
this.conflict = this.state.conflict();
|
|
740
|
+
this.loadChain(this.state.chain());
|
|
741
|
+
this.state.pruneSeen(this.ms());
|
|
742
|
+
}
|
|
743
|
+
ms() {
|
|
744
|
+
return this.now().getTime();
|
|
745
|
+
}
|
|
746
|
+
deviceName() {
|
|
747
|
+
return this.state.deviceName() ?? sanitizeName(hostname());
|
|
748
|
+
}
|
|
749
|
+
record() {
|
|
750
|
+
return publicRecord(this.identity, this.deviceName());
|
|
751
|
+
}
|
|
752
|
+
loadChain(chain) {
|
|
753
|
+
if (!chain) {
|
|
754
|
+
this.chain = void 0;
|
|
755
|
+
this.chainState = void 0;
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
try {
|
|
759
|
+
this.chainState = verifyChain(chain);
|
|
760
|
+
this.chain = chain;
|
|
761
|
+
} catch (e) {
|
|
762
|
+
this.o.host.log.error("relay: the stored device list does not verify", e);
|
|
763
|
+
this.chain = void 0;
|
|
764
|
+
this.chainState = void 0;
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
setChain(chain) {
|
|
768
|
+
this.state.setChain(chain);
|
|
769
|
+
this.loadChain(chain);
|
|
770
|
+
for (const id of [...this.remote.keys()]) if (!this.member(id)) this.remote.delete(id);
|
|
771
|
+
}
|
|
772
|
+
/**
|
|
773
|
+
* An active device of the list other than this one. While there is a conflict about the list,
|
|
774
|
+
* none is: nothing is sent and nothing is accepted.
|
|
775
|
+
*/
|
|
776
|
+
member(deviceId) {
|
|
777
|
+
if (deviceId === this.identity.deviceId || this.conflict) return void 0;
|
|
778
|
+
return this.chainState?.members.get(deviceId);
|
|
779
|
+
}
|
|
780
|
+
isRevoked() {
|
|
781
|
+
return this.relayRevoked || (this.chainState?.revoked.has(this.identity.deviceId) ?? false);
|
|
782
|
+
}
|
|
783
|
+
paired() {
|
|
784
|
+
const s = this.chainState;
|
|
785
|
+
return !!s && s.members.has(this.identity.deviceId) && s.members.size > 1;
|
|
786
|
+
}
|
|
787
|
+
setConflict(kind, detail, peer) {
|
|
788
|
+
if (this.conflict) return;
|
|
789
|
+
const c = {
|
|
790
|
+
kind,
|
|
791
|
+
detail,
|
|
792
|
+
at: this.now().toISOString()
|
|
793
|
+
};
|
|
794
|
+
if (this.chain) c.local = chainHead(this.chain);
|
|
795
|
+
if (this.relayHead) c.relay = this.relayHead;
|
|
796
|
+
if (peer) c.peer = peer;
|
|
797
|
+
this.conflict = c;
|
|
798
|
+
this.state.setConflict(c);
|
|
799
|
+
this.remote.clear();
|
|
800
|
+
this.o.host.log.error("relay: device list conflict, nothing is sent until it is resolved", detail);
|
|
801
|
+
}
|
|
802
|
+
start() {
|
|
803
|
+
this.evaluate();
|
|
804
|
+
const t = setInterval(() => {
|
|
805
|
+
this.evaluate();
|
|
806
|
+
if (this.linkReady) this.publishAll();
|
|
807
|
+
this.expireRemote();
|
|
808
|
+
this.expireHeld();
|
|
809
|
+
}, this.publishMs);
|
|
810
|
+
t.unref();
|
|
811
|
+
this.timers.push(t);
|
|
812
|
+
const prune = setInterval(() => this.state.pruneSeen(this.ms()), 36e5);
|
|
813
|
+
prune.unref();
|
|
814
|
+
this.timers.push(prune);
|
|
815
|
+
}
|
|
816
|
+
stop() {
|
|
817
|
+
this.stopped = true;
|
|
818
|
+
for (const t of this.timers) clearInterval(t);
|
|
819
|
+
if (this.retryTimer) clearTimeout(this.retryTimer);
|
|
820
|
+
if (this.publishTimer) clearTimeout(this.publishTimer);
|
|
821
|
+
this.disconnect();
|
|
822
|
+
this.state.close();
|
|
823
|
+
}
|
|
824
|
+
/**
|
|
825
|
+
* Decide whether to be connected, and connect or disconnect. Called often; runs one check at a
|
|
826
|
+
* time and once more if asked meanwhile. The returned promise settles when the check is done.
|
|
827
|
+
*/
|
|
828
|
+
evaluate() {
|
|
829
|
+
if (this.evaluating) {
|
|
830
|
+
this.evaluateAgain = true;
|
|
831
|
+
return this.evaluating;
|
|
832
|
+
}
|
|
833
|
+
this.evaluating = (async () => {
|
|
834
|
+
do {
|
|
835
|
+
this.evaluateAgain = false;
|
|
138
836
|
try {
|
|
139
|
-
|
|
140
|
-
} catch {
|
|
141
|
-
|
|
142
|
-
rmSync(`${path}.1`, { force: true });
|
|
143
|
-
renameSync(path, `${path}.1`);
|
|
837
|
+
await this.evaluateOnce();
|
|
838
|
+
} catch (e) {
|
|
839
|
+
this.o.host.log.error("relay: state check failed", e);
|
|
144
840
|
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
841
|
+
} while (this.evaluateAgain && !this.stopped);
|
|
842
|
+
})().finally(() => {
|
|
843
|
+
this.evaluating = void 0;
|
|
844
|
+
});
|
|
845
|
+
return this.evaluating;
|
|
846
|
+
}
|
|
847
|
+
async evaluateOnce() {
|
|
848
|
+
if (this.stopped) return;
|
|
849
|
+
if (this.isRevoked()) return this.idle("revoked", "This device was removed from the device list.");
|
|
850
|
+
const want = this.paired() || this.pairingActive();
|
|
851
|
+
const self = this.identity.deviceId;
|
|
852
|
+
if (!want) {
|
|
853
|
+
const stored = await this.accessToken(false, self);
|
|
854
|
+
if (!stored) return this.idle("logged_out", "Not logged in. Run \"conveno login\".");
|
|
855
|
+
if (jwtClaim(stored, "plan") !== "pro") return this.idle("not_pro", NOT_PRO);
|
|
856
|
+
return this.idle("unpaired", "Pair this device first: \"conveno devices pair\".");
|
|
857
|
+
}
|
|
858
|
+
let token;
|
|
859
|
+
try {
|
|
860
|
+
token = await this.accessToken(true, self);
|
|
861
|
+
} catch (e) {
|
|
862
|
+
if (e instanceof AccountError && e.code === "session_expired") return this.idle("logged_out", `${e.message} Run "conveno login" again.`);
|
|
863
|
+
if (!this.link) {
|
|
864
|
+
this.connState = "disconnected";
|
|
865
|
+
this.detail = "Could not renew the access token. Retrying.";
|
|
866
|
+
}
|
|
867
|
+
return;
|
|
148
868
|
}
|
|
869
|
+
if (this.stopped) return;
|
|
870
|
+
if (!token) return this.idle("logged_out", "Not logged in. Run \"conveno login\".");
|
|
871
|
+
if (jwtClaim(token, "plan") !== "pro") return this.idle("not_pro", NOT_PRO);
|
|
872
|
+
if (this.link || this.retryTimer) return;
|
|
873
|
+
this.saveIdentity();
|
|
874
|
+
this.connState = "connecting";
|
|
875
|
+
this.detail = void 0;
|
|
876
|
+
const events = {
|
|
877
|
+
ready: (online) => this.onReady(online),
|
|
878
|
+
frame: (f) => this.onFrame(f),
|
|
879
|
+
down: (detail, code) => this.onDown(detail, code)
|
|
880
|
+
};
|
|
881
|
+
this.link = this.connectImpl({
|
|
882
|
+
url: this.url,
|
|
883
|
+
identity: this.identity,
|
|
884
|
+
token,
|
|
885
|
+
events
|
|
886
|
+
});
|
|
887
|
+
this.link.start();
|
|
888
|
+
}
|
|
889
|
+
saveIdentity() {
|
|
890
|
+
if (this.identitySaved) return;
|
|
891
|
+
saveNewIdentity(this.identityPath, this.identity);
|
|
892
|
+
this.identitySaved = true;
|
|
893
|
+
}
|
|
894
|
+
idle(state, detail) {
|
|
895
|
+
this.connState = state;
|
|
896
|
+
this.detail = detail;
|
|
897
|
+
this.disconnect();
|
|
898
|
+
}
|
|
899
|
+
disconnect() {
|
|
900
|
+
this.link?.stop();
|
|
901
|
+
this.link = void 0;
|
|
902
|
+
this.linkReady = false;
|
|
903
|
+
this.listReceived = false;
|
|
904
|
+
this.online.clear();
|
|
905
|
+
this.remote.clear();
|
|
906
|
+
this.failPendingList("The relay connection closed.");
|
|
907
|
+
}
|
|
908
|
+
onReady(online) {
|
|
909
|
+
this.linkReady = true;
|
|
910
|
+
this.listReceived = false;
|
|
911
|
+
this.failures = 0;
|
|
912
|
+
this.connState = "connected";
|
|
913
|
+
this.detail = void 0;
|
|
914
|
+
this.online.clear();
|
|
915
|
+
for (const d of online) this.online.add(d);
|
|
916
|
+
this.pairingTick();
|
|
917
|
+
}
|
|
918
|
+
onDown(detail, frameCode) {
|
|
919
|
+
const code = frameCode ?? this.lastErrorCode;
|
|
920
|
+
this.lastErrorCode = void 0;
|
|
921
|
+
this.link = void 0;
|
|
922
|
+
this.linkReady = false;
|
|
923
|
+
this.listReceived = false;
|
|
924
|
+
this.online.clear();
|
|
925
|
+
this.remote.clear();
|
|
926
|
+
this.failPendingList("The relay connection closed.");
|
|
927
|
+
if (this.stopped) return;
|
|
928
|
+
if (code === "device_revoked") {
|
|
929
|
+
this.relayRevoked = true;
|
|
930
|
+
this.idle("revoked", "The relay says the device list revokes this device.");
|
|
931
|
+
return;
|
|
932
|
+
}
|
|
933
|
+
this.connState = "disconnected";
|
|
934
|
+
this.detail = detail;
|
|
935
|
+
this.failures++;
|
|
936
|
+
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));
|
|
937
|
+
const delay = Math.round(backoff * (.5 + Math.random() / 2));
|
|
938
|
+
this.retryTimer = setTimeout(() => {
|
|
939
|
+
this.retryTimer = void 0;
|
|
940
|
+
this.evaluate();
|
|
941
|
+
}, delay);
|
|
942
|
+
this.retryTimer.unref();
|
|
943
|
+
}
|
|
944
|
+
onFrame(f) {
|
|
945
|
+
switch (f.t) {
|
|
946
|
+
case "list":
|
|
947
|
+
this.onRelayList(f.chain, f.head !== void 0 && f.length !== void 0 ? {
|
|
948
|
+
head: f.head,
|
|
949
|
+
length: f.length
|
|
950
|
+
} : void 0);
|
|
951
|
+
return;
|
|
952
|
+
case "envelope":
|
|
953
|
+
this.onEnvelope(f);
|
|
954
|
+
return;
|
|
955
|
+
case "presence":
|
|
956
|
+
if (f.online) {
|
|
957
|
+
this.online.add(f.deviceId);
|
|
958
|
+
if (this.listReceived) this.greet(f.deviceId);
|
|
959
|
+
} else {
|
|
960
|
+
this.online.delete(f.deviceId);
|
|
961
|
+
this.remote.delete(f.deviceId);
|
|
962
|
+
}
|
|
963
|
+
return;
|
|
964
|
+
case "pair":
|
|
965
|
+
this.onPair(f.fromDevice, f.toDevice, f.data);
|
|
966
|
+
return;
|
|
967
|
+
case "error":
|
|
968
|
+
this.detail = `The relay reported: ${f.message}`;
|
|
969
|
+
this.lastErrorCode = f.code;
|
|
970
|
+
if (f.code === "list_rejected") this.failPendingList(f.message);
|
|
971
|
+
return;
|
|
972
|
+
default: return;
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
/**
|
|
976
|
+
* The relay's list, after `ready` and whenever it changes. Adopted when it extends this
|
|
977
|
+
* device's list; anything else is a conflict. `headOnly` is what a device that is not a member
|
|
978
|
+
* of the relay's list gets instead of the list.
|
|
979
|
+
*/
|
|
980
|
+
onRelayList(raw, headOnly) {
|
|
981
|
+
let relay;
|
|
982
|
+
if (raw.length > 0) try {
|
|
983
|
+
verifyChain(raw);
|
|
984
|
+
relay = raw;
|
|
985
|
+
} catch {
|
|
986
|
+
this.setConflict("not_prefix", "The relay sent a device list that does not verify.");
|
|
987
|
+
}
|
|
988
|
+
this.relayChain = relay;
|
|
989
|
+
this.relayHead = relay ? chainHead(relay) : headOnly;
|
|
990
|
+
if (!relay && headOnly && this.chain && !this.conflict) this.setConflict("not_prefix", "The relay holds a device list that does not include this device.");
|
|
991
|
+
const pending = this.pendingList;
|
|
992
|
+
if (relay && pending && chainHead(relay).head === pending.head) {
|
|
993
|
+
this.setChain(relay);
|
|
994
|
+
this.pendingList = void 0;
|
|
995
|
+
clearTimeout(pending.timer);
|
|
996
|
+
pending.resolve();
|
|
997
|
+
} else if (this.chain && !this.conflict && !headOnly) {
|
|
998
|
+
const at = relay ? forkPoint(this.chain, relay) : 0;
|
|
999
|
+
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.");
|
|
1000
|
+
else if (relay.length > this.chain.length) this.setChain(relay);
|
|
1001
|
+
}
|
|
1002
|
+
if (this.isRevoked()) {
|
|
1003
|
+
this.evaluate();
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
1006
|
+
const first = !this.listReceived;
|
|
1007
|
+
this.listReceived = true;
|
|
1008
|
+
if (first) for (const d of this.online) this.greet(d);
|
|
1009
|
+
}
|
|
1010
|
+
/**
|
|
1011
|
+
* Ask the relay to store a new version of the list. Resolves once the relay accepted it (and
|
|
1012
|
+
* this device adopted it); rejects when the relay refuses it, does not answer, or the
|
|
1013
|
+
* connection drops.
|
|
1014
|
+
*/
|
|
1015
|
+
publishList(chain) {
|
|
1016
|
+
if (!this.link || !this.linkReady || !this.listReceived) return Promise.reject(/* @__PURE__ */ new Error("The relay is not connected."));
|
|
1017
|
+
if (this.pendingList) return Promise.reject(/* @__PURE__ */ new Error("Another device list change is waiting for the relay."));
|
|
1018
|
+
const { head } = chainHead(chain);
|
|
1019
|
+
return new Promise((resolve, reject) => {
|
|
1020
|
+
const timer = setTimeout(() => this.failPendingList("The relay did not answer."), this.listTimeoutMs);
|
|
1021
|
+
timer.unref();
|
|
1022
|
+
this.pendingList = {
|
|
1023
|
+
head,
|
|
1024
|
+
resolve,
|
|
1025
|
+
reject,
|
|
1026
|
+
timer
|
|
1027
|
+
};
|
|
1028
|
+
this.link?.send({
|
|
1029
|
+
t: "list",
|
|
1030
|
+
v: 1,
|
|
1031
|
+
chain
|
|
1032
|
+
});
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
failPendingList(why) {
|
|
1036
|
+
const p = this.pendingList;
|
|
1037
|
+
if (!p) return;
|
|
1038
|
+
this.pendingList = void 0;
|
|
1039
|
+
clearTimeout(p.timer);
|
|
1040
|
+
p.reject(new Error(why));
|
|
1041
|
+
}
|
|
1042
|
+
/** A device came online: send it our sessions. */
|
|
1043
|
+
greet(deviceId) {
|
|
1044
|
+
if (!this.member(deviceId)) return;
|
|
1045
|
+
this.publishTo(deviceId);
|
|
1046
|
+
}
|
|
1047
|
+
sendPayload(to, payload) {
|
|
1048
|
+
const recipient = this.member(to);
|
|
1049
|
+
if (!recipient || !this.chain || !this.link || !this.linkReady || !this.listReceived) return false;
|
|
1050
|
+
const env = sealEnvelope({
|
|
1051
|
+
sender: this.identity,
|
|
1052
|
+
recipient,
|
|
1053
|
+
id: newMessageId(),
|
|
1054
|
+
plaintext: new TextEncoder().encode(JSON.stringify(payload)),
|
|
1055
|
+
ts: this.ms(),
|
|
1056
|
+
list: chainHead(this.chain)
|
|
1057
|
+
});
|
|
1058
|
+
return this.link.send(env);
|
|
1059
|
+
}
|
|
1060
|
+
/**
|
|
1061
|
+
* An envelope from another device. It is acknowledged to the relay only after it was handled:
|
|
1062
|
+
* a message is in a local mailbox, or stored in relay.db to wait for its sender's session list.
|
|
1063
|
+
*/
|
|
1064
|
+
onEnvelope(env) {
|
|
1065
|
+
let pt;
|
|
1066
|
+
try {
|
|
1067
|
+
pt = openEnvelope(env, {
|
|
1068
|
+
self: this.identity,
|
|
1069
|
+
sender: (d) => this.member(d),
|
|
1070
|
+
replay: this.state,
|
|
1071
|
+
now: this.ms(),
|
|
1072
|
+
record: false
|
|
1073
|
+
});
|
|
1074
|
+
} catch {
|
|
1075
|
+
this.ack(env);
|
|
1076
|
+
return;
|
|
1077
|
+
}
|
|
1078
|
+
if (this.chain && !headMatches(this.chain, env.head, env.len)) {
|
|
1079
|
+
const name = this.chainState?.members.get(env.fromDevice)?.name ?? "another device";
|
|
1080
|
+
this.setConflict("split_view", `${name} holds a device list (length ${env.len}) that does not match this device's.`, {
|
|
1081
|
+
deviceId: env.fromDevice,
|
|
1082
|
+
name,
|
|
1083
|
+
head: env.head,
|
|
1084
|
+
length: env.len
|
|
1085
|
+
});
|
|
1086
|
+
this.state.add(env.id, env.ts);
|
|
1087
|
+
this.ack(env);
|
|
1088
|
+
return;
|
|
1089
|
+
}
|
|
1090
|
+
try {
|
|
1091
|
+
const json = JSON.parse(new TextDecoder().decode(pt));
|
|
1092
|
+
const r = safeParse(RelayPayload, json);
|
|
1093
|
+
this.state.atomically(() => {
|
|
1094
|
+
if (r.ok) this.onPayload(env.fromDevice, r.value, env.id);
|
|
1095
|
+
this.state.add(env.id, env.ts);
|
|
1096
|
+
});
|
|
1097
|
+
} catch (e) {
|
|
1098
|
+
this.o.host.log.error("relay: an envelope could not be handled", e);
|
|
1099
|
+
}
|
|
1100
|
+
this.ack(env);
|
|
1101
|
+
}
|
|
1102
|
+
ack(env) {
|
|
1103
|
+
this.link?.send({
|
|
1104
|
+
t: "ack",
|
|
1105
|
+
id: env.id
|
|
1106
|
+
});
|
|
1107
|
+
}
|
|
1108
|
+
onPayload(from, p, envelopeId) {
|
|
1109
|
+
switch (p.type) {
|
|
1110
|
+
case "sessions": {
|
|
1111
|
+
const last = this.sessionSeq.get(from);
|
|
1112
|
+
if (last !== void 0 && p.seq <= last) return;
|
|
1113
|
+
this.sessionSeq.set(from, p.seq);
|
|
1114
|
+
this.remote.set(from, {
|
|
1115
|
+
deviceName: p.deviceName,
|
|
1116
|
+
sessions: p.sessions.map((s) => ({
|
|
1117
|
+
...s,
|
|
1118
|
+
deviceId: from
|
|
1119
|
+
})),
|
|
1120
|
+
receivedAt: this.ms()
|
|
1121
|
+
});
|
|
1122
|
+
for (const h of this.state.held(from)) {
|
|
1123
|
+
this.state.unhold(h.id);
|
|
1124
|
+
const r = safeParse(RelayPayload, h.payload);
|
|
1125
|
+
if (r.ok && r.value.type === "message") this.onMessage(from, r.value, h.id, h.since);
|
|
1126
|
+
}
|
|
1127
|
+
return;
|
|
1128
|
+
}
|
|
1129
|
+
case "message":
|
|
1130
|
+
this.onMessage(from, p, envelopeId);
|
|
1131
|
+
return;
|
|
1132
|
+
case "bounce": {
|
|
1133
|
+
const sent = this.sent.get(p.messageId);
|
|
1134
|
+
if (!sent || sent.toDevice !== from || sent.toSession !== p.toSession || sent.fromSession !== p.fromSession) return;
|
|
1135
|
+
this.sent.delete(p.messageId);
|
|
1136
|
+
const device = this.chainState?.members.get(from)?.name ?? "another device";
|
|
1137
|
+
this.o.host.notify(sent.fromSession, "message.bounced", `Message ${p.messageId} to session "${sent.toName}" on ${device} was not delivered: ${BOUNCE_TEXT[p.reason]}.`);
|
|
1138
|
+
return;
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
/**
|
|
1143
|
+
* A message from a session on another device. It is delivered only when `from` is one of the
|
|
1144
|
+
* sessions that device publishes, and it is shown with a local alias id and the name
|
|
1145
|
+
* `<device>:<session>`, with the device name from the signed list, whatever the sender put in
|
|
1146
|
+
* the message. One that arrives before the device's session list is stored durably and waits.
|
|
1147
|
+
*/
|
|
1148
|
+
onMessage(from, p, id, since = this.ms()) {
|
|
1149
|
+
const r = this.remote.get(from);
|
|
1150
|
+
if (!r) {
|
|
1151
|
+
if (this.state.heldCount(from) >= HELD_MESSAGES_PER_DEVICE) {
|
|
1152
|
+
this.bounce(from, p, "unknown_sender");
|
|
1153
|
+
return;
|
|
1154
|
+
}
|
|
1155
|
+
this.state.hold(id, from, p, since);
|
|
1156
|
+
return;
|
|
1157
|
+
}
|
|
1158
|
+
const sender = r.sessions.find((s) => s.id === p.message.from);
|
|
1159
|
+
if (!sender) {
|
|
1160
|
+
this.bounce(from, p, "unknown_sender");
|
|
1161
|
+
return;
|
|
1162
|
+
}
|
|
1163
|
+
if (p.message.kind === "system") {
|
|
1164
|
+
this.bounce(from, p, "not_allowed");
|
|
1165
|
+
return;
|
|
1166
|
+
}
|
|
1167
|
+
const device = this.chainState?.members.get(from)?.name ?? r.deviceName;
|
|
1168
|
+
const message = {
|
|
1169
|
+
...p.message,
|
|
1170
|
+
from: this.state.alias(from, sender.id),
|
|
1171
|
+
to: p.toSession,
|
|
1172
|
+
fromName: remoteSessionName(sender.name, device),
|
|
1173
|
+
fromCli: sender.cli
|
|
1174
|
+
};
|
|
1175
|
+
const reason = this.o.host.deliverLocal(message, p.toSession);
|
|
1176
|
+
if (reason !== void 0) this.bounce(from, p, reason);
|
|
1177
|
+
}
|
|
1178
|
+
bounce(to, p, reason) {
|
|
1179
|
+
this.sendPayload(to, {
|
|
1180
|
+
type: "bounce",
|
|
1181
|
+
messageId: p.message.id,
|
|
1182
|
+
toSession: p.toSession,
|
|
1183
|
+
fromSession: p.message.from,
|
|
1184
|
+
reason
|
|
1185
|
+
});
|
|
1186
|
+
}
|
|
1187
|
+
expireHeld() {
|
|
1188
|
+
const now = this.ms();
|
|
1189
|
+
for (const h of this.state.held()) {
|
|
1190
|
+
if (now - h.since <= HELD_MESSAGE_MS) continue;
|
|
1191
|
+
this.state.unhold(h.id);
|
|
1192
|
+
const r = safeParse(RelayPayload, h.payload);
|
|
1193
|
+
if (r.ok && r.value.type === "message") this.bounce(h.from, r.value, "unknown_sender");
|
|
1194
|
+
}
|
|
1195
|
+
for (const [id, m] of this.sent) if (now - m.at > SENT_MS) this.sent.delete(id);
|
|
1196
|
+
}
|
|
1197
|
+
/** Called by the daemon whenever a local session changed. Publishes shortly after. */
|
|
1198
|
+
sessionsChanged() {
|
|
1199
|
+
if (!this.linkReady || this.publishTimer) return;
|
|
1200
|
+
this.publishTimer = setTimeout(() => {
|
|
1201
|
+
this.publishTimer = void 0;
|
|
1202
|
+
this.publishAll();
|
|
1203
|
+
}, 300);
|
|
1204
|
+
this.publishTimer.unref();
|
|
1205
|
+
}
|
|
1206
|
+
publishTo(deviceId) {
|
|
1207
|
+
const sessions = this.o.host.localSessions().filter((s) => !s.remote).map((s) => {
|
|
1208
|
+
const { pid: _p, hostPid: _h, hostPids: _hs, remote: _r, deviceName: _d, ...rest } = s;
|
|
1209
|
+
return {
|
|
1210
|
+
...rest,
|
|
1211
|
+
deviceId: this.identity.deviceId
|
|
1212
|
+
};
|
|
1213
|
+
});
|
|
1214
|
+
this.publishSeq = Math.max(this.publishSeq + 1, this.ms());
|
|
1215
|
+
this.sendPayload(deviceId, {
|
|
1216
|
+
type: "sessions",
|
|
1217
|
+
deviceName: this.deviceName(),
|
|
1218
|
+
seq: this.publishSeq,
|
|
1219
|
+
sessions
|
|
1220
|
+
});
|
|
1221
|
+
}
|
|
1222
|
+
publishAll() {
|
|
1223
|
+
if (!this.listReceived) return;
|
|
1224
|
+
for (const d of this.online) this.publishTo(d);
|
|
1225
|
+
}
|
|
1226
|
+
expireRemote() {
|
|
1227
|
+
const cutoff = this.ms() - REMOTE_EXPIRY_PERIODS * this.publishMs;
|
|
1228
|
+
for (const [id, r] of this.remote) if (r.receivedAt < cutoff) this.remote.delete(id);
|
|
1229
|
+
}
|
|
1230
|
+
/**
|
|
1231
|
+
* Sessions on the other devices, as `session.list` shows them: a local alias id and the name
|
|
1232
|
+
* `<device>:<name>`, so none can collide with a local session.
|
|
1233
|
+
*/
|
|
1234
|
+
remoteSessions(filter = {}) {
|
|
1235
|
+
const out = [];
|
|
1236
|
+
for (const [deviceId, r] of this.remote) {
|
|
1237
|
+
if (!this.member(deviceId)) continue;
|
|
1238
|
+
const device = this.chainState?.members.get(deviceId)?.name ?? r.deviceName;
|
|
1239
|
+
for (const s of r.sessions) {
|
|
1240
|
+
if (filter.cli && s.cli !== filter.cli) continue;
|
|
1241
|
+
const root = s.repo?.root;
|
|
1242
|
+
if (filter.repo && root !== filter.repo && baseName(root ?? s.cwd) !== filter.repo) continue;
|
|
1243
|
+
out.push({
|
|
1244
|
+
...s,
|
|
1245
|
+
id: this.state.alias(deviceId, s.id),
|
|
1246
|
+
name: remoteSessionName(s.name, device),
|
|
1247
|
+
deviceId,
|
|
1248
|
+
remote: true,
|
|
1249
|
+
deviceName: device
|
|
1250
|
+
});
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
return out;
|
|
1254
|
+
}
|
|
1255
|
+
/** A remote session by its local alias id or its full `<device>:<name>`. */
|
|
1256
|
+
resolveRemote(to) {
|
|
1257
|
+
const all = this.remoteSessions().filter((s) => s.status !== "offline");
|
|
1258
|
+
return all.find((s) => s.id === to) ?? all.find((s) => s.name === to);
|
|
1259
|
+
}
|
|
1260
|
+
/** Send a message to a session on another device. Throws when that cannot be done now. */
|
|
1261
|
+
sendRemote(target, message) {
|
|
1262
|
+
if (this.conflict) throw new ConvenoError(RpcErrorCode.Conflict, "The device list has a conflict, so nothing is sent to other devices. Run \"conveno devices\".");
|
|
1263
|
+
const real = this.state.unalias(target.id);
|
|
1264
|
+
if (!real) throw new ConvenoError(RpcErrorCode.NotFound, `No session "${target.name}".`);
|
|
1265
|
+
if (!this.sendPayload(real.device, {
|
|
1266
|
+
type: "message",
|
|
1267
|
+
toSession: real.remote,
|
|
1268
|
+
message
|
|
1269
|
+
})) throw new ConvenoError(RpcErrorCode.NotFound, `Session "${target.name}" is on ${target.deviceName ?? "another device"}, and the relay is not connected. Run "conveno relay status".`);
|
|
1270
|
+
this.sent.set(message.id, {
|
|
1271
|
+
fromSession: message.from,
|
|
1272
|
+
toDevice: real.device,
|
|
1273
|
+
toSession: real.remote,
|
|
1274
|
+
toName: target.name,
|
|
1275
|
+
at: this.ms()
|
|
1276
|
+
});
|
|
1277
|
+
if (this.sent.size > SENT_MAX) {
|
|
1278
|
+
const oldest = this.sent.keys().next().value;
|
|
1279
|
+
if (oldest !== void 0) this.sent.delete(oldest);
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
async status() {
|
|
1283
|
+
await this.evaluating;
|
|
1284
|
+
const self = this.record();
|
|
1285
|
+
const out = {
|
|
1286
|
+
state: this.connState,
|
|
1287
|
+
relayUrl: this.url,
|
|
1288
|
+
device: {
|
|
1289
|
+
deviceId: self.deviceId,
|
|
1290
|
+
name: self.name,
|
|
1291
|
+
fingerprint: deviceFingerprint(self)
|
|
1292
|
+
},
|
|
1293
|
+
peers: this.deviceInfos().filter((d) => !d.self)
|
|
1294
|
+
};
|
|
1295
|
+
if (this.detail !== void 0) out.detail = this.detail;
|
|
1296
|
+
if (this.chain) out.list = chainHead(this.chain);
|
|
1297
|
+
if (this.conflict) out.conflict = this.conflict;
|
|
1298
|
+
return out;
|
|
1299
|
+
}
|
|
1300
|
+
deviceInfos() {
|
|
1301
|
+
const s = this.chainState;
|
|
1302
|
+
if (!s?.members.has(this.identity.deviceId)) {
|
|
1303
|
+
const self = this.record();
|
|
1304
|
+
return [{
|
|
1305
|
+
deviceId: self.deviceId,
|
|
1306
|
+
name: self.name,
|
|
1307
|
+
fingerprint: deviceFingerprint(self),
|
|
1308
|
+
self: true,
|
|
1309
|
+
online: this.linkReady,
|
|
1310
|
+
sessions: 0
|
|
1311
|
+
}];
|
|
1312
|
+
}
|
|
1313
|
+
return [...s.members.values()].map((m) => {
|
|
1314
|
+
const self = m.deviceId === this.identity.deviceId;
|
|
1315
|
+
return {
|
|
1316
|
+
deviceId: m.deviceId,
|
|
1317
|
+
name: m.name,
|
|
1318
|
+
fingerprint: deviceFingerprint(m),
|
|
1319
|
+
self,
|
|
1320
|
+
online: self ? this.linkReady : this.online.has(m.deviceId),
|
|
1321
|
+
sessions: self ? 0 : this.remote.get(m.deviceId)?.sessions.length ?? 0,
|
|
1322
|
+
addedAt: new Date(m.addedAt).toISOString(),
|
|
1323
|
+
addedBy: m.addedBy
|
|
1324
|
+
};
|
|
1325
|
+
});
|
|
1326
|
+
}
|
|
1327
|
+
devices() {
|
|
1328
|
+
const revoked = [...this.chainState?.revoked.entries() ?? []].map(([id, r]) => ({
|
|
1329
|
+
deviceId: id,
|
|
1330
|
+
name: r.device.name,
|
|
1331
|
+
revokedAt: new Date(r.revokedAt).toISOString(),
|
|
1332
|
+
revokedBy: r.by
|
|
1333
|
+
}));
|
|
1334
|
+
const out = {
|
|
1335
|
+
devices: this.deviceInfos(),
|
|
1336
|
+
revoked
|
|
1337
|
+
};
|
|
1338
|
+
if (this.chain) out.list = chainHead(this.chain);
|
|
1339
|
+
if (this.conflict) out.conflict = this.conflict;
|
|
1340
|
+
return out;
|
|
1341
|
+
}
|
|
1342
|
+
/**
|
|
1343
|
+
* Recover from a conflict: adopt the relay's list, but only if its head is the one the owner
|
|
1344
|
+
* read on a device that is a member of it.
|
|
1345
|
+
*/
|
|
1346
|
+
accept(p) {
|
|
1347
|
+
if (!this.conflict) throw new ConvenoError(RpcErrorCode.Conflict, "The device list has no conflict.");
|
|
1348
|
+
const relay = this.relayChain;
|
|
1349
|
+
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.");
|
|
1350
|
+
const head = chainHead(relay);
|
|
1351
|
+
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.`);
|
|
1352
|
+
this.conflict = void 0;
|
|
1353
|
+
this.state.setConflict(void 0);
|
|
1354
|
+
this.setChain(relay);
|
|
1355
|
+
const member = this.chainState?.members.has(this.identity.deviceId) ?? false;
|
|
1356
|
+
if (this.linkReady && this.listReceived) for (const d of this.online) this.greet(d);
|
|
1357
|
+
this.evaluate();
|
|
1358
|
+
return {
|
|
1359
|
+
list: head,
|
|
1360
|
+
member
|
|
1361
|
+
};
|
|
1362
|
+
}
|
|
1363
|
+
rename(p) {
|
|
1364
|
+
const name = sanitizeName(p.name);
|
|
1365
|
+
this.state.setDeviceName(name);
|
|
1366
|
+
return { name };
|
|
1367
|
+
}
|
|
1368
|
+
/**
|
|
1369
|
+
* Revoke a device: append the revocation, and once the relay has accepted it (which also cuts
|
|
1370
|
+
* the device off at the relay), tell the account service to end the device's sessions.
|
|
1371
|
+
*/
|
|
1372
|
+
async revoke(p) {
|
|
1373
|
+
if (this.conflict) throw new ConvenoError(RpcErrorCode.Conflict, "The device list has a conflict. Run \"conveno devices\" to resolve it first.");
|
|
1374
|
+
const s = this.chainState;
|
|
1375
|
+
if (!this.chain || !s?.members.has(this.identity.deviceId)) throw new ConvenoError(RpcErrorCode.NotFound, "This device has no device list yet.");
|
|
1376
|
+
const byId = s.members.get(p.device);
|
|
1377
|
+
const byName = [...s.members.values()].filter((m) => m.name === p.device);
|
|
1378
|
+
if (!byId && byName.length > 1) throw new ConvenoError(RpcErrorCode.Conflict, `Several devices are named "${p.device}". Revoke by device id instead.`);
|
|
1379
|
+
const target = byId ?? byName[0];
|
|
1380
|
+
if (!target) throw new ConvenoError(RpcErrorCode.NotFound, `No active device "${p.device}". Run "conveno devices" to list them.`);
|
|
1381
|
+
let next;
|
|
1382
|
+
try {
|
|
1383
|
+
next = appendRevoke(this.chain, this.identity, target.deviceId, this.ms());
|
|
1384
|
+
} catch (e) {
|
|
1385
|
+
throw new ConvenoError(RpcErrorCode.InvalidParams, e.message);
|
|
1386
|
+
}
|
|
1387
|
+
try {
|
|
1388
|
+
await this.publishList(next);
|
|
1389
|
+
} catch (e) {
|
|
1390
|
+
throw new ConvenoError(RpcErrorCode.Conflict, `The relay did not accept the revocation: ${e.message} Nothing was changed.`);
|
|
1391
|
+
}
|
|
1392
|
+
this.remote.delete(target.deviceId);
|
|
1393
|
+
return { revoked: {
|
|
1394
|
+
deviceId: target.deviceId,
|
|
1395
|
+
name: target.name
|
|
1396
|
+
} };
|
|
1397
|
+
}
|
|
1398
|
+
/**
|
|
1399
|
+
* Forget this device's copy of the list after the owner reset the account's devices, or when
|
|
1400
|
+
* the relay's list no longer includes it. The device is then unpaired and can pair again.
|
|
1401
|
+
*/
|
|
1402
|
+
reset() {
|
|
1403
|
+
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.");
|
|
1404
|
+
this.conflict = void 0;
|
|
1405
|
+
this.state.setConflict(void 0);
|
|
1406
|
+
this.state.setChain(void 0);
|
|
1407
|
+
this.loadChain(void 0);
|
|
1408
|
+
this.relayRevoked = false;
|
|
1409
|
+
this.remote.clear();
|
|
1410
|
+
this.disconnect();
|
|
1411
|
+
this.evaluate();
|
|
1412
|
+
return { reset: true };
|
|
1413
|
+
}
|
|
1414
|
+
pairingActive() {
|
|
1415
|
+
const p = this.pairing;
|
|
1416
|
+
return !!p && p.state !== "done" && p.state !== "failed";
|
|
1417
|
+
}
|
|
1418
|
+
async pairStart(p) {
|
|
1419
|
+
if (this.isRevoked()) throw new ConvenoError(RpcErrorCode.Conflict, "This device was removed from the device list.");
|
|
1420
|
+
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.");
|
|
1421
|
+
if (this.conflict) throw new ConvenoError(RpcErrorCode.Conflict, "The device list has a conflict. Run \"conveno devices\" and resolve it first.");
|
|
1422
|
+
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.");
|
|
1423
|
+
if (this.pairingActive()) this.failPairing("Replaced by a new pairing.");
|
|
1424
|
+
this.saveIdentity();
|
|
1425
|
+
const record = this.record();
|
|
1426
|
+
const pairing = {
|
|
1427
|
+
id: newMessageId(),
|
|
1428
|
+
role: p.role,
|
|
1429
|
+
state: "waiting",
|
|
1430
|
+
localConfirmed: false,
|
|
1431
|
+
createdAt: this.ms(),
|
|
1432
|
+
wrongCodes: 0
|
|
1433
|
+
};
|
|
1434
|
+
if (p.role === "join") {
|
|
1435
|
+
pairing.joiner = new JoinerPairing(this.identity, record);
|
|
1436
|
+
pairing.resend = { message: pairing.joiner.commit() };
|
|
1437
|
+
} else pairing.inviter = new InviterPairing(this.identity, record);
|
|
1438
|
+
this.pairing = pairing;
|
|
1439
|
+
await this.evaluate();
|
|
1440
|
+
if (this.connState === "logged_out" || this.connState === "not_pro") {
|
|
1441
|
+
const detail = this.detail ?? "Cannot pair now.";
|
|
1442
|
+
this.failPairing(detail, false);
|
|
1443
|
+
throw new ConvenoError(RpcErrorCode.PermissionRequired, detail);
|
|
1444
|
+
}
|
|
1445
|
+
const tick = setInterval(() => this.pairingTick(), this.pairResendMs);
|
|
1446
|
+
tick.unref();
|
|
1447
|
+
this.timers.push(tick);
|
|
1448
|
+
this.pairingTick();
|
|
1449
|
+
return this.pairStatus({ pairingId: pairing.id });
|
|
1450
|
+
}
|
|
1451
|
+
pairingTick() {
|
|
1452
|
+
const p = this.pairing;
|
|
1453
|
+
if (!p || !this.pairingActive()) return;
|
|
1454
|
+
if (this.ms() - p.createdAt > PAIRING_TIMEOUT_MS) {
|
|
1455
|
+
this.failPairing("Pairing timed out. Start it again on both devices.");
|
|
1456
|
+
return;
|
|
1457
|
+
}
|
|
1458
|
+
if (p.resend) this.sendPair(p.resend.message, p.resend.to);
|
|
1459
|
+
}
|
|
1460
|
+
sendPair(m, to) {
|
|
1461
|
+
if (!this.link || !this.linkReady) return;
|
|
1462
|
+
this.link.send({
|
|
1463
|
+
t: "pair",
|
|
1464
|
+
v: 1,
|
|
1465
|
+
fromDevice: this.identity.deviceId,
|
|
1466
|
+
...to ? { toDevice: to } : {},
|
|
1467
|
+
data: encodePairMessage(m)
|
|
1468
|
+
});
|
|
1469
|
+
}
|
|
1470
|
+
failPairing(error, notify = true) {
|
|
1471
|
+
const p = this.pairing;
|
|
1472
|
+
if (!p) return;
|
|
1473
|
+
const pairingId = p.joiner?.pairingId ?? p.inviter?.pairingId;
|
|
1474
|
+
if (notify && p.peerDevice && pairingId) this.sendPair({
|
|
1475
|
+
type: "abort",
|
|
1476
|
+
pairingId,
|
|
1477
|
+
reason: error.slice(0, 200)
|
|
1478
|
+
}, p.peerDevice);
|
|
1479
|
+
p.state = "failed";
|
|
1480
|
+
p.error = error;
|
|
1481
|
+
p.resend = void 0;
|
|
1482
|
+
this.evaluate();
|
|
1483
|
+
}
|
|
1484
|
+
onPair(from, to, data) {
|
|
1485
|
+
const p = this.pairing;
|
|
1486
|
+
if (!p) return;
|
|
1487
|
+
if (to !== void 0 && to !== this.identity.deviceId) return;
|
|
1488
|
+
let m;
|
|
1489
|
+
try {
|
|
1490
|
+
m = decodePairMessage(data);
|
|
1491
|
+
} catch {
|
|
1492
|
+
return;
|
|
1493
|
+
}
|
|
1494
|
+
if (m.type === "abort") {
|
|
1495
|
+
if (from === p.peerDevice && p.state !== "done") this.failPairing(`The other device stopped: ${m.reason}`, false);
|
|
1496
|
+
return;
|
|
1497
|
+
}
|
|
1498
|
+
try {
|
|
1499
|
+
if (p.inviter) this.onPairAsInviter(p, p.inviter, from, m);
|
|
1500
|
+
else if (p.joiner) this.onPairAsJoiner(p, p.joiner, from, m);
|
|
1501
|
+
} catch (e) {
|
|
1502
|
+
if (p.state === "done") return;
|
|
1503
|
+
this.failPairing(e instanceof CryptoError ? e.message : "Pairing failed.");
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
onPairAsInviter(p, inv, from, m) {
|
|
1507
|
+
if (m.type === "commit") {
|
|
1508
|
+
if (this.chainState?.members.has(from) || this.chainState?.revoked.has(from) || !this.online.has(from)) return;
|
|
1509
|
+
if (inv.pairingId === void 0 && p.state === "waiting") {
|
|
1510
|
+
p.offer = inv.onCommit(m);
|
|
1511
|
+
p.peerDevice = from;
|
|
1512
|
+
this.sendPair(p.offer, from);
|
|
1513
|
+
} else if (m.pairingId === inv.pairingId && from === p.peerDevice && p.offer) this.sendPair(p.offer, from);
|
|
1514
|
+
return;
|
|
1515
|
+
}
|
|
1516
|
+
if (from !== p.peerDevice || m.pairingId !== inv.pairingId) return;
|
|
1517
|
+
if (m.type === "reveal") {
|
|
1518
|
+
const key = JSON.stringify(m);
|
|
1519
|
+
if (p.lastReveal === key) return;
|
|
1520
|
+
inv.onReveal(m);
|
|
1521
|
+
p.lastReveal = key;
|
|
1522
|
+
if (p.state === "waiting") p.state = "confirm";
|
|
1523
|
+
} else if (m.type === "confirm") {
|
|
1524
|
+
if (p.state === "done" && p.welcome) {
|
|
1525
|
+
this.sendPair(p.welcome, from);
|
|
1526
|
+
return;
|
|
1527
|
+
}
|
|
1528
|
+
if (inv.joinerHasConfirmed) return;
|
|
1529
|
+
inv.onConfirm(m);
|
|
1530
|
+
if (p.localConfirmed) this.finishInvite(p, inv);
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
onPairAsJoiner(p, j, from, m) {
|
|
1534
|
+
if (m.pairingId !== j.pairingId) return;
|
|
1535
|
+
if (m.type === "offer") {
|
|
1536
|
+
if (p.peerDevice !== void 0) return;
|
|
1537
|
+
const reveal = j.onOffer(m);
|
|
1538
|
+
p.peerDevice = from;
|
|
1539
|
+
p.state = "confirm";
|
|
1540
|
+
p.resend = {
|
|
1541
|
+
to: from,
|
|
1542
|
+
message: reveal
|
|
1543
|
+
};
|
|
1544
|
+
this.sendPair(reveal, from);
|
|
1545
|
+
} else if (m.type === "welcome" && from === p.peerDevice && p.localConfirmed) {
|
|
1546
|
+
if (p.state === "done") return;
|
|
1547
|
+
const { chain } = j.onWelcome(m);
|
|
1548
|
+
const relay = this.relayChain;
|
|
1549
|
+
const { head, length } = chainHead(chain);
|
|
1550
|
+
let adopt;
|
|
1551
|
+
if (relay) {
|
|
1552
|
+
if (headMatches(relay, head, length)) adopt = relay;
|
|
1553
|
+
} else if (this.relayHead?.head === head && this.relayHead.length === length) adopt = chain;
|
|
1554
|
+
if (!adopt) {
|
|
1555
|
+
this.failPairing("The relay does not hold the device list the other device sent.");
|
|
1556
|
+
return;
|
|
1557
|
+
}
|
|
1558
|
+
if (!verifyChain(adopt).members.has(this.identity.deviceId)) {
|
|
1559
|
+
this.failPairing("The relay's device list does not include this device.");
|
|
1560
|
+
return;
|
|
1561
|
+
}
|
|
1562
|
+
this.setChain(adopt);
|
|
1563
|
+
p.state = "done";
|
|
1564
|
+
p.resend = void 0;
|
|
1565
|
+
this.evaluate();
|
|
1566
|
+
for (const d of this.online) this.greet(d);
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
/**
|
|
1570
|
+
* Both owners typed the right codes: add the joiner to the list, and once the relay has
|
|
1571
|
+
* accepted the new list, send the joiner its welcome.
|
|
1572
|
+
*/
|
|
1573
|
+
async finishInvite(p, inv) {
|
|
1574
|
+
if (p.finishing || p.state === "done") return;
|
|
1575
|
+
p.finishing = true;
|
|
1576
|
+
p.state = "waiting_peer";
|
|
1577
|
+
try {
|
|
1578
|
+
const { chain, message } = inv.welcome(this.chain, this.ms());
|
|
1579
|
+
await this.publishList(chain);
|
|
1580
|
+
p.welcome = message;
|
|
1581
|
+
p.state = "done";
|
|
1582
|
+
p.resend = void 0;
|
|
1583
|
+
if (p.peerDevice) this.sendPair(message, p.peerDevice);
|
|
1584
|
+
if (p.peerDevice && this.online.has(p.peerDevice)) this.publishTo(p.peerDevice);
|
|
1585
|
+
this.evaluate();
|
|
1586
|
+
} catch (e) {
|
|
1587
|
+
this.failPairing(e instanceof CryptoError ? e.message : `The relay did not accept the new device list: ${e.message}`);
|
|
1588
|
+
} finally {
|
|
1589
|
+
p.finishing = false;
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
pairStatus(q) {
|
|
1593
|
+
const p = this.pairing;
|
|
1594
|
+
if (!p || p.id !== q.pairingId) throw new ConvenoError(RpcErrorCode.NotFound, "No pairing with that id. Start one again.");
|
|
1595
|
+
const flow = p.inviter ?? p.joiner;
|
|
1596
|
+
const out = {
|
|
1597
|
+
pairingId: p.id,
|
|
1598
|
+
role: p.role,
|
|
1599
|
+
state: p.state
|
|
1600
|
+
};
|
|
1601
|
+
const sas = flow?.sas;
|
|
1602
|
+
if (sas !== void 0 && p.state !== "failed") out.sas = sas;
|
|
1603
|
+
const peer = flow?.peer;
|
|
1604
|
+
if (peer) out.peer = {
|
|
1605
|
+
deviceId: peer.deviceId,
|
|
1606
|
+
name: peer.name,
|
|
1607
|
+
fingerprint: deviceFingerprint(peer)
|
|
1608
|
+
};
|
|
1609
|
+
if (p.error !== void 0) out.error = p.error;
|
|
1610
|
+
if (p.state === "waiting" && this.connState !== "connected") out.error = this.detail ?? "Connecting to the relay.";
|
|
1611
|
+
return out;
|
|
1612
|
+
}
|
|
1613
|
+
pairConfirm(q) {
|
|
1614
|
+
const p = this.pairing;
|
|
1615
|
+
if (!p || p.id !== q.pairingId) throw new ConvenoError(RpcErrorCode.NotFound, "No pairing with that id. Start one again.");
|
|
1616
|
+
if (p.state !== "confirm") throw new ConvenoError(RpcErrorCode.Conflict, `The pairing is "${p.state}", not waiting for a confirmation.`);
|
|
1617
|
+
if (!q.accept) {
|
|
1618
|
+
this.failPairing("The owner stopped the pairing.");
|
|
1619
|
+
return this.pairStatus(q);
|
|
1620
|
+
}
|
|
1621
|
+
const expected = (p.inviter ?? p.joiner)?.peerSas;
|
|
1622
|
+
if (!expected || q.code === void 0 || !sasMatches(expected, q.code)) {
|
|
1623
|
+
p.wrongCodes++;
|
|
1624
|
+
if (p.wrongCodes >= PAIR_CODE_ATTEMPTS) {
|
|
1625
|
+
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.");
|
|
1626
|
+
return this.pairStatus(q);
|
|
1627
|
+
}
|
|
1628
|
+
const left = PAIR_CODE_ATTEMPTS - p.wrongCodes;
|
|
1629
|
+
return {
|
|
1630
|
+
...this.pairStatus(q),
|
|
1631
|
+
error: `That is not the code the other device shows. ${left} ${left === 1 ? "try" : "tries"} left.`
|
|
1632
|
+
};
|
|
1633
|
+
}
|
|
1634
|
+
p.localConfirmed = true;
|
|
1635
|
+
if (p.inviter) {
|
|
1636
|
+
if (p.inviter.joinerHasConfirmed) this.finishInvite(p, p.inviter);
|
|
1637
|
+
else p.state = "waiting_peer";
|
|
1638
|
+
} else if (p.joiner && p.peerDevice) {
|
|
1639
|
+
const confirm = p.joiner.confirm();
|
|
1640
|
+
p.state = "waiting_peer";
|
|
1641
|
+
p.resend = {
|
|
1642
|
+
to: p.peerDevice,
|
|
1643
|
+
message: confirm
|
|
1644
|
+
};
|
|
1645
|
+
this.sendPair(confirm, p.peerDevice);
|
|
1646
|
+
}
|
|
1647
|
+
return this.pairStatus(q);
|
|
1648
|
+
}
|
|
1649
|
+
};
|
|
1650
|
+
// ../daemon/src/tickets-store.ts
|
|
1651
|
+
/** Tickets, and the sessions whose permission relay is on. */
|
|
1652
|
+
const TICKET_MIGRATION = {
|
|
1653
|
+
name: "006_tickets",
|
|
1654
|
+
sql: `
|
|
1655
|
+
CREATE TABLE tickets (
|
|
1656
|
+
id TEXT PRIMARY KEY,
|
|
1657
|
+
from_session TEXT NOT NULL,
|
|
1658
|
+
to_session TEXT NOT NULL,
|
|
1659
|
+
-- 'orchestrator' when it was addressed to the role, else the session id.
|
|
1660
|
+
to_ref TEXT NOT NULL,
|
|
1661
|
+
kind TEXT NOT NULL,
|
|
1662
|
+
question TEXT NOT NULL,
|
|
1663
|
+
options TEXT,
|
|
1664
|
+
status TEXT NOT NULL,
|
|
1665
|
+
answer TEXT,
|
|
1666
|
+
answered_by TEXT,
|
|
1667
|
+
answer_message_id TEXT,
|
|
1668
|
+
created_at TEXT NOT NULL,
|
|
1669
|
+
answered_at TEXT,
|
|
1670
|
+
expires_at TEXT
|
|
1671
|
+
);
|
|
1672
|
+
CREATE INDEX tickets_status ON tickets (status, created_at);
|
|
1673
|
+
CREATE INDEX tickets_from ON tickets (from_session);
|
|
1674
|
+
CREATE INDEX tickets_to ON tickets (to_session);
|
|
1675
|
+
CREATE TABLE permission_relay (
|
|
1676
|
+
session_id TEXT PRIMARY KEY,
|
|
1677
|
+
-- The orchestrator when the person turned the relay on: the only one who may approve.
|
|
1678
|
+
approver TEXT NOT NULL,
|
|
1679
|
+
enabled_at TEXT NOT NULL
|
|
1680
|
+
);
|
|
1681
|
+
`
|
|
1682
|
+
};
|
|
1683
|
+
const str$1 = (v) => typeof v === "string" ? v : void 0;
|
|
1684
|
+
function toRow(r) {
|
|
1685
|
+
const options = str$1(r.options);
|
|
1686
|
+
return {
|
|
1687
|
+
ticket: Ticket.parse({
|
|
1688
|
+
id: r.id,
|
|
1689
|
+
fromSession: r.from_session,
|
|
1690
|
+
toSession: r.to_session,
|
|
1691
|
+
kind: r.kind,
|
|
1692
|
+
question: r.question,
|
|
1693
|
+
status: r.status,
|
|
1694
|
+
createdAt: r.created_at,
|
|
1695
|
+
...options ? { options: JSON.parse(options) } : {},
|
|
1696
|
+
...str$1(r.answer) !== void 0 ? { answer: r.answer } : {},
|
|
1697
|
+
...str$1(r.answered_by) !== void 0 ? { answeredBy: r.answered_by } : {},
|
|
1698
|
+
...str$1(r.answer_message_id) !== void 0 ? { answerMessageId: r.answer_message_id } : {},
|
|
1699
|
+
...str$1(r.answered_at) !== void 0 ? { answeredAt: r.answered_at } : {},
|
|
1700
|
+
...str$1(r.expires_at) !== void 0 ? { expiresAt: r.expires_at } : {}
|
|
1701
|
+
}),
|
|
1702
|
+
toRef: r.to_ref
|
|
149
1703
|
};
|
|
150
1704
|
}
|
|
1705
|
+
/** SQLite access for tickets. Methods are synchronous; callers group writes with `Store.tx`. */
|
|
1706
|
+
var TicketStore = class {
|
|
1707
|
+
db;
|
|
1708
|
+
constructor(db) {
|
|
1709
|
+
this.db = db;
|
|
1710
|
+
}
|
|
1711
|
+
all(sql, ...params) {
|
|
1712
|
+
return this.db.prepare(sql).all(...params);
|
|
1713
|
+
}
|
|
1714
|
+
run(sql, ...params) {
|
|
1715
|
+
this.db.prepare(sql).run(...params);
|
|
1716
|
+
}
|
|
1717
|
+
insert(t, toRef) {
|
|
1718
|
+
this.run(`INSERT INTO tickets (id, from_session, to_session, to_ref, kind, question, options, status,
|
|
1719
|
+
created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, t.id, t.fromSession, t.toSession, toRef, t.kind, t.question, t.options ? JSON.stringify(t.options) : null, t.status, t.createdAt, t.expiresAt ?? null);
|
|
1720
|
+
}
|
|
1721
|
+
get(id) {
|
|
1722
|
+
const r = this.all("SELECT * FROM tickets WHERE id = ?", id)[0];
|
|
1723
|
+
return r ? toRow(r) : void 0;
|
|
1724
|
+
}
|
|
1725
|
+
/**
|
|
1726
|
+
* Tickets newest first. With `session`, those it asked or that are addressed to it: by its id,
|
|
1727
|
+
* or to the orchestrator role when `holder` says it holds the role.
|
|
1728
|
+
*/
|
|
1729
|
+
list(filter) {
|
|
1730
|
+
const where = [];
|
|
1731
|
+
const params = [];
|
|
1732
|
+
if (filter.session !== void 0) {
|
|
1733
|
+
where.push(filter.holder ? "(from_session = ? OR to_session = ? OR to_ref = 'orchestrator')" : "(from_session = ? OR to_session = ?)");
|
|
1734
|
+
params.push(filter.session, filter.session);
|
|
1735
|
+
}
|
|
1736
|
+
if (filter.id !== void 0) {
|
|
1737
|
+
where.push("id = ?");
|
|
1738
|
+
params.push(filter.id);
|
|
1739
|
+
}
|
|
1740
|
+
const scope = where.length > 0 ? ` WHERE ${where.join(" AND ")}` : "";
|
|
1741
|
+
const open = this.all(`SELECT COUNT(*) AS n FROM tickets${scope}${scope ? " AND" : " WHERE"} status = 'open'`, ...params)[0];
|
|
1742
|
+
const withStatus = [...where];
|
|
1743
|
+
const listParams = [...params];
|
|
1744
|
+
if (filter.status !== void 0) {
|
|
1745
|
+
withStatus.push("status = ?");
|
|
1746
|
+
listParams.push(filter.status);
|
|
1747
|
+
}
|
|
1748
|
+
const sql = `SELECT * FROM tickets${withStatus.length > 0 ? ` WHERE ${withStatus.join(" AND ")}` : ""} ORDER BY id DESC LIMIT ?`;
|
|
1749
|
+
return {
|
|
1750
|
+
rows: this.all(sql, ...listParams, filter.limit).map(toRow),
|
|
1751
|
+
openCount: Number(open?.n ?? 0)
|
|
1752
|
+
};
|
|
1753
|
+
}
|
|
1754
|
+
answer(id, answer, by, at, messageId) {
|
|
1755
|
+
this.run(`UPDATE tickets SET status = 'answered', answer = ?, answered_by = ?, answered_at = ?,
|
|
1756
|
+
answer_message_id = ? WHERE id = ? AND status = 'open'`, answer, by, at, messageId ?? null, id);
|
|
1757
|
+
}
|
|
1758
|
+
setStatus(id, status) {
|
|
1759
|
+
this.run("UPDATE tickets SET status = ? WHERE id = ? AND status = 'open'", status, id);
|
|
1760
|
+
}
|
|
1761
|
+
/** Open tickets whose `expires_at` is at or before `now`. */
|
|
1762
|
+
dueToExpire(now) {
|
|
1763
|
+
return this.all("SELECT * FROM tickets WHERE status = 'open' AND expires_at IS NOT NULL AND expires_at <= ?", now).map(toRow);
|
|
1764
|
+
}
|
|
1765
|
+
/** A session is gone: drop what it asked, and close what was addressed to it. */
|
|
1766
|
+
forgetSession(id) {
|
|
1767
|
+
this.run("DELETE FROM tickets WHERE from_session = ?", id);
|
|
1768
|
+
this.run("UPDATE tickets SET status = 'cancelled' WHERE to_session = ? AND to_ref != 'orchestrator' AND status = 'open'", id);
|
|
1769
|
+
this.run("DELETE FROM permission_relay WHERE session_id = ?", id);
|
|
1770
|
+
}
|
|
1771
|
+
relays() {
|
|
1772
|
+
return this.all("SELECT session_id, approver FROM permission_relay ORDER BY enabled_at, session_id").map((r) => ({
|
|
1773
|
+
session: r.session_id,
|
|
1774
|
+
approver: r.approver
|
|
1775
|
+
}));
|
|
1776
|
+
}
|
|
1777
|
+
/** The session allowed to approve for `id`, or undefined while the relay is off. */
|
|
1778
|
+
approverOf(id) {
|
|
1779
|
+
const r = this.all("SELECT approver FROM permission_relay WHERE session_id = ?", id)[0];
|
|
1780
|
+
return r ? r.approver : void 0;
|
|
1781
|
+
}
|
|
1782
|
+
setRelay(id, approver, at) {
|
|
1783
|
+
if (approver) this.run("INSERT OR REPLACE INTO permission_relay (session_id, approver, enabled_at) VALUES (?, ?, ?)", id, approver, at);
|
|
1784
|
+
else this.run("DELETE FROM permission_relay WHERE session_id = ?", id);
|
|
1785
|
+
}
|
|
1786
|
+
};
|
|
151
1787
|
// ../daemon/src/store.ts
|
|
152
|
-
const MIGRATIONS = [
|
|
153
|
-
|
|
154
|
-
|
|
1788
|
+
const MIGRATIONS = [
|
|
1789
|
+
{
|
|
1790
|
+
name: "001_initial",
|
|
1791
|
+
sql: `
|
|
155
1792
|
CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
156
1793
|
CREATE TABLE sessions (
|
|
157
1794
|
id TEXT PRIMARY KEY,
|
|
@@ -194,13 +1831,44 @@ const MIGRATIONS = [{
|
|
|
194
1831
|
);
|
|
195
1832
|
INSERT INTO orchestrator (slot, session_id) VALUES (1, NULL);
|
|
196
1833
|
`
|
|
197
|
-
},
|
|
198
|
-
|
|
199
|
-
|
|
1834
|
+
},
|
|
1835
|
+
{
|
|
1836
|
+
name: "002_host_pids",
|
|
1837
|
+
sql: `
|
|
200
1838
|
ALTER TABLE sessions ADD COLUMN host_pids TEXT;
|
|
201
1839
|
UPDATE sessions SET host_pids = '[' || host_pid || ']' WHERE host_pid IS NOT NULL;
|
|
202
1840
|
`
|
|
203
|
-
}
|
|
1841
|
+
},
|
|
1842
|
+
{
|
|
1843
|
+
name: "003_spawned",
|
|
1844
|
+
sql: `
|
|
1845
|
+
ALTER TABLE sessions ADD COLUMN spawned INTEGER NOT NULL DEFAULT 0;
|
|
1846
|
+
`
|
|
1847
|
+
},
|
|
1848
|
+
{
|
|
1849
|
+
name: "004_auto_mode",
|
|
1850
|
+
sql: `
|
|
1851
|
+
ALTER TABLE sessions ADD COLUMN auto INTEGER NOT NULL DEFAULT 0;
|
|
1852
|
+
ALTER TABLE sessions ADD COLUMN auto_explicit INTEGER NOT NULL DEFAULT 0;
|
|
1853
|
+
ALTER TABLE sessions ADD COLUMN auto_paused_at TEXT;
|
|
1854
|
+
ALTER TABLE sessions ADD COLUMN auto_paused_by TEXT;
|
|
1855
|
+
ALTER TABLE sessions ADD COLUMN auto_limit INTEGER;
|
|
1856
|
+
ALTER TABLE sessions ADD COLUMN auto_orch_resumed_at TEXT;
|
|
1857
|
+
ALTER TABLE sessions ADD COLUMN auto_runs TEXT NOT NULL DEFAULT '[]';
|
|
1858
|
+
ALTER TABLE sessions ADD COLUMN turn_hops INTEGER NOT NULL DEFAULT 0;
|
|
1859
|
+
ALTER TABLE mailbox ADD COLUMN hops INTEGER NOT NULL DEFAULT 0;
|
|
1860
|
+
`
|
|
1861
|
+
},
|
|
1862
|
+
{
|
|
1863
|
+
name: "005_peek_metadata",
|
|
1864
|
+
sql: `
|
|
1865
|
+
ALTER TABLE sessions ADD COLUMN cli_session_id TEXT;
|
|
1866
|
+
ALTER TABLE sessions ADD COLUMN transcript_path TEXT;
|
|
1867
|
+
ALTER TABLE sessions ADD COLUMN peekable INTEGER NOT NULL DEFAULT 1;
|
|
1868
|
+
`
|
|
1869
|
+
},
|
|
1870
|
+
TICKET_MIGRATION
|
|
1871
|
+
];
|
|
204
1872
|
const str = (v) => typeof v === "string" ? v : void 0;
|
|
205
1873
|
const num = (v) => typeof v === "number" ? v : void 0;
|
|
206
1874
|
function pidList(v) {
|
|
@@ -214,6 +1882,15 @@ function pidList(v) {
|
|
|
214
1882
|
return;
|
|
215
1883
|
}
|
|
216
1884
|
}
|
|
1885
|
+
function isoList(v) {
|
|
1886
|
+
if (typeof v !== "string") return [];
|
|
1887
|
+
try {
|
|
1888
|
+
const list = JSON.parse(v);
|
|
1889
|
+
return Array.isArray(list) ? list.filter((t) => typeof t === "string") : [];
|
|
1890
|
+
} catch {
|
|
1891
|
+
return [];
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
217
1894
|
function toSessionRow(r) {
|
|
218
1895
|
const row = {
|
|
219
1896
|
id: r.id,
|
|
@@ -223,7 +1900,12 @@ function toSessionRow(r) {
|
|
|
223
1900
|
cwd: r.cwd,
|
|
224
1901
|
status: r.status,
|
|
225
1902
|
deliveryTier: r.delivery_tier,
|
|
1903
|
+
spawned: r.spawned === 1,
|
|
226
1904
|
spawnDepth: r.spawn_depth,
|
|
1905
|
+
auto: r.auto === 1,
|
|
1906
|
+
autoExplicit: r.auto_explicit === 1,
|
|
1907
|
+
autoRuns: isoList(r.auto_runs),
|
|
1908
|
+
turnHops: num(r.turn_hops) ?? 0,
|
|
227
1909
|
startedAt: r.started_at,
|
|
228
1910
|
lastSeenAt: r.last_seen_at
|
|
229
1911
|
};
|
|
@@ -239,14 +1921,27 @@ function toSessionRow(r) {
|
|
|
239
1921
|
if (hostPid !== void 0) row.hostPid = hostPid;
|
|
240
1922
|
const hostPids = pidList(r.host_pids);
|
|
241
1923
|
if (hostPids !== void 0) row.hostPids = hostPids;
|
|
1924
|
+
const cliSessionId = str(r.cli_session_id);
|
|
1925
|
+
if (cliSessionId !== void 0) row.cliSessionId = cliSessionId;
|
|
1926
|
+
const transcriptPath = str(r.transcript_path);
|
|
1927
|
+
if (transcriptPath !== void 0) row.transcriptPath = transcriptPath;
|
|
1928
|
+
if (r.peekable === 0) row.peekable = false;
|
|
242
1929
|
const statusText = str(r.status_text);
|
|
243
1930
|
if (statusText !== void 0) row.statusText = statusText;
|
|
244
1931
|
const spawnedBy = str(r.spawned_by);
|
|
245
1932
|
if (spawnedBy !== void 0) row.spawnedBy = spawnedBy;
|
|
1933
|
+
const pausedAt = str(r.auto_paused_at);
|
|
1934
|
+
if (pausedAt !== void 0) row.autoPausedAt = pausedAt;
|
|
1935
|
+
const pausedBy = str(r.auto_paused_by);
|
|
1936
|
+
if (pausedBy === "limit") row.autoPausedBy = pausedBy;
|
|
1937
|
+
const limit = num(r.auto_limit);
|
|
1938
|
+
if (limit !== void 0) row.autoLimit = limit;
|
|
1939
|
+
const orchResumedAt = str(r.auto_orch_resumed_at);
|
|
1940
|
+
if (orchResumedAt !== void 0) row.autoOrchResumedAt = orchResumedAt;
|
|
246
1941
|
return row;
|
|
247
1942
|
}
|
|
248
1943
|
/** Wire-format session for a stored row. */
|
|
249
|
-
function toSession(row, isOrchestrator) {
|
|
1944
|
+
function toSession(row, isOrchestrator, unreadCount) {
|
|
250
1945
|
const s = {
|
|
251
1946
|
id: row.id,
|
|
252
1947
|
name: row.name,
|
|
@@ -256,10 +1951,16 @@ function toSession(row, isOrchestrator) {
|
|
|
256
1951
|
status: row.status,
|
|
257
1952
|
isOrchestrator,
|
|
258
1953
|
deliveryTier: row.deliveryTier,
|
|
1954
|
+
spawned: row.spawned,
|
|
259
1955
|
spawnDepth: row.spawnDepth,
|
|
1956
|
+
auto: row.auto,
|
|
260
1957
|
startedAt: row.startedAt,
|
|
261
1958
|
lastSeenAt: row.lastSeenAt
|
|
262
1959
|
};
|
|
1960
|
+
if (row.autoPausedAt !== void 0) s.autoPausedAt = row.autoPausedAt;
|
|
1961
|
+
if (row.autoPausedBy !== void 0) s.autoPausedBy = row.autoPausedBy;
|
|
1962
|
+
if (row.autoLimit !== void 0) s.autoLimit = row.autoLimit;
|
|
1963
|
+
if (unreadCount !== void 0) s.unreadCount = unreadCount;
|
|
263
1964
|
if (row.cliVersion !== void 0) s.cliVersion = row.cliVersion;
|
|
264
1965
|
if (row.repoRoot !== void 0) s.repo = row.repoRemoteUrlHash !== void 0 ? {
|
|
265
1966
|
root: row.repoRoot,
|
|
@@ -269,6 +1970,7 @@ function toSession(row, isOrchestrator) {
|
|
|
269
1970
|
if (row.hostPid !== void 0) s.hostPid = row.hostPid;
|
|
270
1971
|
if (row.hostPids !== void 0) s.hostPids = row.hostPids;
|
|
271
1972
|
if (row.statusText !== void 0) s.statusText = row.statusText;
|
|
1973
|
+
if (row.peekable === false) s.peekable = false;
|
|
272
1974
|
if (row.spawnedBy !== void 0) s.spawnedBy = row.spawnedBy;
|
|
273
1975
|
return s;
|
|
274
1976
|
}
|
|
@@ -284,17 +1986,21 @@ function toEntry(r) {
|
|
|
284
1986
|
if (d) entry.deliveredAt = d;
|
|
285
1987
|
if (rd) entry.readAt = rd;
|
|
286
1988
|
if (a) entry.ackedAt = a;
|
|
1989
|
+
const hops = num(r.hops);
|
|
1990
|
+
if (hops !== void 0 && hops > 0) entry.hops = hops;
|
|
287
1991
|
return entry;
|
|
288
1992
|
}
|
|
289
1993
|
/** SQLite persistence. All methods are synchronous; callers group writes with `tx`. */
|
|
290
1994
|
var Store = class {
|
|
291
1995
|
db;
|
|
1996
|
+
tickets;
|
|
292
1997
|
constructor(path) {
|
|
293
1998
|
this.db = new DatabaseSync(path);
|
|
294
1999
|
this.db.exec("PRAGMA journal_mode = WAL");
|
|
295
2000
|
this.db.exec("PRAGMA synchronous = NORMAL");
|
|
296
2001
|
this.db.exec("PRAGMA busy_timeout = 5000");
|
|
297
2002
|
this.migrate();
|
|
2003
|
+
this.tickets = new TicketStore(this.db);
|
|
298
2004
|
}
|
|
299
2005
|
all(sql, ...params) {
|
|
300
2006
|
return this.db.prepare(sql).all(...params);
|
|
@@ -340,8 +2046,10 @@ var Store = class {
|
|
|
340
2046
|
}
|
|
341
2047
|
insertSession(s) {
|
|
342
2048
|
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
|
-
|
|
2049
|
+
pid, host_pid, host_pids, status, status_text, delivery_tier, spawned_by, spawned, spawn_depth,
|
|
2050
|
+
auto, auto_explicit, auto_paused_at, auto_paused_by, auto_limit, auto_runs, turn_hops,
|
|
2051
|
+
started_at, last_seen_at)
|
|
2052
|
+
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, s.auto ? 1 : 0, s.autoExplicit ? 1 : 0, s.autoPausedAt ?? null, s.autoPausedBy ?? null, s.autoLimit ?? null, JSON.stringify(s.autoRuns), s.turnHops, s.startedAt, s.lastSeenAt);
|
|
345
2053
|
}
|
|
346
2054
|
getSession(id) {
|
|
347
2055
|
const r = this.all("SELECT * FROM sessions WHERE id = ?", id)[0];
|
|
@@ -354,6 +2062,50 @@ var Store = class {
|
|
|
354
2062
|
updateSession(id, fields) {
|
|
355
2063
|
const sets = [];
|
|
356
2064
|
const vals = [];
|
|
2065
|
+
if (fields.auto !== void 0) {
|
|
2066
|
+
sets.push("auto = ?");
|
|
2067
|
+
vals.push(fields.auto ? 1 : 0);
|
|
2068
|
+
}
|
|
2069
|
+
if (fields.autoExplicit !== void 0) {
|
|
2070
|
+
sets.push("auto_explicit = ?");
|
|
2071
|
+
vals.push(fields.autoExplicit ? 1 : 0);
|
|
2072
|
+
}
|
|
2073
|
+
if (fields.autoPausedAt !== void 0) {
|
|
2074
|
+
sets.push("auto_paused_at = ?");
|
|
2075
|
+
vals.push(fields.autoPausedAt);
|
|
2076
|
+
}
|
|
2077
|
+
if (fields.autoPausedBy !== void 0) {
|
|
2078
|
+
sets.push("auto_paused_by = ?");
|
|
2079
|
+
vals.push(fields.autoPausedBy);
|
|
2080
|
+
}
|
|
2081
|
+
if (fields.autoLimit !== void 0) {
|
|
2082
|
+
sets.push("auto_limit = ?");
|
|
2083
|
+
vals.push(fields.autoLimit);
|
|
2084
|
+
}
|
|
2085
|
+
if (fields.autoOrchResumedAt !== void 0) {
|
|
2086
|
+
sets.push("auto_orch_resumed_at = ?");
|
|
2087
|
+
vals.push(fields.autoOrchResumedAt);
|
|
2088
|
+
}
|
|
2089
|
+
if (fields.turnHops !== void 0) {
|
|
2090
|
+
sets.push("turn_hops = ?");
|
|
2091
|
+
vals.push(fields.turnHops);
|
|
2092
|
+
}
|
|
2093
|
+
if (fields.autoRuns !== void 0) {
|
|
2094
|
+
sets.push("auto_runs = ?");
|
|
2095
|
+
vals.push(JSON.stringify(fields.autoRuns));
|
|
2096
|
+
}
|
|
2097
|
+
if (fields.cliSessionId !== void 0) {
|
|
2098
|
+
sets.push("cli_session_id = ?");
|
|
2099
|
+
vals.push(fields.cliSessionId);
|
|
2100
|
+
}
|
|
2101
|
+
if (fields.transcriptPath !== void 0) {
|
|
2102
|
+
sets.push("transcript_path = ?");
|
|
2103
|
+
vals.push(fields.transcriptPath);
|
|
2104
|
+
}
|
|
2105
|
+
if (fields.peekable !== void 0) {
|
|
2106
|
+
sets.push("peekable = ?");
|
|
2107
|
+
vals.push(fields.peekable ? 1 : 0);
|
|
2108
|
+
}
|
|
357
2109
|
if (fields.name !== void 0) {
|
|
358
2110
|
sets.push("name = ?");
|
|
359
2111
|
vals.push(fields.name);
|
|
@@ -380,9 +2132,14 @@ var Store = class {
|
|
|
380
2132
|
setHolder(id) {
|
|
381
2133
|
this.run("UPDATE orchestrator SET session_id = ? WHERE slot = 1", id);
|
|
382
2134
|
}
|
|
383
|
-
|
|
2135
|
+
/** `hops`: automatic turns behind the message (the auto-mode limit counts them). */
|
|
2136
|
+
insertMessage(message, recipient, at, hops = 0) {
|
|
384
2137
|
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);
|
|
2138
|
+
this.run("INSERT INTO mailbox (session_id, message_id, state, queued_at, hops) VALUES (?, ?, 'queued', ?, ?)", recipient, message.id, at, hops);
|
|
2139
|
+
}
|
|
2140
|
+
/** Start a new chain for the messages queued for a session: their hops go back to 0. */
|
|
2141
|
+
resetQueuedHops(sessionId) {
|
|
2142
|
+
this.run("UPDATE mailbox SET hops = 0 WHERE session_id = ? AND state = 'queued'", sessionId);
|
|
386
2143
|
}
|
|
387
2144
|
/** Messages queued for a session that no one has been shown yet. */
|
|
388
2145
|
unreadCount(sessionId) {
|
|
@@ -394,13 +2151,14 @@ var Store = class {
|
|
|
394
2151
|
}
|
|
395
2152
|
/** Remove a session, its mailbox, and any message no mailbox refers to any more. */
|
|
396
2153
|
deleteSession(id) {
|
|
2154
|
+
this.tickets.forgetSession(id);
|
|
397
2155
|
this.run("DELETE FROM mailbox WHERE session_id = ?", id);
|
|
398
2156
|
this.run("DELETE FROM messages WHERE id NOT IN (SELECT message_id FROM mailbox)");
|
|
399
2157
|
this.run("DELETE FROM sessions WHERE id = ?", id);
|
|
400
2158
|
}
|
|
401
2159
|
/** Mailbox entries of one session, optionally limited to the given states or message ids. */
|
|
402
2160
|
entries(sessionId, filter = {}) {
|
|
403
|
-
let sql = `SELECT m.json, b.state, b.queued_at, b.delivered_at, b.read_at, b.acked_at
|
|
2161
|
+
let sql = `SELECT m.json, b.state, b.queued_at, b.delivered_at, b.read_at, b.acked_at, b.hops
|
|
404
2162
|
FROM mailbox b JOIN messages m ON m.id = b.message_id WHERE b.session_id = ?`;
|
|
405
2163
|
const params = [sessionId];
|
|
406
2164
|
if (filter.states) {
|
|
@@ -418,8 +2176,265 @@ var Store = class {
|
|
|
418
2176
|
WHERE session_id = ? AND message_id = ?`, e.state, e.deliveredAt ?? null, e.readAt ?? null, e.ackedAt ?? null, sessionId, e.message.id);
|
|
419
2177
|
}
|
|
420
2178
|
};
|
|
2179
|
+
// ../daemon/src/tickets.ts
|
|
2180
|
+
/** An open question expires after this long. The asker's own CLI prompt is unaffected. */
|
|
2181
|
+
const TICKET_TTL_MS = 864e5;
|
|
2182
|
+
/** A permission ticket outlives the hook that asked for it by little: the hook gives up in 90 s. */
|
|
2183
|
+
const PERMISSION_TICKET_TTL_MS = 3e5;
|
|
2184
|
+
const fail = (code, message) => {
|
|
2185
|
+
throw new ConvenoError(code, message);
|
|
2186
|
+
};
|
|
2187
|
+
const clip = (text, max) => {
|
|
2188
|
+
const flat = sanitizeLine(text);
|
|
2189
|
+
return flat.length > max ? `${flat.slice(0, max - 3)}...` : flat;
|
|
2190
|
+
};
|
|
2191
|
+
/** Questions to the orchestrator, answers back to the asker, and the permission relay. */
|
|
2192
|
+
var TicketService = class {
|
|
2193
|
+
host;
|
|
2194
|
+
constructor(host) {
|
|
2195
|
+
this.host = host;
|
|
2196
|
+
}
|
|
2197
|
+
get store() {
|
|
2198
|
+
return this.host.store.tickets;
|
|
2199
|
+
}
|
|
2200
|
+
create(p) {
|
|
2201
|
+
const asker = this.requireOnline(p.sessionId);
|
|
2202
|
+
const target = this.host.resolve(p.to ?? "orchestrator");
|
|
2203
|
+
if (target.id === asker.id) fail(RpcErrorCode.InvalidParams, p.to === void 0 || p.to === "orchestrator" ? "You are the orchestrator, so there is no one above you to ask. Ask the user directly." : "A session cannot ask itself. Name another session in `to`.");
|
|
2204
|
+
return this.open(asker, target, {
|
|
2205
|
+
kind: "question",
|
|
2206
|
+
question: p.question,
|
|
2207
|
+
options: p.options,
|
|
2208
|
+
toRef: p.to === void 0 || p.to === "orchestrator" ? ORCHESTRATOR_ALIAS : target.id,
|
|
2209
|
+
ttlMs: TICKET_TTL_MS
|
|
2210
|
+
});
|
|
2211
|
+
}
|
|
2212
|
+
open(asker, target, t) {
|
|
2213
|
+
const at = this.host.iso();
|
|
2214
|
+
if (this.store.list({
|
|
2215
|
+
session: asker.id,
|
|
2216
|
+
status: "open",
|
|
2217
|
+
limit: 200
|
|
2218
|
+
}).rows.filter((r) => r.ticket.fromSession === asker.id).length >= 50) fail(RpcErrorCode.LimitExceeded, `You already have 50 open tickets. Wait for answers or cancel some.`);
|
|
2219
|
+
const ticket = {
|
|
2220
|
+
id: newTicketId(),
|
|
2221
|
+
fromSession: asker.id,
|
|
2222
|
+
toSession: target.id,
|
|
2223
|
+
kind: t.kind,
|
|
2224
|
+
question: t.question,
|
|
2225
|
+
...t.options ? { options: t.options } : {},
|
|
2226
|
+
status: "open",
|
|
2227
|
+
createdAt: at,
|
|
2228
|
+
expiresAt: new Date(Date.parse(at) + t.ttlMs).toISOString()
|
|
2229
|
+
};
|
|
2230
|
+
const message = {
|
|
2231
|
+
id: newMessageId(),
|
|
2232
|
+
from: asker.id,
|
|
2233
|
+
to: target.id,
|
|
2234
|
+
kind: "question",
|
|
2235
|
+
body: {
|
|
2236
|
+
ticketId: ticket.id,
|
|
2237
|
+
question: t.question,
|
|
2238
|
+
...t.options ? { options: t.options } : {}
|
|
2239
|
+
},
|
|
2240
|
+
urgent: true,
|
|
2241
|
+
createdAt: at,
|
|
2242
|
+
fromName: asker.name,
|
|
2243
|
+
fromCli: asker.cli
|
|
2244
|
+
};
|
|
2245
|
+
this.host.store.tx(() => {
|
|
2246
|
+
this.store.insert(ticket, t.toRef);
|
|
2247
|
+
this.host.queue(message, target, true);
|
|
2248
|
+
});
|
|
2249
|
+
this.host.emit({
|
|
2250
|
+
event: "ticket.created",
|
|
2251
|
+
data: { ticket }
|
|
2252
|
+
}, target.id);
|
|
2253
|
+
return { ticket };
|
|
2254
|
+
}
|
|
2255
|
+
answer(p, client) {
|
|
2256
|
+
const row = this.store.get(p.ticketId);
|
|
2257
|
+
if (!row) fail(RpcErrorCode.NotFound, `No ticket ${p.ticketId}. Run tickets to see the open ones.`);
|
|
2258
|
+
const { ticket, toRef } = row;
|
|
2259
|
+
if (ticket.status !== "open") fail(RpcErrorCode.Conflict, `Ticket ${ticket.id} is already ${ticket.status}, so it cannot be answered.`);
|
|
2260
|
+
let by;
|
|
2261
|
+
let me;
|
|
2262
|
+
if (p.sessionId === void 0) {
|
|
2263
|
+
if (client !== "cli") fail(RpcErrorCode.Unauthorized, "Only a session or the conveno command can answer a ticket. Pass sessionId.");
|
|
2264
|
+
by = HUMAN_ANSWERER;
|
|
2265
|
+
} else {
|
|
2266
|
+
me = this.host.requireSession(p.sessionId);
|
|
2267
|
+
by = me.id;
|
|
2268
|
+
if (me.id === ticket.fromSession) fail(RpcErrorCode.Unauthorized, "A session cannot answer its own ticket.");
|
|
2269
|
+
if (!(me.id === ticket.toSession || toRef === "orchestrator" && this.host.holder() === me.id)) fail(RpcErrorCode.Unauthorized, `Ticket ${ticket.id} is not addressed to you. Only the session it was sent to can answer it.`);
|
|
2270
|
+
}
|
|
2271
|
+
let response = p.response;
|
|
2272
|
+
if (ticket.kind === "permission") {
|
|
2273
|
+
response = p.response.trim().toLowerCase();
|
|
2274
|
+
if (!PERMISSION_ANSWERS.includes(response)) fail(RpcErrorCode.InvalidParams, `Ticket ${ticket.id} is a permission request. Answer "allow" or "deny" and nothing else.`);
|
|
2275
|
+
}
|
|
2276
|
+
const at = this.host.iso();
|
|
2277
|
+
const asker = this.host.store.getSession(ticket.fromSession);
|
|
2278
|
+
let messageId;
|
|
2279
|
+
this.host.store.tx(() => {
|
|
2280
|
+
let message;
|
|
2281
|
+
if (ticket.kind === "question" && asker) {
|
|
2282
|
+
message = {
|
|
2283
|
+
id: newMessageId(),
|
|
2284
|
+
from: me?.id ?? this.host.daemonSender,
|
|
2285
|
+
to: asker.id,
|
|
2286
|
+
kind: "answer",
|
|
2287
|
+
body: {
|
|
2288
|
+
ticketId: ticket.id,
|
|
2289
|
+
response
|
|
2290
|
+
},
|
|
2291
|
+
urgent: true,
|
|
2292
|
+
createdAt: at,
|
|
2293
|
+
...me ? {
|
|
2294
|
+
fromName: me.name,
|
|
2295
|
+
fromCli: me.cli
|
|
2296
|
+
} : {}
|
|
2297
|
+
};
|
|
2298
|
+
this.host.queue(message, asker, false);
|
|
2299
|
+
messageId = message.id;
|
|
2300
|
+
}
|
|
2301
|
+
this.store.answer(ticket.id, response, by, at, messageId);
|
|
2302
|
+
});
|
|
2303
|
+
const done = this.store.get(ticket.id).ticket;
|
|
2304
|
+
this.host.emit({
|
|
2305
|
+
event: "ticket.answered",
|
|
2306
|
+
data: { ticket: done }
|
|
2307
|
+
}, ticket.fromSession);
|
|
2308
|
+
if (ticket.toSession !== ticket.fromSession) this.host.emit({
|
|
2309
|
+
event: "ticket.answered",
|
|
2310
|
+
data: { ticket: done }
|
|
2311
|
+
}, ticket.toSession);
|
|
2312
|
+
return { ticket: done };
|
|
2313
|
+
}
|
|
2314
|
+
list(p, client) {
|
|
2315
|
+
if (p.sessionId === void 0 && client !== "cli") fail(RpcErrorCode.Unauthorized, "Pass sessionId to list your tickets.");
|
|
2316
|
+
if (p.sessionId !== void 0) this.host.requireSession(p.sessionId);
|
|
2317
|
+
const { rows, openCount } = this.store.list({
|
|
2318
|
+
...p.sessionId !== void 0 ? {
|
|
2319
|
+
session: p.sessionId,
|
|
2320
|
+
holder: this.host.holder() === p.sessionId
|
|
2321
|
+
} : {},
|
|
2322
|
+
...p.status !== void 0 ? { status: p.status } : {},
|
|
2323
|
+
...p.ticketId !== void 0 ? { id: p.ticketId } : {},
|
|
2324
|
+
limit: p.limit
|
|
2325
|
+
});
|
|
2326
|
+
return {
|
|
2327
|
+
tickets: rows.map((r) => r.ticket),
|
|
2328
|
+
openCount
|
|
2329
|
+
};
|
|
2330
|
+
}
|
|
2331
|
+
cancel(p, client) {
|
|
2332
|
+
const row = this.store.get(p.ticketId);
|
|
2333
|
+
if (!row) fail(RpcErrorCode.NotFound, `No ticket ${p.ticketId}. Run tickets to see the open ones.`);
|
|
2334
|
+
const { ticket } = row;
|
|
2335
|
+
if (p.sessionId === void 0) {
|
|
2336
|
+
if (client !== "cli") fail(RpcErrorCode.Unauthorized, "Pass sessionId to cancel a ticket.");
|
|
2337
|
+
} else {
|
|
2338
|
+
this.host.requireSession(p.sessionId);
|
|
2339
|
+
if (p.sessionId !== ticket.fromSession) fail(RpcErrorCode.Unauthorized, "Only the session that asked can cancel a ticket.");
|
|
2340
|
+
}
|
|
2341
|
+
if (ticket.status !== "open") fail(RpcErrorCode.Conflict, `Ticket ${ticket.id} is already ${ticket.status}, so it cannot be cancelled.`);
|
|
2342
|
+
this.store.setStatus(ticket.id, "cancelled");
|
|
2343
|
+
return { ticket: this.store.get(ticket.id).ticket };
|
|
2344
|
+
}
|
|
2345
|
+
/** Expire open tickets past their time; tell the asker of a question that it went unanswered. */
|
|
2346
|
+
sweep() {
|
|
2347
|
+
const at = this.host.iso();
|
|
2348
|
+
for (const { ticket } of this.store.dueToExpire(at)) this.host.store.tx(() => {
|
|
2349
|
+
this.store.setStatus(ticket.id, "expired");
|
|
2350
|
+
const asker = this.host.store.getSession(ticket.fromSession);
|
|
2351
|
+
if (ticket.kind === "question" && asker) {
|
|
2352
|
+
const target = this.host.store.getSession(ticket.toSession);
|
|
2353
|
+
this.host.queue({
|
|
2354
|
+
id: newMessageId(),
|
|
2355
|
+
from: this.host.daemonSender,
|
|
2356
|
+
to: asker.id,
|
|
2357
|
+
kind: "system",
|
|
2358
|
+
body: {
|
|
2359
|
+
event: "ticket.expired",
|
|
2360
|
+
detail: `Your question to ${target?.name ?? "the orchestrator"} (ticket ${ticket.id}) got no answer and has expired. Ask again, or decide yourself.`
|
|
2361
|
+
},
|
|
2362
|
+
urgent: false,
|
|
2363
|
+
createdAt: at
|
|
2364
|
+
}, asker, false);
|
|
2365
|
+
}
|
|
2366
|
+
});
|
|
2367
|
+
}
|
|
2368
|
+
relay(p, client) {
|
|
2369
|
+
if (client !== "cli") fail(RpcErrorCode.Unauthorized, "Only the conveno command switches the permission relay. An agent cannot turn it on for itself or another agent.");
|
|
2370
|
+
if (p.enabled !== void 0) {
|
|
2371
|
+
if (p.target === void 0) fail(RpcErrorCode.InvalidParams, "Name the session to switch the relay for.");
|
|
2372
|
+
const target = this.host.requireSession(p.target);
|
|
2373
|
+
if (p.enabled && !target.spawned) fail(RpcErrorCode.InvalidParams, `${target.name} was not started by Conveno, so a person is driving it. The relay is only for sessions started with conveno spawn or spawn_session.`);
|
|
2374
|
+
let approver = null;
|
|
2375
|
+
if (p.enabled) {
|
|
2376
|
+
approver = this.host.holder();
|
|
2377
|
+
if (approver === null) fail(RpcErrorCode.NotFound, "No session holds the orchestrator role, so there is no one to approve. Run orchestrate in the session you want to use, then turn the relay on.");
|
|
2378
|
+
if (approver === target.id) fail(RpcErrorCode.InvalidParams, `${target.name} is the orchestrator, so it cannot relay to itself.`);
|
|
2379
|
+
}
|
|
2380
|
+
this.store.setRelay(target.id, approver, this.host.iso());
|
|
2381
|
+
}
|
|
2382
|
+
return { relays: this.store.relays() };
|
|
2383
|
+
}
|
|
2384
|
+
request(p) {
|
|
2385
|
+
const me = this.requireOnline(p.sessionId);
|
|
2386
|
+
const local = (reason) => ({
|
|
2387
|
+
relay: false,
|
|
2388
|
+
reason
|
|
2389
|
+
});
|
|
2390
|
+
const approverId = this.store.approverOf(me.id);
|
|
2391
|
+
if (approverId === void 0) return local("The permission relay is off for this session.");
|
|
2392
|
+
if (!me.spawned) return local("A person drives this session, so the relay does not apply.");
|
|
2393
|
+
const verdict = classifyPermission({
|
|
2394
|
+
tool: p.tool,
|
|
2395
|
+
command: p.command,
|
|
2396
|
+
paths: p.paths,
|
|
2397
|
+
cwd: p.cwd ?? me.cwd,
|
|
2398
|
+
repoRoot: me.repoRoot
|
|
2399
|
+
});
|
|
2400
|
+
if (!verdict.relay) return local(verdict.reason);
|
|
2401
|
+
const target = this.host.store.getSession(approverId);
|
|
2402
|
+
if (!target || target.status === "offline") return local("The orchestrator this relay was set up with is not online.");
|
|
2403
|
+
if (target.id === me.id) return local("This session is the orchestrator.");
|
|
2404
|
+
if (this.store.list({
|
|
2405
|
+
session: me.id,
|
|
2406
|
+
status: "open",
|
|
2407
|
+
limit: 200
|
|
2408
|
+
}).rows.filter((r) => r.ticket.fromSession === me.id && r.ticket.kind === "permission").length >= 5) return local("Too many permission requests are waiting already.");
|
|
2409
|
+
const lines = [
|
|
2410
|
+
`Permission request (EXPERIMENTAL relay) from ${me.name} (${me.cli}) in ${clip(me.repoRoot ?? me.cwd, 200)}.`,
|
|
2411
|
+
`Tool: ${clip(p.tool, 100)}`,
|
|
2412
|
+
...p.command ? [`Command: ${clip(p.command, 1e3)}`] : [],
|
|
2413
|
+
...p.paths?.length ? [`Files: ${clip(p.paths.join(", "), 1e3)}`] : [],
|
|
2414
|
+
...p.cwd ? [`Working folder: ${clip(p.cwd, 200)}`] : [],
|
|
2415
|
+
...p.description ? [`The CLI says: ${clip(p.description, 300)}`] : [],
|
|
2416
|
+
`Answer "allow" or "deny". The worker waits about 80 seconds, then its own prompt takes over. Allow only what you would run yourself in this repo.`
|
|
2417
|
+
];
|
|
2418
|
+
const { ticket } = this.open(me, target, {
|
|
2419
|
+
kind: "permission",
|
|
2420
|
+
question: lines.join("\n"),
|
|
2421
|
+
options: [...PERMISSION_ANSWERS],
|
|
2422
|
+
toRef: target.id,
|
|
2423
|
+
ttlMs: PERMISSION_TICKET_TTL_MS
|
|
2424
|
+
});
|
|
2425
|
+
return {
|
|
2426
|
+
relay: true,
|
|
2427
|
+
ticket
|
|
2428
|
+
};
|
|
2429
|
+
}
|
|
2430
|
+
requireOnline(id) {
|
|
2431
|
+
const row = this.host.requireSession(id);
|
|
2432
|
+
if (row.status === "offline") fail(RpcErrorCode.NotFound, `Session "${row.name}" is offline. Register the session again before asking.`);
|
|
2433
|
+
return row;
|
|
2434
|
+
}
|
|
2435
|
+
};
|
|
421
2436
|
// ../daemon/src/server.ts
|
|
422
|
-
const DAEMON_VERSION = "0.
|
|
2437
|
+
const DAEMON_VERSION = "0.2.0-rc.1";
|
|
423
2438
|
/** A connection that has not finished the handshake by then is closed. */
|
|
424
2439
|
const AUTH_TIMEOUT_MS = 5e3;
|
|
425
2440
|
/** Unread messages one session may hold. */
|
|
@@ -442,12 +2457,22 @@ const PRUNE_SUPERSEDED_AFTER_MS = 3e5;
|
|
|
442
2457
|
* say, so mail sent to a closed session survives a weekend. Then the session and its mailbox go.
|
|
443
2458
|
*/
|
|
444
2459
|
const PRUNE_UNREAD_AFTER_MS = 6048e5;
|
|
2460
|
+
/** Time the daemon spends reading the process table for one `session.hostOf`. */
|
|
2461
|
+
const HOST_OF_TIMEOUT_MS = 1500;
|
|
445
2462
|
/** Sender id on `system` messages made by the daemon itself (no session sent them). */
|
|
446
2463
|
const DAEMON_SENDER_ID = SessionId.parse("0".repeat(26));
|
|
447
2464
|
const CLI_TIER = {
|
|
448
2465
|
claude: "next_turn",
|
|
449
|
-
codex: "next_turn"
|
|
2466
|
+
codex: "next_turn",
|
|
2467
|
+
cursor: "next_turn",
|
|
2468
|
+
copilot: "next_turn",
|
|
2469
|
+
antigravity: "next_turn"
|
|
450
2470
|
};
|
|
2471
|
+
/**
|
|
2472
|
+
* CLIs whose adapter can wake an idle session in auto mode (Claude Code's asyncRewake listener,
|
|
2473
|
+
* the OpenCode plugin). A message to such a session in auto mode is reported as `live`.
|
|
2474
|
+
*/
|
|
2475
|
+
const CLI_WAKE = /* @__PURE__ */ new Set(["claude", "opencode"]);
|
|
451
2476
|
var Daemon = class {
|
|
452
2477
|
store;
|
|
453
2478
|
token;
|
|
@@ -459,11 +2484,24 @@ var Daemon = class {
|
|
|
459
2484
|
log;
|
|
460
2485
|
authTimeoutMs;
|
|
461
2486
|
pathExists;
|
|
2487
|
+
autoLimits;
|
|
2488
|
+
transcripts;
|
|
2489
|
+
transcriptEnv;
|
|
2490
|
+
processIo;
|
|
462
2491
|
conns = /* @__PURE__ */ new Set();
|
|
2492
|
+
/** Reaches the owner's other devices; set by startDaemon unless disabled. */
|
|
2493
|
+
relay;
|
|
463
2494
|
deviceId;
|
|
2495
|
+
/** The newest idle-wake listener of each session, and the ids it replaced. In memory only. */
|
|
2496
|
+
listeners = /* @__PURE__ */ new Map();
|
|
464
2497
|
idleSince;
|
|
465
2498
|
startedMs;
|
|
466
|
-
|
|
2499
|
+
tickets;
|
|
2500
|
+
constructor(store, token, now, isAlive, idleExitMs, requestIdleExit, requestShutdown, log, authTimeoutMs = AUTH_TIMEOUT_MS, pathExists = existsSync, autoLimits = autoLimitsFromEnv({}), transcripts = {}, transcriptEnv = {
|
|
2501
|
+
home: homedir(),
|
|
2502
|
+
platform: process.platform,
|
|
2503
|
+
env: process.env
|
|
2504
|
+
}, processIo = defaultProcessIo) {
|
|
467
2505
|
this.store = store;
|
|
468
2506
|
this.token = token;
|
|
469
2507
|
this.now = now;
|
|
@@ -474,9 +2512,23 @@ var Daemon = class {
|
|
|
474
2512
|
this.log = log;
|
|
475
2513
|
this.authTimeoutMs = authTimeoutMs;
|
|
476
2514
|
this.pathExists = pathExists;
|
|
2515
|
+
this.autoLimits = autoLimits;
|
|
2516
|
+
this.transcripts = transcripts;
|
|
2517
|
+
this.transcriptEnv = transcriptEnv;
|
|
2518
|
+
this.processIo = processIo;
|
|
477
2519
|
this.deviceId = store.deviceId();
|
|
478
2520
|
this.startedMs = now().getTime();
|
|
479
2521
|
this.idleSince = this.startedMs;
|
|
2522
|
+
this.tickets = new TicketService({
|
|
2523
|
+
store,
|
|
2524
|
+
iso: () => this.iso(),
|
|
2525
|
+
requireSession: (id) => this.requireSession(id),
|
|
2526
|
+
resolve: (to) => this.resolveOnline(to),
|
|
2527
|
+
holder: () => effectiveHolder(store.holder(), this.named(store.allSessions()))?.id ?? null,
|
|
2528
|
+
queue: (message, row, limit) => this.queueMessage(message, row, limit),
|
|
2529
|
+
emit: (payload, onlyTo) => this.emit(payload, onlyTo),
|
|
2530
|
+
daemonSender: DAEMON_SENDER_ID
|
|
2531
|
+
});
|
|
480
2532
|
}
|
|
481
2533
|
iso = () => this.now().toISOString();
|
|
482
2534
|
attach(socket) {
|
|
@@ -558,8 +2610,16 @@ var Daemon = class {
|
|
|
558
2610
|
case "session.rename": return this.rename(req.params);
|
|
559
2611
|
case "session.setStatus": return this.setStatus(req.params);
|
|
560
2612
|
case "session.list": return this.list(req.params);
|
|
561
|
-
case "session.byHost": return this.byHost(req.params.pid);
|
|
2613
|
+
case "session.byHost": return this.byHost(req.params.pid, req.params.cwd);
|
|
2614
|
+
case "session.hostOf": return this.hostOf(req.params);
|
|
562
2615
|
case "session.forget": return this.forget(req.params);
|
|
2616
|
+
case "session.setAuto": return this.setAuto(req.params);
|
|
2617
|
+
case "turn.start": return this.turnStart(req.params.sessionId);
|
|
2618
|
+
case "turn.end": return this.turnEnd(req.params);
|
|
2619
|
+
case "turn.wake": return this.turnWake(req.params);
|
|
2620
|
+
case "session.setCliInfo": return this.setCliInfo(req.params);
|
|
2621
|
+
case "session.setPeekable": return this.setPeekable(req.params);
|
|
2622
|
+
case "session.peek": return this.peek(conn, req.params);
|
|
563
2623
|
case "daemon.shutdown": return { ok: true };
|
|
564
2624
|
case "orchestrator.claim": return this.claim(req.params.sessionId);
|
|
565
2625
|
case "message.send": return this.sendMessage(req.params);
|
|
@@ -567,13 +2627,30 @@ var Daemon = class {
|
|
|
567
2627
|
case "message.deliver": return this.deliver(req.params);
|
|
568
2628
|
case "message.ack": return this.ack(req.params);
|
|
569
2629
|
case "events.subscribe": return this.subscribe(conn, req.params);
|
|
2630
|
+
case "ticket.create": return this.tickets.create(req.params);
|
|
2631
|
+
case "ticket.answer": return this.tickets.answer(req.params, conn.client);
|
|
2632
|
+
case "ticket.list": return this.tickets.list(req.params, conn.client);
|
|
2633
|
+
case "ticket.cancel": return this.tickets.cancel(req.params, conn.client);
|
|
2634
|
+
case "permission.relay": return this.tickets.relay(req.params, conn.client);
|
|
2635
|
+
case "permission.request": return this.tickets.request(req.params);
|
|
2636
|
+
case "relay.status":
|
|
2637
|
+
case "devices.list":
|
|
2638
|
+
case "devices.pair":
|
|
2639
|
+
case "devices.pairStatus":
|
|
2640
|
+
case "devices.pairConfirm":
|
|
2641
|
+
case "devices.revoke":
|
|
2642
|
+
case "devices.rename":
|
|
2643
|
+
case "devices.accept":
|
|
2644
|
+
case "devices.reset": return this.relayCall(req);
|
|
570
2645
|
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
2646
|
}
|
|
572
2647
|
}
|
|
573
2648
|
hello(conn, p) {
|
|
574
2649
|
if (conn.challenge !== void 0) throw new ConvenoError(RpcErrorCode.Conflict, "The handshake already started on this connection.");
|
|
575
2650
|
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.`);
|
|
2651
|
+
conn.kind = p.client;
|
|
576
2652
|
conn.challenge = newAuthNonce();
|
|
2653
|
+
conn.client = p.client;
|
|
577
2654
|
return {
|
|
578
2655
|
protocolVersion: PROTOCOL_VERSION,
|
|
579
2656
|
daemonVersion: DAEMON_VERSION,
|
|
@@ -599,8 +2676,29 @@ var Daemon = class {
|
|
|
599
2676
|
if (!row) throw new ConvenoError(RpcErrorCode.NotFound, `No session with id ${id}. Register the session again.`);
|
|
600
2677
|
return row;
|
|
601
2678
|
}
|
|
2679
|
+
requireOnline(id) {
|
|
2680
|
+
const row = this.requireSession(id);
|
|
2681
|
+
if (row.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${row.name}" is offline. Register the session again.`);
|
|
2682
|
+
return row;
|
|
2683
|
+
}
|
|
602
2684
|
view(row) {
|
|
603
|
-
return toSession(row, effectiveHolder(this.store.holder(), this.named([row]))?.id === row.id);
|
|
2685
|
+
return toSession(row, effectiveHolder(this.store.holder(), this.named([row]))?.id === row.id, this.store.unreadCount(row.id));
|
|
2686
|
+
}
|
|
2687
|
+
/** The orchestrator as routing sees it: the holder, if it is online. */
|
|
2688
|
+
orchestratorNow() {
|
|
2689
|
+
return effectiveHolder(this.store.holder(), this.named(this.store.allSessions()))?.id ?? null;
|
|
2690
|
+
}
|
|
2691
|
+
/** The online session a recipient names (`orchestrator`, a name or an id). */
|
|
2692
|
+
resolveOnline(to) {
|
|
2693
|
+
const rows = this.store.allSessions();
|
|
2694
|
+
const found = resolveRecipient(to, this.named(rows), this.store.holder());
|
|
2695
|
+
return rows.find((r) => r.id === found.id);
|
|
2696
|
+
}
|
|
2697
|
+
/** Queue a message for a session and tell its subscriber. `limit` applies the unread cap. */
|
|
2698
|
+
queueMessage(message, row, limit) {
|
|
2699
|
+
if (limit && this.store.unreadCount(row.id) >= 1e3) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(row.name, MAX_UNREAD_PER_SESSION));
|
|
2700
|
+
this.store.insertMessage(message, row.id, message.createdAt);
|
|
2701
|
+
this.emitMessage(message, row.id);
|
|
604
2702
|
}
|
|
605
2703
|
emit(payload, onlyTo) {
|
|
606
2704
|
for (const c of this.conns) {
|
|
@@ -619,6 +2717,7 @@ var Daemon = class {
|
|
|
619
2717
|
change
|
|
620
2718
|
}
|
|
621
2719
|
});
|
|
2720
|
+
this.relay?.sessionsChanged();
|
|
622
2721
|
}
|
|
623
2722
|
emitMessage(m, recipient) {
|
|
624
2723
|
this.emit({
|
|
@@ -646,8 +2745,13 @@ var Daemon = class {
|
|
|
646
2745
|
deviceId: this.deviceId,
|
|
647
2746
|
cwd: p.cwd,
|
|
648
2747
|
status: "idle",
|
|
649
|
-
deliveryTier: CLI_TIER[p.cli] ?? "inbox",
|
|
2748
|
+
deliveryTier: p.acp ? "acp" : CLI_TIER[p.cli] ?? "inbox",
|
|
2749
|
+
spawned: p.spawned,
|
|
650
2750
|
spawnDepth: parent ? parent.spawnDepth + 1 : 0,
|
|
2751
|
+
auto: p.auto ?? (p.spawned || p.spawnedBy !== void 0),
|
|
2752
|
+
autoExplicit: false,
|
|
2753
|
+
autoRuns: [],
|
|
2754
|
+
turnHops: 0,
|
|
651
2755
|
startedAt: at,
|
|
652
2756
|
lastSeenAt: at
|
|
653
2757
|
};
|
|
@@ -692,6 +2796,7 @@ var Daemon = class {
|
|
|
692
2796
|
this.store.updateSession(sessionId, { status: "offline" });
|
|
693
2797
|
if (after !== before) this.store.setHolder(after);
|
|
694
2798
|
});
|
|
2799
|
+
this.listeners.delete(sessionId);
|
|
695
2800
|
this.emitSession(sessionId, change);
|
|
696
2801
|
if (after !== before) this.emit({
|
|
697
2802
|
event: "orchestrator.changed",
|
|
@@ -729,25 +2834,57 @@ var Daemon = class {
|
|
|
729
2834
|
return { session: this.view(this.requireSession(p.sessionId)) };
|
|
730
2835
|
}
|
|
731
2836
|
list(p) {
|
|
732
|
-
|
|
2837
|
+
const rows = this.store.allSessions().filter((r) => {
|
|
733
2838
|
if (!p.includeOffline && r.status === "offline") return false;
|
|
734
2839
|
if (p.cli && r.cli !== p.cli) return false;
|
|
735
2840
|
if (p.repo && r.repoRoot !== p.repo && baseName(r.repoRoot ?? r.cwd) !== p.repo) return false;
|
|
736
2841
|
return true;
|
|
737
|
-
})
|
|
2842
|
+
});
|
|
2843
|
+
const remote = this.relay?.remoteSessions({
|
|
2844
|
+
cli: p.cli,
|
|
2845
|
+
repo: p.repo
|
|
2846
|
+
}) ?? [];
|
|
2847
|
+
return { sessions: [...rows.map((r) => this.view(r)), ...remote] };
|
|
738
2848
|
}
|
|
739
2849
|
/**
|
|
740
2850
|
* Find the session a hook belongs to: the one online session whose `hostPid` equals `pid`.
|
|
741
2851
|
* Exact equality only, with no walk to farther ancestors, so a hook from a CLI that has no
|
|
742
2852
|
* session matches nothing. Two sessions under one CLI process are ambiguous, so the result is
|
|
743
|
-
* null; the daemon never guesses.
|
|
2853
|
+
* null; the daemon never guesses. With `cwd`, the sessions that share the pid are narrowed to
|
|
2854
|
+
* those registered in the same folder (same comparison as peek: separators, trailing slash, case
|
|
2855
|
+
* on Windows), so several folders on one OpenCode 2.x server stay apart. Two sessions in one
|
|
2856
|
+
* folder still match nothing.
|
|
744
2857
|
*/
|
|
745
|
-
byHost(pid) {
|
|
746
|
-
const holders = this.store.allSessions().filter((r) => r.status !== "offline" && r.hostPid === pid);
|
|
2858
|
+
byHost(pid, cwd) {
|
|
2859
|
+
const holders = this.store.allSessions().filter((r) => r.status !== "offline" && r.hostPid === pid && (cwd === void 0 || samePath(r.cwd, cwd, this.transcriptEnv.platform)));
|
|
747
2860
|
const only = holders.length === 1 ? holders[0] : void 0;
|
|
748
2861
|
return { session: only ? this.view(only) : null };
|
|
749
2862
|
}
|
|
750
2863
|
/**
|
|
2864
|
+
* Walk up from a hook's parent pid to its host CLI, for a hook that would otherwise read the
|
|
2865
|
+
* process table itself. With no online session of the hook's CLI there is nothing the hook could
|
|
2866
|
+
* deliver to, so it answers `online: false` without reading anything. The answer is only the
|
|
2867
|
+
* pid: the hook still goes through `byHost`, which decides whether a session owns it.
|
|
2868
|
+
* `complete: false` means the table could not be read here and the hook should read it itself.
|
|
2869
|
+
*/
|
|
2870
|
+
async hostOf(p) {
|
|
2871
|
+
if (!this.store.allSessions().some((r) => r.status !== "offline" && r.cli === p.cli)) return {
|
|
2872
|
+
online: false,
|
|
2873
|
+
complete: true
|
|
2874
|
+
};
|
|
2875
|
+
const a = await readAncestry({
|
|
2876
|
+
ppid: p.ppid,
|
|
2877
|
+
timeoutMs: HOST_OF_TIMEOUT_MS,
|
|
2878
|
+
launcherPaths: p.launcherPaths ?? [],
|
|
2879
|
+
io: this.processIo
|
|
2880
|
+
});
|
|
2881
|
+
return {
|
|
2882
|
+
online: true,
|
|
2883
|
+
complete: a.complete,
|
|
2884
|
+
...a.complete && a.hostPid !== void 0 ? { hostPid: a.hostPid } : {}
|
|
2885
|
+
};
|
|
2886
|
+
}
|
|
2887
|
+
/**
|
|
751
2888
|
* Remove offline sessions on the owner's request. Selection: with `ids` or `names` the
|
|
752
2889
|
* candidates are the sessions matching either; with neither, every session. `olderThanMs` then
|
|
753
2890
|
* keeps only sessions last seen at least that long ago. Online candidates are never removed:
|
|
@@ -776,11 +2913,82 @@ var Daemon = class {
|
|
|
776
2913
|
skippedOnline: skippedOnline.map(brief)
|
|
777
2914
|
};
|
|
778
2915
|
}
|
|
2916
|
+
/**
|
|
2917
|
+
* A hook reports the CLI's own session id and transcript file. The session is the one online
|
|
2918
|
+
* session whose `hostPid` equals `pid`, as in `byHost`; no unique match changes nothing. A new
|
|
2919
|
+
* CLI session id with no path drops the old path, which belonged to the previous conversation.
|
|
2920
|
+
*/
|
|
2921
|
+
setCliInfo(p) {
|
|
2922
|
+
const holders = this.store.allSessions().filter((r) => r.status !== "offline" && r.hostPid === p.pid);
|
|
2923
|
+
const row = holders.length === 1 ? holders[0] : void 0;
|
|
2924
|
+
if (!row) return { updated: false };
|
|
2925
|
+
const fields = {};
|
|
2926
|
+
if (p.cliSessionId !== void 0) fields.cliSessionId = p.cliSessionId;
|
|
2927
|
+
if (p.transcriptPath !== void 0) fields.transcriptPath = p.transcriptPath;
|
|
2928
|
+
else if (p.cliSessionId !== void 0 && p.cliSessionId !== row.cliSessionId) fields.transcriptPath = null;
|
|
2929
|
+
this.store.updateSession(row.id, fields);
|
|
2930
|
+
return { updated: true };
|
|
2931
|
+
}
|
|
2932
|
+
/** The owner's switch. With no `session`, every online session on this device. */
|
|
2933
|
+
setPeekable(p) {
|
|
2934
|
+
const rows = this.store.allSessions();
|
|
2935
|
+
const targets = p.session === void 0 ? rows.filter((r) => r.status !== "offline") : rows.filter((r) => r.id === p.session || r.name === p.session && r.status !== "offline");
|
|
2936
|
+
if (p.session !== void 0 && targets.length === 0) throw new ConvenoError(RpcErrorCode.NotFound, `No online session "${p.session}". Run "conveno status" to see the names.`);
|
|
2937
|
+
for (const r of targets) this.store.updateSession(r.id, { peekable: p.peekable });
|
|
2938
|
+
return { sessions: targets.map((r) => ({
|
|
2939
|
+
id: r.id,
|
|
2940
|
+
name: r.name,
|
|
2941
|
+
peekable: p.peekable
|
|
2942
|
+
})) };
|
|
2943
|
+
}
|
|
2944
|
+
/**
|
|
2945
|
+
* Read the recent turns of another session's transcript on this device. Redaction is always on.
|
|
2946
|
+
* The target's owner can see every peek in the daemon log (who looked at whom and how many
|
|
2947
|
+
* turns, never the content), and can turn peek off for a session.
|
|
2948
|
+
*/
|
|
2949
|
+
async peek(conn, p) {
|
|
2950
|
+
if (p.sessionId === void 0 && conn.kind !== "cli") throw new ConvenoError(RpcErrorCode.InvalidParams, "A session must give its own sessionId to peek. Only the conveno command may peek without one.");
|
|
2951
|
+
const caller = p.sessionId !== void 0 ? this.requireSession(p.sessionId) : void 0;
|
|
2952
|
+
const target = this.store.getSession(resolveRecipient(p.target, this.named(this.store.allSessions()), this.store.holder()).id);
|
|
2953
|
+
const who = `${caller ? `${caller.name} (${caller.id})` : "the conveno command"} -> ${target.name} (${target.id}, ${target.cli})`;
|
|
2954
|
+
if (target.peekable === false) {
|
|
2955
|
+
this.log.note(`peek refused, peek is off: ${who}`);
|
|
2956
|
+
throw new ConvenoError(RpcErrorCode.PermissionRequired, `Peek is turned off for ${target.name}. Its owner can run "conveno peek on ${target.name}" to allow it.`);
|
|
2957
|
+
}
|
|
2958
|
+
const reader = target.deliveryTier === "acp" ? acpTranscript : this.transcripts[target.cli];
|
|
2959
|
+
if (!reader) throw new ConvenoError(RpcErrorCode.InvalidParams, `peek not supported for ${target.cli} yet.`);
|
|
2960
|
+
const res = await reader.read({
|
|
2961
|
+
cwd: target.cwd,
|
|
2962
|
+
startedAt: target.startedAt,
|
|
2963
|
+
lastTurns: p.lastTurns,
|
|
2964
|
+
...target.cliSessionId !== void 0 ? { cliSessionId: target.cliSessionId } : {},
|
|
2965
|
+
...target.transcriptPath !== void 0 ? { transcriptPath: target.transcriptPath } : {},
|
|
2966
|
+
...target.hostPid !== void 0 ? { hostPid: target.hostPid } : {}
|
|
2967
|
+
}, this.transcriptEnv);
|
|
2968
|
+
if (!res.ok) {
|
|
2969
|
+
this.log.note(`peek found nothing (${res.reason}): ${who}`);
|
|
2970
|
+
throw new ConvenoError(res.reason === "unsupported" ? RpcErrorCode.InvalidParams : RpcErrorCode.NotFound, res.message);
|
|
2971
|
+
}
|
|
2972
|
+
const out = preparePeek(res.entries, res.more, p.maxChars);
|
|
2973
|
+
this.log.note(`peek: ${who}, ${out.turns.length} turns, ${out.redactions} redactions`);
|
|
2974
|
+
return {
|
|
2975
|
+
session: {
|
|
2976
|
+
id: target.id,
|
|
2977
|
+
name: target.name,
|
|
2978
|
+
cli: target.cli
|
|
2979
|
+
},
|
|
2980
|
+
turns: out.turns,
|
|
2981
|
+
truncated: out.truncated,
|
|
2982
|
+
redacted: true,
|
|
2983
|
+
redactions: out.redactions
|
|
2984
|
+
};
|
|
2985
|
+
}
|
|
779
2986
|
forgetRows(rows) {
|
|
780
2987
|
if (rows.length === 0) return;
|
|
781
2988
|
this.store.tx(() => {
|
|
782
2989
|
for (const r of rows) this.store.deleteSession(r.id);
|
|
783
2990
|
});
|
|
2991
|
+
for (const r of rows) this.listeners.delete(r.id);
|
|
784
2992
|
}
|
|
785
2993
|
/**
|
|
786
2994
|
* An offline session whose working folder (or repository root) has been missing for
|
|
@@ -843,7 +3051,14 @@ var Daemon = class {
|
|
|
843
3051
|
if (p.kind === "system") throw new ConvenoError(RpcErrorCode.InvalidParams, "Messages of kind \"system\" are made by the Conveno daemon only. Send kind \"text\" instead.");
|
|
844
3052
|
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
3053
|
const rows = this.store.allSessions();
|
|
846
|
-
|
|
3054
|
+
let target;
|
|
3055
|
+
try {
|
|
3056
|
+
target = resolveRecipient(p.to, this.named(rows), this.store.holder());
|
|
3057
|
+
} catch (e) {
|
|
3058
|
+
const remote = e instanceof ConvenoError && e.code === RpcErrorCode.NotFound ? this.relay?.resolveRemote(p.to) : void 0;
|
|
3059
|
+
if (!remote) throw e;
|
|
3060
|
+
return this.sendToRemote(sender, remote, p);
|
|
3061
|
+
}
|
|
847
3062
|
const targetRow = rows.find((r) => r.id === target.id);
|
|
848
3063
|
if (this.store.unreadCount(targetRow.id) >= 1e3) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(targetRow.name, MAX_UNREAD_PER_SESSION));
|
|
849
3064
|
const at = this.iso();
|
|
@@ -859,17 +3074,208 @@ var Daemon = class {
|
|
|
859
3074
|
fromCli: sender.cli,
|
|
860
3075
|
...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
|
|
861
3076
|
};
|
|
862
|
-
this.store.
|
|
3077
|
+
const enableAuto = sender.id !== targetRow.id && effectiveHolder(this.store.holder(), this.named(rows))?.id === sender.id && !targetRow.auto && !targetRow.autoExplicit;
|
|
3078
|
+
const hops = sender.status === "busy" ? sender.turnHops : 0;
|
|
3079
|
+
this.store.tx(() => {
|
|
3080
|
+
this.store.insertMessage(message, targetRow.id, at, hops);
|
|
3081
|
+
if (enableAuto) this.store.updateSession(targetRow.id, { auto: true });
|
|
3082
|
+
});
|
|
3083
|
+
if (enableAuto) {
|
|
3084
|
+
targetRow.auto = true;
|
|
3085
|
+
this.emitSession(targetRow.id, "updated");
|
|
3086
|
+
}
|
|
863
3087
|
this.emitMessage(message, targetRow.id);
|
|
864
3088
|
return {
|
|
865
3089
|
message,
|
|
866
|
-
delivery: targetRow
|
|
3090
|
+
delivery: this.tierFor(targetRow),
|
|
867
3091
|
deliveredTo: {
|
|
868
3092
|
id: targetRow.id,
|
|
869
3093
|
name: targetRow.name
|
|
870
3094
|
}
|
|
871
3095
|
};
|
|
872
3096
|
}
|
|
3097
|
+
/** `live` for a session in auto mode whose CLI can be woken; otherwise the CLI's own tier. */
|
|
3098
|
+
tierFor(row) {
|
|
3099
|
+
const running = row.auto && row.autoPausedBy === void 0;
|
|
3100
|
+
if (row.deliveryTier === "acp") return running ? "acp" : "inbox";
|
|
3101
|
+
if (running && CLI_WAKE.has(row.cli)) return "live";
|
|
3102
|
+
return row.deliveryTier;
|
|
3103
|
+
}
|
|
3104
|
+
/**
|
|
3105
|
+
* Change auto mode. The owner (no `sessionId`) may do anything. A session may only resume a paused
|
|
3106
|
+
* session, only while it is the orchestrator, and only once per window for that session, so two
|
|
3107
|
+
* agents cannot keep each other going without the owner.
|
|
3108
|
+
*/
|
|
3109
|
+
setAuto(p) {
|
|
3110
|
+
const all = this.store.allSessions();
|
|
3111
|
+
const row = all.find((r) => r.id === p.session) ?? all.find((r) => r.name === p.session && r.status !== "offline") ?? all.findLast((r) => r.name === p.session);
|
|
3112
|
+
if (!row) throw new ConvenoError(RpcErrorCode.NotFound, `No session named "${p.session}". Run conveno status to see the sessions.`);
|
|
3113
|
+
const at = this.iso();
|
|
3114
|
+
const byOrchestrator = p.sessionId !== void 0;
|
|
3115
|
+
if (p.sessionId !== void 0) {
|
|
3116
|
+
const caller = this.requireOnline(p.sessionId);
|
|
3117
|
+
if (this.orchestratorNow() !== caller.id) throw new ConvenoError(RpcErrorCode.PermissionRequired, "Only the orchestrator can resume auto mode for another session. The owner can run: conveno auto resume <session>");
|
|
3118
|
+
if (p.auto !== void 0 || p.limit !== void 0) throw new ConvenoError(RpcErrorCode.PermissionRequired, "A session can only resume auto mode. Turning it on or off and changing the limit is up to the owner: conveno auto");
|
|
3119
|
+
if (row.autoPausedBy === void 0) throw new ConvenoError(RpcErrorCode.PermissionRequired, `Auto mode for "${row.name}" is not paused.`);
|
|
3120
|
+
const last = row.autoOrchResumedAt ? Date.parse(row.autoOrchResumedAt) : NaN;
|
|
3121
|
+
if (this.now().getTime() - last < this.autoLimits.windowMs) {
|
|
3122
|
+
const minutes = Math.round(this.autoLimits.windowMs / 6e4);
|
|
3123
|
+
throw new ConvenoError(RpcErrorCode.PermissionRequired, `The orchestrator already resumed auto mode for "${row.name}" within the last ${minutes} minutes. Only the owner can resume it now: conveno auto resume ${row.name}`);
|
|
3124
|
+
}
|
|
3125
|
+
}
|
|
3126
|
+
const lift = p.resume === true || p.auto === true;
|
|
3127
|
+
this.store.tx(() => {
|
|
3128
|
+
this.store.updateSession(row.id, {
|
|
3129
|
+
...p.auto !== void 0 ? {
|
|
3130
|
+
auto: p.auto,
|
|
3131
|
+
autoExplicit: true
|
|
3132
|
+
} : {},
|
|
3133
|
+
...p.limit !== void 0 ? { autoLimit: p.limit } : {},
|
|
3134
|
+
...lift ? {
|
|
3135
|
+
autoPausedAt: null,
|
|
3136
|
+
autoPausedBy: null,
|
|
3137
|
+
autoRuns: []
|
|
3138
|
+
} : {},
|
|
3139
|
+
...byOrchestrator ? { autoOrchResumedAt: at } : {}
|
|
3140
|
+
});
|
|
3141
|
+
if (lift) this.store.resetQueuedHops(row.id);
|
|
3142
|
+
});
|
|
3143
|
+
this.emitSession(row.id, "updated");
|
|
3144
|
+
return { session: this.view(this.requireSession(row.id)) };
|
|
3145
|
+
}
|
|
3146
|
+
/**
|
|
3147
|
+
* The user typed a prompt: the session is busy, and messages it sends start a new chain (0 hops).
|
|
3148
|
+
* A pause stays until the owner or the orchestrator resumes it.
|
|
3149
|
+
*/
|
|
3150
|
+
turnStart(sessionId) {
|
|
3151
|
+
this.requireOnline(sessionId);
|
|
3152
|
+
this.store.updateSession(sessionId, {
|
|
3153
|
+
status: "busy",
|
|
3154
|
+
turnHops: 0
|
|
3155
|
+
});
|
|
3156
|
+
this.emitSession(sessionId, "updated");
|
|
3157
|
+
return { session: this.view(this.requireSession(sessionId)) };
|
|
3158
|
+
}
|
|
3159
|
+
/** The notice a session gets when its auto mode pauses. It waits for the next prompt. */
|
|
3160
|
+
pauseNotice(row, reason, at) {
|
|
3161
|
+
const minutes = Math.round(this.autoLimits.windowMs / 6e4);
|
|
3162
|
+
const limit = row.autoLimit ?? this.autoLimits.limit;
|
|
3163
|
+
const detail = `Conveno paused auto mode for this session (${pauseLabel(reason)}): ${limit} automatic turns within ${minutes} minutes, or a message that ${limit} automatic turns led to with no person in between (sessions answering each other). Messages still arrive at the next prompt. The owner can resume it with: conveno auto resume ${row.name}; the orchestrator can once per ${minutes} minutes.`;
|
|
3164
|
+
return {
|
|
3165
|
+
id: newMessageId(),
|
|
3166
|
+
from: DAEMON_SENDER_ID,
|
|
3167
|
+
to: row.id,
|
|
3168
|
+
kind: "system",
|
|
3169
|
+
body: {
|
|
3170
|
+
event: "auto.paused",
|
|
3171
|
+
detail
|
|
3172
|
+
},
|
|
3173
|
+
urgent: false,
|
|
3174
|
+
createdAt: at
|
|
3175
|
+
};
|
|
3176
|
+
}
|
|
3177
|
+
/**
|
|
3178
|
+
* Hand the session its waiting messages to continue with, if auto mode and its limit allow it.
|
|
3179
|
+
* On a hand-over the session is busy and its turn carries the hops. With `endOfTurn`, nothing
|
|
3180
|
+
* handed over means the session is now idle. One transaction.
|
|
3181
|
+
*/
|
|
3182
|
+
continueWith(row, allow, endOfTurn) {
|
|
3183
|
+
const nowMs = this.now().getTime();
|
|
3184
|
+
const at = this.iso();
|
|
3185
|
+
const orchestrator = this.orchestratorNow();
|
|
3186
|
+
let pausedBy = row.autoPausedBy;
|
|
3187
|
+
let notice;
|
|
3188
|
+
const res = this.store.tx(() => {
|
|
3189
|
+
const queued = this.store.entries(row.id, { states: ["queued"] });
|
|
3190
|
+
const candidates = allow ? autoCandidates(queued, row.id) : [];
|
|
3191
|
+
const decision = decideAutoContinue({
|
|
3192
|
+
auto: row.auto,
|
|
3193
|
+
...row.autoPausedBy !== void 0 ? { pausedBy: row.autoPausedBy } : {},
|
|
3194
|
+
...row.autoLimit !== void 0 ? { limit: row.autoLimit } : {},
|
|
3195
|
+
runs: row.autoRuns
|
|
3196
|
+
}, candidates, nowMs, this.autoLimits);
|
|
3197
|
+
if (decision.continue) {
|
|
3198
|
+
const taken = takeWithinBytes(candidates.slice(0, 20), RESPONSE_BUDGET_BYTES);
|
|
3199
|
+
const updated = markDelivered(taken, taken.map((e) => e.message.id), at);
|
|
3200
|
+
for (const e of updated) this.store.saveEntry(row.id, e);
|
|
3201
|
+
this.store.updateSession(row.id, {
|
|
3202
|
+
status: "busy",
|
|
3203
|
+
autoRuns: decision.runs,
|
|
3204
|
+
turnHops: turnHops(taken)
|
|
3205
|
+
});
|
|
3206
|
+
return {
|
|
3207
|
+
messages: updated.map((e) => e.message),
|
|
3208
|
+
remaining: queued.length - taken.length
|
|
3209
|
+
};
|
|
3210
|
+
}
|
|
3211
|
+
if (decision.pause !== void 0) {
|
|
3212
|
+
pausedBy = decision.pause;
|
|
3213
|
+
notice = this.pauseNotice(row, decision.pause, at);
|
|
3214
|
+
this.store.insertMessage(notice, row.id, at);
|
|
3215
|
+
this.store.updateSession(row.id, {
|
|
3216
|
+
autoPausedAt: at,
|
|
3217
|
+
autoPausedBy: decision.pause
|
|
3218
|
+
});
|
|
3219
|
+
}
|
|
3220
|
+
if (endOfTurn) this.store.updateSession(row.id, {
|
|
3221
|
+
status: "idle",
|
|
3222
|
+
turnHops: 0
|
|
3223
|
+
});
|
|
3224
|
+
return {
|
|
3225
|
+
messages: [],
|
|
3226
|
+
remaining: queued.length + (notice ? 1 : 0)
|
|
3227
|
+
};
|
|
3228
|
+
});
|
|
3229
|
+
if (notice) this.emitMessage(notice, row.id);
|
|
3230
|
+
if ((res.messages.length > 0 ? row.status !== "busy" : endOfTurn && row.status !== "idle") || notice) this.emitSession(row.id, "updated");
|
|
3231
|
+
return {
|
|
3232
|
+
...res,
|
|
3233
|
+
auto: row.auto,
|
|
3234
|
+
paused: pausedBy !== void 0,
|
|
3235
|
+
...pausedBy !== void 0 ? { pausedBy } : {},
|
|
3236
|
+
orchestrator
|
|
3237
|
+
};
|
|
3238
|
+
}
|
|
3239
|
+
turnEnd(p) {
|
|
3240
|
+
const row = this.requireOnline(p.sessionId);
|
|
3241
|
+
if (row.status === "waiting_on_question") return this.continueWith(row, false, false);
|
|
3242
|
+
return this.continueWith(row, p.allowContinue, true);
|
|
3243
|
+
}
|
|
3244
|
+
/**
|
|
3245
|
+
* An idle-wake listener asks for work. The newest listener of a session wins: an older one gets
|
|
3246
|
+
* `superseded` and stops. A busy session is not woken; its messages wait for the end of the turn.
|
|
3247
|
+
*/
|
|
3248
|
+
turnWake(p) {
|
|
3249
|
+
const row = this.requireOnline(p.sessionId);
|
|
3250
|
+
const known = this.listeners.get(row.id);
|
|
3251
|
+
if (known?.retired.includes(p.listenerId)) return {
|
|
3252
|
+
messages: [],
|
|
3253
|
+
remaining: this.store.unreadCount(row.id),
|
|
3254
|
+
auto: row.auto,
|
|
3255
|
+
paused: row.autoPausedBy !== void 0,
|
|
3256
|
+
...row.autoPausedBy !== void 0 ? { pausedBy: row.autoPausedBy } : {},
|
|
3257
|
+
orchestrator: this.orchestratorNow(),
|
|
3258
|
+
superseded: true
|
|
3259
|
+
};
|
|
3260
|
+
if (known?.current !== p.listenerId) {
|
|
3261
|
+
const retired = known ? [...known.retired, known.current].slice(-64) : [];
|
|
3262
|
+
this.listeners.set(row.id, {
|
|
3263
|
+
current: p.listenerId,
|
|
3264
|
+
retired
|
|
3265
|
+
});
|
|
3266
|
+
if (known) this.emit({
|
|
3267
|
+
event: "session.updated",
|
|
3268
|
+
data: {
|
|
3269
|
+
session: this.view(row),
|
|
3270
|
+
change: "updated"
|
|
3271
|
+
}
|
|
3272
|
+
}, row.id);
|
|
3273
|
+
}
|
|
3274
|
+
return {
|
|
3275
|
+
...this.continueWith(row, row.status === "idle", false),
|
|
3276
|
+
superseded: false
|
|
3277
|
+
};
|
|
3278
|
+
}
|
|
873
3279
|
inbox(p) {
|
|
874
3280
|
this.requireSession(p.sessionId);
|
|
875
3281
|
const at = this.iso();
|
|
@@ -921,6 +3327,79 @@ var Daemon = class {
|
|
|
921
3327
|
};
|
|
922
3328
|
return { subscribed: topics };
|
|
923
3329
|
}
|
|
3330
|
+
relayCall(req) {
|
|
3331
|
+
const relay = this.relay;
|
|
3332
|
+
if (!relay) throw new ConvenoError(RpcErrorCode.MethodNotFound, "The relay is disabled in this daemon.");
|
|
3333
|
+
switch (req.method) {
|
|
3334
|
+
case "relay.status": return relay.status();
|
|
3335
|
+
case "devices.list": return relay.devices();
|
|
3336
|
+
case "devices.pair": return relay.pairStart(req.params);
|
|
3337
|
+
case "devices.pairStatus": return relay.pairStatus(req.params);
|
|
3338
|
+
case "devices.pairConfirm": return relay.pairConfirm(req.params);
|
|
3339
|
+
case "devices.revoke": return relay.revoke(req.params);
|
|
3340
|
+
case "devices.rename": return relay.rename(req.params);
|
|
3341
|
+
case "devices.accept": return relay.accept(req.params);
|
|
3342
|
+
case "devices.reset": return relay.reset();
|
|
3343
|
+
default: throw new ConvenoError(RpcErrorCode.MethodNotFound, `Method not found: ${req.method}`);
|
|
3344
|
+
}
|
|
3345
|
+
}
|
|
3346
|
+
sendToRemote(sender, target, p) {
|
|
3347
|
+
const message = {
|
|
3348
|
+
id: newMessageId(),
|
|
3349
|
+
from: sender.id,
|
|
3350
|
+
to: p.to,
|
|
3351
|
+
kind: p.kind,
|
|
3352
|
+
body: p.body,
|
|
3353
|
+
urgent: p.urgent,
|
|
3354
|
+
createdAt: this.iso(),
|
|
3355
|
+
fromName: sender.name,
|
|
3356
|
+
fromCli: sender.cli,
|
|
3357
|
+
...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
|
|
3358
|
+
};
|
|
3359
|
+
this.relay.sendRemote(target, message);
|
|
3360
|
+
return {
|
|
3361
|
+
message,
|
|
3362
|
+
delivery: target.deliveryTier,
|
|
3363
|
+
deliveredTo: {
|
|
3364
|
+
id: target.id,
|
|
3365
|
+
name: target.name
|
|
3366
|
+
}
|
|
3367
|
+
};
|
|
3368
|
+
}
|
|
3369
|
+
/** The daemon side of the relay: local sessions out, remote messages in. */
|
|
3370
|
+
relayHost() {
|
|
3371
|
+
return {
|
|
3372
|
+
log: this.log,
|
|
3373
|
+
localSessions: () => this.store.allSessions().filter((r) => r.status !== "offline").map((r) => this.view(r)),
|
|
3374
|
+
deliverLocal: (m, to) => {
|
|
3375
|
+
if (m.kind === "system") return "not_allowed";
|
|
3376
|
+
const row = this.store.getSession(to);
|
|
3377
|
+
if (!row) return "session_gone";
|
|
3378
|
+
if (row.status === "offline") return "session_offline";
|
|
3379
|
+
if (this.store.hasMessage(m.id)) return void 0;
|
|
3380
|
+
if (this.store.unreadCount(row.id) >= 1e3) return "mailbox_full";
|
|
3381
|
+
this.store.insertMessage(m, row.id, this.iso());
|
|
3382
|
+
this.emitMessage(m, row.id);
|
|
3383
|
+
},
|
|
3384
|
+
notify: (to, event, detail) => {
|
|
3385
|
+
if (!this.store.getSession(to)) return;
|
|
3386
|
+
const m = {
|
|
3387
|
+
id: newMessageId(),
|
|
3388
|
+
from: DAEMON_SENDER_ID,
|
|
3389
|
+
to,
|
|
3390
|
+
kind: "system",
|
|
3391
|
+
body: {
|
|
3392
|
+
event,
|
|
3393
|
+
detail: detail.slice(0, 2e3)
|
|
3394
|
+
},
|
|
3395
|
+
urgent: false,
|
|
3396
|
+
createdAt: this.iso()
|
|
3397
|
+
};
|
|
3398
|
+
this.store.insertMessage(m, to, this.iso());
|
|
3399
|
+
this.emitMessage(m, to);
|
|
3400
|
+
}
|
|
3401
|
+
};
|
|
3402
|
+
}
|
|
924
3403
|
/**
|
|
925
3404
|
* Prune rules for an offline session, in order:
|
|
926
3405
|
* 1. With unread messages waiting, keep it for PRUNE_UNREAD_AFTER_MS, then delete it and its mail.
|
|
@@ -936,6 +3415,7 @@ var Daemon = class {
|
|
|
936
3415
|
return offlineMs >= (all.some((o) => o.id !== row.id && o.status !== "offline" && o.name === row.name && o.cli === row.cli && place(o) === place(row) && Date.parse(o.startedAt) > Date.parse(row.startedAt)) ? PRUNE_SUPERSEDED_AFTER_MS : PRUNE_OFFLINE_AFTER_MS);
|
|
937
3416
|
}
|
|
938
3417
|
sweep() {
|
|
3418
|
+
this.tickets.sweep();
|
|
939
3419
|
const nowMs = this.now().getTime();
|
|
940
3420
|
let online = 0;
|
|
941
3421
|
const rows = this.store.allSessions();
|
|
@@ -957,6 +3437,20 @@ var Daemon = class {
|
|
|
957
3437
|
}
|
|
958
3438
|
};
|
|
959
3439
|
const unauthorizedMessage = "Finish the handshake first: call hello, then auth. Both use the token in daemon.token in the Conveno data directory.";
|
|
3440
|
+
/** Start the relay client. A broken relay state is logged and leaves the daemon local-only. */
|
|
3441
|
+
function startRelay(daemon, opts, relayOpts) {
|
|
3442
|
+
try {
|
|
3443
|
+
const hub = new RelayHub({
|
|
3444
|
+
...relayOpts,
|
|
3445
|
+
dataDir: opts.dataDir,
|
|
3446
|
+
host: daemon.relayHost()
|
|
3447
|
+
});
|
|
3448
|
+
hub.start();
|
|
3449
|
+
daemon.relay = hub;
|
|
3450
|
+
} catch (e) {
|
|
3451
|
+
daemon.relayHost().log.error("relay: could not start; the daemon runs local-only", e);
|
|
3452
|
+
}
|
|
3453
|
+
}
|
|
960
3454
|
/** Start convenod: take the lock, open the database, listen on the socket. */
|
|
961
3455
|
async function startDaemon(opts) {
|
|
962
3456
|
const platform = process.platform;
|
|
@@ -965,6 +3459,11 @@ async function startDaemon(opts) {
|
|
|
965
3459
|
if (isSocketPathTooLong(socketPath, platform)) throw new Error(socketPathTooLongMessage(socketPath, platform));
|
|
966
3460
|
const now = opts.now ?? (() => /* @__PURE__ */ new Date());
|
|
967
3461
|
const isAlive = opts.isAlive ?? defaultIsAlive;
|
|
3462
|
+
const walker = opts.processIo === void 0 && platform === "win32" ? createWmiWalker({ scriptPath: join(opts.dataDir, "wmi-walk.js") }) : void 0;
|
|
3463
|
+
const processIo = opts.processIo ?? (walker ? {
|
|
3464
|
+
...defaultProcessIo,
|
|
3465
|
+
walk: walker.walk
|
|
3466
|
+
} : defaultProcessIo);
|
|
968
3467
|
ensureDir(opts.dataDir);
|
|
969
3468
|
const releaseLock = await acquireLock(paths.lock, socketPath);
|
|
970
3469
|
let store;
|
|
@@ -980,7 +3479,7 @@ async function startDaemon(opts) {
|
|
|
980
3479
|
close().then(() => opts.onIdleExit?.());
|
|
981
3480
|
}, () => {
|
|
982
3481
|
close().then(() => opts.onShutdown?.());
|
|
983
|
-
}, createDaemonLog(paths.daemonLog, { now }), opts.authTimeoutMs ?? 5e3, opts.pathExists ?? existsSync);
|
|
3482
|
+
}, createDaemonLog(paths.daemonLog, { now }), opts.authTimeoutMs ?? 5e3, opts.pathExists ?? existsSync, opts.autoLimits ?? autoLimitsFromEnv(process.env), opts.transcripts, opts.transcriptEnv, processIo);
|
|
984
3483
|
const srv = createServer((socket) => daemon.attach(socket));
|
|
985
3484
|
server = srv;
|
|
986
3485
|
await new Promise((resolve, reject) => {
|
|
@@ -988,12 +3487,15 @@ async function startDaemon(opts) {
|
|
|
988
3487
|
srv.listen(socketPath, () => resolve());
|
|
989
3488
|
});
|
|
990
3489
|
if (platform !== "win32" && !socketPath.startsWith("\\\\")) chmodSync(socketPath, 384);
|
|
3490
|
+
if (opts.relay !== false) startRelay(daemon, opts, opts.relay ?? {});
|
|
991
3491
|
timer = setInterval(() => daemon.sweep(), opts.sweepIntervalMs ?? 15e3);
|
|
992
3492
|
timer.unref();
|
|
993
3493
|
const liveStore = store;
|
|
994
3494
|
function close() {
|
|
995
3495
|
closing ??= (async () => {
|
|
996
3496
|
if (timer) clearInterval(timer);
|
|
3497
|
+
walker?.close();
|
|
3498
|
+
daemon.relay?.stop();
|
|
997
3499
|
const stopped = new Promise((resolve) => srv.close(() => resolve()));
|
|
998
3500
|
for (const c of daemon.conns) c.socket.destroy();
|
|
999
3501
|
await stopped;
|
|
@@ -1015,10 +3517,264 @@ async function startDaemon(opts) {
|
|
|
1015
3517
|
throw e;
|
|
1016
3518
|
}
|
|
1017
3519
|
}
|
|
3520
|
+
// ../adapters/copilot/dist/transcript.js
|
|
3521
|
+
/**
|
|
3522
|
+
* GitHub Copilot CLI keeps each session in `~/.copilot/session-state/<session-id>/` (COPILOT_HOME
|
|
3523
|
+
* replaces `~/.copilot`): `events.jsonl`, an append-only stream of `{ type, data, id, timestamp }`
|
|
3524
|
+
* records, and `workspace.yaml` with `id`, `cwd`, `created_at` and `updated_at`.
|
|
3525
|
+
*
|
|
3526
|
+
* GitHub does not document this layout. It is taken from community write-ups of Copilot CLI 1.0.11
|
|
3527
|
+
* and later (the events.jsonl reference gist
|
|
3528
|
+
* https://gist.github.com/RockNoggin/8cc87f640ce5e3d284298a6db21f7523 and
|
|
3529
|
+
* https://github.com/microsoft/What-I-Did-Copilot/blob/main/docs/architecture.md) and the open
|
|
3530
|
+
* request for documentation, github/copilot-cli#3551. The reference bundle in
|
|
3531
|
+
* reference/bundles/copilot-cli is a closed binary whose strings do not show the layout, so this
|
|
3532
|
+
* reader is not checked against a real install. It skips what it does not recognise.
|
|
3533
|
+
*/
|
|
3534
|
+
const copilotHome = (env) => env.env.COPILOT_HOME?.trim() || join(env.home, ".copilot");
|
|
3535
|
+
const unquote = (s) => s.trim().replace(/^(["'])(.*)\1$/, "$2");
|
|
3536
|
+
/** The `cwd:` value of a workspace.yaml, which is flat `key: value` lines. */
|
|
3537
|
+
function yamlCwd(yaml) {
|
|
3538
|
+
const m = /^cwd:[ \t]*(.+)$/m.exec(yaml);
|
|
3539
|
+
return m?.[1] ? unquote(m[1]) : void 0;
|
|
3540
|
+
}
|
|
3541
|
+
async function sessionCwd(dir) {
|
|
3542
|
+
try {
|
|
3543
|
+
const cwd = yamlCwd(await readFile(join(dir, "workspace.yaml"), "utf8"));
|
|
3544
|
+
if (cwd) return cwd;
|
|
3545
|
+
} catch {}
|
|
3546
|
+
try {
|
|
3547
|
+
const head = await readHeadLine(join(dir, "events.jsonl"), 262144);
|
|
3548
|
+
const ev = head ? JSON.parse(head) : null;
|
|
3549
|
+
const data = isRecord(ev) && ev.type === "session.start" ? ev.data : void 0;
|
|
3550
|
+
const context = isRecord(data) && isRecord(data.context) ? data.context : void 0;
|
|
3551
|
+
return asString(context?.cwd);
|
|
3552
|
+
} catch {
|
|
3553
|
+
return;
|
|
3554
|
+
}
|
|
3555
|
+
}
|
|
3556
|
+
const textOf = (v) => {
|
|
3557
|
+
if (typeof v === "string") return v;
|
|
3558
|
+
if (Array.isArray(v)) return v.map(textOf).filter(Boolean).join("\n");
|
|
3559
|
+
if (isRecord(v)) return asString(v.text) ?? asString(v.content) ?? "";
|
|
3560
|
+
return "";
|
|
3561
|
+
};
|
|
3562
|
+
/** Normalize one events.jsonl record. Exported for tests. */
|
|
3563
|
+
function parseCopilotEvent(obj) {
|
|
3564
|
+
const data = isRecord(obj.data) ? obj.data : {};
|
|
3565
|
+
if (data.agentId !== void 0) return [];
|
|
3566
|
+
const at = toIso(obj.timestamp);
|
|
3567
|
+
const stamp = at ? { at } : {};
|
|
3568
|
+
switch (obj.type) {
|
|
3569
|
+
case "user.message": {
|
|
3570
|
+
const text = asString(data.content) ?? "";
|
|
3571
|
+
return text === "" ? [] : [{
|
|
3572
|
+
role: "user",
|
|
3573
|
+
text,
|
|
3574
|
+
...stamp
|
|
3575
|
+
}];
|
|
3576
|
+
}
|
|
3577
|
+
case "assistant.message": {
|
|
3578
|
+
const out = [];
|
|
3579
|
+
const text = asString(data.content) ?? "";
|
|
3580
|
+
if (text !== "") out.push({
|
|
3581
|
+
role: "assistant",
|
|
3582
|
+
text,
|
|
3583
|
+
...stamp
|
|
3584
|
+
});
|
|
3585
|
+
if (Array.isArray(data.toolRequests)) for (const r of data.toolRequests) {
|
|
3586
|
+
if (!isRecord(r)) continue;
|
|
3587
|
+
out.push({
|
|
3588
|
+
role: "tool",
|
|
3589
|
+
text: describeToolCall(asString(r.name) ?? "tool", r.arguments ?? r.intentionSummary),
|
|
3590
|
+
...stamp
|
|
3591
|
+
});
|
|
3592
|
+
}
|
|
3593
|
+
return out;
|
|
3594
|
+
}
|
|
3595
|
+
case "tool.execution_complete": {
|
|
3596
|
+
const result = isRecord(data.result) ? data.result : {};
|
|
3597
|
+
const text = textOf(result.content) || textOf(result.detailedContent);
|
|
3598
|
+
return text === "" ? [] : [{
|
|
3599
|
+
role: "tool",
|
|
3600
|
+
text,
|
|
3601
|
+
...stamp
|
|
3602
|
+
}];
|
|
3603
|
+
}
|
|
3604
|
+
default: return [];
|
|
3605
|
+
}
|
|
3606
|
+
}
|
|
3607
|
+
/** Find the session directory, or the reason there is none. */
|
|
3608
|
+
async function locateCopilotSession(q, env) {
|
|
3609
|
+
const root = join(copilotHome(env), "session-state");
|
|
3610
|
+
if (q.cliSessionId && /^[A-Za-z0-9_-]{1,200}$/.test(q.cliSessionId)) {
|
|
3611
|
+
const dir = join(root, q.cliSessionId);
|
|
3612
|
+
if (await stat(join(dir, "events.jsonl")).then(() => true, () => false)) return { dir };
|
|
3613
|
+
}
|
|
3614
|
+
const since = Date.parse(q.startedAt);
|
|
3615
|
+
const floor = Number.isFinite(since) ? since - 5e3 : 0;
|
|
3616
|
+
for (const e of await entriesNewestFirst(root)) {
|
|
3617
|
+
if (!e.dir || e.mtimeMs < floor) continue;
|
|
3618
|
+
if (!await stat(join(e.path, "events.jsonl")).then(() => true, () => false)) continue;
|
|
3619
|
+
const cwd = await sessionCwd(e.path);
|
|
3620
|
+
if (cwd !== void 0 && samePath(cwd, q.cwd, env.platform)) return { dir: e.path };
|
|
3621
|
+
}
|
|
3622
|
+
return { error: "no session in session-state for this working directory since it started" };
|
|
3623
|
+
}
|
|
3624
|
+
const copilotTranscript = { async read(q, env) {
|
|
3625
|
+
try {
|
|
3626
|
+
const found = await locateCopilotSession(q, env);
|
|
3627
|
+
if ("error" in found) return notFound("Copilot", found.error);
|
|
3628
|
+
const { entries, more } = await tailJsonl(join(found.dir, "events.jsonl"), q.lastTurns, parseCopilotEvent);
|
|
3629
|
+
return {
|
|
3630
|
+
ok: true,
|
|
3631
|
+
entries,
|
|
3632
|
+
more
|
|
3633
|
+
};
|
|
3634
|
+
} catch (e) {
|
|
3635
|
+
return notFound("Copilot", e instanceof Error ? e.message : "read failed");
|
|
3636
|
+
}
|
|
3637
|
+
} };
|
|
3638
|
+
// ../adapters/grok/dist/transcript.js
|
|
3639
|
+
/**
|
|
3640
|
+
* Grok Build (xAI) keeps a session at
|
|
3641
|
+
* `$GROK_HOME/sessions/<encoded cwd>/<session id>/chat_history.jsonl`, `$GROK_HOME` defaulting to
|
|
3642
|
+
* `~/.grok`. The cwd directory name is the URL-encoded working directory; one over 255 bytes is
|
|
3643
|
+
* `<slug>-<blake3 hex16>` and holds a `.cwd` file with the real path.
|
|
3644
|
+
* reference/src/grok-build/crates/codegen/xai-dirs/src/lib.rs (grok home),
|
|
3645
|
+
* xai-grok-config/src/paths.rs (`encode_cwd_dirname`, `sessions_cwd_dir_in`),
|
|
3646
|
+
* xai-grok-shell/src/session/persistence.rs (`session_dir_in`).
|
|
3647
|
+
*
|
|
3648
|
+
* Each line of chat_history.jsonl is a `ConversationItem` tagged by `type`: `user`, `assistant`,
|
|
3649
|
+
* `tool_result`, `system`, `reasoning`, `backend_tool_call`
|
|
3650
|
+
* (xai-grok-sampling-types/src/conversation.rs). Items carry no timestamp.
|
|
3651
|
+
*/
|
|
3652
|
+
const grokHome = (env) => env.env.GROK_HOME?.trim() || join(env.home, ".grok");
|
|
3653
|
+
/** `urlencoding::encode`: everything but the unreserved characters `A-Za-z0-9-_.~` is percent-encoded. */
|
|
3654
|
+
function encodeCwdDirname(cwd) {
|
|
3655
|
+
return encodeURIComponent(cwd).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
3656
|
+
}
|
|
3657
|
+
const readText = (p) => readFile(p, "utf8").then((t) => t, () => void 0);
|
|
3658
|
+
const textParts = (content) => {
|
|
3659
|
+
if (typeof content === "string") return content;
|
|
3660
|
+
if (!Array.isArray(content)) return "";
|
|
3661
|
+
return content.map((p) => isRecord(p) && p.type === "text" ? asString(p.text) ?? "" : "").filter(Boolean).join("\n");
|
|
3662
|
+
};
|
|
3663
|
+
/** The user's own words: the CLI wraps the typed text in `<user_query>`. */
|
|
3664
|
+
const unwrapQuery = (text) => {
|
|
3665
|
+
return (/<user_query>([\s\S]*?)(?:<\/user_query>|$)/.exec(text)?.[1] ?? text).trim();
|
|
3666
|
+
};
|
|
3667
|
+
/** Normalize one chat_history.jsonl line. Exported for tests. */
|
|
3668
|
+
function parseGrokItem(obj) {
|
|
3669
|
+
switch (obj.type) {
|
|
3670
|
+
case "user": {
|
|
3671
|
+
const reason = obj.synthetic_reason;
|
|
3672
|
+
if (reason !== void 0 && reason !== null && reason !== "human") return [];
|
|
3673
|
+
const text = unwrapQuery(textParts(obj.content));
|
|
3674
|
+
return text === "" ? [] : [{
|
|
3675
|
+
role: "user",
|
|
3676
|
+
text
|
|
3677
|
+
}];
|
|
3678
|
+
}
|
|
3679
|
+
case "assistant": {
|
|
3680
|
+
const out = [];
|
|
3681
|
+
const text = asString(obj.content) ?? "";
|
|
3682
|
+
if (text !== "") out.push({
|
|
3683
|
+
role: "assistant",
|
|
3684
|
+
text
|
|
3685
|
+
});
|
|
3686
|
+
if (Array.isArray(obj.tool_calls)) {
|
|
3687
|
+
for (const c of obj.tool_calls) if (isRecord(c)) out.push({
|
|
3688
|
+
role: "tool",
|
|
3689
|
+
text: describeToolCall(asString(c.name) ?? "tool", c.arguments)
|
|
3690
|
+
});
|
|
3691
|
+
}
|
|
3692
|
+
return out;
|
|
3693
|
+
}
|
|
3694
|
+
case "tool_result": {
|
|
3695
|
+
const text = asString(obj.content) ?? "";
|
|
3696
|
+
return text === "" ? [] : [{
|
|
3697
|
+
role: "tool",
|
|
3698
|
+
text
|
|
3699
|
+
}];
|
|
3700
|
+
}
|
|
3701
|
+
default: return [];
|
|
3702
|
+
}
|
|
3703
|
+
}
|
|
3704
|
+
/** The directory of sessions for a working directory, or undefined. */
|
|
3705
|
+
async function cwdDir(root, cwd) {
|
|
3706
|
+
const direct = join(root, encodeCwdDirname(cwd));
|
|
3707
|
+
if (await stat(direct).then((s) => s.isDirectory(), () => false)) return direct;
|
|
3708
|
+
let names;
|
|
3709
|
+
try {
|
|
3710
|
+
names = await readdir(root);
|
|
3711
|
+
} catch {
|
|
3712
|
+
return;
|
|
3713
|
+
}
|
|
3714
|
+
for (const name of names) {
|
|
3715
|
+
const dir = join(root, name);
|
|
3716
|
+
if ((await readText(join(dir, ".cwd")))?.trim() === cwd) return dir;
|
|
3717
|
+
}
|
|
3718
|
+
}
|
|
3719
|
+
/** Find the chat_history.jsonl for a session, or the reason there is none. */
|
|
3720
|
+
async function locateGrokHistory(q, env) {
|
|
3721
|
+
const dir = await cwdDir(join(grokHome(env), "sessions"), q.cwd);
|
|
3722
|
+
if (dir === void 0) return { error: "no Grok sessions for this working directory" };
|
|
3723
|
+
if (q.cliSessionId && /^[A-Za-z0-9_-]{1,200}$/.test(q.cliSessionId)) {
|
|
3724
|
+
const path = join(dir, q.cliSessionId, "chat_history.jsonl");
|
|
3725
|
+
if (await stat(path).then(() => true, () => false)) return { path };
|
|
3726
|
+
}
|
|
3727
|
+
const since = Date.parse(q.startedAt);
|
|
3728
|
+
const floor = Number.isFinite(since) ? since - 5e3 : 0;
|
|
3729
|
+
let best;
|
|
3730
|
+
for (const e of await entriesNewestFirst(dir)) {
|
|
3731
|
+
if (!e.dir) continue;
|
|
3732
|
+
const path = join(e.path, "chat_history.jsonl");
|
|
3733
|
+
const s = await stat(path).catch(() => void 0);
|
|
3734
|
+
if (s && s.mtimeMs >= floor && (!best || s.mtimeMs > best.mtimeMs)) best = {
|
|
3735
|
+
path,
|
|
3736
|
+
mtimeMs: s.mtimeMs
|
|
3737
|
+
};
|
|
3738
|
+
}
|
|
3739
|
+
if (best) return { path: best.path };
|
|
3740
|
+
return { error: "no Grok session in this working directory since it started" };
|
|
3741
|
+
}
|
|
3742
|
+
const grokTranscript = { async read(q, env) {
|
|
3743
|
+
try {
|
|
3744
|
+
const found = await locateGrokHistory(q, env);
|
|
3745
|
+
if ("error" in found) return notFound("Grok", found.error);
|
|
3746
|
+
const { entries, more } = await tailJsonl(found.path, q.lastTurns, parseGrokItem);
|
|
3747
|
+
return {
|
|
3748
|
+
ok: true,
|
|
3749
|
+
entries,
|
|
3750
|
+
more
|
|
3751
|
+
};
|
|
3752
|
+
} catch (e) {
|
|
3753
|
+
return notFound("Grok", e instanceof Error ? e.message : "read failed");
|
|
3754
|
+
}
|
|
3755
|
+
} };
|
|
3756
|
+
// ../daemon/src/transcripts.ts
|
|
3757
|
+
/**
|
|
3758
|
+
* The transcript reader of each CLI the daemon can peek into. A CLI missing here answers
|
|
3759
|
+
* "peek not supported for <cli> yet". Cursor and Antigravity are listed with the reason, so the
|
|
3760
|
+
* message says why.
|
|
3761
|
+
*/
|
|
3762
|
+
function defaultTranscriptReaders() {
|
|
3763
|
+
return {
|
|
3764
|
+
claude: claudeTranscript,
|
|
3765
|
+
codex: codexTranscript,
|
|
3766
|
+
opencode: openCodeTranscript,
|
|
3767
|
+
copilot: copilotTranscript,
|
|
3768
|
+
grok: grokTranscript,
|
|
3769
|
+
cursor: unsupportedTranscript("cursor", "its chat storage is not documented"),
|
|
3770
|
+
antigravity: unsupportedTranscript("antigravity", "its conversation store is not documented")
|
|
3771
|
+
};
|
|
3772
|
+
}
|
|
1018
3773
|
// ../daemon/src/bin.ts
|
|
1019
3774
|
async function main() {
|
|
1020
3775
|
const handle = await startDaemon({
|
|
1021
3776
|
dataDir: dataDir(process.platform, process.env, homedir()),
|
|
3777
|
+
transcripts: defaultTranscriptReaders(),
|
|
1022
3778
|
onIdleExit: () => {
|
|
1023
3779
|
process.stderr.write("convenod: no sessions for a while, exiting.\n");
|
|
1024
3780
|
process.exit(0);
|