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

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,16 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import { homedir, hostname, userInfo } from "node:os";
3
- import { $t as turnHops, A as currentAccessToken, An as defaultSocketPath, B as effectiveHolder, Bn as newTicketId, C as claimOrchestrator, Ct as proofsMatch, Dn as Ticket, E as clientProof, Et as readAncestry, F as defaultProcessIo, Fn as makeEventNotification, Gn as socketPathTooLongMessage, H as entriesNewestFirst, Hn as parseRelayFrame, Ht as samePath, I as describeToolCall, In as makeResult, Jt as tailJsonl, Kt as statusAfterLiveness, L as detectRepo, Ln as newDeviceId, M as dataDir, N as dataPaths, Nn as isSocketPathTooLong, Ot as readHeadLine, P as decideAutoContinue, Pn as makeError, Q as holderAfterDeparture, Qt as tooManyUnreadMessage, Rn as newMessageId, Rt as resolveRecipient, S as bindAccountDevice, Sn as SessionId, T as classifyPermission, Tt as readAccountTokens, U as evaluateLiveness, Un as safeParse, Vn as parseIpcRequest, Wn as sanitizeLine, Xt as takeWithinBytes, Z as generateSessionName, Zt as toIso, _ as asString, _n as PERMISSION_ANSWERS, _t as pendingForInjection, at as jwtClaim, b as autoLimitsFromEnv, bn as RpcErrorCode, cn as DeviceId, ct as markDelivered, d as ackEntries, dt as notFound, en as unsupportedTranscript, fn as HUMAN_ANSWERER, gn as OWNER_SESSION_ID, gt as pauseLabel, hn as ORCHESTRATOR_ALIAS, j as daemonProof, jn as encodeFrame, k as createWmiWalker, kn as createLineDecoder, 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 PROTOCOL_VERSION, x as baseName, xt as planSpawn, y as autoCandidates, yn as RelayPayload, zn as newSessionId } from "./dist-DUqXHTRg.js";
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";
4
5
  import { randomBytes } from "node:crypto";
5
6
  import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
6
7
  import { connect, createServer } from "node:net";
7
8
  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-BmpWfYuM.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-DIAtMDWW.js";
10
10
  import { execFileSync } from "node:child_process";
11
11
  import { DatabaseSync } from "node:sqlite";
12
- import { c as claudeTranscript, i as codexTranscript, t as openCodeTranscript } from "./dist-CfwMkSGH.js";
13
- import { readFile, readdir, stat } from "node:fs/promises";
14
12
  // ../daemon/src/lifecycle.ts
15
13
  /** Thrown when another Conveno daemon already owns the lock file or answers on the socket. */
16
14
  var DaemonAlreadyRunningError = class extends Error {
@@ -160,75 +158,6 @@ function createDaemonLog(path, opts = {}) {
160
158
  }
161
159
  };
162
160
  }
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
161
  const HANDSHAKE_TIMEOUT_MS = 15e3;
233
162
  /**
234
163
  * One WebSocket to the relay: challenge, signed hello, then frames. It does not reconnect by
@@ -1155,8 +1084,9 @@ var RelayHub = class {
1155
1084
  this.state.hold(id, from, p, since);
1156
1085
  return;
1157
1086
  }
1158
- const sender = r.sessions.find((s) => s.id === p.message.from);
1159
- if (!sender) {
1087
+ const isOwner = p.message.from === OWNER_SESSION_ID;
1088
+ const sender = isOwner ? void 0 : r.sessions.find((s) => s.id === p.message.from);
1089
+ if (!isOwner && !sender) {
1160
1090
  this.bounce(from, p, "unknown_sender");
1161
1091
  return;
1162
1092
  }
@@ -1165,14 +1095,20 @@ var RelayHub = class {
1165
1095
  return;
1166
1096
  }
1167
1097
  const device = this.chainState?.members.get(from)?.name ?? r.deviceName;
1168
- const message = {
1098
+ const { fromCli: _c, ...rest } = p.message;
1099
+ const message = sender ? {
1169
1100
  ...p.message,
1170
1101
  from: this.state.alias(from, sender.id),
1171
1102
  to: p.toSession,
1172
1103
  fromName: remoteSessionName(sender.name, device),
1173
1104
  fromCli: sender.cli
1105
+ } : {
1106
+ ...rest,
1107
+ from: OWNER_SESSION_ID,
1108
+ to: p.toSession,
1109
+ fromName: "you"
1174
1110
  };
1175
- const reason = this.o.host.deliverLocal(message, p.toSession);
1111
+ const reason = this.o.host.deliverLocal(message, p.toSession, p.hops ?? 0);
1176
1112
  if (reason !== void 0) this.bounce(from, p, reason);
1177
1113
  }
1178
1114
  bounce(to, p, reason) {
@@ -1258,14 +1194,15 @@ var RelayHub = class {
1258
1194
  return all.find((s) => s.id === to) ?? all.find((s) => s.name === to);
1259
1195
  }
1260
1196
  /** Send a message to a session on another device. Throws when that cannot be done now. */
