@conveno/cli 0.2.0-rc.15 → 0.2.0-rc.17

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 CHANGED
@@ -25,7 +25,7 @@ conveno init
25
25
 
26
26
  Then open two CLI sessions, for example Claude Code and Codex. Make one the lead (in the app, with `conveno lead <session>`, or by asking it to coordinate) and ask it to hand out work. The other session wakes up and starts. `conveno status` lists the sessions.
27
27
 
28
- Or run `conveno` with no arguments. It opens a full-screen app (Sessions, New, Devices, Setup) for the keyboard and mouse: `/` searches, `?` shows the keys. Turn the mouse off in Setup or with `CONVENO_MOUSE=0`.
28
+ Or run `conveno` with no arguments. It opens a full-screen app for the keyboard and mouse: a table of your sessions with an Activity box and a detail pane, and a menu (`/` or ctrl+p) whose screens open as dialogs. `?` shows the keys. Turn the mouse off in Setup or with `CONVENO_MOUSE=0`.
29
29
 
30
30
  `conveno uninstall` reverts what `init` did. A file that has not changed since `init` is restored byte for byte. If a CLI has rewritten it since, only Conveno's entries are removed.
31
31
 
@@ -39,7 +39,7 @@ Or run `conveno` with no arguments. It opens a full-screen app (Sessions, New, D
39
39
  | `conveno send <to> <text...> [--urgent]` | Send a message as you to a session name or id, `lead`, or `device:name`. `-` reads the text from standard input. |
40
40
  | `conveno rename <session> <new-name>` | Rename an online session. |
41
41
  | `conveno lead <session>` | Make a session the lead. `conveno lead --clear` leaves no lead. |
42
- | `conveno spawn <cli> [--cwd <dir>] [--name <name>] [--task <text> \| --task-file <path>] [--window] [--access <read\|edit\|full>] [--yes]` | Start a worker session of `claude`, `codex`, `opencode`, `antigravity` or `grok`, and print its name once it registers. The CLI must be installed. By default the worker runs in the background through the CLI's Agent Client Protocol server, with `conveno acp-host` driving it. It keeps running: each message sent to it becomes its next prompt at once when it is idle, or when its current turn ends. `--window` opens the real CLI in a new terminal instead, so you can watch it and take over: Windows Terminal (`wt -w 0 new-tab`, else a new console window) on Windows, Terminal.app (iTerm2 when it is your terminal) on macOS, and on Linux a new tmux window when you are inside tmux, else the first of `x-terminal-emulator`, `gnome-terminal`, `konsole`, `kitty`, `wezterm`, `alacritty` and `xterm`. The ACP commands are `claude-agent-acp` (install `@agentclientprotocol/claude-agent-acp`), `codex-acp` (install `@agentclientprotocol/codex-acp`), `opencode acp`, `agy acp` and `grok agent stdio`; a missing one is an error that says what to install. For Claude Code and Codex, `conveno init` can allow running the adapter with `npx -y <package>@<pinned version>`, and `CONVENO_ACP_CODEX_CMD` / `CONVENO_ACP_CLAUDE_CMD` replace the command. In the background a tool call the `--access` preset (`read`, `edit` or `full`; default `full`) does not cover is asked of the session that spawned the worker. The first task is optional. `--name` sets the session name (a taken or reserved one is refused); otherwise the usual `<cli>@<repo>-<n>` name is used. `--cwd` defaults to the current folder, which must be inside your home folder; an explicit `--cwd` can be anywhere. It asks first and `--yes` skips the question; without a terminal it exits 2 unless `--yes` is given. At most 8 spawned sessions run at once (`CONVENO_SPAWN_MAX` changes that), and a spawned session cannot spawn more than 3 levels deep. A task is at most 16000 characters. See `packages/protocol/PROTOCOL.md`. |
42
+ | `conveno spawn <cli> [--cwd <dir>] [--name <name>] [--task <text> \| --task-file <path>] [--window] [--access <read\|edit\|full>] [--model <name>] [--effort <name>] [--yes]` | Start a worker session of `claude`, `codex`, `opencode`, `antigravity` or `grok`, and print its name once it registers. The CLI must be installed. By default the worker runs in the background through the CLI's Agent Client Protocol server, with `conveno acp-host` driving it. It keeps running: each message sent to it becomes its next prompt at once when it is idle, or when its current turn ends. `--window` opens the real CLI in a new terminal instead, so you can watch it and take over: Windows Terminal (`wt -w 0 new-tab`, else a new console window) on Windows, Terminal.app (iTerm2 when it is your terminal) on macOS, and on Linux a new tmux window when you are inside tmux, else the first of `x-terminal-emulator`, `gnome-terminal`, `konsole`, `kitty`, `wezterm`, `alacritty` and `xterm`. The ACP commands are `claude-agent-acp` (install `@agentclientprotocol/claude-agent-acp`), `codex-acp` (install `@agentclientprotocol/codex-acp`), `opencode acp`, `agy acp` and `grok agent stdio`; a missing one is an error that says what to install. For Claude Code and Codex, `conveno init` can allow running the adapter with `npx -y <package>@<pinned version>`, and `CONVENO_ACP_CODEX_CMD` / `CONVENO_ACP_CLAUDE_CMD` replace the command. In the background a tool call the `--access` preset (`read`, `edit` or `full`; default `full`) does not cover is asked of the session that spawned the worker. The first task is optional. `--name` sets the session name (a taken or reserved one is refused); otherwise the usual `<cli>@<repo>-<n>` name is used. `--cwd` defaults to the current folder, which must be inside your home folder; an explicit `--cwd` can be anywhere. It asks first and `--yes` skips the question; without a terminal it exits 2 unless `--yes` is given. At most 8 spawned sessions run at once (`CONVENO_SPAWN_MAX` changes that), and a spawned session cannot spawn more than 3 levels deep. `--model` and `--effort` pick the CLI's own model and effort names; without them your setting for that CLI applies, else the CLI's default. A task is at most 16000 characters. See `packages/protocol/PROTOCOL.md`. |
43
43
  | `conveno stop <worker>` | Stop a background worker. It cancels a running turn, ends its CLI and the processes it started, tells the spawning session why, and goes offline. A worker in a window is yours to close. |
44
44
  | `conveno doctor [--cli <list>]` | Check each CLI and the daemon, and say how to fix what is wrong. `--cli claude,codex` checks only those CLIs, so problems in the others do not count. |
45
45
  | `conveno devices [pair\|join\|revoke\|rename\|accept\|reset]` | Pro. List your devices, or pair a new machine: `pair` on one device and `join` on the new one at the same time, then type the 8-digit code each screen shows. `revoke` removes a device for good. Needs a Pro login on both. |
@@ -1,8 +1,10 @@
1
1
  import { writeFileSync } from "node:fs";
2
- import { n as runAcpHostFromFile, r as stopRequestPath, t as killProcessTree } from "./dist-fI_XSoCQ.js";
3
- import { Kt as readSpawnRecord, an as spawnRecordPath } from "./dist-ZL7d4_97.js";
4
- import { a as parseFlags, n as COMMANDS } from "./args-CpAvszNY.js";
2
+ import { i as stopRequestPath, r as runAcpHostFromFile, t as killProcessTree } from "./dist-hyKfBSdF.js";
3
+ import { Qt as readSpawnRecord, hn as spawnRecordPath, mn as spawnRecordOfSession } from "./dist-Dc50_P_f.js";
4
+ import { a as parseFlags, n as COMMANDS } from "./args-CtyKPZuN.js";
5
+ import { n as connectOpts } from "./ctx-tYftvhz_.js";
5
6
  import { a as fail, n as cmd } from "./fmt-C2SsP5Y0.js";
7
+ import { t as findSession } from "./pick-iuG24FX9.js";
6
8
  // src/acp.ts
7
9
  /** How long `conveno stop` waits for a worker to end by itself before it ends the process tree. */
8
10
  const STOP_WAIT_MS = 1e4;
@@ -32,14 +34,26 @@ async function runAcpHostCmd(ctx, argv) {
32
34
  });
