@conveno/cli 0.1.1 → 0.2.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,481 @@
1
+ import { spawn } from "node:child_process";
2
+ import { mkdir, open, readFile, rm, stat } from "node:fs/promises";
3
+ import { createConnection } from "node:net";
4
+ import { homedir } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { An as encodeFrame, Ct as proofsMatch, E as clientProof, M as dataDir, Mn as isSocketPathTooLong, N as dataPaths, On as createLineDecoder, Wn as socketPathTooLongMessage, _n as PROTOCOL_VERSION, bn as RpcResponse, dn as EventPayload, j as daemonProof, jn as ipcMethods, kn as defaultSocketPath, r as ConvenoError, ut as newAuthNonce, yn as RpcErrorCode } from "./dist-_sq6DmrE.js";
7
+ // ../client/dist/index.js
8
+ const DEFAULT_REQUEST_TIMEOUT_MS = 5e3;
9
+ const DEFAULT_START_TIMEOUT_MS = 1e4;
10
+ const LOCK_STALE_MS = 1e4;
11
+ const CLIENT_METHODS = [
12
+ "session.register",
13
+ "session.heartbeat",
14
+ "session.unregister",
15
+ "session.rename",
16
+ "session.setStatus",
17
+ "session.byHost",
18
+ "session.hostOf",
19
+ "session.forget",
20
+ "session.setAuto",
21
+ "turn.start",
22
+ "turn.end",
23
+ "turn.wake",
24
+ "daemon.shutdown",
25
+ "session.list",
26
+ "orchestrator.claim",
27
+ "message.send",
28
+ "message.inbox",
29
+ "message.deliver",
30
+ "message.ack",
31
+ "session.setCliInfo",
32
+ "session.setPeekable",
33
+ "session.peek",
34
+ "events.subscribe",
35
+ "ticket.create",
36
+ "ticket.answer",
37
+ "ticket.list",
38
+ "ticket.cancel",
39
+ "permission.relay",
40
+ "permission.request",
41
+ "relay.status",
42
+ "devices.list",
43
+ "devices.pair",
44
+ "devices.pairStatus",
45
+ "devices.pairConfirm",
46
+ "devices.revoke",
47
+ "devices.rename",
48
+ "devices.accept",
49
+ "devices.reset"
50
+ ];
51
+ /**
52
+ * Methods that must not be sent twice. If the connection drops after one of these went out, the
53
+ * daemon may have acted on it, so the caller gets an error instead of a silent retry.
54
+ */
55
+ const NOT_REPLAYABLE = /* @__PURE__ */ new Set([
56
+ "message.send",
57
+ "session.register",
58
+ "daemon.shutdown",
59
+ "turn.end",
60
+ "turn.wake",
61
+ "ticket.create",
62
+ "permission.request",
63
+ "devices.pair",
64
+ "devices.pairConfirm",
65
+ "devices.revoke",
66
+ "devices.accept",
67
+ "devices.reset"
68
+ ]);
69
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
70
+ const errCode = (e) => e?.code;
71
+ const isMissingDaemon = (e) => errCode(e) === "ENOENT" || errCode(e) === "ECONNREFUSED";
72
+ /** An error whose message is already written for the user. Never remapped. */
73
+ var ClientError = class extends Error {
74
+ constructor(message, options) {
75
+ super(message, options);
76
+ this.name = "ConvenoClientError";
77
+ this.kind = options?.kind;
78
+ }
79
+ kind;
80
+ };
81
+ /** The socket broke or closed. `sent` tells whether the request may have reached the daemon. */
82
+ var ConnectionLost = class extends Error {
83
+ sent;
84
+ constructor(message, sent, options) {
85
+ super(message, options);
86
+ this.sent = sent;
87
+ this.name = "ConnectionLost";
88
+ }
89
+ };
90
+ const noDaemonMessage = (socketPath) => `No Conveno daemon is listening at ${socketPath}. Run "conveno daemon start", or enable autoStart.`;
91
+ /** Turn a Node socket error into a message that says what happened and what to do. */
92
+ function plainError(e, socketPath) {
93
+ if (e instanceof ClientError || e instanceof ConvenoError) return e;
94
+ const code = errCode(e) ?? errCode(e?.cause);
95
+ switch (code) {
96
+ case "ECONNREFUSED":
97
+ case "ENOENT": return new ClientError(noDaemonMessage(socketPath), {
98
+ cause: e,
99
+ kind: "no_daemon"
100
+ });
101
+ case "EACCES":
102
+ case "EPERM": return new ClientError(`Permission denied on the Conveno daemon socket at ${socketPath}. It may belong to another user. Check who owns it, or remove it and run "conveno daemon start".`, {
103
+ cause: e,
104
+ kind: "permission"
105
+ });
106
+ case "EPIPE":
107
+ case "ECONNRESET": return new ClientError(`The connection to the Conveno daemon at ${socketPath} broke. Run "conveno daemon status", then try again.`, {
108
+ cause: e,
109
+ kind: "connection"
110
+ });
111
+ case "ENAMETOOLONG": return new ClientError(socketPathTooLongMessage(socketPath, process.platform), {
112
+ cause: e,
113
+ kind: "socket_path_too_long"
114
+ });
115
+ default:
116
+ if (code !== void 0) return new ClientError(`Could not talk to the Conveno daemon at ${socketPath} (${code}). Run "conveno daemon status", then try again.`, {
117
+ cause: e,
118
+ kind: "connection"
119
+ });
120
+ return e instanceof Error ? e : new Error(String(e));
121
+ }
122
+ }
123
+ function rpcErrorCode(code) {
124
+ return Object.values(RpcErrorCode).includes(code) ? code : RpcErrorCode.InternalError;
125
+ }
126
+ function openSocket(path) {
127
+ return new Promise((resolve, reject) => {
128
+ const socket = createConnection(path);
129
+ const onError = (e) => reject(e);
130
+ socket.once("error", onError);
131
+ socket.once("connect", () => {
132
+ socket.off("error", onError);
133
+ resolve(socket);
134
+ });
135
+ });
136
+ }
137
+ async function readToken(tokenPath) {
138
+ let text;
139
+ try {
140
+ text = await readFile(tokenPath, "utf8");
141
+ } catch (e) {
142
+ if (errCode(e) === "ENOENT") throw Object.assign(new ClientError(`The Conveno daemon token file is missing at ${tokenPath}. Run "conveno daemon start", then try again.`, { kind: "no_daemon" }), { code: "ENOENT" });
143
+ throw e;
144
+ }
145
+ const token = text.trim();
146
+ if (!token) throw new ClientError(`The Conveno daemon token file ${tokenPath} is empty. Run "conveno daemon stop", then "conveno daemon start".`, { kind: "token_empty" });
147
+ return token;
148
+ }
149
+ var Connection = class {
150
+ socket;
151
+ timeoutMs;
152
+ onEvent;
153
+ nextId = 1;
154
+ pending = /* @__PURE__ */ new Map();
155
+ decoder = createLineDecoder();
156
+ closed = false;
157
+ constructor(socket, timeoutMs, onEvent = () => {}) {
158
+ this.socket = socket;
159
+ this.timeoutMs = timeoutMs;
160
+ this.onEvent = onEvent;
161
+ socket.on("data", (chunk) => {
162
+ for (const r of this.decoder.push(chunk)) if (r.ok) this.onMessage(r.value);
163
+ });
164
+ socket.on("error", (e) => this.failAll(new ConnectionLost(e.message, true, { cause: e })));
165
+ socket.on("close", () => this.failAll(new ConnectionLost("Connection to the Conveno daemon closed.", true)));
166
+ }
167
+ get isClosed() {
168
+ return this.closed;
169
+ }
170
+ onMessage(value) {
171
+ if (value?.method === "event") {
172
+ const parsed = EventPayload.safeParse(value.params);
173
+ if (parsed.success) this.onEvent(parsed.data);
174
+ return;
175
+ }
176
+ const res = RpcResponse.safeParse(value);
177
+ if (!res.success || typeof res.data.id !== "number") return;
178
+ const p = this.pending.get(res.data.id);
179
+ if (!p) return;
180
+ this.pending.delete(res.data.id);
181
+ clearTimeout(p.timer);
182
+ if ("error" in res.data) p.reject(new ConvenoError(rpcErrorCode(res.data.error.code), res.data.error.message));
183
+ else p.resolve(res.data.result);
184
+ }
185
+ failAll(e) {
186
+ this.closed = true;
187
+ for (const [id, p] of this.pending) {
188
+ clearTimeout(p.timer);
189
+ this.pending.delete(id);
190
+ p.reject(e);
191
+ }
192
+ }
193
+ call(method, params) {
194
+ if (this.closed) return Promise.reject(new ConnectionLost("Connection to the Conveno daemon is closed.", false));
195
+ const id = this.nextId++;
196
+ return new Promise((resolve, reject) => {
197
+ const timer = setTimeout(() => {
198
+ this.pending.delete(id);
199
+ reject(new ClientError(`Request ${method} timed out after ${this.timeoutMs} ms. Check that the daemon is running with "conveno daemon status".`, { kind: "connection" }));
200
+ }, this.timeoutMs);
201
+ this.pending.set(id, {
202
+ resolve,
203
+ reject,
204
+ timer
205
+ });
206
+ try {
207
+ this.socket.write(encodeFrame({
208
+ jsonrpc: "2.0",
209
+ id,
210
+ method,
211
+ params
212
+ }));
213
+ } catch (e) {
214
+ clearTimeout(timer);
215
+ this.pending.delete(id);
216
+ reject(e);
217
+ }
218
+ });
219
+ }
220
+ close() {
221
+ this.failAll(new ClientError("The Conveno client is closed."));
222
+ return new Promise((resolve) => {
223
+ if (this.socket.destroyed) return resolve();
224
+ this.socket.once("close", () => resolve());
225
+ this.socket.destroy();
226
+ });
227
+ }
228
+ };
229
+ function validate(method, params) {
230
+ const parsed = ipcMethods[method].params.safeParse(params ?? {});
231
+ if (!parsed.success) {
232
+ const detail = parsed.error.issues.map((i) => i.path.length > 0 ? `"${i.path.join(".")}": ${i.message}` : i.message).join("; ");
233
+ const lead = parsed.error.issues.every((i) => i.path.length > 0) ? "Invalid " : "Invalid request: ";
234
+ throw new ConvenoError(RpcErrorCode.InvalidParams, `${lead}${detail}.`);
235
+ }
236
+ return parsed.data;
237
+ }
238
+ function checkResult(method, result) {
239
+ const r = ipcMethods[method].result.safeParse(result);
240
+ if (!r.success) throw new ConvenoError(RpcErrorCode.InternalError, `The daemon returned an unexpected result for ${method}. Update the daemon and client to the same version.`);
241
+ return r.data;
242
+ }
243
+ /** One typed call on one connection. Used for the handshake and by `Link`. */
244
+ async function typedCall(conn, method, params) {
245
+ const wire = validate(method, params);
246
+ return checkResult(method, await conn.call(method, wire));
247
+ }
248
+ /**
249
+ * Open a socket and run the mutual handshake. The token never crosses the wire: the daemon must
250
+ * prove it knows it before the client proves the same back.
251
+ */
252
+ async function handshake(socketPath, tokenPath, kind, timeoutMs, onEvent) {
253
+ const conn = new Connection(await openSocket(socketPath), timeoutMs, onEvent);
254
+ try {
255
+ const token = await readToken(tokenPath);
256
+ const nonce = newAuthNonce();
257
+ const hello = await typedCall(conn, "hello", {
258
+ protocolVersion: PROTOCOL_VERSION,
259
+ client: kind,
260
+ nonce
261
+ });
262
+ if (!proofsMatch(hello.proof, daemonProof(token, nonce))) throw new ClientError(`The process on ${socketPath} is not the Conveno daemon. Stop it, or remove the socket, and try again.`, { kind: "not_daemon" });
263
+ await typedCall(conn, "auth", { proof: clientProof(token, hello.challenge) });
264
+ return conn;
265
+ } catch (e) {
266
+ await conn.close();
267
+ throw e;
268
+ }
269
+ }
270
+ function requireDaemonEntry(entry) {
271
+ if (entry) return entry;
272
+ throw new ClientError("Cannot find the Conveno daemon program. Pass daemonEntry to connect(), or run \"conveno daemon start\" yourself.", { kind: "daemon_missing" });
273
+ }
274
+ /**
275
+ * Start the daemon detached, with its stdout and stderr in `logPath`, truncated at each start. The
276
+ * daemon writes its own `daemon.log` once it runs; this file catches what it prints before that,
277
+ * such as a crash at startup, which would otherwise be lost.
278
+ */
279
+ async function spawnDaemon(entry, logPath) {
280
+ await mkdir(dirname(logPath), { recursive: true });
281
+ const fh = await open(logPath, "w", 384);
282
+ try {
283
+ const child = spawn(process.execPath, [entry], {
284
+ detached: true,
285
+ stdio: [
286
+ "ignore",
287
+ fh.fd,
288
+ fh.fd
289
+ ],
290
+ windowsHide: true
291
+ });
292
+ const spawned = { child };
293
+ child.on("error", (e) => {
294
+ spawned.spawnError = e;
295
+ });
296
+ child.on("exit", (code, signal) => {
297
+ spawned.exit = {
298
+ code,
299
+ signal
300
+ };
301
+ });
302
+ child.unref();
303
+ return spawned;
304
+ } finally {
305
+ await fh.close();
306
+ }
307
+ }
308
+ /** The last lines the daemon printed at startup, for an error message. */
309
+ async function startLogTail(logPath, lines = 12) {
310
+ try {
311
+ return (await readFile(logPath, "utf8")).trimEnd().split(/\r?\n/).slice(-lines).join("\n");
312
+ } catch {
313
+ return "";
314
+ }
315
+ }
316
+ function startFailureDetail(logPath, tail) {
317
+ return tail ? ` Its output, from ${logPath}:\n${tail}` : ` It printed nothing; its output would be in ${logPath}.`;
318
+ }
319
+ /** Take the start lock. Returns a release function, or null if another client holds it. */
320
+ async function acquireStartLock(path) {
321
+ for (let i = 0; i < 2; i++) try {
322
+ await (await open(path, "wx")).close();
323
+ return () => rm(path, { force: true });
324
+ } catch (e) {
325
+ if (errCode(e) !== "EEXIST") throw e;
326
+ try {
327
+ const s = await stat(path);
328
+ if (Date.now() - s.mtimeMs < LOCK_STALE_MS) return null;
329
+ await rm(path, { force: true });
330
+ } catch {}
331
+ }
332
+ return null;
333
+ }
334
+ async function startAndConnect(entry, dir, attempt, socketPath, startTimeout) {
335
+ await mkdir(dir, { recursive: true });
336
+ const logPath = dataPaths(process.platform, dir).daemonStartLog;
337
+ const release = await acquireStartLock(join(dir, "client-start.lock"));
338
+ const deadline = Date.now() + startTimeout;
339
+ let delay = 25;
340
+ let last;
341
+ try {
342
+ const spawned = release ? await spawnDaemon(entry, logPath) : void 0;
343
+ for (;;) {
344
+ await sleep(delay);
345
+ delay = Math.min(delay * 2, 250);
346
+ const ended = spawned?.exit ?? spawned?.spawnError;
347
+ try {
348
+ return await attempt();
349
+ } catch (e) {
350
+ if (!isMissingDaemon(e)) throw e;
351
+ last = e;
352
+ }
353
+ if (spawned && ended) throw new ClientError(`The Conveno daemon ${spawned.spawnError ? `could not be started (${spawned.spawnError.message})` : `exited with ${spawned.exit?.signal ? `signal ${spawned.exit.signal}` : `code ${spawned.exit?.code}`} before it listened on ${socketPath}`}.${startFailureDetail(logPath, await startLogTail(logPath))}`, {
354
+ cause: spawned.spawnError ?? last,
355
+ kind: "start_exited"
356
+ });
357
+ if (Date.now() >= deadline) break;
358
+ }
359
+ } finally {
360
+ await release?.();
361
+ }
362
+ throw new ClientError(`The Conveno daemon did not start within ${startTimeout} ms (socket ${socketPath}).${startFailureDetail(logPath, await startLogTail(logPath))}`, {
363
+ cause: last,
364
+ kind: "start_timeout"
365
+ });
366
+ }
367
+ /**
368
+ * The client's one logical connection. When the socket breaks, for instance because the daemon
369
+ * restarted, the next call reconnects, redoes the handshake (starting the daemon when allowed),
370
+ * re-subscribes to events, and retries once.
371
+ */
372
+ var Link = class {
373
+ dial;
374
+ socketPath;
375
+ conn;
376
+ reconnecting;
377
+ closed = false;
378
+ subscription;
379
+ handlers = /* @__PURE__ */ new Set();
380
+ constructor(dial, socketPath) {
381
+ this.dial = dial;
382
+ this.socketPath = socketPath;
383
+ }
384
+ dispatch = (e) => {
385
+ for (const h of [...this.handlers]) try {
386
+ h(e);
387
+ } catch {}
388
+ };
389
+ async open() {
390
+ this.conn = await this.dial(this.dispatch);
391
+ }
392
+ onEvent(handler) {
393
+ this.handlers.add(handler);
394
+ return () => {
395
+ this.handlers.delete(handler);
396
+ };
397
+ }
398
+ async call(method, params) {
399
+ const wire = validate(method, params);
400
+ if (this.closed) throw new ClientError("The Conveno client is closed.");
401
+ const used = this.conn;
402
+ let result;
403
+ try {
404
+ result = await used.call(method, wire);
405
+ } catch (e) {
406
+ if (!(e instanceof ConnectionLost) || this.closed) throw plainError(e, this.socketPath);
407
+ if (e.sent && NOT_REPLAYABLE.has(method)) {
408
+ await this.reconnect(used).catch(() => {});
409
+ throw new ClientError(`The connection to the Conveno daemon was lost while sending ${method}. It may or may not have gone through. Check, then try again.`, { cause: e });
410
+ }
411
+ await this.reconnect(used);
412
+ try {
413
+ result = await this.conn.call(method, wire);
414
+ } catch (e2) {
415
+ throw plainError(e2, this.socketPath);
416
+ }
417
+ }
418
+ if (method === "events.subscribe") this.subscription = wire;
419
+ return checkResult(method, result);
420
+ }
421
+ reconnect(failed) {
422
+ if (this.conn !== failed) return Promise.resolve();
423
+ this.reconnecting ??= (async () => {
424
+ try {
425
+ const next = await this.dial(this.dispatch);
426
+ if (this.closed) {
427
+ await next.close();
428
+ return;
429
+ }
430
+ this.conn = next;
431
+ if (this.subscription) await typedCall(next, "events.subscribe", this.subscription).catch(() => {});
432
+ } finally {
433
+ this.reconnecting = void 0;
434
+ }
435
+ })();
436
+ return this.reconnecting;
437
+ }
438
+ async close() {
439
+ this.closed = true;
440
+ await this.conn.close();
441
+ }
442
+ };
443
+ /**
444
+ * Connect to the daemon, complete the mutual handshake, and return a typed client. When nothing is
445
+ * listening and `autoStart` is not false, spawns the daemon detached and retries with backoff. A
446
+ * later call that finds the connection broken reconnects the same way and retries once.
447
+ */
448
+ async function connect(opts) {
449
+ const platform = process.platform;
450
+ const dir = opts.dataDir ?? dataDir(platform, process.env, homedir());
451
+ const socketPath = opts.socketPath ?? defaultSocketPath(platform, process.env, homedir());
452
+ if (isSocketPathTooLong(socketPath, platform)) throw new ClientError(socketPathTooLongMessage(socketPath, platform), { kind: "socket_path_too_long" });
453
+ const tokenPath = dataPaths(platform, dir).token;
454
+ const timeout = opts.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
455
+ const dial = async (onEvent) => {
456
+ const attempt = () => handshake(socketPath, tokenPath, opts.kind, timeout, onEvent);
457
+ try {
458
+ try {
459
+ return await attempt();
460
+ } catch (e) {
461
+ if (!isMissingDaemon(e)) throw e;
462
+ if (opts.autoStart === false) throw new ClientError(noDaemonMessage(socketPath), {
463
+ cause: e,
464
+ kind: "no_daemon"
465
+ });
466
+ return await startAndConnect(requireDaemonEntry(opts.daemonEntry), dir, attempt, socketPath, opts.startTimeoutMs ?? DEFAULT_START_TIMEOUT_MS);
467
+ }
468
+ } catch (e) {
469
+ throw plainError(e, socketPath);
470
+ }
471
+ };
472
+ const link = new Link(dial, socketPath);
473
+ await link.open();
474
+ const client = {
475
+ onEvent: (handler) => link.onEvent(handler),
476
+ close: () => link.close()
477
+ };
478
+ for (const method of CLIENT_METHODS) client[method] = (params) => link.call(method, params);
479
+ return client;
480
+ }
481
+ export { connect as n, ClientError as t };