@conveno/cli 0.2.0-rc.6 → 0.2.0-rc.8

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/dist/daemon.js CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import { homedir, hostname, userInfo } from "node:os";
3
- import { t as codexAdapter } from "./dist-CNyzLyZh.js";
4
- import { $t as Message, A as daemonProof, B as evaluateLiveness, Bt as tooManyUnreadMessage, F as detectRepo, K as generateSessionName, Lt as statusAfterLiveness, M as dataPaths, N as decideAutoContinue, O as createWmiWalker, Ot as resolveRecipient, P as defaultProcessIo, Q as jwtClaim, R as effectiveHolder, S as claimOrchestrator, Sn as socketPathTooLongMessage, T as clientProof, Tt as requeueEntries, Ut as validateRename, Vt as turnHops, W as formatContinuation, Xt as EVENT_NAMES, Yt as DeviceId, Z as isOnline, _n as newSessionId, _t as readAncestry, b as baseName, bn as safeParse, cn as defaultSocketPath, ct as pendingForInjection, dn as isSocketPathTooLong, fn as makeError, ft as planSpawn, gn as newMessageId, gt as readAccountTokens, hn as newDeviceId, in as RpcErrorCode, j as dataDir, k as currentAccessToken, l as RESPONSE_BUDGET_BYTES, ln as encodeFrame, mn as makeResult, mt as proofsMatch, n as AccountError, nn as PROTOCOL_VERSION, nt as newAuthNonce, on as SessionId, p as ackEntries, pn as makeEventNotification, q as holderAfterDeparture, r as ConvenoError, rn as RelayPayload, sn as createLineDecoder, tn as OWNER_SESSION_ID, tt as markDelivered, v as autoCandidates, vn as parseIpcRequest, w as clearOrchestrator, x as bindAccountDevice, xn as sanitizeLine, y as autoLimitsFromEnv, yn as parseRelayFrame, yt as readInbox, zt as takeWithinBytes } from "./dist-BTLBO1Rp.js";
3
+ import { t as codexAdapter } from "./dist-B1EVHdIM.js";
4
+ import { $ as jwtClaim, $t as EVENT_NAMES, A as daemonProof, At as resolveRecipient, B as evaluateLiveness, Cn as parseRelayFrame, En as socketPathTooLongMessage, Et as requeueEntries, F as detectRepo, G as formatHookContext, Ht as takeWithinChars, J as holderAfterDeparture, Kt as validateRename, M as dataPaths, N as decideAutoContinue, O as createWmiWalker, P as defaultProcessIo, Q as isOnline, Qt as DeviceId, R as effectiveHolder, S as claimOrchestrator, Sn as parseIpcRequest, T as clientProof, Tn as sanitizeLine, Ut as tooManyUnreadMessage, Vt as takeWithinBytes, W as formatContinuation, Wt as turnHops, _n as makeEventNotification, _t as readAccountTokens, an as PROTOCOL_VERSION, b as baseName, bn as newMessageId, bt as readInbox, dn as createLineDecoder, fn as defaultSocketPath, gn as makeError, hn as isSocketPathTooLong, ht as proofsMatch, in as OWNER_SESSION_ID, j as dataDir, k as currentAccessToken, l as RESPONSE_BUDGET_BYTES, lt as pendingForInjection, n as AccountError, nn as Message, nt as markDelivered, on as RelayPayload, p as ackEntries, pn as encodeFrame, pt as planSpawn, q as generateSessionName, r as ConvenoError, rt as newAuthNonce, sn as RpcErrorCode, un as SessionId, v as autoCandidates, vn as makeResult, vt as readAncestry, w as clearOrchestrator, wn as safeParse, x as bindAccountDevice, xn as newSessionId, xt as readSettings, y as autoLimitsFromEnv, yn as newDeviceId, zt as statusAfterLiveness } from "./dist-BBdba94T.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-DIAtMDWW.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-C6cMQ00I.js";
10
10
  import { execFileSync } from "node:child_process";
11
11
  import { DatabaseSync } from "node:sqlite";
12
12
  // ../daemon/src/lifecycle.ts