33
35
  }
34
36
  }
35
- function findWorker(ctx, name, command) {
37
+ /**
38
+ * The worker `name` means: a session's name now, which a rename may have changed, or, when no
39
+ * online session has that name, the name it was spawned with (its record's file name).
40
+ */
41
+ async function findWorker(ctx, name, command) {
36
42
  if (!name) return fail(ctx, {
37
43
  what: `conveno ${command} needs a worker name`,
38
44
  fix: `Run ${cmd(ctx.theme, "conveno status")} to see the names.`,
39
45
  exit: 2,
40
46
  ref: "e_usage"
41
47
  });
42
- const rec = /^[a-z0-9][a-z0-9._@-]{0,63}$/.test(name) ? readSpawnRecord(spawnRecordPath(ctx.dataDir, name)) : void 0;
48
+ const live = await byCurrentName(ctx, name);
49
+ if (live === null) return fail(ctx, {
50
+ what: `${name} is not a worker started here`,
51
+ detail: ["Only sessions started by conveno spawn or spawn_session on this machine are workers."],
52
+ fix: `Run ${cmd(ctx.theme, "conveno status")} to see the names.`,
53
+ exit: 1,
54
+ ref: "e_not_found"
55
+ });
56
+ const rec = live ?? (/^[a-z0-9][a-z0-9._@-]{0,63}$/.test(name) ? readSpawnRecord(spawnRecordPath(ctx.dataDir, name)) : void 0);
43
57
  if (!rec) return fail(ctx, {
44
58
  what: `No running worker named "${name}"`,
45
59
  detail: ["Only sessions started by conveno spawn or spawn_session on this machine are workers."],
@@ -50,6 +64,24 @@ function findWorker(ctx, name, command) {
50
64
  return rec;
51
65
  }
52
66
  /**
67
+ * The record of the online session named `name`, through the daemon; null when that session has
68
+ * no record (it is not a worker started here). Undefined when no online session has that name, or
69
+ * the daemon is not running.
70
+ */
71
+ async function byCurrentName(ctx, name) {
72
+ const client = await ctx.connect(connectOpts(ctx, false)).catch(() => void 0);
73
+ if (!client) return void 0;
74
+ try {
75
+ const session = await findSession(client, name);
76
+ if (!session) return void 0;
77
+ return spawnRecordOfSession(ctx.dataDir, session.id) ?? null;
78
+ } catch {
79
+ return;
80
+ } finally {
81
+ await client.close().catch(() => void 0);
82
+ }
83
+ }
84
+ /**
53
85
  * `conveno stop <worker>`. An ACP worker gets a stop request: its host sends `session/cancel` for
54
86
  * a running turn, ends the agent, reports to the spawner and takes the session offline. A worker in a
55
87
  * terminal window is the user's to close.
@@ -60,7 +92,7 @@ async function runStop(ctx, argv) {
60
92
  const parsed = parseFlags(ctx, spec, argv);
61
93
  if (typeof parsed === "number") return parsed;
62
94
  const [name] = parsed.positionals;
63
- const rec = findWorker(ctx, name, "stop");
95
+ const rec = await findWorker(ctx, name, "stop");
64
96
  if (typeof rec === "number") return rec;
65
97
  const t = ctx.theme;
66
98
  if (!rec.acp) return fail(ctx, {
@@ -76,7 +108,7 @@ async function runStop(ctx, argv) {
76
108
  while (alive() && Date.now() < end) await new Promise((r) => setTimeout(r, 100));
77
109
  if (alive() && rec.pid !== void 0) killProcessTree(rec.pid, ctx.platform);
78
110
  if (rec.agentPid !== void 0 && ctx.isAlive(rec.agentPid)) killProcessTree(rec.agentPid, ctx.platform);
79
- ctx.out(`${t.status("ok")} ${t.bold(`Stopped ${rec.name}`)}\n`);
111
+ ctx.out(`${t.status("ok")} ${t.bold(`Stopped ${name ?? rec.name}`)}\n`);
80
112
  return 0;
81
113
  }
82
114
  export { runAcpHostCmd, runStop };
@@ -1,6 +1,6 @@
1
1
  import { execFile } from "node:child_process";
2
- import { t as RELAY_SUBCOMMAND } from "./dist-Bv1bmmme.js";
3
- import { nn as runWaker } from "./dist-ZL7d4_97.js";
2
+ import { t as RELAY_SUBCOMMAND } from "./dist-CTw3arJP.js";
3
+ import { un as runWaker } from "./dist-Dc50_P_f.js";
4
4
  import { n as connectOpts } from "./ctx-tYftvhz_.js";
5
5
  // src/agy-relay.ts
6
6
  /**
@@ -163,6 +163,16 @@ const COMMANDS = [
163
163
  value: "<read|edit|full>",
164
164
  help: "Background: what the worker may do without asking (default: your setting, full unless changed)"
165
165
  },
166
+ model: {
167
+ type: "string",
168
+ value: "<name>",
169
+ help: "The CLI's own model name (default: your setting for that CLI, else the CLI's default)"
170
+ },
171
+ effort: {
172
+ type: "string",
173
+ value: "<name>",
174
+ help: "The CLI's own effort name (default: your setting for that CLI, else the CLI's default)"
175
+ },
166
176
  yes: {
167
177
  type: "boolean",
168
178
  short: "y",
@@ -170,6 +180,8 @@ const COMMANDS = [
170
180
  }
171
181
  },
172
182
  notes: [
183
+ "--model and --effort pick the model and effort by the CLI's own names. A name the CLI does not offer",
184
+ "leaves its default. In a window they become the CLI's launch flags; OpenCode has no effort flag.",
173
185
  "--access sets what a background worker may do without asking: read (look only), edit (also",
174
186
  "change files and fetch pages) or full (everything). Without it, your setting applies; full unless changed.",
175
187
  "By default the worker runs in the background over ACP and stays alive. Each message sent to",
package/dist/bin.js CHANGED
@@ -40,9 +40,9 @@ for (const stream of [process.stdout, process.stderr]) stream.on("error", (err)
40
40
  });
41
41
  try {
42
42
  let code;
43
- if (isHook) code = await (await import("./hook-entry-CmuvppGf.js")).runHookEntry(argv.slice(1));
43
+ if (isHook) code = await (await import("./hook-entry-B1Yt2cwr.js")).runHookEntry(argv.slice(1));
44
44
  else {
45
- const [{ main }, { createRuntimeCtx }] = await Promise.all([import("./main-1QSm5UjR.js"), import("./runtime-CeFKWoIL.js")]);
45
+ const [{ main }, { createRuntimeCtx }] = await Promise.all([import("./main-CQx2xc_w.js"), import("./runtime-hZwjrEPc.js")]);
46
46
  code = await main(argv, createRuntimeCtx());
47
47
  }
48
48
  if (isHook) process.exit(code);
package/dist/daemon.js CHANGED
@@ -1,13 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { homedir, hostname, userInfo } from "node:os";
3
- import { t as codexAdapter } from "./dist-DDzIkwf9.js";
4
- import { $ as formatContinuation, $n as sanitizeLine, $t as resolveRecipient, A as claimOrchestrator, B as dataDir, Bn as defaultSocketPath, Bt as readAccountTokens, Ct as oneWindowPerHost, D as autoLimitsFromEnv, E as autoCandidates, En as EVENT_NAMES, Gn as makeEventNotification, Gt as readSettings, H as decideAutoContinue, In as SESSION_ENDED_TEXT, It as planSpawn, Jn as newMessageId, Kn as makeResult, L as createWmiWalker, M as clearOrchestrator, Mn as PROTOCOL_VERSION, N as clientProof, Nn as RelayPayload, O as baseName, Pn as RpcErrorCode, Qn as safeParse, R as currentAccessToken, Rn as SessionId, Rt as proofsMatch, S as appendHookLog, St as newAuthNonce, Tn as DeviceId, U as defaultProcessIo, Un as isSocketPathTooLong, Ut as readInbox, V as dataPaths, Vn as encodeFrame, Vt as readAncestry, W as detectRepo, Wn as makeError, Xn as parseIpcRequest, Xt as requeueEntries, Y as evaluateLiveness, Yn as newSessionId, Zn as parseRelayFrame, _ as ackEntries, _t as leadLogPath, bt as markDelivered, cn as statusAfterLiveness, dn as takeWithinChars, dt as isOnline, er as socketPathTooLongMessage, et as formatHookContext, fn as tooManyUnreadMessage, ft as jwtClaim, gn as validateRename, gt as leadLogLine, i as ConvenoError, jn as OWNER_SESSION_ID, k as bindAccountDevice, kn as Message, kt as pendingForInjection, l as RESPONSE_BUDGET_BYTES, n as AccountError, nt as generateSessionName, pn as turnHops, q as effectiveHolder, qn as newDeviceId, rt as holderAfterDeparture, un as takeWithinBytes, z as daemonProof, zn as createLineDecoder } from "./dist-ZL7d4_97.js";
2
+ import { homedir, hostname } from "node:os";
3
+ import { t as codexAdapter } from "./dist-CvKAege3.js";
4
+ import { $n as defaultSocketPath, A as claimOrchestrator, B as daemonProof, Cn as turnHops, Ct as markDelivered, D as autoLimitsFromEnv, Dt as newAuthNonce, E as autoCandidates, En as validateRename, G as detectRepo, Gn as RELAY_CLIENT_NAME, Gt as readAccountTokens, H as dataPaths, J as effectiveHolder, Jt as readInbox, Kn as RelayPayload, Kt as readAncestry, Ln as DeviceId, N as clearOrchestrator, Nn as writePrivateFileSync, O as baseName, Ot as oneWindowPerHost, P as clientProof, Pt as pendingForInjection, Qn as createLineDecoder, R as createWmiWalker, Rn as EVENT_NAMES, S as appendHookLog, Sn as tooManyUnreadMessage, U as decideAutoContinue, Un as OWNER_SESSION_ID, Ut as proofsMatch, V as dataDir, Vn as Message, W as defaultProcessIo, Wn as PROTOCOL_VERSION, X as evaluateLiveness, Yn as SESSION_ENDED_TEXT, Zn as SessionId, Zt as readSettings, _ as ackEntries, ar as makeResult, at as holderAfterDeparture, bn as takeWithinBytes, cn as restrictToUser, cr as newSessionId, dr as safeParse, en as relayUrl, er as encodeFrame, fr as sanitizeLine, ir as makeEventNotification, it as generateSessionName, k as bindAccountDevice, l as RESPONSE_BUDGET_BYTES, lr as parseIpcRequest, mt as jwtClaim, nr as isSocketPathTooLong, nt as formatHookContext, on as resolveRecipient, or as newDeviceId, pn as signedInAccountApi, pr as socketPathTooLongMessage, pt as isOnline, qn as RpcErrorCode, r as ConvenoError, rn as requeueEntries, rr as makeError, sr as newMessageId, t as AccountError, tt as formatContinuation, ur as parseRelayFrame, vn as statusAfterLiveness, vt as leadLogLine, xn as takeWithinChars, yt as leadLogPath, z as currentAccessToken } from "./dist-Dc50_P_f.js";
5
5
  import { randomBytes } from "node:crypto";
6
6
  import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
7
7
  import { connect, createServer } from "node:net";
8
8
  import { dirname, join, posix, win32 } from "node:path";
9
- import { _ as sasMatches, a as JoinerPairing, b as signRelayHello, c as decodePairMessage, d as forkPoint, f as generateIdentity, g as publicRecord, h as parseIdentity, i as InviterPairing, l as deviceFingerprint, m as openEnvelope, n as ENVELOPE_MAX_AGE_MS, o as appendRevoke, p as headMatches, r as ENVELOPE_MAX_FUTURE_MS, s as chainHead, t as CryptoError, u as encodePairMessage, v as sealEnvelope, x as verifyChain, y as serializeIdentity } from "./dist-Bx22a5AV.js";
10
- import { execFileSync } from "node:child_process";
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-B1pfP_d5.js";
11
10
  import { DatabaseSync } from "node:sqlite";
12
11
  // ../daemon/src/lifecycle.ts
13
12
  /** Thrown when another Conveno daemon already owns the lock file or answers on the socket. */
@@ -98,8 +97,8 @@ async function clearStaleSocket(socketPath) {
98
97
  }
99
98
  }
100
99
  /**
101
- * Read the auth token, creating it (32 random bytes, hex) with mode 0600 on first start.
102
- * On Windows the mode is ignored; the file inherits the ACL of the per-user data directory.
100
+ * Read the auth token, creating it (32 random bytes, hex) with mode 0600 on first start, or a
101
+ * user-only ACL on Windows, where the mode is ignored.
103
102
  */
104
103
  function loadOrCreateToken(tokenPath) {
105
104
  if (existsSync(tokenPath)) {
@@ -110,8 +109,7 @@ function loadOrCreateToken(tokenPath) {
110
109
  }
111
110
  }
112
111
  const token = randomBytes(32).toString("hex");
113
- writeFileSync(tokenPath, `${token}\n`, { mode: 384 });
114
- if (process.platform !== "win32") chmodSync(tokenPath, 384);
112
+ writePrivateFileSync(tokenPath, `${token}\n`);
115
113
  return token;
116
114
  }
117
115
  function ensureDir(dir) {
@@ -120,6 +118,8 @@ function ensureDir(dir) {
120
118
  mode: 448
121
119
  });
122
120
  }
121
+ // ../daemon/package.json
122
+ var version = "0.2.0-rc.17";
123
123
  const describeError = (e) => e instanceof Error ? e.stack ?? `${e.name}: ${e.message}` : String(e);
124
124
  /**
125
125
  * The daemon's own log, for errors it did not expect and for events the owner should be able to
@@ -158,6 +158,7 @@ function createDaemonLog(path, opts = {}) {
158
158
  }
159
159
  };
160
160
  }
161
+ // ../daemon/src/relay/connection.ts
161
162
  const HANDSHAKE_TIMEOUT_MS = 15e3;
162
163
  /**
163
164
  * One WebSocket to the relay: challenge, signed hello, then frames. It does not reconnect by
@@ -172,6 +173,7 @@ var RelayConnection = class {
172
173
  stateValue = "idle";
173
174
  stopped = false;
174
175
  explaining = false;
176
+ loggedVersion = false;
175
177
  constructor(o) {
176
178
  this.o = o;
177
179
  }
@@ -218,12 +220,26 @@ var RelayConnection = class {
218
220
  } catch {
219
221
  return;
220
222
  }
223
+ const v = json?.v;
224
+ if (typeof v === "number" && v !== 1) {
225
+ if (!this.loggedVersion) {
226
+ this.loggedVersion = true;
227
+ this.o.log?.(`relay: dropped a frame of relay protocol version ${v}; this client speaks 1`);
228
+ }
229
+ if (this.stateValue === "connecting") this.fail("The relay speaks a newer protocol than this version of Conveno.", "upgrade_required");
230
+ return;
231
+ }
221
232
  const r = parseRelayFrame(json);
222
233
  if (!r.ok) return;
223
234
  const f = r.value;
224
235
  if (this.stateValue === "connecting") {
225
- if (f.t === "challenge") this.ws?.send(JSON.stringify(signRelayHello(this.o.identity, f.nonce)));
226
- else if (f.t === "ready") {
236
+ if (f.t === "challenge") {
237
+ const hello = signRelayHello(this.o.identity, f.nonce);
238
+ this.ws?.send(JSON.stringify(this.o.client ? {
239
+ ...hello,
240
+ client: this.o.client
241
+ } : hello));
242
+ } else if (f.t === "ready") {
227
243
  if (this.handshake) clearTimeout(this.handshake);
228
244
  this.stateValue = "ready";
229
245
  this.pinger = setInterval(() => {
@@ -233,7 +249,7 @@ var RelayConnection = class {
233
249
  }, this.o.pingMs ?? 3e4);
234
250
  this.pinger.unref();
235
251
  this.o.events.ready(f.online);
236
- } else if (f.t === "error") this.fail(f.message, f.code);
252
+ } else if (f.t === "error") this.fail(f.message, f.code, f.minVersion);
237
253
  return;
238
254
  }
239
255
  this.o.events.frame(f);
@@ -252,11 +268,11 @@ var RelayConnection = class {
252
268
  this.fail("The relay could not be reached.");
253
269
  }
254
270
  }
255
- fail(detail, code) {
271
+ fail(detail, code, minVersion) {
256
272
  if (this.stopped || this.stateValue === "disconnected") return;
257
273
  this.stateValue = "disconnected";
258
274
  this.cleanup();
259
- this.o.events.down(detail, code);
275
+ this.o.events.down(detail, code, minVersion);
260
276
  }
261
277
  cleanup() {
262
278
  if (this.handshake) clearTimeout(this.handshake);
@@ -276,46 +292,6 @@ function relayPaths(join, dataDir) {
276
292
  database: join(dataDir, "relay.db")
277
293
  };
278
294
  }
279
- /**
280
- * The icacls command that leaves only the current user with access to `path`: inherited entries
281
- * removed (`/inheritance:r`), full control granted to the user, replacing any earlier grant
282
- * (`/grant:r`). For a directory, `inherit` makes the grant apply to files and folders created in
283
- * it (`(OI)(CI)`), so they are user-only from the moment they exist.
284
- * See https://learn.microsoft.com/windows-server/administration/windows-commands/icacls.
285
- * icacls is run from System32 by absolute path, never looked up on PATH.
286
- */
287
- function userOnlyAclPlan(path, env, user, isFile, inherit = false) {
288
- const systemRoot = env.SystemRoot ?? env.SYSTEMROOT ?? "C:\\Windows";
289
- const icacls = win32.join(systemRoot, "System32", "icacls.exe");
290
- const domain = env.USERDOMAIN;
291
- const grant = `${domain ? `${domain}\\${user}` : user}:${inherit ? "(OI)(CI)" : ""}F`;
292
- return planSpawn(icacls, [
293
- path,
294
- "/inheritance:r",
295
- "/grant:r",
296
- grant
297
- ], {
298
- platform: "win32",
299
- env,
300
- ...isFile ? { isFile } : {}
301
- });
302
- }
303
- /**
304
- * Make a file readable by the current user only: mode 0600 on POSIX, a user-only ACL on Windows
305
- * (where the mode is ignored).
306
- */
307
- function restrictToUser(path, platform = process.platform, directory = false) {
308
- if (platform !== "win32") {
309
- chmodSync(path, directory ? 448 : 384);
310
- return;
311
- }
312
- const plan = userOnlyAclPlan(path, process.env, userInfo().username, void 0, directory);
313
- execFileSync(plan.file, plan.args, {
314
- stdio: "ignore",
315
- windowsHide: true,
316
- ...plan.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
317
- });
318
- }
319
295
  const restrictIfPresent = (path) => {
320
296
  if (process.platform !== "win32" && existsSync(path)) chmodSync(path, 384);
321
297
  };
@@ -354,7 +330,12 @@ function keyStagingDir(path, o, platform) {
354
330
  }
355
331
  return dir;
356
332
  }
357
- /** The identity stored at `path`, or undefined. Upgrades an old Windows key file's ACL once. */
333
+ /**
334
+ * The identity stored at `path`, or undefined. Upgrades an old Windows key file's ACL once (a
335
+ * marker file `<key>.acl` records it). The relay device id is separate from the session store's,
336
+ * so deleting this file (with relay.db) gives the machine a fresh identity that can be paired
337
+ * again after a revocation.
338
+ */
358
339
  function loadIdentity(path, o = {}) {
359
340
  if (!existsSync(path)) return void 0;
360
341
  const platform = o.platform ?? process.platform;
@@ -556,6 +537,11 @@ const AUTH_CODES = /* @__PURE__ */ new Set([
556
537
  "device_mismatch",
557
538
  "device_revoked"
558
539
  ]);
540
+ /** What the owner sees when the relay refuses this version of Conveno. */
541
+ function upgradeText(clientVersion, minVersion) {
542
+ const pkg = clientVersion?.includes("-") ? "@conveno/cli@next" : "@conveno/cli@latest";
543
+ return `${minVersion ? `The relay needs Conveno ${minVersion} or newer. ` : ""}Update Conveno to keep using your other computers: npm i -g ${pkg}`;
544
+ }
559
545
  /** Messages that arrive before the sending device's session list wait this long for it. */
560
546
  const HELD_MESSAGES_PER_DEVICE = 50;
561
547
  const HELD_MESSAGE_MS = 12e4;
@@ -626,6 +612,8 @@ var RelayHub = class {
626
612
  pendingList;
627
613
  /** The relay refused this device because its list revokes it. */
628
614
  relayRevoked = false;
615
+ /** The relay refused this version of Conveno: what to tell the owner. No retry until restart. */
616
+ upgradeRequired;
629
617
  sent = /* @__PURE__ */ new Map();
630
618
  sessionSeq = /* @__PURE__ */ new Map();
631
619
  publishSeq = 0;
@@ -636,6 +624,7 @@ var RelayHub = class {
636
624
  failures = 0;
637
625
  /** The code of the last `error` frame, for the close that usually follows it. */
638
626
  lastErrorCode;
627
+ lastErrorMin;
639
628
  online = /* @__PURE__ */ new Set();
640
629
  remote = /* @__PURE__ */ new Map();
641
630
  pairing;
@@ -653,13 +642,14 @@ var RelayHub = class {
653
642
  this.identitySaved = stored !== void 0;
654
643
  this.state = new RelayState(paths.database);
655
644
  this.now = o.now ?? (() => /* @__PURE__ */ new Date());
656
- this.url = o.relayUrl ?? process.env.CONVENO_RELAY_URL ?? "wss://relay.conveno.dev/v1/connect";
645
+ this.url = o.relayUrl ?? relayUrl();
657
646
  const accountFile = dataPaths(platform, o.dataDir).account;
658
647
  this.accessToken = o.accessToken ?? (async (refresh, deviceId) => {
659
648
  if (!refresh) return (await readAccountTokens(accountFile))?.accessToken ?? null;
660
- const token = await currentAccessToken(accountFile);
649
+ const io = { apiBase: signedInAccountApi(accountFile) };
650
+ const token = await currentAccessToken(accountFile, io);
661
651
  if (token === null || jwtClaim(token, "did") === deviceId) return token;
662
- return bindAccountDevice(accountFile, deviceId);
652
+ return bindAccountDevice(accountFile, deviceId, io);
663
653
  });
664
654
  this.connectImpl = o.connect ?? ((c) => new RelayConnection(c));
665
655
  this.publishMs = o.publishIntervalMs ?? 6e4;
@@ -776,6 +766,7 @@ var RelayHub = class {
776
766
  async evaluateOnce() {
777
767
  if (this.stopped) return;
778
768
  if (this.isRevoked()) return this.idle("revoked", "This device was removed from the device list.");
769
+ if (this.upgradeRequired) return this.idle("upgrade_required", this.upgradeRequired);
779
770
  const want = this.paired() || this.pairingActive();
780
771
  const self = this.identity.deviceId;
781
772
  if (!want) {
@@ -805,13 +796,18 @@ var RelayHub = class {
805
796
  const events = {
806
797
  ready: (online) => this.onReady(online),
807
798
  frame: (f) => this.onFrame(f),
808
- down: (detail, code) => this.onDown(detail, code)
799
+ down: (detail, code, min) => this.onDown(detail, code, min)
809
800
  };
810
801
  this.link = this.connectImpl({
811
802
  url: this.url,
812
803
  identity: this.identity,
813
804
  token,
814
- events
805
+ events,
806
+ ...this.o.clientVersion ? { client: {
807
+ name: RELAY_CLIENT_NAME,
808
+ version: this.o.clientVersion
809
+ } } : {},
810
+ log: (line) => this.o.host.log.note(line)
815
811
  });
816
812
  this.link.start();
817
813
  }
@@ -844,9 +840,11 @@ var RelayHub = class {
844
840
  for (const d of online) this.online.add(d);
845
841
  this.pairingTick();
846
842
  }
847
- onDown(detail, frameCode) {
843
+ onDown(detail, frameCode, frameMin) {
848
844
  const code = frameCode ?? this.lastErrorCode;
845
+ const min = frameMin ?? this.lastErrorMin;
849
846
  this.lastErrorCode = void 0;
847
+ this.lastErrorMin = void 0;
850
848
  this.link = void 0;
851
849
  this.linkReady = false;
852
850
  this.listReceived = false;
@@ -859,6 +857,12 @@ var RelayHub = class {
859
857
  this.idle("revoked", "The relay says the device list revokes this device.");
860
858
  return;
861
859
  }
860
+ if (code === "upgrade_required") {
861
+ this.upgradeRequired = upgradeText(this.o.clientVersion, min);
862
+ this.o.host.log.note(`relay: refused this version of Conveno (${detail})`);
863
+ this.idle("upgrade_required", this.upgradeRequired);
864
+ return;
865
+ }
862
866
  this.connState = "disconnected";
863
867
  this.detail = detail;
864
868
  this.failures++;
@@ -896,6 +900,7 @@ var RelayHub = class {
896
900
  case "error":
897
901
  this.detail = `The relay reported: ${f.message}`;
898
902
  this.lastErrorCode = f.code;
903
+ this.lastErrorMin = f.minVersion;
899
904
  if (f.code === "list_rejected") this.failPendingList(f.message);
900
905
  return;
901
906
  default: return;
@@ -1949,6 +1954,19 @@ var Store = class {
1949
1954
  this.run("DELETE FROM messages WHERE id NOT IN (SELECT message_id FROM mailbox)");
1950
1955
  this.run("DELETE FROM sessions WHERE id = ?", id);
1951
1956
  }
1957
+ /**
1958
+ * The newest `limit` messages from one session to another, newest first, with who got each.
1959
+ * Never system messages, nor ones to or from the owner.
1960
+ */
1961
+ recentMessages(limit) {
1962
+ return this.all(`SELECT m.json, b.session_id FROM mailbox b JOIN messages m ON m.id = b.message_id
1963
+ WHERE b.session_id != ? AND json_extract(m.json, '$.kind') != 'system'
1964
+ AND json_extract(m.json, '$.from') != ?
1965
+ ORDER BY b.queued_at DESC, b.rowid DESC LIMIT ?`, OWNER_SESSION_ID, OWNER_SESSION_ID, limit).map((r) => ({
1966
+ message: Message.parse(JSON.parse(r.json)),
1967
+ recipient: r.session_id
1968
+ }));
1969
+ }
1952
1970
  /** Mailbox entries of one session, optionally limited to the given states or message ids. */
1953
1971
  entries(sessionId, filter = {}) {
1954
1972
  let sql = `SELECT m.json, b.state, b.queued_at, b.delivered_at, b.read_at, b.acked_at, b.hops
@@ -1970,7 +1988,7 @@ var Store = class {
1970
1988
  }
1971
1989
  };
1972
1990
  // ../daemon/src/server.ts
1973
- const DAEMON_VERSION = "0.2.0-rc.15";
1991
+ const DAEMON_VERSION = version;
1974
1992
  /** A connection that has not finished the handshake by then is closed. */
1975
1993
  const AUTH_TIMEOUT_MS = 5e3;
1976
1994
  /** Unread messages one session may hold. */
@@ -2048,6 +2066,8 @@ var Daemon = class {
2048
2066
  /** Permission requests of workers that wait for their spawner, by request id. In memory only. */
2049
2067
  /** When each session last sent a message (since this daemon started). */
2050
2068
  lastSent = /* @__PURE__ */ new Map();
2069
+ /** The model label a worker host reported at registration. Memory only. */
2070
+ modelLabels = /* @__PURE__ */ new Map();
2051
2071
  asks = /* @__PURE__ */ new Map();
2052
2072
  /** When each session went offline, for the removal grace. In memory only. */
2053
2073
  offlineSince = /* @__PURE__ */ new Map();
@@ -2164,7 +2184,11 @@ var Daemon = class {
2164
2184
  case "hello": return this.hello(conn, req.params);
2165
2185
  case "auth": return this.auth(conn, req.params);
2166
2186
  case "session.register": return this.registerAsync(req.params);
2167
- case "session.heartbeat": return this.heartbeat(req.params.sessionId, req.params.pid);
2187
+ case "session.heartbeat": {
2188
+ const beat = this.heartbeat(req.params.sessionId, req.params.pid);
2189
+ if (req.params.model !== void 0) this.setModelLabel(req.params.sessionId, req.params.model);
2190
+ return beat;
2191
+ }
2168
2192
  case "session.unregister": return this.unregister(req.params.sessionId, req.params.pid);
2169
2193
  case "session.remove": return this.remove(req.params.sessionId);
2170
2194
  case "session.rename": return this.rename(req.params);
@@ -2185,6 +2209,7 @@ var Daemon = class {
2185
2209
  case "permission.answer": return this.permissionAnswer(req.params);
2186
2210
  case "message.send": return this.sendMessage(req.params);
2187
2211
  case "owner.send": return this.ownerSend(conn, req.params);
2212
+ case "message.recent": return this.recent(conn, req.params);
2188
2213
  case "message.inbox": return this.inbox(req.params);
2189
2214
  case "message.deliver": return this.deliver(req.params);
2190
2215
  case "message.ack": return this.ack(req.params);
@@ -2248,7 +2273,8 @@ var Daemon = class {
2248
2273
  deliveryTier: tier
2249
2274
  }, holder?.id === row.id, this.store.unreadCount(row.id) + this.stalledWoken(row.id)),
2250
2275
  wakeable: tier === "live" || tier === "acp",
2251
- ...this.lastSent.has(row.id) ? { lastSentAt: this.lastSent.get(row.id) } : {}
2276
+ ...this.lastSent.has(row.id) ? { lastSentAt: this.lastSent.get(row.id) } : {},
2277
+ ...this.modelLabels.has(row.id) ? { model: this.modelLabels.get(row.id) } : {}
2252
2278
  };
2253
2279
  }
2254
2280
  /** The orchestrator as routing sees it: the holder, if it is online. */
@@ -2352,6 +2378,7 @@ var Daemon = class {
2352
2378
  return r;
2353
2379
  });
2354
2380
  this.attachedOf(row);
2381
+ if (p.model !== void 0) this.setModelLabel(row.id, p.model);
2355
2382
  this.emitSession(row.id, "registered");
2356
2383
  this.claimPreferredLead(row);
2357
2384
  return { session: this.view(this.store.getSession(row.id) ?? row) };
@@ -2391,6 +2418,12 @@ var Daemon = class {
2391
2418
  this.emitSession(sessionId, "updated");
2392
2419
  return { lastSeenAt: at };
2393
2420
  }
2421
+ /** The model label a session reports, as one line of plain text (it is shown in a terminal). */
2422
+ setModelLabel(sessionId, model) {
2423
+ const clean = sanitizeLine(model);
2424
+ if (clean === "") this.modelLabels.delete(sessionId);
2425
+ else this.modelLabels.set(sessionId, clean);
2426
+ }
2394
2427
  depart(sessionId, change) {
2395
2428
  const before = this.store.holder();
2396
2429
  const after = holderAfterDeparture(before, sessionId);
@@ -2459,6 +2492,8 @@ var Daemon = class {
2459
2492
  this.offlineSince.delete(sessionId);
2460
2493
  this.attached.delete(sessionId);
2461
2494
  this.hookAt.delete(sessionId);
2495
+ this.lastSent.delete(sessionId);
2496
+ this.modelLabels.delete(sessionId);
2462
2497
  this.settleAsksOf(sessionId);
2463
2498
  this.emit({
2464
2499
  event: "session.updated",
@@ -2730,6 +2765,8 @@ var Daemon = class {
2730
2765
  this.attached.delete(from.id);
2731
2766
  this.hookAt.delete(from.id);
2732
2767
  this.offlineSince.delete(from.id);
2768
+ this.lastSent.delete(from.id);
2769
+ this.modelLabels.delete(from.id);
2733
2770
  this.relay?.sessionsChanged();
2734
2771
  if (lead) this.emit({
2735
2772
  event: "orchestrator.changed",
@@ -2762,6 +2799,8 @@ var Daemon = class {
2762
2799
  this.offlineSince.delete(r.id);
2763
2800
  this.attached.delete(r.id);
2764
2801
  this.hookAt.delete(r.id);
2802
+ this.lastSent.delete(r.id);
2803
+ this.modelLabels.delete(r.id);
2765
2804
  }
2766
2805
  }
2767
2806
  leadName(id) {
@@ -2974,7 +3013,7 @@ var Daemon = class {
2974
3013
  return this.sendToRemote(make(p.to), remote, sender.hops);
2975
3014
  }
2976
3015
  const targetRow = rows.find((r) => r.id === target.id);
2977
- if (this.store.unreadCount(targetRow.id) >= 1e3) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(targetRow.name, MAX_UNREAD_PER_SESSION));
3016
+ if (this.store.unreadCount(targetRow.id) >= MAX_UNREAD_PER_SESSION) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(targetRow.name, MAX_UNREAD_PER_SESSION));
2978
3017
  const message = make(p.to);
2979
3018
  this.store.insertMessage(message, targetRow.id, at, sender.hops);
2980
3019
  this.emitMessage(message, targetRow.id);
@@ -2990,6 +3029,29 @@ var Daemon = class {
2990
3029
  requireCli(conn, what) {
2991
3030
  if (conn.client !== "cli") throw new ConvenoError(RpcErrorCode.Unauthorized, `Only the conveno command and app can ${what}. A session cannot act as the owner.`);
2992
3031
  }
3032
+ /** The last messages between sessions, oldest first, for the app's activity list. */
3033
+ recent(conn, p) {
3034
+ this.requireCli(conn, "list recent messages");
3035
+ return { messages: this.store.recentMessages(p.limit).flatMap(({ message: m, recipient }) => {
3036
+ if (m.kind === "system") return [];
3037
+ const to = this.store.getSession(recipient);
3038
+ if (!to) return [];
3039
+ const said = sanitizeLine(m.kind === "text" ? firstLineOf(m.body.text) : m.body.goal);
3040
+ const chars = [...said];
3041
+ const text = chars.length > 200 ? `${chars.slice(0, 199).join("")}…` : said;
3042
+ return [{
3043
+ id: m.id,
3044
+ from: m.from,
3045
+ ...m.fromName !== void 0 ? { fromName: m.fromName } : {},
3046
+ ...m.fromCli !== void 0 ? { fromCli: m.fromCli } : {},
3047
+ to: to.id,
3048
+ toName: to.name,
3049
+ toCli: to.cli,
3050
+ text,
3051
+ createdAt: m.createdAt
3052
+ }];
3053
+ }).reverse() };
3054
+ }
2993
3055
  ownerSend(conn, p) {
2994
3056
  this.requireCli(conn, "send as the owner");
2995
3057
  return this.deliverFrom({
@@ -3369,7 +3431,7 @@ var Daemon = class {
3369
3431
  if (!row) return "session_gone";
3370
3432
  if (row.status === "offline") return "session_offline";
3371
3433
  if (this.store.hasMessage(m.id)) return void 0;
3372
- if (this.store.unreadCount(row.id) >= 1e3) return "mailbox_full";
3434
+ if (this.store.unreadCount(row.id) >= MAX_UNREAD_PER_SESSION) return "mailbox_full";
3373
3435
  this.store.insertMessage(m, row.id, this.iso(), hops);
3374
3436
  this.emitMessage(m, row.id);
3375
3437
  },
@@ -3448,6 +3510,7 @@ const unauthorizedMessage = "Finish the handshake first: call hello, then auth.
3448
3510
  function startRelay(daemon, opts, relayOpts) {
3449
3511
  try {
3450
3512
  const hub = new RelayHub({
3513
+ clientVersion: DAEMON_VERSION,
3451
3514
  ...relayOpts,
3452
3515
  dataDir: opts.dataDir,
3453
3516
  host: daemon.relayHost()
@@ -3487,7 +3550,7 @@ async function startDaemon(opts) {
3487
3550
  close().then(() => opts.onIdleExit?.());
3488
3551
  }, () => {
3489
3552
  close().then(() => opts.onShutdown?.());
3490
- }, daemonLog, opts.authTimeoutMs ?? 5e3, opts.autoLimits ?? autoLimitsFromEnv(process.env), processIo, opts.platform, opts.wakers ?? {}, paths.settings, leadLogPath(opts.dataDir));
3553
+ }, daemonLog, opts.authTimeoutMs ?? AUTH_TIMEOUT_MS, opts.autoLimits ?? autoLimitsFromEnv(process.env), processIo, opts.platform, opts.wakers ?? {}, paths.settings, leadLogPath(opts.dataDir));
3491
3554
  daemon.removeAllOffline();
3492
3555
  const srv = createServer((socket) => daemon.attach(socket));
3493
3556
  server = srv;
@@ -3536,6 +3599,10 @@ async function startDaemon(opts) {
3536
3599
  throw e;
3537
3600
  }
3538
3601
  }
3602
+ /** The first line of a text that has something on it. */
3603
+ function firstLineOf(text) {
3604
+ return text.split(/\r?\n/).find((l) => l.trim() !== "") ?? "";
3605
+ }
3539
3606
  // ../daemon/src/bin.ts
3540
3607
  async function main() {
3541
3608
  const handle = await startDaemon({
@@ -1,4 +1,4 @@
1
- import { t as ClientError } from "./dist-C59LTq60.js";
1
+ import { t as ClientError } from "./dist-BgAfkqeX.js";
2
2
  import { n as cmd, s as plainError } from "./fmt-C2SsP5Y0.js";
3
3
  // src/daemonError.ts
4
4
  /**
@@ -2,7 +2,7 @@ import { randomBytes as randomBytes$1 } from "@noble/ciphers/utils.js";
2
2
  import { equalBytes } from "@noble/curves/utils.js";
3
3
  import { sha256 } from "@noble/hashes/sha2.js";
4
4
  import { bytesToHex, concatBytes, utf8ToBytes } from "@noble/hashes/utils.js";
5
- import { Tn as DeviceId, ar as literal, cr as string, ir as discriminatedUnion, nr as array, or as number, sr as object, tr as _enum } from "./dist-ZL7d4_97.js";
5
+ import { Ln as DeviceId, _r as discriminatedUnion, br as object, hr as array, mr as _enum, vr as literal, xr as string, yr as number } from "./dist-Dc50_P_f.js";
6
6
  import { ed25519, x25519 } from "@noble/curves/ed25519.js";
7
7
  import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
8
8
  import { expand, extract } from "@noble/hashes/hkdf.js";