1261
- sendRemote(target, message) {
1197
+ sendRemote(target, message, hops = 0) {
1262
1198
  if (this.conflict) throw new ConvenoError(RpcErrorCode.Conflict, "The device list has a conflict, so nothing is sent to other devices. Run \"conveno devices\".");
1263
1199
  const real = this.state.unalias(target.id);
1264
1200
  if (!real) throw new ConvenoError(RpcErrorCode.NotFound, `No session "${target.name}".`);
1265
1201
  if (!this.sendPayload(real.device, {
1266
1202
  type: "message",
1267
1203
  toSession: real.remote,
1268
- message
1204
+ message,
1205
+ ...hops > 0 ? { hops } : {}
1269
1206
  })) throw new ConvenoError(RpcErrorCode.NotFound, `Session "${target.name}" is on ${target.deviceName ?? "another device"}, and the relay is not connected. Run "conveno relay status".`);
1270
1207
  this.sent.set(message.id, {
1271
1208
  fromSession: message.from,
@@ -1647,143 +1584,6 @@ var RelayHub = class {
1647
1584
  return this.pairStatus(q);
1648
1585
  }
1649
1586
  };
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
1703
- };
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
- };
1787
1587
  // ../daemon/src/store.ts
1788
1588
  const MIGRATIONS = [
1789
1589
  {
@@ -1867,7 +1667,31 @@ const MIGRATIONS = [
1867
1667
  ALTER TABLE sessions ADD COLUMN peekable INTEGER NOT NULL DEFAULT 1;
1868
1668
  `
1869
1669
  },
1870
- TICKET_MIGRATION
1670
+ {
1671
+ name: "006_cleanup",
1672
+ sql: `
1673
+ DROP TABLE IF EXISTS tickets;
1674
+ DROP TABLE IF EXISTS permission_relay;
1675
+ DELETE FROM mailbox WHERE session_id = '${OWNER_SESSION_ID}';
1676
+ DELETE FROM messages WHERE id NOT IN (SELECT message_id FROM mailbox);
1677
+ ALTER TABLE sessions DROP COLUMN auto;
1678
+ ALTER TABLE sessions DROP COLUMN auto_explicit;
1679
+ ALTER TABLE sessions DROP COLUMN auto_paused_at;
1680
+ ALTER TABLE sessions DROP COLUMN auto_paused_by;
1681
+ ALTER TABLE sessions DROP COLUMN auto_limit;
1682
+ ALTER TABLE sessions DROP COLUMN auto_orch_resumed_at;
1683
+ ALTER TABLE sessions DROP COLUMN peekable;
1684
+ ALTER TABLE sessions DROP COLUMN cli_session_id;
1685
+ ALTER TABLE sessions DROP COLUMN transcript_path;
1686
+ `
1687
+ },
1688
+ {
1689
+ name: "007_native_id",
1690
+ sql: `
1691
+ ALTER TABLE sessions ADD COLUMN native_id TEXT;
1692
+ CREATE INDEX sessions_native_id ON sessions (native_id);
1693
+ `
1694
+ }
1871
1695
  ];
1872
1696
  const str = (v) => typeof v === "string" ? v : void 0;
1873
1697
  const num = (v) => typeof v === "number" ? v : void 0;
@@ -1902,8 +1726,6 @@ function toSessionRow(r) {
1902
1726
  deliveryTier: r.delivery_tier,
1903
1727
  spawned: r.spawned === 1,
1904
1728
  spawnDepth: r.spawn_depth,
1905
- auto: r.auto === 1,
1906
- autoExplicit: r.auto_explicit === 1,
1907
1729
  autoRuns: isoList(r.auto_runs),
1908
1730
  turnHops: num(r.turn_hops) ?? 0,
1909
1731
  startedAt: r.started_at,
@@ -1921,23 +1743,12 @@ function toSessionRow(r) {
1921
1743
  if (hostPid !== void 0) row.hostPid = hostPid;
1922
1744
  const hostPids = pidList(r.host_pids);
1923
1745
  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;
1929
1746
  const statusText = str(r.status_text);
1930
1747
  if (statusText !== void 0) row.statusText = statusText;
1931
1748
  const spawnedBy = str(r.spawned_by);
1932
1749
  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;
1750
+ const nativeId = str(r.native_id);
1751
+ if (nativeId !== void 0) row.nativeId = nativeId;
1941
1752
  return row;
1942
1753
  }
1943
1754
  /** Wire-format session for a stored row. */
@@ -1953,13 +1764,9 @@ function toSession(row, isOrchestrator, unreadCount) {
1953
1764
  deliveryTier: row.deliveryTier,
1954
1765
  spawned: row.spawned,
1955
1766
  spawnDepth: row.spawnDepth,
1956
- auto: row.auto,
1957
1767
  startedAt: row.startedAt,
1958
1768
  lastSeenAt: row.lastSeenAt
1959
1769
  };
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
1770
  if (unreadCount !== void 0) s.unreadCount = unreadCount;
1964
1771
  if (row.cliVersion !== void 0) s.cliVersion = row.cliVersion;
1965
1772
  if (row.repoRoot !== void 0) s.repo = row.repoRemoteUrlHash !== void 0 ? {
@@ -1970,8 +1777,8 @@ function toSession(row, isOrchestrator, unreadCount) {
1970
1777
  if (row.hostPid !== void 0) s.hostPid = row.hostPid;
1971
1778
  if (row.hostPids !== void 0) s.hostPids = row.hostPids;
1972
1779
  if (row.statusText !== void 0) s.statusText = row.statusText;
1973
- if (row.peekable === false) s.peekable = false;
1974
1780
  if (row.spawnedBy !== void 0) s.spawnedBy = row.spawnedBy;
1781
+ if (row.nativeId !== void 0) s.nativeId = row.nativeId;
1975
1782
  return s;
1976
1783
  }
1977
1784
  function toEntry(r) {
@@ -1993,14 +1800,12 @@ function toEntry(r) {
1993
1800
  /** SQLite persistence. All methods are synchronous; callers group writes with `tx`. */
1994
1801
  var Store = class {
1995
1802
  db;
1996
- tickets;
1997
1803
  constructor(path) {
1998
1804
  this.db = new DatabaseSync(path);
1999
1805
  this.db.exec("PRAGMA journal_mode = WAL");
2000
1806
  this.db.exec("PRAGMA synchronous = NORMAL");
2001
1807
  this.db.exec("PRAGMA busy_timeout = 5000");
2002
1808
  this.migrate();
2003
- this.tickets = new TicketStore(this.db);
2004
1809
  }
2005
1810
  all(sql, ...params) {
2006
1811
  return this.db.prepare(sql).all(...params);
@@ -2047,9 +1852,8 @@ var Store = class {
2047
1852
  insertSession(s) {
2048
1853
  this.run(`INSERT INTO sessions (id, name, cli, cli_version, device_id, cwd, repo_root, repo_remote_hash,
2049
1854
  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);
1855
+ auto_runs, turn_hops, started_at, last_seen_at)
1856
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, s.id, s.name, s.cli, s.cliVersion ?? null, s.deviceId, s.cwd, s.repoRoot ?? null, s.repoRemoteUrlHash ?? null, s.pid ?? null, s.hostPid ?? null, s.hostPids ? JSON.stringify(s.hostPids) : null, s.status, s.statusText ?? null, s.deliveryTier, s.spawnedBy ?? null, s.spawned ? 1 : 0, s.spawnDepth, JSON.stringify(s.autoRuns), s.turnHops, s.startedAt, s.lastSeenAt);
2053
1857
  }
2054
1858
  getSession(id) {
2055
1859
  const r = this.all("SELECT * FROM sessions WHERE id = ?", id)[0];
@@ -2062,29 +1866,9 @@ var Store = class {
2062
1866
  updateSession(id, fields) {
2063
1867
  const sets = [];
2064
1868
  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);
1869
+ if (fields.nativeId !== void 0) {
1870
+ sets.push("native_id = ?");
1871
+ vals.push(fields.nativeId);
2088
1872
  }
2089
1873
  if (fields.turnHops !== void 0) {
2090
1874
  sets.push("turn_hops = ?");
@@ -2094,18 +1878,6 @@ var Store = class {
2094
1878
  sets.push("auto_runs = ?");
2095
1879
  vals.push(JSON.stringify(fields.autoRuns));
2096
1880
  }
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
- }
2109
1881
  if (fields.name !== void 0) {
2110
1882
  sets.push("name = ?");
2111
1883
  vals.push(fields.name);
@@ -2132,15 +1904,11 @@ var Store = class {
2132
1904
  setHolder(id) {
2133
1905
  this.run("UPDATE orchestrator SET session_id = ? WHERE slot = 1", id);
2134
1906
  }
2135
- /** `hops`: automatic turns behind the message (the auto-mode limit counts them). */
1907
+ /** `hops`: automatic turns behind the message (the wake limit counts them). */
2136
1908
  insertMessage(message, recipient, at, hops = 0) {
2137
1909
  this.run("INSERT INTO messages (id, json) VALUES (?, ?)", message.id, JSON.stringify(message));
2138
1910
  this.run("INSERT INTO mailbox (session_id, message_id, state, queued_at, hops) VALUES (?, ?, 'queued', ?, ?)", recipient, message.id, at, hops);
2139
1911
  }
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);
2143
- }
2144
1912
  /** Messages queued for a session that no one has been shown yet. */
2145
1913
  unreadCount(sessionId) {
2146
1914
  const r = this.all("SELECT COUNT(*) AS n FROM mailbox WHERE session_id = ? AND state = 'queued'", sessionId)[0];
@@ -2151,45 +1919,10 @@ var Store = class {
2151
1919
  }
2152
1920
  /** Remove a session, its mailbox, and any message no mailbox refers to any more. */
2153
1921
  deleteSession(id) {
2154
- this.tickets.forgetSession(id);
2155
1922
  this.run("DELETE FROM mailbox WHERE session_id = ?", id);
2156
1923
  this.run("DELETE FROM messages WHERE id NOT IN (SELECT message_id FROM mailbox)");
2157
1924
  this.run("DELETE FROM sessions WHERE id = ?", id);
2158
1925
  }
2159
- /**
2160
- * Trim a mailbox nobody else cleans up: delete handled entries (anything but queued) that are
2161
- * beyond the newest `keep` entries or were last touched before `olderThanIso`. Queued entries
2162
- * stay. Returns how many were deleted.
2163
- */
2164
- pruneMailbox(sessionId, keep, olderThanIso) {
2165
- const res = this.db.prepare(`DELETE FROM mailbox WHERE session_id = ? AND state <> 'queued' AND (
2166
- message_id NOT IN (SELECT message_id FROM mailbox WHERE session_id = ?
2167
- ORDER BY message_id DESC LIMIT ?)
2168
- OR COALESCE(read_at, delivered_at, queued_at) < ?)`).run(sessionId, sessionId, keep, olderThanIso);
2169
- const n = Number(res.changes);
2170
- if (n > 0) this.run("DELETE FROM messages WHERE id NOT IN (SELECT message_id FROM mailbox)");
2171
- return n;
2172
- }
2173
- /**
2174
- * Messages a session received (it has a mailbox entry) or sent, newest first, optionally only
2175
- * those older than `before`. Message ids are ULIDs, so id order is time order.
2176
- */
2177
- messagesOf(sessionId, limit, before) {
2178
- return this.all(`SELECT m.json FROM messages m
2179
- WHERE (m.id IN (SELECT message_id FROM mailbox WHERE session_id = ?)
2180
- OR json_extract(m.json, '$.from') = ?)
2181
- ${before ? "AND m.id < ?" : ""}
2182
- ORDER BY m.id DESC LIMIT ?`, ...before ? [
2183
- sessionId,
2184
- sessionId,
2185
- before,
2186
- limit
2187
- ] : [
2188
- sessionId,
2189
- sessionId,
2190
- limit
2191
- ]).map((r) => Message.parse(JSON.parse(r.json)));
2192
- }
2193
1926
  /** Mailbox entries of one session, optionally limited to the given states or message ids. */
2194
1927
  entries(sessionId, filter = {}) {
2195
1928
  let sql = `SELECT m.json, b.state, b.queued_at, b.delivered_at, b.read_at, b.acked_at, b.hops
@@ -2210,284 +1943,25 @@ var Store = class {
2210
1943
  WHERE session_id = ? AND message_id = ?`, e.state, e.deliveredAt ?? null, e.readAt ?? null, e.ackedAt ?? null, sessionId, e.message.id);
2211
1944
  }
2212
1945
  };
2213
- // ../daemon/src/tickets.ts
2214
- /** An open question expires after this long. The asker's own CLI prompt is unaffected. */
2215
- const TICKET_TTL_MS = 864e5;
2216
- /** A permission ticket outlives the hook that asked for it by little: the hook gives up in 90 s. */
2217
- const PERMISSION_TICKET_TTL_MS = 3e5;
2218
- const OWNER = {
2219
- id: OWNER_SESSION_ID,
2220
- name: "you"
2221
- };
2222
- const fail = (code, message) => {
2223
- throw new ConvenoError(code, message);
2224
- };
2225
- const clip = (text, max) => {
2226
- const flat = sanitizeLine(text);
2227
- return flat.length > max ? `${flat.slice(0, max - 3)}...` : flat;
2228
- };
2229
- /** Questions to the orchestrator, answers back to the asker, and the permission relay. */
2230
- var TicketService = class {
2231
- host;
2232
- constructor(host) {
2233
- this.host = host;
2234
- }
2235
- get store() {
2236
- return this.host.store.tickets;
2237
- }
2238
- create(p) {
2239
- const asker = this.requireOnline(p.sessionId);
2240
- const toOwner = p.to === "you" || p.to === OWNER_SESSION_ID;
2241
- const target = toOwner ? OWNER : this.host.resolve(p.to ?? "orchestrator");
2242
- 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`.");
2243
- return this.open(asker, target, {
2244
- kind: "question",
2245
- question: p.question,
2246
- options: p.options,
2247
- toRef: toOwner ? "you" : p.to === void 0 || p.to === "orchestrator" ? ORCHESTRATOR_ALIAS : target.id,
2248
- ttlMs: TICKET_TTL_MS
2249
- });
2250
- }
2251
- open(asker, target, t) {
2252
- const at = this.host.iso();
2253
- if (this.store.list({
2254
- session: asker.id,
2255
- status: "open",
2256
- limit: 200
2257
- }).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.`);
2258
- const ticket = {
2259
- id: newTicketId(),
2260
- fromSession: asker.id,
2261
- toSession: target.id,
2262
- kind: t.kind,
2263
- question: t.question,
2264
- ...t.options ? { options: t.options } : {},
2265
- status: "open",
2266
- createdAt: at,
2267
- expiresAt: new Date(Date.parse(at) + t.ttlMs).toISOString()
2268
- };
2269
- const message = {
2270
- id: newMessageId(),
2271
- from: asker.id,
2272
- to: target.id,
2273
- kind: "question",
2274
- body: {
2275
- ticketId: ticket.id,
2276
- question: t.question,
2277
- ...t.options ? { options: t.options } : {}
2278
- },
2279
- urgent: true,
2280
- createdAt: at,
2281
- fromName: asker.name,
2282
- fromCli: asker.cli
2283
- };
2284
- this.host.store.tx(() => {
2285
- this.store.insert(ticket, t.toRef);
2286
- if (target.id !== OWNER_SESSION_ID) this.host.queue(message, target, true);
2287
- });
2288
- this.host.emit({
2289
- event: "ticket.created",
2290
- data: { ticket }
2291
- }, target.id);
2292
- return { ticket };
2293
- }
2294
- answer(p, client) {
2295
- const row = this.store.get(p.ticketId);
2296
- if (!row) fail(RpcErrorCode.NotFound, `No ticket ${p.ticketId}. Run tickets to see the open ones.`);
2297
- const { ticket, toRef } = row;
2298
- if (ticket.status !== "open") fail(RpcErrorCode.Conflict, `Ticket ${ticket.id} is already ${ticket.status}, so it cannot be answered.`);
2299
- let by;
2300
- let me;
2301
- if (p.sessionId === void 0) {
2302
- if (client !== "cli") fail(RpcErrorCode.Unauthorized, "Only a session or the conveno command can answer a ticket. Pass sessionId.");
2303
- by = HUMAN_ANSWERER;
2304
- } else {
2305
- me = this.host.requireSession(p.sessionId);
2306
- by = me.id;
2307
- if (me.id === ticket.fromSession) fail(RpcErrorCode.Unauthorized, "A session cannot answer its own ticket.");
2308
- 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.`);
2309
- }
2310
- let response = p.response;
2311
- if (ticket.kind === "permission") {
2312
- response = p.response.trim().toLowerCase();
2313
- if (!PERMISSION_ANSWERS.includes(response)) fail(RpcErrorCode.InvalidParams, `Ticket ${ticket.id} is a permission request. Answer "allow" or "deny" and nothing else.`);
2314
- }
2315
- const at = this.host.iso();
2316
- const asker = this.host.store.getSession(ticket.fromSession);
2317
- let messageId;
2318
- this.host.store.tx(() => {
2319
- let message;
2320
- if (ticket.kind === "question" && asker) {
2321
- message = {
2322
- id: newMessageId(),
2323
- from: me?.id ?? OWNER_SESSION_ID,
2324
- to: asker.id,
2325
- kind: "answer",
2326
- body: {
2327
- ticketId: ticket.id,
2328
- response
2329
- },
2330
- urgent: true,
2331
- createdAt: at,
2332
- fromName: me?.name ?? "you",
2333
- ...me ? { fromCli: me.cli } : {}
2334
- };
2335
- this.host.queue(message, asker, false);
2336
- messageId = message.id;
2337
- }
2338
- this.store.answer(ticket.id, response, by, at, messageId);
2339
- });
2340
- const done = this.store.get(ticket.id).ticket;
2341
- this.host.emit({
2342
- event: "ticket.answered",
2343
- data: { ticket: done }
2344
- }, [ticket.fromSession, ticket.toSession]);
2345
- return { ticket: done };
2346
- }
2347
- list(p, client) {
2348
- if (p.sessionId === void 0 && client !== "cli") fail(RpcErrorCode.Unauthorized, "Pass sessionId to list your tickets.");
2349
- if (p.sessionId !== void 0) this.host.requireSession(p.sessionId);
2350
- const { rows, openCount } = this.store.list({
2351
- ...p.sessionId !== void 0 ? {
2352
- session: p.sessionId,
2353
- holder: this.host.holder() === p.sessionId
2354
- } : {},
2355
- ...p.status !== void 0 ? { status: p.status } : {},
2356
- ...p.ticketId !== void 0 ? { id: p.ticketId } : {},
2357
- limit: p.limit
2358
- });
2359
- return {
2360
- tickets: rows.map((r) => r.ticket),
2361
- openCount
2362
- };
2363
- }
2364
- cancel(p, client) {
2365
- const row = this.store.get(p.ticketId);
2366
- if (!row) fail(RpcErrorCode.NotFound, `No ticket ${p.ticketId}. Run tickets to see the open ones.`);
2367
- const { ticket } = row;
2368
- if (p.sessionId === void 0) {
2369
- if (client !== "cli") fail(RpcErrorCode.Unauthorized, "Pass sessionId to cancel a ticket.");
2370
- } else {
2371
- this.host.requireSession(p.sessionId);
2372
- if (p.sessionId !== ticket.fromSession) fail(RpcErrorCode.Unauthorized, "Only the session that asked can cancel a ticket.");
2373
- }
2374
- if (ticket.status !== "open") fail(RpcErrorCode.Conflict, `Ticket ${ticket.id} is already ${ticket.status}, so it cannot be cancelled.`);
2375
- this.store.setStatus(ticket.id, "cancelled");
2376
- return { ticket: this.store.get(ticket.id).ticket };
2377
- }
2378
- /** Expire open tickets past their time; tell the asker of a question that it went unanswered. */
2379
- sweep() {
2380
- const at = this.host.iso();
2381
- for (const { ticket } of this.store.dueToExpire(at)) this.host.store.tx(() => {
2382
- this.store.setStatus(ticket.id, "expired");
2383
- const asker = this.host.store.getSession(ticket.fromSession);
2384
- if (ticket.kind === "question" && asker) {
2385
- const target = this.host.store.getSession(ticket.toSession);
2386
- this.host.queue({
2387
- id: newMessageId(),
2388
- from: this.host.daemonSender,
2389
- to: asker.id,
2390
- kind: "system",
2391
- body: {
2392
- event: "ticket.expired",
2393
- detail: `Your question to ${ticket.toSession === OWNER_SESSION_ID ? "the user" : target?.name ?? "the orchestrator"} (ticket ${ticket.id}) got no answer and has expired. Ask again, or decide yourself.`
2394
- },
2395
- urgent: false,
2396
- createdAt: at
2397
- }, asker, false);
2398
- }
2399
- });
2400
- }
2401
- relay(p, client) {
2402
- 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.");
2403
- if (p.enabled !== void 0) {
2404
- if (p.target === void 0) fail(RpcErrorCode.InvalidParams, "Name the session to switch the relay for.");
2405
- const target = this.host.requireSession(p.target);
2406
- 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.`);
2407
- let approver = null;
2408
- if (p.enabled) {
2409
- approver = this.host.holder();
2410
- 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.");
2411
- if (approver === target.id) fail(RpcErrorCode.InvalidParams, `${target.name} is the orchestrator, so it cannot relay to itself.`);
2412
- }
2413
- this.store.setRelay(target.id, approver, this.host.iso());
2414
- }
2415
- return { relays: this.store.relays() };
2416
- }
2417
- request(p) {
2418
- const me = this.requireOnline(p.sessionId);
2419
- const local = (reason) => ({
2420
- relay: false,
2421
- reason
2422
- });
2423
- const approverId = this.store.approverOf(me.id);
2424
- if (approverId === void 0) return local("The permission relay is off for this session.");
2425
- if (!me.spawned) return local("A person drives this session, so the relay does not apply.");
2426
- const verdict = classifyPermission({
2427
- tool: p.tool,
2428
- command: p.command,
2429
- paths: p.paths,
2430
- cwd: p.cwd ?? me.cwd,
2431
- repoRoot: me.repoRoot
2432
- });
2433
- if (!verdict.relay) return local(verdict.reason);
2434
- const target = this.host.store.getSession(approverId);
2435
- if (!target || target.status === "offline") return local("The orchestrator this relay was set up with is not online.");
2436
- if (target.id === me.id) return local("This session is the orchestrator.");
2437
- if (this.store.list({
2438
- session: me.id,
2439
- status: "open",
2440
- limit: 200
2441
- }).rows.filter((r) => r.ticket.fromSession === me.id && r.ticket.kind === "permission").length >= 5) return local("Too many permission requests are waiting already.");
2442
- const lines = [
2443
- `Permission request (EXPERIMENTAL relay) from ${me.name} (${me.cli}) in ${clip(me.repoRoot ?? me.cwd, 200)}.`,
2444
- `Tool: ${clip(p.tool, 100)}`,
2445
- ...p.command ? [`Command: ${clip(p.command, 1e3)}`] : [],
2446
- ...p.paths?.length ? [`Files: ${clip(p.paths.join(", "), 1e3)}`] : [],
2447
- ...p.cwd ? [`Working folder: ${clip(p.cwd, 200)}`] : [],
2448
- ...p.description ? [`The CLI says: ${clip(p.description, 300)}`] : [],
2449
- `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.`
2450
- ];
2451
- const { ticket } = this.open(me, target, {
2452
- kind: "permission",
2453
- question: lines.join("\n"),
2454
- options: [...PERMISSION_ANSWERS],
2455
- toRef: target.id,
2456
- ttlMs: PERMISSION_TICKET_TTL_MS
2457
- });
2458
- return {
2459
- relay: true,
2460
- ticket
2461
- };
2462
- }
2463
- requireOnline(id) {
2464
- const row = this.host.requireSession(id);
2465
- if (row.status === "offline") fail(RpcErrorCode.NotFound, `Session "${row.name}" is offline. Register the session again before asking.`);
2466
- return row;
2467
- }
2468
- };
2469
1946
  // ../daemon/src/server.ts