@@ -1944,7 +1944,7 @@ var Store = class {
1944
1944
  }
1945
1945
  };
1946
1946
  // ../daemon/src/server.ts
1947
- const DAEMON_VERSION = "0.2.0-rc.6";
1947
+ const DAEMON_VERSION = "0.2.0-rc.8";
1948
1948
  /** A connection that has not finished the handshake by then is closed. */
1949
1949
  const AUTH_TIMEOUT_MS = 5e3;
1950
1950
  /** Unread messages one session may hold. */
@@ -1961,6 +1961,8 @@ const HOST_OF_TIMEOUT_MS = 1500;
1961
1961
  const DAEMON_WAKE_BYTES = 16e3;
1962
1962
  /** First wait before a daemon wake is tried again; doubles up to the max. */
1963
1963
  const WAKE_RETRY_MS = 15e3;
1964
+ /** A wake still not a turn after this long counts as unread in status (see `stalledWoken`). */
1965
+ const WOKEN_STALL_MS = 3e4;
1964
1966
  const WAKE_RETRY_MAX_MS = 3e5;
1965
1967
  /** Sender id on `system` messages made by the daemon itself (no session sent them). */
1966
1968
  const DAEMON_SENDER_ID = SessionId.parse("0".repeat(26));
@@ -1985,6 +1987,7 @@ var Daemon = class {
1985
1987
  processIo;
1986
1988
  platform;
1987
1989
  wakers;
1990
+ settingsPath;
1988
1991
  conns = /* @__PURE__ */ new Set();
1989
1992
  /** Reaches the owner's other devices; set by startDaemon unless disabled. */
1990
1993
  relay;
@@ -2005,13 +2008,19 @@ var Daemon = class {
2005
2008
  wakeRetry = /* @__PURE__ */ new Map();
2006
2009
  /** Set when the daemon shuts down: closing connections must not touch the store any more. */
2007
2010
  stopping = false;
2008
- /** CLIs whose daemon waker answered `unsupported`: not asked again while the daemon runs. */
2011
+ /**
2012
+ * Sessions whose daemon waker answered \`unsupported\` (no \`queue\` in that binary, an ephemeral
2013
+ * thread): not asked again for them while the daemon runs, so a new daemon checks afresh. Other
2014
+ * sessions of the same CLI are still woken.
2015
+ */
2009
2016
  wakersOff = /* @__PURE__ */ new Set();
2017
+ /** When each session's last daemon wake was handed over, to tell a wake that never became a turn. */
2018
+ wokenAt = /* @__PURE__ */ new Map();
2010
2019
  idleSince;
2011
2020
  startedMs;
2012
2021
  /** When each session went offline, for the removal grace. In memory only. */
2013
2022
  offlineSince = /* @__PURE__ */ new Map();
2014
- constructor(store, token, now, isAlive, idleExitMs, requestIdleExit, requestShutdown, log, authTimeoutMs = AUTH_TIMEOUT_MS, autoLimits = autoLimitsFromEnv({}), processIo = defaultProcessIo, platform = process.platform, wakers = {}) {
2023
+ constructor(store, token, now, isAlive, idleExitMs, requestIdleExit, requestShutdown, log, authTimeoutMs = AUTH_TIMEOUT_MS, autoLimits = autoLimitsFromEnv({}), processIo = defaultProcessIo, platform = process.platform, wakers = {}, settingsPath) {
2015
2024
  this.store = store;
2016
2025
  this.token = token;
2017
2026
  this.now = now;
@@ -2025,6 +2034,7 @@ var Daemon = class {
2025
2034
  this.processIo = processIo;
2026
2035
  this.platform = platform;
2027
2036
  this.wakers = wakers;
2037
+ this.settingsPath = settingsPath;
2028
2038
  this.deviceId = store.deviceId();
2029
2039
  this.startedMs = now().getTime();
2030
2040
  this.idleSince = this.startedMs;
@@ -2110,7 +2120,7 @@ var Daemon = class {
2110
2120
  case "session.rename": return this.rename(req.params);
2111
2121
  case "session.setStatus": return this.setStatus(req.params);
2112
2122
  case "session.list": return this.list(req.params);
2113
- case "session.byHost": return this.byHost(req.params.pid, req.params.cwd, req.params.nativeId);
2123
+ case "session.byHost": return this.byHost(req.params);
2114
2124
  case "session.hostOf": return this.hostOf(req.params);
2115
2125
  case "session.setNative": return this.setNative(req.params);
2116
2126
  case "turn.start": return this.turnStart(req.params.sessionId);
@@ -2180,7 +2190,7 @@ var Daemon = class {
2180
2190
  return toSession({
2181
2191
  ...row,
2182
2192
  deliveryTier: this.tierFor(row)
2183
- }, holder?.id === row.id, this.store.unreadCount(row.id));
2193
+ }, holder?.id === row.id, this.store.unreadCount(row.id) + this.stalledWoken(row.id));
2184
2194
  }
2185
2195
  /** The orchestrator as routing sees it: the holder, if it is online. */
2186
2196
  orchestratorNow() {
@@ -2255,7 +2265,18 @@ var Daemon = class {
2255
2265
  return r;
2256
2266
  });
2257
2267
  this.emitSession(row.id, "registered");
2258
- return { session: this.view(row) };
2268
+ this.claimPreferredLead(row);
2269
+ return { session: this.view(this.store.getSession(row.id) ?? row) };
2270
+ }
2271
+ /**
2272
+ * The saved preferred lead CLI takes the lead when it registers and nobody online leads. The
2273
+ * settings are read on each register, so a change needs no restart. It is the normal claim.
2274
+ */
2275
+ claimPreferredLead(row) {
2276
+ if (this.settingsPath === void 0) return;
2277
+ if (readSettings(this.settingsPath).leadCli !== row.cli) return;
2278
+ if (this.orchestratorNow() !== null) return;
2279
+ this.claim(row.id);
2259
2280
  }
2260
2281
  async registerAsync(p) {
2261
2282
  return this.register(p, await this.detect(p));
@@ -2345,15 +2366,29 @@ var Daemon = class {
2345
2366
  * on Windows), so several folders on one OpenCode 2.x server stay apart. Two sessions in one
2346
2367
  * folder still match nothing.
2347
2368
  */
2348
- byHost(pid, cwd, nativeId) {
2369
+ byHost(p) {
2370
+ const { pid, cwd, nativeId } = p;
2371
+ const rows = this.store.allSessions().filter((r) => p.includeOffline || r.status !== "offline");
2372
+ const live = (list) => {
2373
+ const online = list.filter((r) => r.status !== "offline");
2374
+ return online.length > 0 ? online : list;
2375
+ };
2349
2376
  if (nativeId !== void 0) {
2350
- const own = this.store.allSessions().find((r) => r.status !== "offline" && r.nativeId === nativeId);
2351
- return { session: own ? this.view(own) : null };
2352
- }
2353
- const holders = this.store.allSessions().filter((r) => r.status !== "offline" && r.hostPid === pid && (cwd === void 0 || samePath(r.cwd, cwd, this.platform)));
2377
+ const own = live(rows.filter((r) => r.nativeId === nativeId))[0];
2378
+ if (!own) return { session: null };
2379
+ const pids = [...own.hostPid === void 0 ? [] : [own.hostPid], ...own.hostPids ?? []];
2380
+ if (pids.length === 0 || pids.includes(pid)) return { session: this.view(own) };
2381
+ const mine = this.pidHolders(rows, pid, cwd, live);
2382
+ return { session: this.view(mine.length === 1 ? mine[0] : own) };
2383
+ }
2384
+ const holders = this.pidHolders(rows, pid, cwd, live);
2354
2385
  const only = holders.length === 1 ? holders[0] : void 0;
2355
2386
  return { session: only ? this.view(only) : null };
2356
2387
  }
2388
+ /** Sessions whose host is `pid` (in `cwd`, when given), online ones first. */
2389
+ pidHolders(rows, pid, cwd, live) {
2390
+ return live(rows.filter((r) => r.hostPid === pid && (cwd === void 0 || samePath(r.cwd, cwd, this.platform))));
2391
+ }
2357
2392
  /**
2358
2393
  * Walk up from a hook's parent pid to its host CLI, for a hook that would otherwise read the
2359
2394
  * process table itself. With no online session of the hook's CLI there is nothing the hook could
@@ -2410,6 +2445,8 @@ var Daemon = class {
2410
2445
  for (const r of gone) {
2411
2446
  this.listeners.delete(r.id);
2412
2447
  this.woken.delete(r.id);
2448
+ this.wokenAt.delete(r.id);
2449
+ this.wakersOff.delete(r.id);
2413
2450
  this.offlineSince.delete(r.id);
2414
2451
  }
2415
2452
  }
@@ -2596,7 +2633,7 @@ var Daemon = class {
2596
2633
  }
2597
2634
  }
2598
2635
  daemonWakerFor(row) {
2599
- if (row.nativeId === void 0 || this.wakersOff.has(row.cli)) return void 0;
2636
+ if (row.nativeId === void 0 || this.wakersOff.has(row.id)) return void 0;
2600
2637
  return this.wakers[row.cli];
2601
2638
  }
2602
2639
  /**
@@ -2646,7 +2683,7 @@ var Daemon = class {
2646
2683
  }
2647
2684
  if (outcome === "unsupported") {
2648
2685
  this.wakeRetry.delete(id);
2649
- this.wakersOff.add(row.cli);
2686
+ this.wakersOff.add(row.id);
2650
2687
  this.relay?.sessionsChanged();
2651
2688
  }
2652
2689
  if (this.store.getSession(id)?.status === "offline") {
@@ -2671,6 +2708,17 @@ var Daemon = class {
2671
2708
  }
2672
2709
  markWoken(id, messages) {
2673
2710
  this.woken.set(id, new Set(messages.map((m) => m.id)));
2711
+ this.wokenAt.set(id, this.now().getTime());
2712
+ }
2713
+ /**
2714
+ * Messages a wake handed over that no turn took up: the CLI accepted them but the turn never
2715
+ * started (Codex keeps queued input while a turn is interrupted). Counted as unread so status
2716
+ * shows them. A turn start or end clears \`woken\`.
2717
+ */
2718
+ stalledWoken(id) {
2719
+ const at = this.wokenAt.get(id);
2720
+ if (at === void 0 || this.now().getTime() - at < WOKEN_STALL_MS) return 0;
2721
+ return this.woken.get(id)?.size ?? 0;
2674
2722
  }
2675
2723
  /**
2676
2724
  * Delivered messages go back to queued. When they are from the last wake and that wake made the
@@ -2722,7 +2770,7 @@ var Daemon = class {
2722
2770
  * On a hand-over the session is busy and its turn carries the hops. With `endOfTurn`, nothing
2723
2771
  * handed over means the session is now idle. One transaction.
2724
2772
  */
2725
- continueWith(row, allow, endOfTurn, maxBytes = RESPONSE_BUDGET_BYTES) {
2773
+ continueWith(row, allow, endOfTurn, maxBytes = RESPONSE_BUDGET_BYTES, maxChars) {
2726
2774
  const nowMs = this.now().getTime();
2727
2775
  const at = this.iso();
2728
2776
  const orchestrator = this.orchestratorNow();
@@ -2731,14 +2779,19 @@ var Daemon = class {
2731
2779
  const candidates = allow ? autoCandidates(queued, row.id) : [];
2732
2780
  const decision = decideAutoContinue({ runs: row.autoRuns }, candidates, nowMs, this.autoLimits);
2733
2781
  if (decision.continue) {
2734
- const taken = takeWithinBytes(candidates.slice(0, 20), maxBytes);
2782
+ const fit = takeWithinBytes(candidates.slice(0, 20), maxBytes);
2783
+ const { taken, preview } = maxChars === void 0 ? { taken: fit } : takeWithinChars(fit, maxChars, (ms, cut) => formatContinuation(ms, orchestrator, queued.length - (cut ? 0 : ms.length)));
2735
2784
  const updated = markDelivered(taken, taken.map((e) => e.message.id), at);
2736
2785
  for (const e of updated) this.store.saveEntry(row.id, e);
2737
2786
  this.store.updateSession(row.id, {
2738
2787
  status: "busy",
2739
2788
  autoRuns: decision.runs,
2740
- turnHops: turnHops(taken)
2789
+ turnHops: turnHops(preview ? fit.slice(0, 1) : taken)
2741
2790
  });
2791
+ if (preview) return {
2792
+ messages: [preview],
2793
+ remaining: queued.length
2794
+ };
2742
2795
  return {
2743
2796
  messages: updated.map((e) => e.message),
2744
2797
  remaining: queued.length - taken.length
@@ -2763,7 +2816,7 @@ var Daemon = class {
2763
2816
  const row = this.requireOnline(p.sessionId);
2764
2817
  this.woken.delete(p.sessionId);
2765
2818
  if (row.status === "waiting_on_question") return this.continueWith(row, false, false);
2766
- return this.continueWith(row, p.allowContinue, true);
2819
+ return this.continueWith(row, p.allowContinue, true, RESPONSE_BUDGET_BYTES, p.maxChars);
2767
2820
  }
2768
2821
  /**
2769
2822
  * An idle-wake listener asks for work. The newest listener of a session wins: an older one gets
@@ -2795,7 +2848,7 @@ var Daemon = class {
2795
2848
  }, row.id);
2796
2849
  } else known.conn = conn;
2797
2850
  if (!wasConnected) this.relay?.sessionsChanged();
2798
- const d = this.continueWith(row, row.status === "idle", false);
2851
+ const d = this.continueWith(row, row.status === "idle", false, RESPONSE_BUDGET_BYTES, p.maxChars);
2799
2852
  if (d.messages.length > 0) this.markWoken(row.id, d.messages);
2800
2853
  return {
2801
2854
  ...d,
@@ -2829,9 +2882,14 @@ var Daemon = class {
2829
2882
  const at = this.iso();
2830
2883
  return this.store.tx(() => {
2831
2884
  const pending = pendingForInjection(this.store.entries(p.sessionId, { states: ["queued"] }));
2832
- const taken = takeWithinBytes(pending.slice(0, p.limit), RESPONSE_BUDGET_BYTES);
2885
+ const fit = takeWithinBytes(pending.slice(0, p.limit), RESPONSE_BUDGET_BYTES);
2886
+ const { taken, preview } = p.maxChars === void 0 ? { taken: fit } : takeWithinChars(fit, p.maxChars, (ms) => formatHookContext(ms));
2833
2887
  const updated = markDelivered(taken, taken.map((e) => e.message.id), at);
2834
2888
  for (const e of updated) this.store.saveEntry(p.sessionId, e);
2889
+ if (preview) return {
2890
+ messages: [preview],
2891
+ remaining: pending.length
2892
+ };
2835
2893
  return {
2836
2894
  messages: updated.map((e) => e.message),
2837
2895
  remaining: pending.length - taken.length
@@ -3002,7 +3060,7 @@ async function startDaemon(opts) {
3002
3060
  close().then(() => opts.onIdleExit?.());
3003
3061
  }, () => {
3004
3062
  close().then(() => opts.onShutdown?.());
3005
- }, daemonLog, opts.authTimeoutMs ?? 5e3, opts.autoLimits ?? autoLimitsFromEnv(process.env), processIo, opts.platform, opts.wakers ?? {});
3063
+ }, daemonLog, opts.authTimeoutMs ?? 5e3, opts.autoLimits ?? autoLimitsFromEnv(process.env), processIo, opts.platform, opts.wakers ?? {}, paths.settings);
3006
3064
  daemon.removeAllOffline();
3007
3065
  const srv = createServer((socket) => daemon.attach(socket));
3008
3066
  server = srv;
@@ -1,4 +1,4 @@
1
- import { t as ClientError } from "./dist-BYVibI3a.js";
1
+ import { t as ClientError } from "./dist-WTkKRM39.js";
2
2
  import { n as cmd, s as plainError } from "./fmt-C2SsP5Y0.js";
3
3
  // src/daemonError.ts
4
4
  /**