2470
- const DAEMON_VERSION = "0.2.0-rc.4";
1947
+ const DAEMON_VERSION = "0.2.0-rc.6";
2471
1948
  /** A connection that has not finished the handshake by then is closed. */
2472
1949
  const AUTH_TIMEOUT_MS = 5e3;
2473
1950
  /** Unread messages one session may hold. */
2474
1951
  const MAX_UNREAD_PER_SESSION = 1e3;
2475
- const OWNER_READ_KEEP_MS = 2592e6;
2476
- const OWNER_PRUNE_EVERY_MS = 36e5;
2477
- const PRUNE_OFFLINE_AFTER_MS = 864e5;
2478
- /**
2479
- * An offline session that a newer live session has replaced (same name, CLI and repo) is deleted
2480
- * after this grace. It cannot come back: a heartbeat is refused while another live session holds
2481
- * its name.
2482
- */
2483
- const PRUNE_SUPERSEDED_AFTER_MS = 3e5;
2484
1952
  /**
2485
- * An offline session with unread (queued) messages keeps them this long, whatever the other rules
2486
- * say, so mail sent to a closed session survives a weekend. Then the session and its mailbox go.
1953
+ * An offline session is removed this long after it went offline. The grace lets a session whose
1954
+ * host process is still alive come back with a heartbeat. Sessions already offline when the daemon
1955
+ * starts are removed at once.
2487
1956
  */
2488
- const PRUNE_UNREAD_AFTER_MS = 6048e5;
1957
+ const OFFLINE_GRACE_MS = 6e4;
2489
1958
  /** Time the daemon spends reading the process table for one `session.hostOf`. */
2490
1959
  const HOST_OF_TIMEOUT_MS = 1500;
1960
+ /** Message bytes one daemon wake hands over: the text goes on a command line (\`codex queue\`). */
1961
+ const DAEMON_WAKE_BYTES = 16e3;
1962
+ /** First wait before a daemon wake is tried again; doubles up to the max. */
1963
+ const WAKE_RETRY_MS = 15e3;
1964
+ const WAKE_RETRY_MAX_MS = 3e5;
2491
1965
  /** Sender id on `system` messages made by the daemon itself (no session sent them). */
2492
1966
  const DAEMON_SENDER_ID = SessionId.parse("0".repeat(26));
2493
1967
  const CLI_TIER = {
@@ -2497,11 +1971,6 @@ const CLI_TIER = {
2497
1971
  copilot: "next_turn",
2498
1972
  antigravity: "next_turn"
2499
1973
  };
2500
- /**
2501
- * CLIs whose adapter can wake an idle session in auto mode (Claude Code's asyncRewake listener,
2502
- * the OpenCode plugin). A message to such a session in auto mode is reported as `live`.
2503
- */
2504
- const CLI_WAKE = /* @__PURE__ */ new Set(["claude", "opencode"]);
2505
1974
  var Daemon = class {
2506
1975
  store;
2507
1976
  token;
@@ -2512,26 +1981,37 @@ var Daemon = class {
2512
1981
  requestShutdown;
2513
1982
  log;
2514
1983
  authTimeoutMs;
2515
- pathExists;
2516
1984
  autoLimits;
2517
- transcripts;
2518
- transcriptEnv;
2519
1985
  processIo;
1986
+ platform;
1987
+ wakers;
2520
1988
  conns = /* @__PURE__ */ new Set();
2521
1989
  /** Reaches the owner's other devices; set by startDaemon unless disabled. */
2522
1990
  relay;
2523
1991
  deviceId;
2524
- /** The newest idle-wake listener of each session, and the ids it replaced. In memory only. */
1992
+ /**
1993
+ * The newest idle-wake listener of each session, the ids it replaced, and the connection it
1994
+ * asked on. The session counts as wakeable while that connection is open. In memory only.
1995
+ */
2525
1996
  listeners = /* @__PURE__ */ new Map();
1997
+ /**
1998
+ * Messages the last wake handed each session, until its turn starts or ends. A requeue of
1999
+ * these makes the session idle again. In memory only.
2000
+ */
2001
+ woken = /* @__PURE__ */ new Map();
2002
+ /** Sessions a daemon waker is working on, so one session gets one wake at a time. */
2003
+ daemonWaking = /* @__PURE__ */ new Set();
2004
+ /** Daemon wakes to try again (after \`failed\` or the wake limit), by session. In memory only. */
2005
+ wakeRetry = /* @__PURE__ */ new Map();
2006
+ /** Set when the daemon shuts down: closing connections must not touch the store any more. */
2007
+ stopping = false;
2008
+ /** CLIs whose daemon waker answered `unsupported`: not asked again while the daemon runs. */
2009
+ wakersOff = /* @__PURE__ */ new Set();
2526
2010
  idleSince;
2527
2011
  startedMs;
2528
- ownerPrunedMs = 0;
2529
- tickets;
2530
- constructor(store, token, now, isAlive, idleExitMs, requestIdleExit, requestShutdown, log, authTimeoutMs = AUTH_TIMEOUT_MS, pathExists = existsSync, autoLimits = autoLimitsFromEnv({}), transcripts = {}, transcriptEnv = {
2531
- home: homedir(),
2532
- platform: process.platform,
2533
- env: process.env
2534
- }, processIo = defaultProcessIo) {
2012
+ /** When each session went offline, for the removal grace. In memory only. */
2013
+ 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 = {}) {
2535
2015
  this.store = store;
2536
2016
  this.token = token;
2537
2017
  this.now = now;
@@ -2541,24 +2021,13 @@ var Daemon = class {
2541
2021
  this.requestShutdown = requestShutdown;
2542
2022
  this.log = log;
2543
2023
  this.authTimeoutMs = authTimeoutMs;
2544
- this.pathExists = pathExists;
2545
2024
  this.autoLimits = autoLimits;
2546
- this.transcripts = transcripts;
2547
- this.transcriptEnv = transcriptEnv;
2548
2025
  this.processIo = processIo;
2026
+ this.platform = platform;
2027
+ this.wakers = wakers;
2549
2028
  this.deviceId = store.deviceId();
2550
2029
  this.startedMs = now().getTime();
2551
2030
  this.idleSince = this.startedMs;
2552
- this.tickets = new TicketService({
2553
- store,
2554
- iso: () => this.iso(),
2555
- requireSession: (id) => this.requireSession(id),
2556
- resolve: (to) => this.resolveOnline(to),
2557
- holder: () => effectiveHolder(store.holder(), this.named(store.allSessions()))?.id ?? null,
2558
- queue: (message, to, limit) => this.queueMessage(message, to, limit),
2559
- emit: (payload, onlyTo) => this.emit(payload, onlyTo),
2560
- daemonSender: DAEMON_SENDER_ID
2561
- });
2562
2031
  }
2563
2032
  iso = () => this.now().toISOString();
2564
2033
  attach(socket) {
@@ -2579,6 +2048,7 @@ var Daemon = class {
2579
2048
  socket.on("close", () => {
2580
2049
  clearTimeout(authTimer);
2581
2050
  this.conns.delete(conn);
2051
+ this.listenerGone(conn);
2582
2052
  });
2583
2053
  socket.on("error", () => socket.destroy());
2584
2054
  }
@@ -2640,33 +2110,22 @@ var Daemon = class {
2640
2110
  case "session.rename": return this.rename(req.params);
2641
2111
  case "session.setStatus": return this.setStatus(req.params);
2642
2112
  case "session.list": return this.list(req.params);
2643
- case "session.byHost": return this.byHost(req.params.pid, req.params.cwd);
2113
+ case "session.byHost": return this.byHost(req.params.pid, req.params.cwd, req.params.nativeId);
2644
2114
  case "session.hostOf": return this.hostOf(req.params);
2645
- case "session.forget": return this.forget(req.params);
2646
- case "session.setAuto": return this.setAuto(req.params);
2115
+ case "session.setNative": return this.setNative(req.params);
2647
2116
  case "turn.start": return this.turnStart(req.params.sessionId);
2648
2117
  case "turn.end": return this.turnEnd(req.params);
2649
- case "turn.wake": return this.turnWake(req.params);
2650
- case "session.setCliInfo": return this.setCliInfo(req.params);
2651
- case "session.setPeekable": return this.setPeekable(req.params);
2652
- case "session.peek": return this.peek(conn, req.params);
2118
+ case "turn.wake": return this.turnWake(conn, req.params);
2653
2119
  case "daemon.shutdown": return { ok: true };
2654
2120
  case "orchestrator.claim": return this.claim(req.params.sessionId);
2121
+ case "orchestrator.clear": return this.clearLead(conn);
2655
2122
  case "message.send": return this.sendMessage(req.params);
2656
- case "message.history": return this.messageHistory(conn, req.params);
2657
- case "owner.inbox": return this.ownerInbox(conn, req.params);
2658
- case "owner.ack": return this.ownerAck(conn, req.params);
2659
2123
  case "owner.send": return this.ownerSend(conn, req.params);
2660
2124
  case "message.inbox": return this.inbox(req.params);
2661
2125
  case "message.deliver": return this.deliver(req.params);
2662
2126
  case "message.ack": return this.ack(req.params);
2127
+ case "message.requeue": return this.requeue(req.params);
2663
2128
  case "events.subscribe": return this.subscribe(conn, req.params);
2664
- case "ticket.create": return this.tickets.create(req.params);
2665
- case "ticket.answer": return this.tickets.answer(req.params, conn.client);
2666
- case "ticket.list": return this.tickets.list(req.params, conn.client);
2667
- case "ticket.cancel": return this.tickets.cancel(req.params, conn.client);
2668
- case "permission.relay": return this.tickets.relay(req.params, conn.client);
2669
- case "permission.request": return this.tickets.request(req.params);
2670
2129
  case "relay.status":
2671
2130
  case "devices.list":
2672
2131
  case "devices.pair":
@@ -2715,28 +2174,18 @@ var Daemon = class {
2715
2174
  if (row.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${row.name}" is offline. Register the session again.`);
2716
2175
  return row;
2717
2176
  }
2177
+ /** The wire view of a session. Its `deliveryTier` is the live one (`tierFor`). */
2718
2178
  view(row) {
2719
- return toSession(row, effectiveHolder(this.store.holder(), this.named([row]))?.id === row.id, this.store.unreadCount(row.id));
2179
+ const holder = effectiveHolder(this.store.holder(), this.named([row]));
2180
+ return toSession({
2181
+ ...row,
2182
+ deliveryTier: this.tierFor(row)
2183
+ }, holder?.id === row.id, this.store.unreadCount(row.id));
2720
2184
  }
2721
2185
  /** The orchestrator as routing sees it: the holder, if it is online. */
2722
2186
  orchestratorNow() {
2723
2187
  return effectiveHolder(this.store.holder(), this.named(this.store.allSessions()))?.id ?? null;
2724
2188
  }
2725
- /** The online session a recipient names (`orchestrator`, a name or an id). */
2726
- resolveOnline(to) {
2727
- const rows = this.store.allSessions();
2728
- const found = resolveRecipient(to, this.named(rows), this.store.holder());
2729
- return rows.find((r) => r.id === found.id);
2730
- }
2731
- /**
2732
- * Queue a message for a session, or for the owner, and tell its subscriber. `limit` applies the
2733
- * unread cap.
2734
- */
2735
- queueMessage(message, row, limit) {
2736
- if (limit && this.store.unreadCount(row.id) >= 1e3) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(row.name, MAX_UNREAD_PER_SESSION));
2737
- this.store.insertMessage(message, row.id, message.createdAt);
2738
- this.emitMessage(message, row.id);
2739
- }
2740
2189
  emit(payload, onlyTo) {
2741
2190
  const only = onlyTo === void 0 || Array.isArray(onlyTo) ? onlyTo : [onlyTo];
2742
2191
  for (const c of this.conns) {
@@ -2757,11 +2206,13 @@ var Daemon = class {
2757
2206
  });
2758
2207
  this.relay?.sessionsChanged();
2759
2208
  }
2209
+ /** Every message that lands in a local mailbox goes through here. */
2760
2210
  emitMessage(m, recipient) {
2761
2211
  this.emit({
2762
2212
  event: "message.received",
2763
2213
  data: { message: m }
2764
2214
  }, recipient);
2215
+ this.daemonWake(recipient);
2765
2216
  }
2766
2217
  async detect(p) {
2767
2218
  if (p.repo) return p.repo;
@@ -2786,8 +2237,6 @@ var Daemon = class {
2786
2237
  deliveryTier: p.acp ? "acp" : CLI_TIER[p.cli] ?? "inbox",
2787
2238
  spawned: p.spawned,
2788
2239
  spawnDepth: parent ? parent.spawnDepth + 1 : 0,
2789
- auto: p.auto ?? (p.spawned || p.spawnedBy !== void 0),
2790
- autoExplicit: false,
2791
2240
  autoRuns: [],
2792
2241
  turnHops: 0,
2793
2242
  startedAt: at,
@@ -2824,6 +2273,7 @@ var Daemon = class {
2824
2273
  status: "idle",
2825
2274
  lastSeenAt: at
2826
2275
  });
2276
+ this.offlineSince.delete(sessionId);
2827
2277
  this.emitSession(sessionId, "updated");
2828
2278
  return { lastSeenAt: at };
2829
2279
  }
@@ -2835,6 +2285,8 @@ var Daemon = class {
2835
2285
  if (after !== before) this.store.setHolder(after);
2836
2286
  });
2837
2287
  this.listeners.delete(sessionId);
2288
+ this.woken.delete(sessionId);
2289
+ this.offlineSince.set(sessionId, this.now().getTime());
2838
2290
  this.emitSession(sessionId, change);
2839
2291
  if (after !== before) this.emit({
2840
2292
  event: "orchestrator.changed",
@@ -2873,7 +2325,7 @@ var Daemon = class {
2873
2325
  }
2874
2326
  list(p) {
2875
2327
  const rows = this.store.allSessions().filter((r) => {
2876
- if (!p.includeOffline && r.status === "offline") return false;
2328
+ if (r.status === "offline" && !p.includeOffline) return false;
2877
2329
  if (p.cli && r.cli !== p.cli) return false;
2878
2330
  if (p.repo && r.repoRoot !== p.repo && baseName(r.repoRoot ?? r.cwd) !== p.repo) return false;
2879
2331
  return true;
@@ -2889,12 +2341,16 @@ var Daemon = class {
2889
2341
  * Exact equality only, with no walk to farther ancestors, so a hook from a CLI that has no
2890
2342
  * session matches nothing. Two sessions under one CLI process are ambiguous, so the result is
2891
2343
  * null; the daemon never guesses. With `cwd`, the sessions that share the pid are narrowed to
2892
- * those registered in the same folder (same comparison as peek: separators, trailing slash, case
2344
+ * those registered in the same folder (separators, trailing slash, case
2893
2345
  * on Windows), so several folders on one OpenCode 2.x server stay apart. Two sessions in one
2894
2346
  * folder still match nothing.
2895
2347
  */
2896
- byHost(pid, cwd) {
2897
- const holders = this.store.allSessions().filter((r) => r.status !== "offline" && r.hostPid === pid && (cwd === void 0 || samePath(r.cwd, cwd, this.transcriptEnv.platform)));
2348
+ byHost(pid, cwd, nativeId) {
2349
+ 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)));
2898
2354
  const only = holders.length === 1 ? holders[0] : void 0;
2899
2355
  return { session: only ? this.view(only) : null };
2900
2356
  }
@@ -2923,122 +2379,39 @@ var Daemon = class {
2923
2379
  };
2924
2380
  }
2925
2381
  /**
2926
- * Remove offline sessions on the owner's request. Selection: with `ids` or `names` the
2927
- * candidates are the sessions matching either; with neither, every session. `olderThanMs` then
2928
- * keeps only sessions last seen at least that long ago. Online candidates are never removed:
2929
- * those picked by `ids` or `names` come back in `skippedOnline`, and with `olderThanMs` alone
2930
- * they are ignored, since the caller asked for offline sessions. A removed session takes its
2931
- * mailbox with it, in one transaction.
2382
+ * A hook records the CLI's own id for its session. One online session holds an id at a time,
2383
+ * so a CLI that reuses an id for a new session (a resumed thread) moves it there.
2932
2384
  */
2933
- forget(p) {
2934
- const nowMs = this.now().getTime();
2935
- const explicit = p.ids !== void 0 || p.names !== void 0;
2936
- const ids = new Set(p.ids ?? []);
2937
- const names = p.names ?? [];
2938
- const matched = this.store.allSessions().filter((r) => {
2939
- if (explicit && !ids.has(r.id) && !names.some((n) => nameMatchesPattern(n, r.name))) return false;
2940
- return p.olderThanMs === void 0 || nowMs - Date.parse(r.lastSeenAt) >= p.olderThanMs;
2941
- });
2942
- const brief = (r) => ({
2943
- id: r.id,
2944
- name: r.name
2385
+ setNative(p) {
2386
+ const row = this.requireOnline(p.sessionId);
2387
+ if (row.nativeId === p.nativeId) return { session: this.view(row) };
2388
+ const others = this.store.allSessions().filter((r) => r.id !== row.id && r.nativeId === p.nativeId);
2389
+ this.store.tx(() => {
2390
+ for (const o of others) this.store.updateSession(o.id, { nativeId: null });
2391
+ this.store.updateSession(row.id, { nativeId: p.nativeId });
2945
2392
  });
2946
- const offline = matched.filter((r) => r.status === "offline");
2947
- const skippedOnline = explicit ? matched.filter((r) => r.status !== "offline") : [];
2948
- if (!p.dryRun) this.forgetRows(offline);
2949
- return {
2950
- forgotten: offline.map(brief),
2951
- skippedOnline: skippedOnline.map(brief)
2952
- };
2953
- }
2954
- /**
2955
- * A hook reports the CLI's own session id and transcript file. The session is the one online
2956
- * session whose `hostPid` equals `pid`, as in `byHost`; no unique match changes nothing. A new
2957
- * CLI session id with no path drops the old path, which belonged to the previous conversation.
2958
- */
2959
- setCliInfo(p) {
2960
- const holders = this.store.allSessions().filter((r) => r.status !== "offline" && r.hostPid === p.pid);
2961
- const row = holders.length === 1 ? holders[0] : void 0;
2962
- if (!row) return { updated: false };
2963
- const fields = {};
2964
- if (p.cliSessionId !== void 0) fields.cliSessionId = p.cliSessionId;
2965
- if (p.transcriptPath !== void 0) fields.transcriptPath = p.transcriptPath;
2966
- else if (p.cliSessionId !== void 0 && p.cliSessionId !== row.cliSessionId) fields.transcriptPath = null;
2967
- this.store.updateSession(row.id, fields);
2968
- return { updated: true };
2969
- }
2970
- /** The owner's switch. With no `session`, every online session on this device. */
2971
- setPeekable(p) {
2972
- const rows = this.store.allSessions();
2973
- 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");
2974
- 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.`);
2975
- for (const r of targets) this.store.updateSession(r.id, { peekable: p.peekable });
2976
- return { sessions: targets.map((r) => ({
2977
- id: r.id,
2978
- name: r.name,
2979
- peekable: p.peekable
2980
- })) };
2981
- }
2982
- /**
2983
- * Read the recent turns of another session's transcript on this device. Redaction is always on.
2984
- * The target's owner can see every peek in the daemon log (who looked at whom and how many
2985
- * turns, never the content), and can turn peek off for a session.
2986
- */
2987
- async peek(conn, p) {
2988
- 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.");
2989
- const caller = p.sessionId !== void 0 ? this.requireSession(p.sessionId) : void 0;
2990
- const target = this.store.getSession(resolveRecipient(p.target, this.named(this.store.allSessions()), this.store.holder()).id);
2991
- const who = `${caller ? `${caller.name} (${caller.id})` : "the conveno command"} -> ${target.name} (${target.id}, ${target.cli})`;
2992
- if (target.peekable === false) {
2993
- this.log.note(`peek refused, peek is off: ${who}`);
2994
- throw new ConvenoError(RpcErrorCode.PermissionRequired, `Peek is turned off for ${target.name}. Its owner can run "conveno peek on ${target.name}" to allow it.`);
2995
- }
2996
- const reader = target.deliveryTier === "acp" ? acpTranscript : this.transcripts[target.cli];
2997
- if (!reader) throw new ConvenoError(RpcErrorCode.InvalidParams, `peek not supported for ${target.cli} yet.`);
2998
- const res = await reader.read({
2999
- cwd: target.cwd,
3000
- startedAt: target.startedAt,
3001
- lastTurns: p.lastTurns,
3002
- ...target.cliSessionId !== void 0 ? { cliSessionId: target.cliSessionId } : {},
3003
- ...target.transcriptPath !== void 0 ? { transcriptPath: target.transcriptPath } : {},
3004
- ...target.hostPid !== void 0 ? { hostPid: target.hostPid } : {}
3005
- }, this.transcriptEnv);
3006
- if (!res.ok) {
3007
- this.log.note(`peek found nothing (${res.reason}): ${who}`);
3008
- throw new ConvenoError(res.reason === "unsupported" ? RpcErrorCode.InvalidParams : RpcErrorCode.NotFound, res.message);
3009
- }
3010
- const out = preparePeek(res.entries, res.more, p.maxChars);
3011
- this.log.note(`peek: ${who}, ${out.turns.length} turns, ${out.redactions} redactions`);
3012
- return {
3013
- session: {
3014
- id: target.id,
3015
- name: target.name,
3016
- cli: target.cli
3017
- },
3018
- turns: out.turns,
3019
- truncated: out.truncated,
3020
- redacted: true,
3021
- redactions: out.redactions
3022
- };
2393
+ for (const o of others) this.emitSession(o.id, "updated");
2394
+ this.emitSession(row.id, "updated");
2395
+ this.daemonWake(row.id);
2396
+ return { session: this.view(this.requireSession(row.id)) };
3023
2397
  }
3024
- forgetRows(rows) {
3025
- if (rows.length === 0) return;
2398
+ /** Delete offline sessions and their mail. \`graceMs\` 0 removes every one at once. */
2399
+ removeOffline(graceMs) {
2400
+ const nowMs = this.now().getTime();
2401
+ const gone = this.store.allSessions().filter((r) => {
2402
+ if (r.status !== "offline") return false;
2403
+ const since = this.offlineSince.get(r.id) ?? Date.parse(r.lastSeenAt);
2404
+ return nowMs - since >= graceMs;
2405
+ });
2406
+ if (gone.length === 0) return;
3026
2407
  this.store.tx(() => {
3027
- for (const r of rows) this.store.deleteSession(r.id);
2408
+ for (const r of gone) this.store.deleteSession(r.id);
3028
2409
  });
3029
- for (const r of rows) this.listeners.delete(r.id);
3030
- }
3031
- /**
3032
- * An offline session whose working folder (or repository root) has been missing for
3033
- * PRUNE_MISSING_FOLDER_AFTER_MS is forgotten. One with unread messages is left to the unread
3034
- * rule, so queued mail is never dropped early. One whose host process still runs is kept,
3035
- * because it can come back with a heartbeat.
3036
- */
3037
- workspaceGone(row, nowMs) {
3038
- if (nowMs - Date.parse(row.lastSeenAt) < 3e5) return false;
3039
- if (this.store.unreadCount(row.id) > 0) return false;
3040
- if (row.hostPid !== void 0 && this.isAlive(row.hostPid)) return false;
3041
- return !this.pathExists(row.cwd) || row.repoRoot !== void 0 && !this.pathExists(row.repoRoot);
2410
+ for (const r of gone) {
2411
+ this.listeners.delete(r.id);
2412
+ this.woken.delete(r.id);
2413
+ this.offlineSince.delete(r.id);
2414
+ }
3042
2415
  }
3043
2416
  claim(sessionId) {
3044
2417
  this.requireSession(sessionId);
@@ -3083,6 +2456,44 @@ var Daemon = class {
3083
2456
  previous: res.previous
3084
2457
  };
3085
2458
  }
2459
+ clearLead(conn) {
2460
+ this.requireCli(conn, "clear the lead");
2461
+ const holder = this.store.holder();
2462
+ const res = clearOrchestrator(holder, this.named(this.store.allSessions()));
2463
+ const at = this.iso();
2464
+ const sent = [];
2465
+ this.store.tx(() => {
2466
+ this.store.setHolder(null);
2467
+ for (const n of res.notices) {
2468
+ const m = {
2469
+ id: newMessageId(),
2470
+ from: DAEMON_SENDER_ID,
2471
+ to: n.to,
2472
+ kind: "system",
2473
+ body: {
2474
+ event: n.event,
2475
+ detail: n.detail
2476
+ },
2477
+ urgent: false,
2478
+ createdAt: at
2479
+ };
2480
+ this.store.insertMessage(m, n.to, at);
2481
+ sent.push(m);
2482
+ }
2483
+ });
2484
+ if (holder !== null) {
2485
+ this.emit({
2486
+ event: "orchestrator.changed",
2487
+ data: {
2488
+ orchestrator: null,
2489
+ previous: holder
2490
+ }
2491
+ });
2492
+ if (res.previous) this.emitSession(res.previous, "updated");
2493
+ for (const m of sent) this.emitMessage(m, m.to);
2494
+ }
2495
+ return { previous: res.previous };
2496
+ }
3086
2497
  sendMessage(p) {
3087
2498
  const sender = this.requireSession(p.sessionId);
3088
2499
  if (sender.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${sender.name}" is offline. Register the session again before sending.`);
@@ -3099,9 +2510,8 @@ var Daemon = class {
3099
2510
  return to === "you" || to === OWNER_SESSION_ID;
3100
2511
  }
3101
2512
  /**
3102
- * Route one message from `sender` (a session, or the owner) to a session, the owner, or a
3103
- * session on another device. The owner is not a session: a message to `you` waits in the owner's
3104
- * mailbox, which no hook or wake ever reads.
2513
+ * Route one message from \`sender\` (a session, or the owner) to a session, or to a session on
2514
+ * another device. The owner is not a session and has no inbox: a session cannot message \`you\`.
3105
2515
  */
3106
2516
  deliverFrom(sender, p) {
3107
2517
  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.`);
@@ -3119,42 +2529,19 @@ var Daemon = class {
3119
2529
  ...sender.cli !== void 0 ? { fromCli: sender.cli } : {},
3120
2530
  ...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
3121
2531
  });
3122
- if (this.isOwnerRecipient(p.to)) {
3123
- if (sender.id === OWNER_SESSION_ID) throw new ConvenoError(RpcErrorCode.InvalidParams, "You cannot send a message to yourself.");
3124
- const message = make("you");
3125
- this.store.tx(() => this.queueMessage(message, {
3126
- id: OWNER_SESSION_ID,
3127
- name: "you"
3128
- }, true));
3129
- return {
3130
- message,
3131
- delivery: "inbox",
3132
- deliveredTo: {
3133
- id: OWNER_SESSION_ID,
3134
- name: "you"
3135
- }
3136
- };
3137
- }
2532
+ if (this.isOwnerRecipient(p.to)) throw new ConvenoError(RpcErrorCode.InvalidParams, sender.id === OWNER_SESSION_ID ? "You cannot send a message to yourself." : "The user reads your replies in this session. Answer there instead of sending a message.");
3138
2533
  let target;
3139
2534
  try {
3140
2535
  target = resolveRecipient(p.to, this.named(rows), this.store.holder());
3141
2536
  } catch (e) {
3142
2537
  const remote = e instanceof ConvenoError && e.code === RpcErrorCode.NotFound ? this.relay?.resolveRemote(p.to) : void 0;
3143
2538
  if (!remote) throw e;
3144
- return this.sendToRemote(make(p.to), remote);
2539
+ return this.sendToRemote(make(p.to), remote, sender.hops);
3145
2540
  }
3146
2541
  const targetRow = rows.find((r) => r.id === target.id);
3147
2542
  if (this.store.unreadCount(targetRow.id) >= 1e3) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(targetRow.name, MAX_UNREAD_PER_SESSION));
3148
2543
  const message = make(p.to);
3149
- const enableAuto = sender.id !== targetRow.id && effectiveHolder(this.store.holder(), this.named(rows))?.id === sender.id && !targetRow.auto && !targetRow.autoExplicit;
3150
- this.store.tx(() => {
3151
- this.store.insertMessage(message, targetRow.id, at, sender.hops);
3152
- if (enableAuto) this.store.updateSession(targetRow.id, { auto: true });
3153
- });
3154
- if (enableAuto) {
3155
- targetRow.auto = true;
3156
- this.emitSession(targetRow.id, "updated");
3157
- }
2544
+ this.store.insertMessage(message, targetRow.id, at, sender.hops);
3158
2545
  this.emitMessage(message, targetRow.id);
3159
2546
  return {
3160
2547
  message,
@@ -3168,35 +2555,8 @@ var Daemon = class {
3168
2555
  requireCli(conn, what) {
3169
2556
  if (conn.client !== "cli") throw new ConvenoError(RpcErrorCode.Unauthorized, `Only the conveno command and app can ${what}. A session cannot act as the owner.`);
3170
2557
  }
3171
- ownerInbox(conn, p) {
3172
- this.requireCli(conn, "read the owner's messages");
3173
- return this.readInboxOf(OWNER_SESSION_ID, p.unreadOnly, p.limit, true);
3174
- }
3175
- messageHistory(conn, p) {
3176
- this.requireCli(conn, "read a session's message history");
3177
- if (!(p.session === OWNER_SESSION_ID || this.store.getSession(p.session) !== void 0 || (this.relay?.remoteSessions?.() ?? []).some((s) => s.id === p.session))) throw new ConvenoError(RpcErrorCode.NotFound, `No session with id ${p.session}.`);
3178
- const rows = this.store.messagesOf(p.session, p.limit + 1, p.before);
3179
- const more = rows.length > p.limit;
3180
- return {
3181
- messages: rows.slice(0, p.limit).reverse(),
3182
- more
3183
- };
3184
- }
3185
- ownerAck(conn, p) {
3186
- this.requireCli(conn, "mark the owner's messages as handled");
3187
- return this.ackFor(OWNER_SESSION_ID, p.ids);
3188
- }
3189
2558
  ownerSend(conn, p) {
3190
2559
  this.requireCli(conn, "send as the owner");
3191
- if (!this.isOwnerRecipient(p.to) && this.relay?.resolveRemote(p.to)) {
3192
- let local = true;
3193
- try {
3194
- resolveRecipient(p.to, this.named(this.store.allSessions()), this.store.holder());
3195
- } catch {
3196
- local = false;
3197
- }
3198
- if (!local) throw new ConvenoError(RpcErrorCode.InvalidParams, "Sending to another machine from the app isn't supported yet. Message a session on this machine instead.");
3199
- }
3200
2560
  return this.deliverFrom({
3201
2561
  id: OWNER_SESSION_ID,
3202
2562
  name: "you",
@@ -3209,108 +2569,169 @@ var Daemon = class {
3209
2569
  ...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
3210
2570
  });
3211
2571
  }
3212
- /** `live` for a session in auto mode whose CLI can be woken; otherwise the CLI's own tier. */
2572
+ /**
2573
+ * \`acp\` for an ACP host. \`live\` while something can wake the session: a listener's connection
2574
+ * is open, or the session is busy in a turn a listener's CLI ends with its own hook (it continues
2575
+ * with what waits, then arms a new listener), or a daemon waker can reach it. Otherwise the CLI's
2576
+ * own tier.
2577
+ */
3213
2578
  tierFor(row) {
3214
- const running = row.auto && row.autoPausedBy === void 0;
3215
- if (row.deliveryTier === "acp") return running ? "acp" : "inbox";
3216
- if (running && CLI_WAKE.has(row.cli)) return "live";
2579
+ if (row.deliveryTier === "acp") return "acp";
2580
+ if (this.listenerConnected(row.id)) return "live";
2581
+ if (row.status === "busy" && this.listeners.has(row.id)) return "live";
2582
+ if (this.daemonWakerFor(row)) return "live";
3217
2583
  return row.deliveryTier;
3218
2584
  }
2585
+ listenerConnected(id) {
2586
+ const conn = this.listeners.get(id)?.conn;
2587
+ return conn !== void 0 && this.conns.has(conn) && !conn.socket.destroyed;
2588
+ }
2589
+ /** A connection closed: a listener that asked on it no longer makes its session wakeable. */
2590
+ listenerGone(conn) {
2591
+ if (this.stopping) return;
2592
+ for (const [id, rec] of this.listeners) {
2593
+ if (rec.conn !== conn) continue;
2594
+ rec.conn = void 0;
2595
+ this.emitSession(id, "updated");
2596
+ }
2597
+ }
2598
+ daemonWakerFor(row) {
2599
+ if (row.nativeId === void 0 || this.wakersOff.has(row.cli)) return void 0;
2600
+ return this.wakers[row.cli];
2601
+ }
3219
2602
  /**
3220
- * Change auto mode. The owner (no `sessionId`) may do anything. A session may only resume a paused
3221
- * session, only while it is the orchestrator, and only once per window for that session, so two
3222
- * agents cannot keep each other going without the owner.
2603
+ * A message landed for \`id\`. When its CLI has a daemon waker, no listener is connected and the
2604
+ * session is idle, hand the waiting messages to the waker (under the wake limit, like
2605
+ * \`turn.wake\`, and under \`DAEMON_WAKE_BYTES\`, since they go on a command line). \`queued\`
2606
+ * and \`unknown\` keep them delivered (a wake that timed out may have landed: a requeue could
2607
+ * deliver them twice). \`failed\` and \`unsupported\` put them back; after \`failed\` or the wake
2608
+ * limit, the sweep tries again with a growing delay. One wake per session at a time.
3223
2609
  */
3224
- setAuto(p) {
3225
- const all = this.store.allSessions();
3226
- 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);
3227
- if (!row) throw new ConvenoError(RpcErrorCode.NotFound, `No session named "${p.session}". Run conveno status to see the sessions.`);
3228
- const at = this.iso();
3229
- const byOrchestrator = p.sessionId !== void 0;
3230
- if (p.sessionId !== void 0) {
3231
- const caller = this.requireOnline(p.sessionId);
3232
- 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>");
3233
- 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");
3234
- if (row.autoPausedBy === void 0) throw new ConvenoError(RpcErrorCode.PermissionRequired, `Auto mode for "${row.name}" is not paused.`);
3235
- const last = row.autoOrchResumedAt ? Date.parse(row.autoOrchResumedAt) : NaN;
3236
- if (this.now().getTime() - last < this.autoLimits.windowMs) {
3237
- const minutes = Math.round(this.autoLimits.windowMs / 6e4);
3238
- 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}`);
3239
- }
2610
+ daemonWake(id) {
2611
+ if (this.daemonWaking.has(id)) return;
2612
+ const row = this.store.getSession(id);
2613
+ const wake = row?.status === "idle" && !this.listenerConnected(id) && this.daemonWakerFor(row);
2614
+ if (!row || !wake) {
2615
+ this.wakeRetry.delete(id);
2616
+ return;
3240
2617
  }
3241
- const lift = p.resume === true || p.auto === true;
3242
- this.store.tx(() => {
3243
- this.store.updateSession(row.id, {
3244
- ...p.auto !== void 0 ? {
3245
- auto: p.auto,
3246
- autoExplicit: true
3247
- } : {},
3248
- ...p.limit !== void 0 ? { autoLimit: p.limit } : {},
3249
- ...lift ? {
3250
- autoPausedAt: null,
3251
- autoPausedBy: null,
3252
- autoRuns: []
3253
- } : {},
3254
- ...byOrchestrator ? { autoOrchResumedAt: at } : {}
2618
+ const d = this.continueWith(row, true, false, DAEMON_WAKE_BYTES);
2619
+ if (d.messages.length === 0) {
2620
+ const queued = this.store.entries(id, { states: ["queued"] });
2621
+ if (autoCandidates(queued, id).length > 0) this.scheduleWakeRetry(id);
2622
+ else this.wakeRetry.delete(id);
2623
+ return;
2624
+ }
2625
+ this.markWoken(id, d.messages);
2626
+ this.daemonWaking.add(id);
2627
+ const text = formatContinuation(d.messages, d.orchestrator, d.remaining);
2628
+ const session = this.view(this.requireSession(id));
2629
+ (async () => {
2630
+ let outcome;
2631
+ try {
2632
+ outcome = await wake({
2633
+ session,
2634
+ text,
2635
+ messages: d.messages,
2636
+ ...row.nativeId !== void 0 ? { nativeId: row.nativeId } : {}
2637
+ });
2638
+ } catch (e) {
2639
+ this.log.error(`${row.cli} waker failed`, e);
2640
+ outcome = "failed";
2641
+ }
2642
+ this.daemonWaking.delete(id);
2643
+ if (outcome === "queued" || outcome === "unknown" || this.stopping) {
2644
+ this.wakeRetry.delete(id);
2645
+ return;
2646
+ }
2647
+ if (outcome === "unsupported") {
2648
+ this.wakeRetry.delete(id);
2649
+ this.wakersOff.add(row.cli);
2650
+ this.relay?.sessionsChanged();
2651
+ }
2652
+ if (this.store.getSession(id)?.status === "offline") {
2653
+ this.wakeRetry.delete(id);
2654
+ return;
2655
+ }
2656
+ this.requeueFor(id, d.messages.map((m) => m.id));
2657
+ if (outcome === "failed") this.scheduleWakeRetry(id);
2658
+ })();
2659
+ }
2660
+ /** Try a daemon wake of \`id\` again later, each time waiting twice as long, up to a cap. */
2661
+ scheduleWakeRetry(id) {
2662
+ const delayMs = Math.min((this.wakeRetry.get(id)?.delayMs ?? 0) * 2 || WAKE_RETRY_MS, WAKE_RETRY_MAX_MS);
2663
+ this.wakeRetry.set(id, {
2664
+ atMs: this.now().getTime() + delayMs,
2665
+ delayMs
2666
+ });
2667
+ }
2668
+ /** Run the daemon wakes whose retry is due. Called by the sweep. */
2669
+ retryDaemonWakes(nowMs) {
2670
+ for (const [id, r] of [...this.wakeRetry]) if (r.atMs <= nowMs) this.daemonWake(id);
2671
+ }
2672
+ markWoken(id, messages) {
2673
+ this.woken.set(id, new Set(messages.map((m) => m.id)));
2674
+ }
2675
+ /**
2676
+ * Delivered messages go back to queued. When they are from the last wake and that wake made the
2677
+ * session busy, the wake never became a turn: the session is idle again and the wake does not
2678
+ * count against the limit.
2679
+ */
2680
+ requeue(p) {
2681
+ this.requireSession(p.sessionId);
2682
+ return this.requeueFor(p.sessionId, p.ids);
2683
+ }
2684
+ requeueFor(id, ids) {
2685
+ const woken = this.woken.get(id);
2686
+ const fromWake = woken !== void 0 && ids.some((m) => woken.has(m));
2687
+ const res = this.store.tx(() => {
2688
+ const r = requeueEntries(this.store.entries(id, { ids: [...ids] }), ids);
2689
+ for (const e of r.changed) this.store.saveEntry(id, e);
2690
+ const row = this.requireSession(id);
2691
+ const idle = fromWake && r.changed.length > 0 && row.status === "busy";
2692
+ if (idle) this.store.updateSession(id, {
2693
+ status: "idle",
2694
+ turnHops: 0,
2695
+ autoRuns: row.autoRuns.slice(0, -1)
3255
2696
  });
3256
- if (lift) this.store.resetQueuedHops(row.id);
2697
+ return {
2698
+ requeued: r.changed.length,
2699
+ idle
2700
+ };
3257
2701
  });
3258
- this.emitSession(row.id, "updated");
3259
- return { session: this.view(this.requireSession(row.id)) };
2702
+ if (fromWake) this.woken.delete(id);
2703
+ if (res.idle) this.emitSession(id, "updated");
2704
+ return { requeued: res.requeued };
3260
2705
  }
3261
2706
  /**
3262
2707
  * The user typed a prompt: the session is busy, and messages it sends start a new chain (0 hops).
3263
- * A pause stays until the owner or the orchestrator resumes it.
3264
2708
  */
3265
2709
  turnStart(sessionId) {
3266
- this.requireOnline(sessionId);
3267
- this.store.updateSession(sessionId, {
2710
+ const row = this.requireOnline(sessionId);
2711
+ const fromWake = this.woken.has(sessionId) && row.status === "busy";
2712
+ this.woken.delete(sessionId);
2713
+ this.store.updateSession(sessionId, fromWake ? { status: "busy" } : {
3268
2714
  status: "busy",
3269
2715
  turnHops: 0
3270
2716
  });
3271
2717
  this.emitSession(sessionId, "updated");
3272
2718
  return { session: this.view(this.requireSession(sessionId)) };
3273
2719
  }
3274
- /** The notice a session gets when its auto mode pauses. It waits for the next prompt. */
3275
- pauseNotice(row, reason, at) {
3276
- const minutes = Math.round(this.autoLimits.windowMs / 6e4);
3277
- const limit = row.autoLimit ?? this.autoLimits.limit;
3278
- 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.`;
3279
- return {
3280
- id: newMessageId(),
3281
- from: DAEMON_SENDER_ID,
3282
- to: row.id,
3283
- kind: "system",
3284
- body: {
3285
- event: "auto.paused",
3286
- detail
3287
- },
3288
- urgent: false,
3289
- createdAt: at
3290
- };
3291
- }
3292
2720
  /**
3293
- * Hand the session its waiting messages to continue with, if auto mode and its limit allow it.
2721
+ * Hand the session its waiting messages to continue with, if the wake limit allows it.
3294
2722
  * On a hand-over the session is busy and its turn carries the hops. With `endOfTurn`, nothing
3295
2723
  * handed over means the session is now idle. One transaction.
3296
2724
  */
3297
- continueWith(row, allow, endOfTurn) {
2725
+ continueWith(row, allow, endOfTurn, maxBytes = RESPONSE_BUDGET_BYTES) {
3298
2726
  const nowMs = this.now().getTime();
3299
2727
  const at = this.iso();
3300
2728
  const orchestrator = this.orchestratorNow();
3301
- let pausedBy = row.autoPausedBy;
3302
- let notice;
3303
2729
  const res = this.store.tx(() => {
3304
2730
  const queued = this.store.entries(row.id, { states: ["queued"] });
3305
2731
  const candidates = allow ? autoCandidates(queued, row.id) : [];
3306
- const decision = decideAutoContinue({
3307
- auto: row.auto,
3308
- ...row.autoPausedBy !== void 0 ? { pausedBy: row.autoPausedBy } : {},
3309
- ...row.autoLimit !== void 0 ? { limit: row.autoLimit } : {},
3310
- runs: row.autoRuns
3311
- }, candidates, nowMs, this.autoLimits);
2732
+ const decision = decideAutoContinue({ runs: row.autoRuns }, candidates, nowMs, this.autoLimits);
3312
2733
  if (decision.continue) {
3313
- const taken = takeWithinBytes(candidates.slice(0, 20), RESPONSE_BUDGET_BYTES);
2734
+ const taken = takeWithinBytes(candidates.slice(0, 20), maxBytes);
3314
2735
  const updated = markDelivered(taken, taken.map((e) => e.message.id), at);
3315
2736
  for (const e of updated) this.store.saveEntry(row.id, e);
3316
2737
  this.store.updateSession(row.id, {
@@ -3323,36 +2744,24 @@ var Daemon = class {
3323
2744
  remaining: queued.length - taken.length
3324
2745
  };
3325
2746
  }
3326
- if (decision.pause !== void 0) {
3327
- pausedBy = decision.pause;
3328
- notice = this.pauseNotice(row, decision.pause, at);
3329
- this.store.insertMessage(notice, row.id, at);
3330
- this.store.updateSession(row.id, {
3331
- autoPausedAt: at,
3332
- autoPausedBy: decision.pause
3333
- });
3334
- }
3335
2747
  if (endOfTurn) this.store.updateSession(row.id, {
3336
2748
  status: "idle",
3337
2749
  turnHops: 0
3338
2750
  });
3339
2751
  return {
3340
2752
  messages: [],
3341
- remaining: queued.length + (notice ? 1 : 0)
2753
+ remaining: queued.length
3342
2754
  };
3343
2755
  });
3344
- if (notice) this.emitMessage(notice, row.id);
3345
- if ((res.messages.length > 0 ? row.status !== "busy" : endOfTurn && row.status !== "idle") || notice) this.emitSession(row.id, "updated");
2756
+ if (res.messages.length > 0 ? row.status !== "busy" : endOfTurn && row.status !== "idle") this.emitSession(row.id, "updated");
3346
2757
  return {
3347
2758
  ...res,
3348
- auto: row.auto,
3349
- paused: pausedBy !== void 0,
3350
- ...pausedBy !== void 0 ? { pausedBy } : {},
3351
2759
  orchestrator
3352
2760
  };
3353
2761
  }
3354
2762
  turnEnd(p) {
3355
2763
  const row = this.requireOnline(p.sessionId);
2764
+ this.woken.delete(p.sessionId);
3356
2765
  if (row.status === "waiting_on_question") return this.continueWith(row, false, false);
3357
2766
  return this.continueWith(row, p.allowContinue, true);
3358
2767
  }
@@ -3360,23 +2769,22 @@ var Daemon = class {
3360
2769
  * An idle-wake listener asks for work. The newest listener of a session wins: an older one gets
3361
2770
  * `superseded` and stops. A busy session is not woken; its messages wait for the end of the turn.
3362
2771
  */
3363
- turnWake(p) {
2772
+ turnWake(conn, p) {
3364
2773
  const row = this.requireOnline(p.sessionId);
3365
2774
  const known = this.listeners.get(row.id);
3366
2775
  if (known?.retired.includes(p.listenerId)) return {
3367
2776
  messages: [],
3368
2777
  remaining: this.store.unreadCount(row.id),
3369
- auto: row.auto,
3370
- paused: row.autoPausedBy !== void 0,
3371
- ...row.autoPausedBy !== void 0 ? { pausedBy: row.autoPausedBy } : {},
3372
2778
  orchestrator: this.orchestratorNow(),
3373
2779
  superseded: true
3374
2780
  };
2781
+ const wasConnected = this.listenerConnected(row.id);
3375
2782
  if (known?.current !== p.listenerId) {
3376
2783
  const retired = known ? [...known.retired, known.current].slice(-64) : [];
3377
2784
  this.listeners.set(row.id, {
3378
2785
  current: p.listenerId,
3379
- retired
2786
+ retired,
2787
+ conn
3380
2788
  });
3381
2789
  if (known) this.emit({
3382
2790
  event: "session.updated",
@@ -3385,9 +2793,12 @@ var Daemon = class {
3385
2793
  change: "updated"
3386
2794
  }
3387
2795
  }, row.id);
3388
- }
2796
+ } else known.conn = conn;
2797
+ if (!wasConnected) this.relay?.sessionsChanged();
2798
+ const d = this.continueWith(row, row.status === "idle", false);
2799
+ if (d.messages.length > 0) this.markWoken(row.id, d.messages);
3389
2800
  return {
3390
- ...this.continueWith(row, row.status === "idle", false),
2801
+ ...d,
3391
2802
  superseded: false
3392
2803
  };
3393
2804
  }
@@ -3395,16 +2806,15 @@ var Daemon = class {
3395
2806
  this.requireSession(p.sessionId);
3396
2807
  return this.readInboxOf(p.sessionId, p.unreadOnly, p.limit);
3397
2808
  }
3398
- /** A mailbox's messages, oldest first, marked read. The owner's mailbox has no session row. */
3399
- readInboxOf(id, unreadOnly, limit, newest = false) {
2809
+ /** A mailbox's messages, oldest first, marked read. */
2810
+ readInboxOf(id, unreadOnly, limit) {
3400
2811
  const at = this.iso();
3401
2812
  return this.store.tx(() => {
3402
2813
  const entries = this.store.entries(id, unreadOnly ? { states: ["queued"] } : {});
3403
2814
  const res = readInbox(entries, {
3404
2815
  unreadOnly,
3405
2816
  limit,
3406
- maxBytes: RESPONSE_BUDGET_BYTES,
3407
- newest
2817
+ maxBytes: RESPONSE_BUDGET_BYTES
3408
2818
  }, at);
3409
2819
  const changed = new Set(res.returned.map((e) => e.message.id));
3410
2820
  for (const e of res.entries) if (changed.has(e.message.id)) this.store.saveEntry(id, e);
@@ -3468,8 +2878,8 @@ var Daemon = class {
3468
2878
  default: throw new ConvenoError(RpcErrorCode.MethodNotFound, `Method not found: ${req.method}`);
3469
2879
  }
3470
2880
  }
3471
- sendToRemote(message, target) {
3472
- this.relay.sendRemote(target, message);
2881
+ sendToRemote(message, target, hops) {
2882
+ this.relay.sendRemote(target, message, hops);
3473
2883
  return {
3474
2884
  message,
3475
2885
  delivery: target.deliveryTier,
@@ -3483,19 +2893,22 @@ var Daemon = class {
3483
2893
  relayHost() {
3484
2894
  return {
3485
2895
  log: this.log,
3486
- localSessions: () => this.store.allSessions().filter((r) => r.status !== "offline").map((r) => this.view(r)),
3487
- deliverLocal: (m, to) => {
2896
+ localSessions: () => this.store.allSessions().filter((r) => r.status !== "offline").map((r) => {
2897
+ const { nativeId: _n, ...s } = this.view(r);
2898
+ return s;
2899
+ }),
2900
+ deliverLocal: (m, to, hops = 0) => {
3488
2901
  if (m.kind === "system") return "not_allowed";
3489
2902
  const row = this.store.getSession(to);
3490
2903
  if (!row) return "session_gone";
3491
2904
  if (row.status === "offline") return "session_offline";
3492
2905
  if (this.store.hasMessage(m.id)) return void 0;
3493
2906
  if (this.store.unreadCount(row.id) >= 1e3) return "mailbox_full";
3494
- this.store.insertMessage(m, row.id, this.iso());
2907
+ this.store.insertMessage(m, row.id, this.iso(), hops);
3495
2908
  this.emitMessage(m, row.id);
3496
2909
  },
3497
2910
  notify: (to, event, detail) => {
3498
- if (to !== OWNER_SESSION_ID && !this.store.getSession(to)) return;
2911
+ if (!this.store.getSession(to)) return;
3499
2912
  const m = {
3500
2913
  id: newMessageId(),
3501
2914
  from: DAEMON_SENDER_ID,
@@ -3513,34 +2926,18 @@ var Daemon = class {
3513
2926
  }
3514
2927
  };
3515
2928
  }
3516
- /**
3517
- * Prune rules for an offline session, in order:
3518
- * 1. With unread messages waiting, keep it for PRUNE_UNREAD_AFTER_MS, then delete it and its mail.
3519
- * 2. Replaced by a newer live session with the same name, CLI and repo: delete after
3520
- * PRUNE_SUPERSEDED_AFTER_MS.
3521
- * 3. Otherwise delete after PRUNE_OFFLINE_AFTER_MS.
3522
- * Besides these rules, `workspaceGone` forgets an offline session whose folder has been gone a while.
3523
- */
3524
- shouldPrune(row, all, nowMs) {
3525
- const offlineMs = nowMs - Date.parse(row.lastSeenAt);
3526
- if (this.store.unreadCount(row.id) > 0) return offlineMs >= PRUNE_UNREAD_AFTER_MS;
3527
- const place = (r) => r.repoRoot ?? r.cwd;
3528
- 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);
2929
+ /** Remove every offline session at once. The daemon does this when it starts. */
2930
+ removeAllOffline() {
2931
+ this.removeOffline(0);
3529
2932
  }
3530
2933
  sweep() {
3531
- this.tickets.sweep();
3532
2934
  const nowMs = this.now().getTime();
3533
- if (nowMs - this.ownerPrunedMs >= OWNER_PRUNE_EVERY_MS) {
3534
- this.ownerPrunedMs = nowMs;
3535
- this.store.pruneMailbox(OWNER_SESSION_ID, 500, (/* @__PURE__ */ new Date(nowMs - OWNER_READ_KEEP_MS)).toISOString());
3536
- }
2935
+ this.removeOffline(OFFLINE_GRACE_MS);
2936
+ this.retryDaemonWakes(nowMs);
3537
2937
  let online = 0;
3538
2938
  const rows = this.store.allSessions();
3539
2939
  for (const row of rows) {
3540
- if (row.status === "offline") {
3541
- if (this.shouldPrune(row, rows, nowMs) || this.workspaceGone(row, nowMs)) this.forgetRows([row]);
3542
- continue;
3543
- }
2940
+ if (row.status === "offline") continue;
3544
2941
  const lastSeenMs = Math.max(Date.parse(row.lastSeenAt), this.startedMs);
3545
2942
  const verdict = evaluateLiveness({
3546
2943
  lastSeenMs,
@@ -3553,6 +2950,14 @@ var Daemon = class {
3553
2950
  else if (nowMs - this.idleSince >= this.idleExitMs) this.requestIdleExit();
3554
2951
  }
3555
2952
  };
2953
+ /** Do two directory paths name the same place, ignoring trailing separators (and case on Windows)? */
2954
+ function samePath(a, b, platform) {
2955
+ const norm = (p) => {
2956
+ const s = p.replace(/[\\/]+$/, "");
2957
+ return platform === "win32" ? s.replace(/\\/g, "/").toLowerCase() : s;
2958
+ };
2959
+ return norm(a) === norm(b);
2960
+ }
3556
2961
  const unauthorizedMessage = "Finish the handshake first: call hello, then auth. Both use the token in daemon.token in the Conveno data directory.";
3557
2962
  /** Start the relay client. A broken relay state is logged and leaves the daemon local-only. */
3558
2963
  function startRelay(daemon, opts, relayOpts) {
@@ -3592,11 +2997,13 @@ async function startDaemon(opts) {
3592
2997
  await clearStaleSocket(socketPath);
3593
2998
  let closing;
3594
2999
  let timer;
3000
+ const daemonLog = createDaemonLog(paths.daemonLog, { now });
3595
3001
  const daemon = new Daemon(store, token, now, isAlive, opts.idleExitMs ?? 6e5, () => {
3596
3002
  close().then(() => opts.onIdleExit?.());
3597
3003
  }, () => {
3598
3004
  close().then(() => opts.onShutdown?.());
3599
- }, createDaemonLog(paths.daemonLog, { now }), opts.authTimeoutMs ?? 5e3, opts.pathExists ?? existsSync, opts.autoLimits ?? autoLimitsFromEnv(process.env), opts.transcripts, opts.transcriptEnv, processIo);
3005
+ }, daemonLog, opts.authTimeoutMs ?? 5e3, opts.autoLimits ?? autoLimitsFromEnv(process.env), processIo, opts.platform, opts.wakers ?? {});
3006
+ daemon.removeAllOffline();
3600
3007
  const srv = createServer((socket) => daemon.attach(socket));
3601
3008
  server = srv;
3602
3009
  await new Promise((resolve, reject) => {
@@ -3611,6 +3018,7 @@ async function startDaemon(opts) {
3611
3018
  function close() {
3612
3019
  closing ??= (async () => {
3613
3020
  if (timer) clearInterval(timer);
3021
+ daemon.stopping = true;
3614
3022
  walker?.close();
3615
3023
  daemon.relay?.stop();
3616
3024
  const stopped = new Promise((resolve) => srv.close(() => resolve()));
@@ -3629,7 +3037,10 @@ async function startDaemon(opts) {
3629
3037
  testRelay: {
3630
3038
  host: () => daemon.relayHost(),
3631
3039
  set: (relay) => {
3632
- daemon.relay = relay;
3040
+ daemon.relay = relay && {
3041
+ sessionsChanged: () => {},
3042
+ ...relay
3043
+ };
3633
3044
  }
3634
3045
  }
3635
3046
  };
@@ -3640,264 +3051,11 @@ async function startDaemon(opts) {
3640
3051
  throw e;
3641
3052
  }
3642
3053
  }
3643
- // ../adapters/copilot/dist/transcript.js
3644
- /**
3645
- * GitHub Copilot CLI keeps each session in `~/.copilot/session-state/<session-id>/` (COPILOT_HOME
3646
- * replaces `~/.copilot`): `events.jsonl`, an append-only stream of `{ type, data, id, timestamp }`
3647
- * records, and `workspace.yaml` with `id`, `cwd`, `created_at` and `updated_at`.
3648
- *
3649
- * GitHub does not document this layout. It is taken from community write-ups of Copilot CLI 1.0.11
3650
- * and later (the events.jsonl reference gist
3651
- * https://gist.github.com/RockNoggin/8cc87f640ce5e3d284298a6db21f7523 and
3652
- * https://github.com/microsoft/What-I-Did-Copilot/blob/main/docs/architecture.md) and the open
3653
- * request for documentation, github/copilot-cli#3551. The reference bundle in
3654
- * reference/bundles/copilot-cli is a closed binary whose strings do not show the layout, so this
3655
- * reader is not checked against a real install. It skips what it does not recognise.
3656
- */
3657
- const copilotHome = (env) => env.env.COPILOT_HOME?.trim() || join(env.home, ".copilot");
3658
- const unquote = (s) => s.trim().replace(/^(["'])(.*)\1$/, "$2");
3659
- /** The `cwd:` value of a workspace.yaml, which is flat `key: value` lines. */
3660
- function yamlCwd(yaml) {
3661
- const m = /^cwd:[ \t]*(.+)$/m.exec(yaml);
3662
- return m?.[1] ? unquote(m[1]) : void 0;
3663
- }
3664
- async function sessionCwd(dir) {
3665
- try {
3666
- const cwd = yamlCwd(await readFile(join(dir, "workspace.yaml"), "utf8"));
3667
- if (cwd) return cwd;
3668
- } catch {}
3669
- try {
3670
- const head = await readHeadLine(join(dir, "events.jsonl"), 262144);
3671
- const ev = head ? JSON.parse(head) : null;
3672
- const data = isRecord(ev) && ev.type === "session.start" ? ev.data : void 0;
3673
- const context = isRecord(data) && isRecord(data.context) ? data.context : void 0;
3674
- return asString(context?.cwd);
3675
- } catch {
3676
- return;
3677
- }
3678
- }
3679
- const textOf = (v) => {
3680
- if (typeof v === "string") return v;
3681
- if (Array.isArray(v)) return v.map(textOf).filter(Boolean).join("\n");
3682
- if (isRecord(v)) return asString(v.text) ?? asString(v.content) ?? "";
3683
- return "";
3684
- };
3685
- /** Normalize one events.jsonl record. Exported for tests. */
3686
- function parseCopilotEvent(obj) {
3687
- const data = isRecord(obj.data) ? obj.data : {};
3688
- if (data.agentId !== void 0) return [];
3689
- const at = toIso(obj.timestamp);
3690
- const stamp = at ? { at } : {};
3691
- switch (obj.type) {
3692
- case "user.message": {
3693
- const text = asString(data.content) ?? "";
3694
- return text === "" ? [] : [{
3695
- role: "user",
3696
- text,
3697
- ...stamp
3698
- }];
3699
- }
3700
- case "assistant.message": {
3701
- const out = [];
3702
- const text = asString(data.content) ?? "";
3703
- if (text !== "") out.push({
3704
- role: "assistant",
3705
- text,
3706
- ...stamp
3707
- });
3708
- if (Array.isArray(data.toolRequests)) for (const r of data.toolRequests) {
3709
- if (!isRecord(r)) continue;
3710
- out.push({
3711
- role: "tool",
3712
- text: describeToolCall(asString(r.name) ?? "tool", r.arguments ?? r.intentionSummary),
3713
- ...stamp
3714
- });
3715
- }
3716
- return out;
3717
- }
3718
- case "tool.execution_complete": {
3719
- const result = isRecord(data.result) ? data.result : {};
3720
- const text = textOf(result.content) || textOf(result.detailedContent);
3721
- return text === "" ? [] : [{
3722
- role: "tool",
3723
- text,
3724
- ...stamp
3725
- }];
3726
- }
3727
- default: return [];
3728
- }
3729
- }
3730
- /** Find the session directory, or the reason there is none. */
3731
- async function locateCopilotSession(q, env) {
3732
- const root = join(copilotHome(env), "session-state");
3733
- if (q.cliSessionId && /^[A-Za-z0-9_-]{1,200}$/.test(q.cliSessionId)) {
3734
- const dir = join(root, q.cliSessionId);
3735
- if (await stat(join(dir, "events.jsonl")).then(() => true, () => false)) return { dir };
3736
- }
3737
- const since = Date.parse(q.startedAt);
3738
- const floor = Number.isFinite(since) ? since - 5e3 : 0;
3739
- for (const e of await entriesNewestFirst(root)) {
3740
- if (!e.dir || e.mtimeMs < floor) continue;
3741
- if (!await stat(join(e.path, "events.jsonl")).then(() => true, () => false)) continue;
3742
- const cwd = await sessionCwd(e.path);
3743
- if (cwd !== void 0 && samePath(cwd, q.cwd, env.platform)) return { dir: e.path };
3744
- }
3745
- return { error: "no session in session-state for this working directory since it started" };
3746
- }
3747
- const copilotTranscript = { async read(q, env) {
3748
- try {
3749
- const found = await locateCopilotSession(q, env);
3750
- if ("error" in found) return notFound("Copilot", found.error);
3751
- const { entries, more } = await tailJsonl(join(found.dir, "events.jsonl"), q.lastTurns, parseCopilotEvent);
3752
- return {
3753
- ok: true,
3754
- entries,
3755
- more
3756
- };
3757
- } catch (e) {
3758
- return notFound("Copilot", e instanceof Error ? e.message : "read failed");
3759
- }
3760
- } };
3761
- // ../adapters/grok/dist/transcript.js
3762
- /**
3763
- * Grok Build (xAI) keeps a session at
3764
- * `$GROK_HOME/sessions/<encoded cwd>/<session id>/chat_history.jsonl`, `$GROK_HOME` defaulting to
3765
- * `~/.grok`. The cwd directory name is the URL-encoded working directory; one over 255 bytes is
3766
- * `<slug>-<blake3 hex16>` and holds a `.cwd` file with the real path.
3767
- * reference/src/grok-build/crates/codegen/xai-dirs/src/lib.rs (grok home),
3768
- * xai-grok-config/src/paths.rs (`encode_cwd_dirname`, `sessions_cwd_dir_in`),
3769
- * xai-grok-shell/src/session/persistence.rs (`session_dir_in`).
3770
- *
3771
- * Each line of chat_history.jsonl is a `ConversationItem` tagged by `type`: `user`, `assistant`,
3772
- * `tool_result`, `system`, `reasoning`, `backend_tool_call`
3773
- * (xai-grok-sampling-types/src/conversation.rs). Items carry no timestamp.
3774
- */
3775
- const grokHome = (env) => env.env.GROK_HOME?.trim() || join(env.home, ".grok");
3776
- /** `urlencoding::encode`: everything but the unreserved characters `A-Za-z0-9-_.~` is percent-encoded. */
3777
- function encodeCwdDirname(cwd) {
3778
- return encodeURIComponent(cwd).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
3779
- }
3780
- const readText = (p) => readFile(p, "utf8").then((t) => t, () => void 0);
3781
- const textParts = (content) => {
3782
- if (typeof content === "string") return content;
3783
- if (!Array.isArray(content)) return "";
3784
- return content.map((p) => isRecord(p) && p.type === "text" ? asString(p.text) ?? "" : "").filter(Boolean).join("\n");
3785
- };
3786
- /** The user's own words: the CLI wraps the typed text in `<user_query>`. */
3787
- const unwrapQuery = (text) => {
3788
- return (/<user_query>([\s\S]*?)(?:<\/user_query>|$)/.exec(text)?.[1] ?? text).trim();
3789
- };
3790
- /** Normalize one chat_history.jsonl line. Exported for tests. */
3791
- function parseGrokItem(obj) {
3792
- switch (obj.type) {
3793
- case "user": {
3794
- const reason = obj.synthetic_reason;
3795
- if (reason !== void 0 && reason !== null && reason !== "human") return [];
3796
- const text = unwrapQuery(textParts(obj.content));
3797
- return text === "" ? [] : [{
3798
- role: "user",
3799
- text
3800
- }];
3801
- }
3802
- case "assistant": {
3803
- const out = [];
3804
- const text = asString(obj.content) ?? "";
3805
- if (text !== "") out.push({
3806
- role: "assistant",
3807
- text
3808
- });
3809
- if (Array.isArray(obj.tool_calls)) {
3810
- for (const c of obj.tool_calls) if (isRecord(c)) out.push({
3811
- role: "tool",
3812
- text: describeToolCall(asString(c.name) ?? "tool", c.arguments)
3813
- });
3814
- }
3815
- return out;
3816
- }
3817
- case "tool_result": {
3818
- const text = asString(obj.content) ?? "";
3819
- return text === "" ? [] : [{
3820
- role: "tool",
3821
- text
3822
- }];
3823
- }
3824
- default: return [];
3825
- }
3826
- }
3827
- /** The directory of sessions for a working directory, or undefined. */
3828
- async function cwdDir(root, cwd) {
3829
- const direct = join(root, encodeCwdDirname(cwd));
3830
- if (await stat(direct).then((s) => s.isDirectory(), () => false)) return direct;
3831
- let names;
3832
- try {
3833
- names = await readdir(root);
3834
- } catch {
3835
- return;
3836
- }
3837
- for (const name of names) {
3838
- const dir = join(root, name);
3839
- if ((await readText(join(dir, ".cwd")))?.trim() === cwd) return dir;
3840
- }
3841
- }
3842
- /** Find the chat_history.jsonl for a session, or the reason there is none. */
3843
- async function locateGrokHistory(q, env) {
3844
- const dir = await cwdDir(join(grokHome(env), "sessions"), q.cwd);
3845
- if (dir === void 0) return { error: "no Grok sessions for this working directory" };
3846
- if (q.cliSessionId && /^[A-Za-z0-9_-]{1,200}$/.test(q.cliSessionId)) {
3847
- const path = join(dir, q.cliSessionId, "chat_history.jsonl");
3848
- if (await stat(path).then(() => true, () => false)) return { path };
3849
- }
3850
- const since = Date.parse(q.startedAt);
3851
- const floor = Number.isFinite(since) ? since - 5e3 : 0;
3852
- let best;
3853
- for (const e of await entriesNewestFirst(dir)) {
3854
- if (!e.dir) continue;
3855
- const path = join(e.path, "chat_history.jsonl");
3856
- const s = await stat(path).catch(() => void 0);
3857
- if (s && s.mtimeMs >= floor && (!best || s.mtimeMs > best.mtimeMs)) best = {
3858
- path,
3859
- mtimeMs: s.mtimeMs
3860
- };
3861
- }
3862
- if (best) return { path: best.path };
3863
- return { error: "no Grok session in this working directory since it started" };
3864
- }
3865
- const grokTranscript = { async read(q, env) {
3866
- try {
3867
- const found = await locateGrokHistory(q, env);
3868
- if ("error" in found) return notFound("Grok", found.error);
3869
- const { entries, more } = await tailJsonl(found.path, q.lastTurns, parseGrokItem);
3870
- return {
3871
- ok: true,
3872
- entries,
3873
- more
3874
- };
3875
- } catch (e) {
3876
- return notFound("Grok", e instanceof Error ? e.message : "read failed");
3877
- }
3878
- } };
3879
- // ../daemon/src/transcripts.ts
3880
- /**
3881
- * The transcript reader of each CLI the daemon can peek into. A CLI missing here answers
3882
- * "peek not supported for <cli> yet". Cursor and Antigravity are listed with the reason, so the
3883
- * message says why.
3884
- */
3885
- function defaultTranscriptReaders() {
3886
- return {
3887
- claude: claudeTranscript,
3888
- codex: codexTranscript,
3889
- opencode: openCodeTranscript,
3890
- copilot: copilotTranscript,
3891
- grok: grokTranscript,
3892
- cursor: unsupportedTranscript("cursor", "its chat storage is not documented"),
3893
- antigravity: unsupportedTranscript("antigravity", "its conversation store is not documented")
3894
- };
3895
- }
3896
3054
  // ../daemon/src/bin.ts
3897
3055
  async function main() {
3898
3056
  const handle = await startDaemon({
3899
3057
  dataDir: dataDir(process.platform, process.env, homedir()),
3900
- transcripts: defaultTranscriptReaders(),
3058
+ wakers: { codex: codexAdapter.daemonWake },
3901
3059
  onIdleExit: () => {
3902
3060
  process.stderr.write("convenod: no sessions for a while, exiting.\n");
3903
3061
  process.exit(0);