@conveno/cli 0.2.0-rc.5 → 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 toIso, A as currentAccessToken, At as readHeadLine, B as effectiveHolder, Bn as newDeviceId, Bt as resolveRecipient, C as claimOrchestrator, Ct as planSpawn, Dt as readAccountTokens, E as clientProof, F as defaultProcessIo, Fn as isLeadAlias, Gn as parseRelayFrame, H as entriesNewestFirst, Hn as newSessionId, I as describeToolCall, In as isSocketPathTooLong, Jn as socketPathTooLongMessage, Jt as statusAfterLiveness, Kn as safeParse, L as detectRepo, Ln as makeError, M as dataDir, Mn as defaultSocketPath, N as dataPaths, Nn as encodeFrame, Ot as readAncestry, P as decideAutoContinue, Q as holderAfterDeparture, Qt as takeWithinBytes, Rn as makeEventNotification, S as bindAccountDevice, Sn as RpcErrorCode, T as classifyPermission, Tt as proofsMatch, U as evaluateLiveness, Un as newTicketId, Vn as newMessageId, Wn as parseIpcRequest, Wt as samePath, Xt as tailJsonl, Z as generateSessionName, _ as asString, _n as ORCHESTRATOR_ALIAS, at as jwtClaim, b as autoLimitsFromEnv, bn as PROTOCOL_VERSION, ct as markDelivered, d as ackEntries, dn as EVENT_NAMES, dt as notFound, en as tooManyUnreadMessage, ft as notifyDesktopWanted, hn as Message, in as validateRename, j as daemonProof, jn as createLineDecoder, jt as readInbox, k as createWmiWalker, kn as Ticket, lt as nameMatchesPattern, mn as HUMAN_ANSWERER, n as AccountError, nn as unsupportedTranscript, p as acpTranscript, qn as sanitizeLine, r as ConvenoError, rt as isRecord, s as RESPONSE_BUDGET_BYTES, tn as turnHops, tt as isOnline, un as DeviceId, ut as newAuthNonce, vn as OWNER_SESSION_ID, vt as pauseLabel, wn as SessionId, x as baseName, xn as RelayPayload, y as autoCandidates, yn as PERMISSION_ANSWERS, yt as pendingForInjection, zn as makeResult } from "./dist-TrWRppjR.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
- import { delimiter, dirname, join, posix, win32 } from "node:path";
8
- import { execFileSync, spawn } from "node:child_process";
9
- import { n as redactWithReport, t as redact } from "./dist-DcmKjrmu.js";
10
- 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-E3XvoT1Q.js";
8
+ import { dirname, join, posix, win32 } from "node:path";
9
+ import { _ as sasMatches, a as JoinerPairing, b as signRelayHello, c as decodePairMessage, d as forkPoint, f as generateIdentity, g as publicRecord, h as parseIdentity, i as InviterPairing, l as deviceFingerprint, m as openEnvelope, n as ENVELOPE_MAX_AGE_MS, o as appendRevoke, p as headMatches, r as ENVELOPE_MAX_FUTURE_MS, s as chainHead, t as CryptoError, u as encodePairMessage, v as sealEnvelope, x as verifyChain, y as serializeIdentity } from "./dist-DIAtMDWW.js";
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-C8JRuLiZ.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,265 +158,6 @@ function createDaemonLog(path, opts = {}) {
160
158
  }
161
159
  };
162
160
  }
163
- /** The OS command is killed after this long. */
164
- const NOTIFY_TIMEOUT_MS = 5e3;
165
- const NOTIFY_TITLE = "Conveno";
166
- const noopNotifier = {
167
- notify() {},
168
- close() {}
169
- };
170
- const CONTROL = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g;
171
- /** One line, no control characters, trimmed. */
172
- function flatten(s) {
173
- return s.replace(CONTROL, " ").replace(/\s+/g, " ").trim();
174
- }
175
- function clip$2(s, max) {
176
- const chars = [...s];
177
- return chars.length > max ? `${chars.slice(0, max - 3).join("")}...` : s;
178
- }
179
- /** The body for one item: "name asks: first line..." with secrets removed. */
180
- function bodyFor(item) {
181
- const verb = item.kind === "question" ? "asks" : item.kind === "permission" ? "wants to" : "says";
182
- const name = clip$2(flatten(redact(item.from)), 40) || "A session";
183
- const first = clip$2(flatten(redact(item.text)), 80);
184
- return first ? `${name} ${verb}: ${first}` : `${name} ${verb === "wants to" ? "needs you" : verb}`;
185
- }
186
- /** The body for several things at once. */
187
- function batchBody(n) {
188
- return `${n} things need you`;
189
- }
190
- /** Escape a string for an AppleScript string literal. */
191
- function appleScriptString(s) {
192
- return `"${s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
193
- }
194
- /** Escape text for XML content. */
195
- function xmlEscape(s) {
196
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
197
- }
198
- /** The PowerShell script for a toast. Text is XML-escaped, then placed in a single-quoted string. */
199
- function toastScript(title, body) {
200
- return [
201
- "$ErrorActionPreference = 'Stop'",
202
- "[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null",
203
- "[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null",
204
- "$appId = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe'",
205
- "$doc = New-Object Windows.Data.Xml.Dom.XmlDocument",
206
- `$doc.LoadXml(${`'${`<toast><visual><binding template="ToastGeneric"><text>${xmlEscape(title)}</text><text>${xmlEscape(body)}</text></binding></visual></toast>`.replace(/['\u2018\u2019\u201A\u201B]/g, (q) => q + q)}'`})`,
207
- "$toast = [Windows.UI.Notifications.ToastNotification]::new($doc)",
208
- "[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($appId).Show($toast)"
209
- ].join("\n");
210
- }
211
- /** The command that shows a notification on a platform. */
212
- function commandFor(platform, title, body) {
213
- const t = flatten(title);
214
- const b = flatten(body);
215
- if (platform === "darwin") return {
216
- cmd: "osascript",
217
- args: ["-e", `display notification ${appleScriptString(b)} with title ${appleScriptString(t)}`]
218
- };
219
- if (platform === "win32") return {
220
- cmd: "powershell.exe",
221
- args: [
222
- "-NoProfile",
223
- "-NonInteractive",
224
- "-WindowStyle",
225
- "Hidden",
226
- "-EncodedCommand",
227
- Buffer.from(toastScript(t, b), "utf16le").toString("base64")
228
- ]
229
- };
230
- return {
231
- cmd: "notify-send",
232
- args: [
233
- "--app-name=Conveno",
234
- "--",
235
- xmlEscape(t),
236
- xmlEscape(b)
237
- ]
238
- };
239
- }
240
- function truthy(v) {
241
- return v !== void 0 && v !== "" && ![
242
- "0",
243
- "false",
244
- "no",
245
- "off"
246
- ].includes(v.toLowerCase());
247
- }
248
- function findOnPath(cmd, env) {
249
- for (const dir of (env.PATH ?? "").split(delimiter)) if (dir && existsSync(join(dir, cmd))) return true;
250
- return false;
251
- }
252
- /**
253
- * Build the notifier the daemon uses. It stays quiet under CI and tests unless `run` is given,
254
- * when the owner turned it off, and on a Linux box with no display or no notify-send.
255
- */
256
- function createNotifier(opts) {
257
- const env = opts.env ?? process.env;
258
- const platform = opts.platform ?? process.platform;
259
- const now = opts.now ?? Date.now;
260
- const windowMs = opts.windowMs ?? 1e4;
261
- const onPath = opts.onPath ?? ((c) => findOnPath(c, env));
262
- let reported = false;
263
- const fail = (what, e) => {
264
- if (reported) return;
265
- reported = true;
266
- try {
267
- opts.onError?.(what, e);
268
- } catch {}
269
- };
270
- const available = () => {
271
- if (opts.run === void 0 && (truthy(env.CI) || truthy(env.VITEST))) return false;
272
- if (platform === "linux") {
273
- if (!env.DISPLAY && !env.WAYLAND_DISPLAY) return false;
274
- if (!onPath("notify-send")) return false;
275
- }
276
- return true;
277
- };
278
- const spawnIt = (c) => {
279
- let child;
280
- try {
281
- child = spawn(c.cmd, c.args, {
282
- detached: true,
283
- stdio: "ignore",
284
- windowsHide: true
285
- });
286
- } catch (e) {
287
- fail("could not start the notification command", e);
288
- return;
289
- }
290
- child.on("error", (e) => fail("the notification command failed", e));
291
- const timer = setTimeout(() => {
292
- try {
293
- child.kill();
294
- } catch {}
295
- }, NOTIFY_TIMEOUT_MS);
296
- timer.unref();
297
- child.on("exit", () => clearTimeout(timer));
298
- child.unref();
299
- };
300
- const run = opts.run ?? spawnIt;
301
- let lastAt = Number.NEGATIVE_INFINITY;
302
- let pending = [];
303
- let timer;
304
- const show = (body) => {
305
- lastAt = now();
306
- try {
307
- run(commandFor(platform, NOTIFY_TITLE, body));
308
- } catch (e) {
309
- fail("could not show a notification", e);
310
- }
311
- };
312
- const flush = () => {
313
- timer = void 0;
314
- const items = pending;
315
- pending = [];
316
- if (items.length === 0) return;
317
- if (!notifyDesktopWanted(opts.settingsPath, env) || !available()) return;
318
- show(items.length === 1 ? bodyFor(items[0]) : batchBody(items.length));
319
- };
320
- return {
321
- notify(item) {
322
- try {
323
- if (!notifyDesktopWanted(opts.settingsPath, env) || !available()) return;
324
- const wait = lastAt + windowMs - now();
325
- if (wait <= 0 && pending.length === 0) {
326
- show(bodyFor(item));
327
- return;
328
- }
329
- pending.push(item);
330
- if (!timer) {
331
- timer = setTimeout(flush, Math.max(0, wait));
332
- timer.unref();
333
- }
334
- } catch (e) {
335
- fail("could not queue a notification", e);
336
- }
337
- },
338
- close() {
339
- if (timer) clearTimeout(timer);
340
- timer = void 0;
341
- pending = [];
342
- }
343
- };
344
- }
345
- /** The text of a message to the owner, for the notification line. */
346
- function ownerNoticeText(body) {
347
- const b = body ?? {};
348
- if (typeof b.text === "string") return b.text;
349
- if (typeof b.question === "string") return b.question;
350
- if (typeof b.goal === "string") return b.goal;
351
- return "";
352
- }
353
- // ../daemon/src/peek.ts
354
- /** Longest text of one turn that is returned. A tool output is cut to this. */
355
- const PEEK_TURN_MAX_CHARS = 4e3;
356
- /**
357
- * Longest text of one turn that is redacted. A larger one is cut first, at a word boundary, so the
358
- * redaction pass stays fast. The cut can only remove the end of a secret, never expose more.
359
- */
360
- const PEEK_REDACT_INPUT_MAX = 2e5;
361
- const CLIP = "\n[clipped]";
362
- /** Cut `text` to at most `max` characters, at a word boundary when one is near. */
363
- function clip$1(text, max, marker = CLIP) {
364
- if (text.length <= max) return text;
365
- const room = Math.max(0, max - marker.length);
366
- let cut = text.slice(0, room);
367
- const space = cut.search(/\s\S*$/);
368
- if (space > room - 80 && space > 0) cut = cut.slice(0, space);
369
- return cut + marker;
370
- }
371
- /**
372
- * Drop control characters other than tab and newline, and invisible direction and zero-width
373
- * characters: a transcript can carry terminal escapes, and the reader may show this text.
374
- */
375
- function stripControl(text) {
376
- let out = "";
377
- for (const ch of text) {
378
- const c = ch.codePointAt(0);
379
- 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;
380
- }
381
- return out;
382
- }
383
- /**
384
- * Turn what a reader returned into the wire result: redact every turn (always), clip each turn,
385
- * then keep the newest turns that fit in `maxChars`. Redaction runs on the whole turn text before
386
- * it is clipped, so a secret is never cut in the middle and left half visible.
387
- */
388
- function preparePeek(entries, more, maxChars) {
389
- let redactions = 0;
390
- let truncated = more;
391
- const perTurn = Math.min(PEEK_TURN_MAX_CHARS, maxChars);
392
- const prepared = entries.map((e) => {
393
- const raw = stripControl(e.text);
394
- const input = clip$1(raw, PEEK_REDACT_INPUT_MAX, "");
395
- const { text, findings } = redactWithReport(input);
396
- for (const n of Object.values(findings)) redactions += n;
397
- const clipped = clip$1(text, perTurn);
398
- if (clipped !== text || input !== raw) truncated = true;
399
- return {
400
- role: e.role,
401
- text: clipped,
402
- ...e.at ? { at: e.at } : {}
403
- };
404
- });
405
- const kept = [];
406
- let total = 0;
407
- for (let i = prepared.length - 1; i >= 0; i--) {
408
- const t = prepared[i];
409
- if (total + t.text.length > maxChars) {
410
- truncated = true;
411
- break;
412
- }
413
- total += t.text.length;
414
- kept.unshift(t);
415
- }
416
- return {
417
- turns: kept,
418
- truncated,
419
- redactions
420
- };
421
- }
422
161
  const HANDSHAKE_TIMEOUT_MS = 15e3;
423
162
  /**
424
163
  * One WebSocket to the relay: challenge, signed hello, then frames. It does not reconnect by
@@ -1345,8 +1084,9 @@ var RelayHub = class {
1345
1084
  this.state.hold(id, from, p, since);
1346
1085
  return;
1347
1086
  }
1348
- const sender = r.sessions.find((s) => s.id === p.message.from);
1349
- 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) {
1350
1090
  this.bounce(from, p, "unknown_sender");
1351
1091
  return;
1352
1092
  }
@@ -1355,14 +1095,20 @@ var RelayHub = class {
1355
1095
  return;
1356
1096
  }
1357
1097
  const device = this.chainState?.members.get(from)?.name ?? r.deviceName;
1358
- const message = {
1098
+ const { fromCli: _c, ...rest } = p.message;
1099
+ const message = sender ? {
1359
1100
  ...p.message,
1360
1101
  from: this.state.alias(from, sender.id),
1361
1102
  to: p.toSession,
1362
1103
  fromName: remoteSessionName(sender.name, device),
1363
1104
  fromCli: sender.cli
1105
+ } : {
1106
+ ...rest,
1107
+ from: OWNER_SESSION_ID,
1108
+ to: p.toSession,
1109
+ fromName: "you"
1364
1110
  };
1365
- const reason = this.o.host.deliverLocal(message, p.toSession);
1111
+ const reason = this.o.host.deliverLocal(message, p.toSession, p.hops ?? 0);
1366
1112
  if (reason !== void 0) this.bounce(from, p, reason);
1367
1113
  }
1368
1114
  bounce(to, p, reason) {
@@ -1448,14 +1194,15 @@ var RelayHub = class {
1448
1194
  return all.find((s) => s.id === to) ?? all.find((s) => s.name === to);
1449
1195
  }
1450
1196
  /** Send a message to a session on another device. Throws when that cannot be done now. */
1451
- sendRemote(target, message) {
1197
+ sendRemote(target, message, hops = 0) {
1452
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\".");
1453
1199
  const real = this.state.unalias(target.id);
1454
1200
  if (!real) throw new ConvenoError(RpcErrorCode.NotFound, `No session "${target.name}".`);
1455
1201
  if (!this.sendPayload(real.device, {
1456
1202
  type: "message",
1457
1203
  toSession: real.remote,
1458
- message
1204
+ message,
1205
+ ...hops > 0 ? { hops } : {}
1459
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".`);
1460
1207
  this.sent.set(message.id, {
1461
1208
  fromSession: message.from,
@@ -1837,143 +1584,6 @@ var RelayHub = class {
1837
1584
  return this.pairStatus(q);
1838
1585
  }
1839
1586
  };
1840
- // ../daemon/src/tickets-store.ts
1841
- /** Tickets, and the sessions whose permission relay is on. */
1842
- const TICKET_MIGRATION = {
1843
- name: "006_tickets",
1844
- sql: `
1845
- CREATE TABLE tickets (
1846
- id TEXT PRIMARY KEY,
1847
- from_session TEXT NOT NULL,
1848
- to_session TEXT NOT NULL,
1849
- -- 'orchestrator' when it was addressed to the role, else the session id.
1850
- to_ref TEXT NOT NULL,
1851
- kind TEXT NOT NULL,
1852
- question TEXT NOT NULL,
1853
- options TEXT,
1854
- status TEXT NOT NULL,
1855
- answer TEXT,
1856
- answered_by TEXT,
1857
- answer_message_id TEXT,
1858
- created_at TEXT NOT NULL,
1859
- answered_at TEXT,
1860
- expires_at TEXT
1861
- );
1862
- CREATE INDEX tickets_status ON tickets (status, created_at);
1863
- CREATE INDEX tickets_from ON tickets (from_session);
1864
- CREATE INDEX tickets_to ON tickets (to_session);
1865
- CREATE TABLE permission_relay (
1866
- session_id TEXT PRIMARY KEY,
1867
- -- The orchestrator when the person turned the relay on: the only one who may approve.
1868
- approver TEXT NOT NULL,
1869
- enabled_at TEXT NOT NULL
1870
- );
1871
- `
1872
- };
1873
- const str$1 = (v) => typeof v === "string" ? v : void 0;
1874
- function toRow(r) {
1875
- const options = str$1(r.options);
1876
- return {
1877
- ticket: Ticket.parse({
1878
- id: r.id,
1879
- fromSession: r.from_session,
1880
- toSession: r.to_session,
1881
- kind: r.kind,
1882
- question: r.question,
1883
- status: r.status,
1884
- createdAt: r.created_at,
1885
- ...options ? { options: JSON.parse(options) } : {},
1886
- ...str$1(r.answer) !== void 0 ? { answer: r.answer } : {},
1887
- ...str$1(r.answered_by) !== void 0 ? { answeredBy: r.answered_by } : {},
1888
- ...str$1(r.answer_message_id) !== void 0 ? { answerMessageId: r.answer_message_id } : {},
1889
- ...str$1(r.answered_at) !== void 0 ? { answeredAt: r.answered_at } : {},
1890
- ...str$1(r.expires_at) !== void 0 ? { expiresAt: r.expires_at } : {}
1891
- }),
1892
- toRef: r.to_ref
1893
- };
1894
- }
1895
- /** SQLite access for tickets. Methods are synchronous; callers group writes with `Store.tx`. */
1896
- var TicketStore = class {
1897
- db;
1898
- constructor(db) {
1899
- this.db = db;
1900
- }
1901
- all(sql, ...params) {
1902
- return this.db.prepare(sql).all(...params);
1903
- }
1904
- run(sql, ...params) {
1905
- this.db.prepare(sql).run(...params);
1906
- }
1907
- insert(t, toRef) {
1908
- this.run(`INSERT INTO tickets (id, from_session, to_session, to_ref, kind, question, options, status,
1909
- 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);
1910
- }
1911
- get(id) {
1912
- const r = this.all("SELECT * FROM tickets WHERE id = ?", id)[0];
1913
- return r ? toRow(r) : void 0;
1914
- }
1915
- /**
1916
- * Tickets newest first. With `session`, those it asked or that are addressed to it: by its id,
1917
- * or to the orchestrator role when `holder` says it holds the role.
1918
- */
1919
- list(filter) {
1920
- const where = [];
1921
- const params = [];
1922
- if (filter.session !== void 0) {
1923
- where.push(filter.holder ? "(from_session = ? OR to_session = ? OR to_ref = 'orchestrator')" : "(from_session = ? OR to_session = ?)");
1924
- params.push(filter.session, filter.session);
1925
- }
1926
- if (filter.id !== void 0) {
1927
- where.push("id = ?");
1928
- params.push(filter.id);
1929
- }
1930
- const scope = where.length > 0 ? ` WHERE ${where.join(" AND ")}` : "";
1931
- const open = this.all(`SELECT COUNT(*) AS n FROM tickets${scope}${scope ? " AND" : " WHERE"} status = 'open'`, ...params)[0];
1932
- const withStatus = [...where];
1933
- const listParams = [...params];
1934
- if (filter.status !== void 0) {
1935
- withStatus.push("status = ?");
1936
- listParams.push(filter.status);
1937
- }
1938
- const sql = `SELECT * FROM tickets${withStatus.length > 0 ? ` WHERE ${withStatus.join(" AND ")}` : ""} ORDER BY id DESC LIMIT ?`;
1939
- return {
1940
- rows: this.all(sql, ...listParams, filter.limit).map(toRow),
1941
- openCount: Number(open?.n ?? 0)
1942
- };
1943
- }
1944
- answer(id, answer, by, at, messageId) {
1945
- this.run(`UPDATE tickets SET status = 'answered', answer = ?, answered_by = ?, answered_at = ?,
1946
- answer_message_id = ? WHERE id = ? AND status = 'open'`, answer, by, at, messageId ?? null, id);
1947
- }
1948
- setStatus(id, status) {
1949
- this.run("UPDATE tickets SET status = ? WHERE id = ? AND status = 'open'", status, id);
1950
- }
1951
- /** Open tickets whose `expires_at` is at or before `now`. */
1952
- dueToExpire(now) {
1953
- return this.all("SELECT * FROM tickets WHERE status = 'open' AND expires_at IS NOT NULL AND expires_at <= ?", now).map(toRow);
1954
- }
1955
- /** A session is gone: drop what it asked, and close what was addressed to it. */
1956
- forgetSession(id) {
1957
- this.run("DELETE FROM tickets WHERE from_session = ?", id);
1958
- this.run("UPDATE tickets SET status = 'cancelled' WHERE to_session = ? AND to_ref != 'orchestrator' AND status = 'open'", id);
1959
- this.run("DELETE FROM permission_relay WHERE session_id = ?", id);
1960
- }
1961
- relays() {
1962
- return this.all("SELECT session_id, approver FROM permission_relay ORDER BY enabled_at, session_id").map((r) => ({
1963
- session: r.session_id,
1964
- approver: r.approver
1965
- }));
1966
- }
1967
- /** The session allowed to approve for `id`, or undefined while the relay is off. */
1968
- approverOf(id) {
1969
- const r = this.all("SELECT approver FROM permission_relay WHERE session_id = ?", id)[0];
1970
- return r ? r.approver : void 0;
1971
- }
1972
- setRelay(id, approver, at) {
1973
- if (approver) this.run("INSERT OR REPLACE INTO permission_relay (session_id, approver, enabled_at) VALUES (?, ?, ?)", id, approver, at);
1974
- else this.run("DELETE FROM permission_relay WHERE session_id = ?", id);
1975
- }
1976
- };
1977
1587
  // ../daemon/src/store.ts
1978
1588
  const MIGRATIONS = [
1979
1589
  {
@@ -2057,7 +1667,31 @@ const MIGRATIONS = [
2057
1667
  ALTER TABLE sessions ADD COLUMN peekable INTEGER NOT NULL DEFAULT 1;
2058
1668
  `
2059
1669
  },
2060
- 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
+ }
2061
1695
  ];
2062
1696
  const str = (v) => typeof v === "string" ? v : void 0;
2063
1697
  const num = (v) => typeof v === "number" ? v : void 0;
@@ -2092,8 +1726,6 @@ function toSessionRow(r) {
2092
1726
  deliveryTier: r.delivery_tier,
2093
1727
  spawned: r.spawned === 1,
2094
1728
  spawnDepth: r.spawn_depth,
2095
- auto: r.auto === 1,
2096
- autoExplicit: r.auto_explicit === 1,
2097
1729
  autoRuns: isoList(r.auto_runs),
2098
1730
  turnHops: num(r.turn_hops) ?? 0,
2099
1731
  startedAt: r.started_at,
@@ -2111,23 +1743,12 @@ function toSessionRow(r) {
2111
1743
  if (hostPid !== void 0) row.hostPid = hostPid;
2112
1744
  const hostPids = pidList(r.host_pids);
2113
1745
  if (hostPids !== void 0) row.hostPids = hostPids;
2114
- const cliSessionId = str(r.cli_session_id);
2115
- if (cliSessionId !== void 0) row.cliSessionId = cliSessionId;
2116
- const transcriptPath = str(r.transcript_path);
2117
- if (transcriptPath !== void 0) row.transcriptPath = transcriptPath;
2118
- if (r.peekable === 0) row.peekable = false;
2119
1746
  const statusText = str(r.status_text);
2120
1747
  if (statusText !== void 0) row.statusText = statusText;
2121
1748
  const spawnedBy = str(r.spawned_by);
2122
1749
  if (spawnedBy !== void 0) row.spawnedBy = spawnedBy;
2123
- const pausedAt = str(r.auto_paused_at);
2124
- if (pausedAt !== void 0) row.autoPausedAt = pausedAt;
2125
- const pausedBy = str(r.auto_paused_by);
2126
- if (pausedBy === "limit") row.autoPausedBy = pausedBy;
2127
- const limit = num(r.auto_limit);
2128
- if (limit !== void 0) row.autoLimit = limit;
2129
- const orchResumedAt = str(r.auto_orch_resumed_at);
2130
- if (orchResumedAt !== void 0) row.autoOrchResumedAt = orchResumedAt;
1750
+ const nativeId = str(r.native_id);
1751
+ if (nativeId !== void 0) row.nativeId = nativeId;
2131
1752
  return row;
2132
1753
  }
2133
1754
  /** Wire-format session for a stored row. */
@@ -2143,13 +1764,9 @@ function toSession(row, isOrchestrator, unreadCount) {
2143
1764
  deliveryTier: row.deliveryTier,
2144
1765
  spawned: row.spawned,
2145
1766
  spawnDepth: row.spawnDepth,
2146
- auto: row.auto,
2147
1767
  startedAt: row.startedAt,
2148
1768
  lastSeenAt: row.lastSeenAt
2149
1769
  };
2150
- if (row.autoPausedAt !== void 0) s.autoPausedAt = row.autoPausedAt;
2151
- if (row.autoPausedBy !== void 0) s.autoPausedBy = row.autoPausedBy;
2152
- if (row.autoLimit !== void 0) s.autoLimit = row.autoLimit;
2153
1770
  if (unreadCount !== void 0) s.unreadCount = unreadCount;
2154
1771
  if (row.cliVersion !== void 0) s.cliVersion = row.cliVersion;
2155
1772
  if (row.repoRoot !== void 0) s.repo = row.repoRemoteUrlHash !== void 0 ? {
@@ -2160,8 +1777,8 @@ function toSession(row, isOrchestrator, unreadCount) {
2160
1777
  if (row.hostPid !== void 0) s.hostPid = row.hostPid;
2161
1778
  if (row.hostPids !== void 0) s.hostPids = row.hostPids;
2162
1779
  if (row.statusText !== void 0) s.statusText = row.statusText;
2163
- if (row.peekable === false) s.peekable = false;
2164
1780
  if (row.spawnedBy !== void 0) s.spawnedBy = row.spawnedBy;
1781
+ if (row.nativeId !== void 0) s.nativeId = row.nativeId;
2165
1782
  return s;
2166
1783
  }
2167
1784
  function toEntry(r) {
@@ -2183,14 +1800,12 @@ function toEntry(r) {
2183
1800
  /** SQLite persistence. All methods are synchronous; callers group writes with `tx`. */
2184
1801
  var Store = class {
2185
1802
  db;
2186
- tickets;
2187
1803
  constructor(path) {
2188
1804
  this.db = new DatabaseSync(path);
2189
1805
  this.db.exec("PRAGMA journal_mode = WAL");
2190
1806
  this.db.exec("PRAGMA synchronous = NORMAL");
2191
1807
  this.db.exec("PRAGMA busy_timeout = 5000");
2192
1808
  this.migrate();
2193
- this.tickets = new TicketStore(this.db);
2194
1809
  }
2195
1810
  all(sql, ...params) {
2196
1811
  return this.db.prepare(sql).all(...params);
@@ -2237,9 +1852,8 @@ var Store = class {
2237
1852
  insertSession(s) {
2238
1853
  this.run(`INSERT INTO sessions (id, name, cli, cli_version, device_id, cwd, repo_root, repo_remote_hash,
2239
1854
  pid, host_pid, host_pids, status, status_text, delivery_tier, spawned_by, spawned, spawn_depth,
2240
- auto, auto_explicit, auto_paused_at, auto_paused_by, auto_limit, auto_runs, turn_hops,
2241
- started_at, last_seen_at)
2242
- 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);
2243
1857
  }
2244
1858
  getSession(id) {
2245
1859
  const r = this.all("SELECT * FROM sessions WHERE id = ?", id)[0];
@@ -2252,29 +1866,9 @@ var Store = class {
2252
1866
  updateSession(id, fields) {
2253
1867
  const sets = [];
2254
1868
  const vals = [];
2255
- if (fields.auto !== void 0) {
2256
- sets.push("auto = ?");
2257
- vals.push(fields.auto ? 1 : 0);
2258
- }
2259
- if (fields.autoExplicit !== void 0) {
2260
- sets.push("auto_explicit = ?");
2261
- vals.push(fields.autoExplicit ? 1 : 0);
2262
- }
2263
- if (fields.autoPausedAt !== void 0) {
2264
- sets.push("auto_paused_at = ?");
2265
- vals.push(fields.autoPausedAt);
2266
- }
2267
- if (fields.autoPausedBy !== void 0) {
2268
- sets.push("auto_paused_by = ?");
2269
- vals.push(fields.autoPausedBy);
2270
- }
2271
- if (fields.autoLimit !== void 0) {
2272
- sets.push("auto_limit = ?");
2273
- vals.push(fields.autoLimit);
2274
- }
2275
- if (fields.autoOrchResumedAt !== void 0) {
2276
- sets.push("auto_orch_resumed_at = ?");
2277
- vals.push(fields.autoOrchResumedAt);
1869
+ if (fields.nativeId !== void 0) {
1870
+ sets.push("native_id = ?");
1871
+ vals.push(fields.nativeId);
2278
1872
  }
2279
1873
  if (fields.turnHops !== void 0) {
2280
1874
  sets.push("turn_hops = ?");
@@ -2284,18 +1878,6 @@ var Store = class {
2284
1878
  sets.push("auto_runs = ?");
2285
1879
  vals.push(JSON.stringify(fields.autoRuns));
2286
1880
  }
2287
- if (fields.cliSessionId !== void 0) {
2288
- sets.push("cli_session_id = ?");
2289
- vals.push(fields.cliSessionId);
2290
- }
2291
- if (fields.transcriptPath !== void 0) {
2292
- sets.push("transcript_path = ?");
2293
- vals.push(fields.transcriptPath);
2294
- }
2295
- if (fields.peekable !== void 0) {
2296
- sets.push("peekable = ?");
2297
- vals.push(fields.peekable ? 1 : 0);
2298
- }
2299
1881
  if (fields.name !== void 0) {
2300
1882
  sets.push("name = ?");
2301
1883
  vals.push(fields.name);
@@ -2322,15 +1904,11 @@ var Store = class {
2322
1904
  setHolder(id) {
2323
1905
  this.run("UPDATE orchestrator SET session_id = ? WHERE slot = 1", id);
2324
1906
  }
2325
- /** `hops`: automatic turns behind the message (the auto-mode limit counts them). */
1907
+ /** `hops`: automatic turns behind the message (the wake limit counts them). */
2326
1908
  insertMessage(message, recipient, at, hops = 0) {
2327
1909
  this.run("INSERT INTO messages (id, json) VALUES (?, ?)", message.id, JSON.stringify(message));
2328
1910
  this.run("INSERT INTO mailbox (session_id, message_id, state, queued_at, hops) VALUES (?, ?, 'queued', ?, ?)", recipient, message.id, at, hops);
2329
1911
  }
2330
- /** Start a new chain for the messages queued for a session: their hops go back to 0. */
2331
- resetQueuedHops(sessionId) {
2332
- this.run("UPDATE mailbox SET hops = 0 WHERE session_id = ? AND state = 'queued'", sessionId);
2333
- }
2334
1912
  /** Messages queued for a session that no one has been shown yet. */
2335
1913
  unreadCount(sessionId) {
2336
1914
  const r = this.all("SELECT COUNT(*) AS n FROM mailbox WHERE session_id = ? AND state = 'queued'", sessionId)[0];
@@ -2341,45 +1919,10 @@ var Store = class {
2341
1919
  }
2342
1920
  /** Remove a session, its mailbox, and any message no mailbox refers to any more. */
2343
1921
  deleteSession(id) {
2344
- this.tickets.forgetSession(id);
2345
1922
  this.run("DELETE FROM mailbox WHERE session_id = ?", id);
2346
1923
  this.run("DELETE FROM messages WHERE id NOT IN (SELECT message_id FROM mailbox)");
2347
1924
  this.run("DELETE FROM sessions WHERE id = ?", id);
2348
1925
  }
2349
- /**
2350
- * Trim a mailbox nobody else cleans up: delete handled entries (anything but queued) that are
2351
- * beyond the newest `keep` entries or were last touched before `olderThanIso`. Queued entries
2352
- * stay. Returns how many were deleted.
2353
- */
2354
- pruneMailbox(sessionId, keep, olderThanIso) {
2355
- const res = this.db.prepare(`DELETE FROM mailbox WHERE session_id = ? AND state <> 'queued' AND (
2356
- message_id NOT IN (SELECT message_id FROM mailbox WHERE session_id = ?
2357
- ORDER BY message_id DESC LIMIT ?)
2358
- OR COALESCE(read_at, delivered_at, queued_at) < ?)`).run(sessionId, sessionId, keep, olderThanIso);
2359
- const n = Number(res.changes);
2360
- if (n > 0) this.run("DELETE FROM messages WHERE id NOT IN (SELECT message_id FROM mailbox)");
2361
- return n;
2362
- }
2363
- /**
2364
- * Messages a session received (it has a mailbox entry) or sent, newest first, optionally only
2365
- * those older than `before`. Message ids are ULIDs, so id order is time order.
2366
- */
2367
- messagesOf(sessionId, limit, before) {
2368
- return this.all(`SELECT m.json FROM messages m
2369
- WHERE (m.id IN (SELECT message_id FROM mailbox WHERE session_id = ?)
2370
- OR json_extract(m.json, '$.from') = ?)
2371
- ${before ? "AND m.id < ?" : ""}
2372
- ORDER BY m.id DESC LIMIT ?`, ...before ? [
2373
- sessionId,
2374
- sessionId,
2375
- before,
2376
- limit
2377
- ] : [
2378
- sessionId,
2379
- sessionId,
2380
- limit
2381
- ]).map((r) => Message.parse(JSON.parse(r.json)));
2382
- }
2383
1926
  /** Mailbox entries of one session, optionally limited to the given states or message ids. */
2384
1927
  entries(sessionId, filter = {}) {
2385
1928
  let sql = `SELECT m.json, b.state, b.queued_at, b.delivered_at, b.read_at, b.acked_at, b.hops
@@ -2400,294 +1943,25 @@ var Store = class {
2400
1943
  WHERE session_id = ? AND message_id = ?`, e.state, e.deliveredAt ?? null, e.readAt ?? null, e.ackedAt ?? null, sessionId, e.message.id);
2401
1944
  }
2402
1945
  };
2403
- // ../daemon/src/tickets.ts
2404
- /** An open question expires after this long. The asker's own CLI prompt is unaffected. */
2405
- const TICKET_TTL_MS = 864e5;
2406
- /** A permission ticket outlives the hook that asked for it by little: the hook gives up in 90 s. */
2407
- const PERMISSION_TICKET_TTL_MS = 3e5;
2408
- const OWNER = {
2409
- id: OWNER_SESSION_ID,
2410
- name: "you"
2411
- };
2412
- const fail = (code, message) => {
2413
- throw new ConvenoError(code, message);
2414
- };
2415
- const clip = (text, max) => {
2416
- const flat = sanitizeLine(text);
2417
- return flat.length > max ? `${flat.slice(0, max - 3)}...` : flat;
2418
- };
2419
- /** The "Tool: ..." and "Command: ..." lines of a permission request, as one short line. */
2420
- function permissionLine(question) {
2421
- const tool = /^Tool: (.*)$/m.exec(question)?.[1];
2422
- return `run ${/^Command: (.*)$/m.exec(question)?.[1] ?? tool ?? "a tool"}`;
2423
- }
2424
- /** Questions to the orchestrator, answers back to the asker, and the permission relay. */
2425
- var TicketService = class {
2426
- host;
2427
- constructor(host) {
2428
- this.host = host;
2429
- }
2430
- get store() {
2431
- return this.host.store.tickets;
2432
- }
2433
- create(p) {
2434
- const asker = this.requireOnline(p.sessionId);
2435
- const toOwner = p.to === "you" || p.to === OWNER_SESSION_ID;
2436
- const target = toOwner ? OWNER : this.host.resolve(p.to ?? "orchestrator");
2437
- if (target.id === asker.id) fail(RpcErrorCode.InvalidParams, p.to === void 0 || isLeadAlias(p.to) ? "You are the lead, so there is no one above you to ask. Ask the user directly." : "A session cannot ask itself. Name another session in `to`.");
2438
- return this.open(asker, target, {
2439
- kind: "question",
2440
- question: p.question,
2441
- options: p.options,
2442
- toRef: toOwner ? "you" : p.to === void 0 || isLeadAlias(p.to) ? ORCHESTRATOR_ALIAS : target.id,
2443
- ttlMs: TICKET_TTL_MS
2444
- });
2445
- }
2446
- open(asker, target, t) {
2447
- const at = this.host.iso();
2448
- if (this.store.list({
2449
- session: asker.id,
2450
- status: "open",
2451
- limit: 200
2452
- }).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.`);
2453
- const ticket = {
2454
- id: newTicketId(),
2455
- fromSession: asker.id,
2456
- toSession: target.id,
2457
- kind: t.kind,
2458
- question: t.question,
2459
- ...t.options ? { options: t.options } : {},
2460
- status: "open",
2461
- createdAt: at,
2462
- expiresAt: new Date(Date.parse(at) + t.ttlMs).toISOString()
2463
- };
2464
- const message = {
2465
- id: newMessageId(),
2466
- from: asker.id,
2467
- to: target.id,
2468
- kind: "question",
2469
- body: {
2470
- ticketId: ticket.id,
2471
- question: t.question,
2472
- ...t.options ? { options: t.options } : {}
2473
- },
2474
- urgent: true,
2475
- createdAt: at,
2476
- fromName: asker.name,
2477
- fromCli: asker.cli
2478
- };
2479
- this.host.store.tx(() => {
2480
- this.store.insert(ticket, t.toRef);
2481
- if (target.id !== OWNER_SESSION_ID) this.host.queue(message, target, true);
2482
- });
2483
- this.host.emit({
2484
- event: "ticket.created",
2485
- data: { ticket }
2486
- }, target.id);
2487
- if (target.id === OWNER_SESSION_ID || t.kind === "permission") this.host.notify({
2488
- from: asker.name,
2489
- text: t.kind === "permission" ? permissionLine(t.question) : t.question,
2490
- kind: t.kind === "permission" ? "permission" : "question"
2491
- });
2492
- return { ticket };
2493
- }
2494
- answer(p, client) {
2495
- const row = this.store.get(p.ticketId);
2496
- if (!row) fail(RpcErrorCode.NotFound, `No ticket ${p.ticketId}. Run tickets to see the open ones.`);
2497
- const { ticket, toRef } = row;
2498
- if (ticket.status !== "open") fail(RpcErrorCode.Conflict, `Ticket ${ticket.id} is already ${ticket.status}, so it cannot be answered.`);
2499
- let by;
2500
- let me;
2501
- if (p.sessionId === void 0) {
2502
- if (client !== "cli") fail(RpcErrorCode.Unauthorized, "Only a session or the conveno command can answer a ticket. Pass sessionId.");
2503
- by = HUMAN_ANSWERER;
2504
- } else {
2505
- me = this.host.requireSession(p.sessionId);
2506
- by = me.id;
2507
- if (me.id === ticket.fromSession) fail(RpcErrorCode.Unauthorized, "A session cannot answer its own ticket.");
2508
- 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.`);
2509
- }
2510
- let response = p.response;
2511
- if (ticket.kind === "permission") {
2512
- response = p.response.trim().toLowerCase();
2513
- if (!PERMISSION_ANSWERS.includes(response)) fail(RpcErrorCode.InvalidParams, `Ticket ${ticket.id} is a permission request. Answer "allow" or "deny" and nothing else.`);
2514
- }
2515
- const at = this.host.iso();
2516
- const asker = this.host.store.getSession(ticket.fromSession);
2517
- let messageId;
2518
- this.host.store.tx(() => {
2519
- let message;
2520
- if (ticket.kind === "question" && asker) {
2521
- message = {
2522
- id: newMessageId(),
2523
- from: me?.id ?? OWNER_SESSION_ID,
2524
- to: asker.id,
2525
- kind: "answer",
2526
- body: {
2527
- ticketId: ticket.id,
2528
- response
2529
- },
2530
- urgent: true,
2531
- createdAt: at,
2532
- fromName: me?.name ?? "you",
2533
- ...me ? { fromCli: me.cli } : {}
2534
- };
2535
- this.host.queue(message, asker, false);
2536
- messageId = message.id;
2537
- }
2538
- this.store.answer(ticket.id, response, by, at, messageId);
2539
- });
2540
- const done = this.store.get(ticket.id).ticket;
2541
- this.host.emit({
2542
- event: "ticket.answered",
2543
- data: { ticket: done }
2544
- }, [ticket.fromSession, ticket.toSession]);
2545
- return { ticket: done };
2546
- }
2547
- list(p, client) {
2548
- if (p.sessionId === void 0 && client !== "cli") fail(RpcErrorCode.Unauthorized, "Pass sessionId to list your tickets.");
2549
- if (p.sessionId !== void 0) this.host.requireSession(p.sessionId);
2550
- const { rows, openCount } = this.store.list({
2551
- ...p.sessionId !== void 0 ? {
2552
- session: p.sessionId,
2553
- holder: this.host.holder() === p.sessionId
2554
- } : {},
2555
- ...p.status !== void 0 ? { status: p.status } : {},
2556
- ...p.ticketId !== void 0 ? { id: p.ticketId } : {},
2557
- limit: p.limit
2558
- });
2559
- return {
2560
- tickets: rows.map((r) => r.ticket),
2561
- openCount
2562
- };
2563
- }
2564
- cancel(p, client) {
2565
- const row = this.store.get(p.ticketId);
2566
- if (!row) fail(RpcErrorCode.NotFound, `No ticket ${p.ticketId}. Run tickets to see the open ones.`);
2567
- const { ticket } = row;
2568
- if (p.sessionId === void 0) {
2569
- if (client !== "cli") fail(RpcErrorCode.Unauthorized, "Pass sessionId to cancel a ticket.");
2570
- } else {
2571
- this.host.requireSession(p.sessionId);
2572
- if (p.sessionId !== ticket.fromSession) fail(RpcErrorCode.Unauthorized, "Only the session that asked can cancel a ticket.");
2573
- }
2574
- if (ticket.status !== "open") fail(RpcErrorCode.Conflict, `Ticket ${ticket.id} is already ${ticket.status}, so it cannot be cancelled.`);
2575
- this.store.setStatus(ticket.id, "cancelled");
2576
- return { ticket: this.store.get(ticket.id).ticket };
2577
- }
2578
- /** Expire open tickets past their time; tell the asker of a question that it went unanswered. */
2579
- sweep() {
2580
- const at = this.host.iso();
2581
- for (const { ticket } of this.store.dueToExpire(at)) this.host.store.tx(() => {
2582
- this.store.setStatus(ticket.id, "expired");
2583
- const asker = this.host.store.getSession(ticket.fromSession);
2584
- if (ticket.kind === "question" && asker) {
2585
- const target = this.host.store.getSession(ticket.toSession);
2586
- this.host.queue({
2587
- id: newMessageId(),
2588
- from: this.host.daemonSender,
2589
- to: asker.id,
2590
- kind: "system",
2591
- body: {
2592
- event: "ticket.expired",
2593
- 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.`
2594
- },
2595
- urgent: false,
2596
- createdAt: at
2597
- }, asker, false);
2598
- }
2599
- });
2600
- }
2601
- relay(p, client) {
2602
- 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.");
2603
- if (p.enabled !== void 0) {
2604
- if (p.target === void 0) fail(RpcErrorCode.InvalidParams, "Name the session to switch the relay for.");
2605
- const target = this.host.requireSession(p.target);
2606
- 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.`);
2607
- let approver = null;
2608
- if (p.enabled) {
2609
- approver = this.host.holder();
2610
- 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.");
2611
- if (approver === target.id) fail(RpcErrorCode.InvalidParams, `${target.name} is the orchestrator, so it cannot relay to itself.`);
2612
- }
2613
- this.store.setRelay(target.id, approver, this.host.iso());
2614
- }
2615
- return { relays: this.store.relays() };
2616
- }
2617
- request(p) {
2618
- const me = this.requireOnline(p.sessionId);
2619
- const local = (reason) => ({
2620
- relay: false,
2621
- reason
2622
- });
2623
- const approverId = this.store.approverOf(me.id);
2624
- if (approverId === void 0) return local("The permission relay is off for this session.");
2625
- if (!me.spawned) return local("A person drives this session, so the relay does not apply.");
2626
- const verdict = classifyPermission({
2627
- tool: p.tool,
2628
- command: p.command,
2629
- paths: p.paths,
2630
- cwd: p.cwd ?? me.cwd,
2631
- repoRoot: me.repoRoot
2632
- });
2633
- if (!verdict.relay) return local(verdict.reason);
2634
- const target = this.host.store.getSession(approverId);
2635
- if (!target || target.status === "offline") return local("The orchestrator this relay was set up with is not online.");
2636
- if (target.id === me.id) return local("This session is the orchestrator.");
2637
- if (this.store.list({
2638
- session: me.id,
2639
- status: "open",
2640
- limit: 200
2641
- }).rows.filter((r) => r.ticket.fromSession === me.id && r.ticket.kind === "permission").length >= 5) return local("Too many permission requests are waiting already.");
2642
- const lines = [
2643
- `Permission request (EXPERIMENTAL relay) from ${me.name} (${me.cli}) in ${clip(me.repoRoot ?? me.cwd, 200)}.`,
2644
- `Tool: ${clip(p.tool, 100)}`,
2645
- ...p.command ? [`Command: ${clip(p.command, 1e3)}`] : [],
2646
- ...p.paths?.length ? [`Files: ${clip(p.paths.join(", "), 1e3)}`] : [],
2647
- ...p.cwd ? [`Working folder: ${clip(p.cwd, 200)}`] : [],
2648
- ...p.description ? [`The CLI says: ${clip(p.description, 300)}`] : [],
2649
- `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.`
2650
- ];
2651
- const { ticket } = this.open(me, target, {
2652
- kind: "permission",
2653
- question: lines.join("\n"),
2654
- options: [...PERMISSION_ANSWERS],
2655
- toRef: target.id,
2656
- ttlMs: PERMISSION_TICKET_TTL_MS
2657
- });
2658
- return {
2659
- relay: true,
2660
- ticket
2661
- };
2662
- }
2663
- requireOnline(id) {
2664
- const row = this.host.requireSession(id);
2665
- if (row.status === "offline") fail(RpcErrorCode.NotFound, `Session "${row.name}" is offline. Register the session again before asking.`);
2666
- return row;
2667
- }
2668
- };
2669
1946
  // ../daemon/src/server.ts
2670
- const DAEMON_VERSION = "0.2.0-rc.5";
1947
+ const DAEMON_VERSION = "0.2.0-rc.6";
2671
1948
  /** A connection that has not finished the handshake by then is closed. */
2672
1949
  const AUTH_TIMEOUT_MS = 5e3;
2673
1950
  /** Unread messages one session may hold. */
2674
1951
  const MAX_UNREAD_PER_SESSION = 1e3;
2675
- const OWNER_READ_KEEP_MS = 2592e6;
2676
- const OWNER_PRUNE_EVERY_MS = 36e5;
2677
- const PRUNE_OFFLINE_AFTER_MS = 864e5;
2678
- /**
2679
- * An offline session that a newer live session has replaced (same name, CLI and repo) is deleted
2680
- * after this grace. It cannot come back: a heartbeat is refused while another live session holds
2681
- * its name.
2682
- */
2683
- const PRUNE_SUPERSEDED_AFTER_MS = 3e5;
2684
1952
  /**
2685
- * An offline session with unread (queued) messages keeps them this long, whatever the other rules
2686
- * 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.
2687
1956
  */
2688
- const PRUNE_UNREAD_AFTER_MS = 6048e5;
1957
+ const OFFLINE_GRACE_MS = 6e4;
2689
1958
  /** Time the daemon spends reading the process table for one `session.hostOf`. */
2690
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;
2691
1965
  /** Sender id on `system` messages made by the daemon itself (no session sent them). */
2692
1966
  const DAEMON_SENDER_ID = SessionId.parse("0".repeat(26));
2693
1967
  const CLI_TIER = {
@@ -2697,11 +1971,6 @@ const CLI_TIER = {
2697
1971
  copilot: "next_turn",
2698
1972
  antigravity: "next_turn"
2699
1973
  };
2700
- /**
2701
- * CLIs whose adapter can wake an idle session in auto mode (Claude Code's asyncRewake listener,
2702
- * the OpenCode plugin). A message to such a session in auto mode is reported as `live`.
2703
- */
2704
- const CLI_WAKE = /* @__PURE__ */ new Set(["claude", "opencode"]);
2705
1974
  var Daemon = class {
2706
1975
  store;
2707
1976
  token;
@@ -2712,27 +1981,37 @@ var Daemon = class {
2712
1981
  requestShutdown;
2713
1982
  log;
2714
1983
  authTimeoutMs;
2715
- pathExists;
2716
1984
  autoLimits;
2717
- transcripts;
2718
- transcriptEnv;
2719
1985
  processIo;
2720
- notifier;
1986
+ platform;
1987
+ wakers;
2721
1988
  conns = /* @__PURE__ */ new Set();
2722
1989
  /** Reaches the owner's other devices; set by startDaemon unless disabled. */
2723
1990
  relay;
2724
1991
  deviceId;
2725
- /** 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
+ */
2726
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();
2727
2010
  idleSince;
2728
2011
  startedMs;
2729
- ownerPrunedMs = 0;
2730
- tickets;
2731
- constructor(store, token, now, isAlive, idleExitMs, requestIdleExit, requestShutdown, log, authTimeoutMs = AUTH_TIMEOUT_MS, pathExists = existsSync, autoLimits = autoLimitsFromEnv({}), transcripts = {}, transcriptEnv = {
2732
- home: homedir(),
2733
- platform: process.platform,
2734
- env: process.env
2735
- }, processIo = defaultProcessIo, notifier = noopNotifier) {
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 = {}) {
2736
2015
  this.store = store;
2737
2016
  this.token = token;
2738
2017
  this.now = now;
@@ -2742,31 +2021,15 @@ var Daemon = class {
2742
2021
  this.requestShutdown = requestShutdown;
2743
2022
  this.log = log;
2744
2023
  this.authTimeoutMs = authTimeoutMs;
2745
- this.pathExists = pathExists;
2746
2024
  this.autoLimits = autoLimits;
2747
- this.transcripts = transcripts;
2748
- this.transcriptEnv = transcriptEnv;
2749
2025
  this.processIo = processIo;
2750
- this.notifier = notifier;
2026
+ this.platform = platform;
2027
+ this.wakers = wakers;
2751
2028
  this.deviceId = store.deviceId();
2752
2029
  this.startedMs = now().getTime();
2753
2030
  this.idleSince = this.startedMs;
2754
- this.tickets = new TicketService({
2755
- store,
2756
- iso: () => this.iso(),
2757
- requireSession: (id) => this.requireSession(id),
2758
- resolve: (to) => this.resolveOnline(to),
2759
- holder: () => effectiveHolder(store.holder(), this.named(store.allSessions()))?.id ?? null,
2760
- queue: (message, to, limit) => this.queueMessage(message, to, limit),
2761
- emit: (payload, onlyTo) => this.emit(payload, onlyTo),
2762
- daemonSender: DAEMON_SENDER_ID,
2763
- notify: (item) => this.notifier.notify(item)
2764
- });
2765
2031
  }
2766
2032
  iso = () => this.now().toISOString();
2767
- closeNotifier() {
2768
- this.notifier.close();
2769
- }
2770
2033
  attach(socket) {
2771
2034
  const conn = {
2772
2035
  socket,
@@ -2785,6 +2048,7 @@ var Daemon = class {
2785
2048
  socket.on("close", () => {
2786
2049
  clearTimeout(authTimer);
2787
2050
  this.conns.delete(conn);
2051
+ this.listenerGone(conn);
2788
2052
  });
2789
2053
  socket.on("error", () => socket.destroy());
2790
2054
  }
@@ -2846,33 +2110,22 @@ var Daemon = class {
2846
2110
  case "session.rename": return this.rename(req.params);
2847
2111
  case "session.setStatus": return this.setStatus(req.params);
2848
2112
  case "session.list": return this.list(req.params);
2849
- 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);
2850
2114
  case "session.hostOf": return this.hostOf(req.params);
2851
- case "session.forget": return this.forget(req.params);
2852
- case "session.setAuto": return this.setAuto(req.params);
2115
+ case "session.setNative": return this.setNative(req.params);
2853
2116
  case "turn.start": return this.turnStart(req.params.sessionId);
2854
2117
  case "turn.end": return this.turnEnd(req.params);
2855
- case "turn.wake": return this.turnWake(req.params);
2856
- case "session.setCliInfo": return this.setCliInfo(req.params);
2857
- case "session.setPeekable": return this.setPeekable(req.params);
2858
- case "session.peek": return this.peek(conn, req.params);
2118
+ case "turn.wake": return this.turnWake(conn, req.params);
2859
2119
  case "daemon.shutdown": return { ok: true };
2860
2120
  case "orchestrator.claim": return this.claim(req.params.sessionId);
2121
+ case "orchestrator.clear": return this.clearLead(conn);
2861
2122
  case "message.send": return this.sendMessage(req.params);
2862
- case "message.history": return this.messageHistory(conn, req.params);
2863
- case "owner.inbox": return this.ownerInbox(conn, req.params);
2864
- case "owner.ack": return this.ownerAck(conn, req.params);
2865
2123
  case "owner.send": return this.ownerSend(conn, req.params);
2866
2124
  case "message.inbox": return this.inbox(req.params);
2867
2125
  case "message.deliver": return this.deliver(req.params);
2868
2126
  case "message.ack": return this.ack(req.params);
2127
+ case "message.requeue": return this.requeue(req.params);
2869
2128
  case "events.subscribe": return this.subscribe(conn, req.params);
2870
- case "ticket.create": return this.tickets.create(req.params);
2871
- case "ticket.answer": return this.tickets.answer(req.params, conn.client);
2872
- case "ticket.list": return this.tickets.list(req.params, conn.client);
2873
- case "ticket.cancel": return this.tickets.cancel(req.params, conn.client);
2874
- case "permission.relay": return this.tickets.relay(req.params, conn.client);
2875
- case "permission.request": return this.tickets.request(req.params);
2876
2129
  case "relay.status":
2877
2130
  case "devices.list":
2878
2131
  case "devices.pair":
@@ -2921,28 +2174,18 @@ var Daemon = class {
2921
2174
  if (row.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${row.name}" is offline. Register the session again.`);
2922
2175
  return row;
2923
2176
  }
2177
+ /** The wire view of a session. Its `deliveryTier` is the live one (`tierFor`). */
2924
2178
  view(row) {
2925
- 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));
2926
2184
  }
2927
2185
  /** The orchestrator as routing sees it: the holder, if it is online. */
2928
2186
  orchestratorNow() {
2929
2187
  return effectiveHolder(this.store.holder(), this.named(this.store.allSessions()))?.id ?? null;
2930
2188
  }
2931
- /** The online session a recipient names (`orchestrator`, a name or an id). */
2932
- resolveOnline(to) {
2933
- const rows = this.store.allSessions();
2934
- const found = resolveRecipient(to, this.named(rows), this.store.holder());
2935
- return rows.find((r) => r.id === found.id);
2936
- }
2937
- /**
2938
- * Queue a message for a session, or for the owner, and tell its subscriber. `limit` applies the
2939
- * unread cap.
2940
- */
2941
- queueMessage(message, row, limit) {
2942
- if (limit && this.store.unreadCount(row.id) >= 1e3) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(row.name, MAX_UNREAD_PER_SESSION));
2943
- this.store.insertMessage(message, row.id, message.createdAt);
2944
- this.emitMessage(message, row.id);
2945
- }
2946
2189
  emit(payload, onlyTo) {
2947
2190
  const only = onlyTo === void 0 || Array.isArray(onlyTo) ? onlyTo : [onlyTo];
2948
2191
  for (const c of this.conns) {
@@ -2963,11 +2206,13 @@ var Daemon = class {
2963
2206
  });
2964
2207
  this.relay?.sessionsChanged();
2965
2208
  }
2209
+ /** Every message that lands in a local mailbox goes through here. */
2966
2210
  emitMessage(m, recipient) {
2967
2211
  this.emit({
2968
2212
  event: "message.received",
2969
2213
  data: { message: m }
2970
2214
  }, recipient);
2215
+ this.daemonWake(recipient);
2971
2216
  }
2972
2217
  async detect(p) {
2973
2218
  if (p.repo) return p.repo;
@@ -2992,8 +2237,6 @@ var Daemon = class {
2992
2237
  deliveryTier: p.acp ? "acp" : CLI_TIER[p.cli] ?? "inbox",
2993
2238
  spawned: p.spawned,
2994
2239
  spawnDepth: parent ? parent.spawnDepth + 1 : 0,
2995
- auto: p.auto ?? (p.spawned || p.spawnedBy !== void 0),
2996
- autoExplicit: false,
2997
2240
  autoRuns: [],
2998
2241
  turnHops: 0,
2999
2242
  startedAt: at,
@@ -3030,6 +2273,7 @@ var Daemon = class {
3030
2273
  status: "idle",
3031
2274
  lastSeenAt: at
3032
2275
  });
2276
+ this.offlineSince.delete(sessionId);
3033
2277
  this.emitSession(sessionId, "updated");
3034
2278
  return { lastSeenAt: at };
3035
2279
  }
@@ -3041,6 +2285,8 @@ var Daemon = class {
3041
2285
  if (after !== before) this.store.setHolder(after);
3042
2286
  });
3043
2287
  this.listeners.delete(sessionId);
2288
+ this.woken.delete(sessionId);
2289
+ this.offlineSince.set(sessionId, this.now().getTime());
3044
2290
  this.emitSession(sessionId, change);
3045
2291
  if (after !== before) this.emit({
3046
2292
  event: "orchestrator.changed",
@@ -3079,7 +2325,7 @@ var Daemon = class {
3079
2325
  }
3080
2326
  list(p) {
3081
2327
  const rows = this.store.allSessions().filter((r) => {
3082
- if (!p.includeOffline && r.status === "offline") return false;
2328
+ if (r.status === "offline" && !p.includeOffline) return false;
3083
2329
  if (p.cli && r.cli !== p.cli) return false;
3084
2330
  if (p.repo && r.repoRoot !== p.repo && baseName(r.repoRoot ?? r.cwd) !== p.repo) return false;
3085
2331
  return true;
@@ -3095,12 +2341,16 @@ var Daemon = class {
3095
2341
  * Exact equality only, with no walk to farther ancestors, so a hook from a CLI that has no
3096
2342
  * session matches nothing. Two sessions under one CLI process are ambiguous, so the result is
3097
2343
  * null; the daemon never guesses. With `cwd`, the sessions that share the pid are narrowed to
3098
- * 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
3099
2345
  * on Windows), so several folders on one OpenCode 2.x server stay apart. Two sessions in one
3100
2346
  * folder still match nothing.
3101
2347
  */
3102
- byHost(pid, cwd) {
3103
- 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)));
3104
2354
  const only = holders.length === 1 ? holders[0] : void 0;
3105
2355
  return { session: only ? this.view(only) : null };
3106
2356
  }
@@ -3129,122 +2379,39 @@ var Daemon = class {
3129
2379
  };
3130
2380
  }
3131
2381
  /**
3132
- * Remove offline sessions on the owner's request. Selection: with `ids` or `names` the
3133
- * candidates are the sessions matching either; with neither, every session. `olderThanMs` then
3134
- * keeps only sessions last seen at least that long ago. Online candidates are never removed:
3135
- * those picked by `ids` or `names` come back in `skippedOnline`, and with `olderThanMs` alone
3136
- * they are ignored, since the caller asked for offline sessions. A removed session takes its
3137
- * 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.
3138
2384
  */
3139
- forget(p) {
3140
- const nowMs = this.now().getTime();
3141
- const explicit = p.ids !== void 0 || p.names !== void 0;
3142
- const ids = new Set(p.ids ?? []);
3143
- const names = p.names ?? [];
3144
- const matched = this.store.allSessions().filter((r) => {
3145
- if (explicit && !ids.has(r.id) && !names.some((n) => nameMatchesPattern(n, r.name))) return false;
3146
- return p.olderThanMs === void 0 || nowMs - Date.parse(r.lastSeenAt) >= p.olderThanMs;
3147
- });
3148
- const brief = (r) => ({
3149
- id: r.id,
3150
- 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 });
3151
2392
  });
3152
- const offline = matched.filter((r) => r.status === "offline");
3153
- const skippedOnline = explicit ? matched.filter((r) => r.status !== "offline") : [];
3154
- if (!p.dryRun) this.forgetRows(offline);
3155
- return {
3156
- forgotten: offline.map(brief),
3157
- skippedOnline: skippedOnline.map(brief)
3158
- };
3159
- }
3160
- /**
3161
- * A hook reports the CLI's own session id and transcript file. The session is the one online
3162
- * session whose `hostPid` equals `pid`, as in `byHost`; no unique match changes nothing. A new
3163
- * CLI session id with no path drops the old path, which belonged to the previous conversation.
3164
- */
3165
- setCliInfo(p) {
3166
- const holders = this.store.allSessions().filter((r) => r.status !== "offline" && r.hostPid === p.pid);
3167
- const row = holders.length === 1 ? holders[0] : void 0;
3168
- if (!row) return { updated: false };
3169
- const fields = {};
3170
- if (p.cliSessionId !== void 0) fields.cliSessionId = p.cliSessionId;
3171
- if (p.transcriptPath !== void 0) fields.transcriptPath = p.transcriptPath;
3172
- else if (p.cliSessionId !== void 0 && p.cliSessionId !== row.cliSessionId) fields.transcriptPath = null;
3173
- this.store.updateSession(row.id, fields);
3174
- return { updated: true };
3175
- }
3176
- /** The owner's switch. With no `session`, every online session on this device. */
3177
- setPeekable(p) {
3178
- const rows = this.store.allSessions();
3179
- 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");
3180
- 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.`);
3181
- for (const r of targets) this.store.updateSession(r.id, { peekable: p.peekable });
3182
- return { sessions: targets.map((r) => ({
3183
- id: r.id,
3184
- name: r.name,
3185
- peekable: p.peekable
3186
- })) };
3187
- }
3188
- /**
3189
- * Read the recent turns of another session's transcript on this device. Redaction is always on.
3190
- * The target's owner can see every peek in the daemon log (who looked at whom and how many
3191
- * turns, never the content), and can turn peek off for a session.
3192
- */
3193
- async peek(conn, p) {
3194
- 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.");
3195
- const caller = p.sessionId !== void 0 ? this.requireSession(p.sessionId) : void 0;
3196
- const target = this.store.getSession(resolveRecipient(p.target, this.named(this.store.allSessions()), this.store.holder()).id);
3197
- const who = `${caller ? `${caller.name} (${caller.id})` : "the conveno command"} -> ${target.name} (${target.id}, ${target.cli})`;
3198
- if (target.peekable === false) {
3199
- this.log.note(`peek refused, peek is off: ${who}`);
3200
- throw new ConvenoError(RpcErrorCode.PermissionRequired, `Peek is turned off for ${target.name}. Its owner can run "conveno peek on ${target.name}" to allow it.`);
3201
- }
3202
- const reader = target.deliveryTier === "acp" ? acpTranscript : this.transcripts[target.cli];
3203
- if (!reader) throw new ConvenoError(RpcErrorCode.InvalidParams, `peek not supported for ${target.cli} yet.`);
3204
- const res = await reader.read({
3205
- cwd: target.cwd,
3206
- startedAt: target.startedAt,
3207
- lastTurns: p.lastTurns,
3208
- ...target.cliSessionId !== void 0 ? { cliSessionId: target.cliSessionId } : {},
3209
- ...target.transcriptPath !== void 0 ? { transcriptPath: target.transcriptPath } : {},
3210
- ...target.hostPid !== void 0 ? { hostPid: target.hostPid } : {}
3211
- }, this.transcriptEnv);
3212
- if (!res.ok) {
3213
- this.log.note(`peek found nothing (${res.reason}): ${who}`);
3214
- throw new ConvenoError(res.reason === "unsupported" ? RpcErrorCode.InvalidParams : RpcErrorCode.NotFound, res.message);
3215
- }
3216
- const out = preparePeek(res.entries, res.more, p.maxChars);
3217
- this.log.note(`peek: ${who}, ${out.turns.length} turns, ${out.redactions} redactions`);
3218
- return {
3219
- session: {
3220
- id: target.id,
3221
- name: target.name,
3222
- cli: target.cli
3223
- },
3224
- turns: out.turns,
3225
- truncated: out.truncated,
3226
- redacted: true,
3227
- redactions: out.redactions
3228
- };
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)) };
3229
2397
  }
3230
- forgetRows(rows) {
3231
- 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;
3232
2407
  this.store.tx(() => {
3233
- for (const r of rows) this.store.deleteSession(r.id);
2408
+ for (const r of gone) this.store.deleteSession(r.id);
3234
2409
  });
3235
- for (const r of rows) this.listeners.delete(r.id);
3236
- }
3237
- /**
3238
- * An offline session whose working folder (or repository root) has been missing for
3239
- * PRUNE_MISSING_FOLDER_AFTER_MS is forgotten. One with unread messages is left to the unread
3240
- * rule, so queued mail is never dropped early. One whose host process still runs is kept,
3241
- * because it can come back with a heartbeat.
3242
- */
3243
- workspaceGone(row, nowMs) {
3244
- if (nowMs - Date.parse(row.lastSeenAt) < 3e5) return false;
3245
- if (this.store.unreadCount(row.id) > 0) return false;
3246
- if (row.hostPid !== void 0 && this.isAlive(row.hostPid)) return false;
3247
- 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
+ }
3248
2415
  }
3249
2416
  claim(sessionId) {
3250
2417
  this.requireSession(sessionId);
@@ -3289,6 +2456,44 @@ var Daemon = class {
3289
2456
  previous: res.previous
3290
2457
  };
3291
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
+ }
3292
2497
  sendMessage(p) {
3293
2498
  const sender = this.requireSession(p.sessionId);
3294
2499
  if (sender.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${sender.name}" is offline. Register the session again before sending.`);
@@ -3305,9 +2510,8 @@ var Daemon = class {
3305
2510
  return to === "you" || to === OWNER_SESSION_ID;
3306
2511
  }
3307
2512
  /**
3308
- * Route one message from `sender` (a session, or the owner) to a session, the owner, or a
3309
- * session on another device. The owner is not a session: a message to `you` waits in the owner's
3310
- * 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\`.
3311
2515
  */
3312
2516
  deliverFrom(sender, p) {
3313
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.`);
@@ -3325,47 +2529,19 @@ var Daemon = class {
3325
2529
  ...sender.cli !== void 0 ? { fromCli: sender.cli } : {},
3326
2530
  ...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
3327
2531
  });
3328
- if (this.isOwnerRecipient(p.to)) {
3329
- if (sender.id === OWNER_SESSION_ID) throw new ConvenoError(RpcErrorCode.InvalidParams, "You cannot send a message to yourself.");
3330
- const message = make("you");
3331
- this.store.tx(() => this.queueMessage(message, {
3332
- id: OWNER_SESSION_ID,
3333
- name: "you"
3334
- }, true));
3335
- this.notifier.notify({
3336
- from: sender.name,
3337
- text: ownerNoticeText(message.body),
3338
- kind: "message"
3339
- });
3340
- return {
3341
- message,
3342
- delivery: "inbox",
3343
- deliveredTo: {
3344
- id: OWNER_SESSION_ID,
3345
- name: "you"
3346
- }
3347
- };
3348
- }
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.");
3349
2533
  let target;
3350
2534
  try {
3351
2535
  target = resolveRecipient(p.to, this.named(rows), this.store.holder());
3352
2536
  } catch (e) {
3353
2537
  const remote = e instanceof ConvenoError && e.code === RpcErrorCode.NotFound ? this.relay?.resolveRemote(p.to) : void 0;
3354
2538
  if (!remote) throw e;
3355
- return this.sendToRemote(make(p.to), remote);
2539
+ return this.sendToRemote(make(p.to), remote, sender.hops);
3356
2540
  }
3357
2541
  const targetRow = rows.find((r) => r.id === target.id);
3358
2542
  if (this.store.unreadCount(targetRow.id) >= 1e3) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(targetRow.name, MAX_UNREAD_PER_SESSION));
3359
2543
  const message = make(p.to);
3360
- const enableAuto = sender.id !== targetRow.id && effectiveHolder(this.store.holder(), this.named(rows))?.id === sender.id && !targetRow.auto && !targetRow.autoExplicit;
3361
- this.store.tx(() => {
3362
- this.store.insertMessage(message, targetRow.id, at, sender.hops);
3363
- if (enableAuto) this.store.updateSession(targetRow.id, { auto: true });
3364
- });
3365
- if (enableAuto) {
3366
- targetRow.auto = true;
3367
- this.emitSession(targetRow.id, "updated");
3368
- }
2544
+ this.store.insertMessage(message, targetRow.id, at, sender.hops);
3369
2545
  this.emitMessage(message, targetRow.id);
3370
2546
  return {
3371
2547
  message,
@@ -3379,35 +2555,8 @@ var Daemon = class {
3379
2555
  requireCli(conn, what) {
3380
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.`);
3381
2557
  }
3382
- ownerInbox(conn, p) {
3383
- this.requireCli(conn, "read the owner's messages");
3384
- return this.readInboxOf(OWNER_SESSION_ID, p.unreadOnly, p.limit, true);
3385
- }
3386
- messageHistory(conn, p) {
3387
- this.requireCli(conn, "read a session's message history");
3388
- 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}.`);
3389
- const rows = this.store.messagesOf(p.session, p.limit + 1, p.before);
3390
- const more = rows.length > p.limit;
3391
- return {
3392
- messages: rows.slice(0, p.limit).reverse(),
3393
- more
3394
- };
3395
- }
3396
- ownerAck(conn, p) {
3397
- this.requireCli(conn, "mark the owner's messages as handled");
3398
- return this.ackFor(OWNER_SESSION_ID, p.ids);
3399
- }
3400
2558
  ownerSend(conn, p) {
3401
2559
  this.requireCli(conn, "send as the owner");
3402
- if (!this.isOwnerRecipient(p.to) && this.relay?.resolveRemote(p.to)) {
3403
- let local = true;
3404
- try {
3405
- resolveRecipient(p.to, this.named(this.store.allSessions()), this.store.holder());
3406
- } catch {
3407
- local = false;
3408
- }
3409
- 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.");
3410
- }
3411
2560
  return this.deliverFrom({
3412
2561
  id: OWNER_SESSION_ID,
3413
2562
  name: "you",
@@ -3420,108 +2569,169 @@ var Daemon = class {
3420
2569
  ...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
3421
2570
  });
3422
2571
  }
3423
- /** `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
+ */
3424
2578
  tierFor(row) {
3425
- const running = row.auto && row.autoPausedBy === void 0;
3426
- if (row.deliveryTier === "acp") return running ? "acp" : "inbox";
3427
- 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";
3428
2583
  return row.deliveryTier;
3429
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
+ }
3430
2602
  /**
3431
- * Change auto mode. The owner (no `sessionId`) may do anything. A session may only resume a paused
3432
- * session, only while it is the orchestrator, and only once per window for that session, so two
3433
- * 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.
3434
2609
  */
3435
- setAuto(p) {
3436
- const all = this.store.allSessions();
3437
- 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);
3438
- if (!row) throw new ConvenoError(RpcErrorCode.NotFound, `No session named "${p.session}". Run conveno status to see the sessions.`);
3439
- const at = this.iso();
3440
- const byOrchestrator = p.sessionId !== void 0;
3441
- if (p.sessionId !== void 0) {
3442
- const caller = this.requireOnline(p.sessionId);
3443
- 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>");
3444
- 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");
3445
- if (row.autoPausedBy === void 0) throw new ConvenoError(RpcErrorCode.PermissionRequired, `Auto mode for "${row.name}" is not paused.`);
3446
- const last = row.autoOrchResumedAt ? Date.parse(row.autoOrchResumedAt) : NaN;
3447
- if (this.now().getTime() - last < this.autoLimits.windowMs) {
3448
- const minutes = Math.round(this.autoLimits.windowMs / 6e4);
3449
- 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}`);
3450
- }
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;
3451
2617
  }
3452
- const lift = p.resume === true || p.auto === true;
3453
- this.store.tx(() => {
3454
- this.store.updateSession(row.id, {
3455
- ...p.auto !== void 0 ? {
3456
- auto: p.auto,
3457
- autoExplicit: true
3458
- } : {},
3459
- ...p.limit !== void 0 ? { autoLimit: p.limit } : {},
3460
- ...lift ? {
3461
- autoPausedAt: null,
3462
- autoPausedBy: null,
3463
- autoRuns: []
3464
- } : {},
3465
- ...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)
3466
2696
  });
3467
- if (lift) this.store.resetQueuedHops(row.id);
2697
+ return {
2698
+ requeued: r.changed.length,
2699
+ idle
2700
+ };
3468
2701
  });
3469
- this.emitSession(row.id, "updated");
3470
- 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 };
3471
2705
  }
3472
2706
  /**
3473
2707
  * The user typed a prompt: the session is busy, and messages it sends start a new chain (0 hops).
3474
- * A pause stays until the owner or the orchestrator resumes it.
3475
2708
  */
3476
2709
  turnStart(sessionId) {
3477
- this.requireOnline(sessionId);
3478
- 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" } : {
3479
2714
  status: "busy",
3480
2715
  turnHops: 0
3481
2716
  });
3482
2717
  this.emitSession(sessionId, "updated");
3483
2718
  return { session: this.view(this.requireSession(sessionId)) };
3484
2719
  }
3485
- /** The notice a session gets when its auto mode pauses. It waits for the next prompt. */
3486
- pauseNotice(row, reason, at) {
3487
- const minutes = Math.round(this.autoLimits.windowMs / 6e4);
3488
- const limit = row.autoLimit ?? this.autoLimits.limit;
3489
- 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.`;
3490
- return {
3491
- id: newMessageId(),
3492
- from: DAEMON_SENDER_ID,
3493
- to: row.id,
3494
- kind: "system",
3495
- body: {
3496
- event: "auto.paused",
3497
- detail
3498
- },
3499
- urgent: false,
3500
- createdAt: at
3501
- };
3502
- }
3503
2720
  /**
3504
- * 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.
3505
2722
  * On a hand-over the session is busy and its turn carries the hops. With `endOfTurn`, nothing
3506
2723
  * handed over means the session is now idle. One transaction.
3507
2724
  */
3508
- continueWith(row, allow, endOfTurn) {
2725
+ continueWith(row, allow, endOfTurn, maxBytes = RESPONSE_BUDGET_BYTES) {
3509
2726
  const nowMs = this.now().getTime();
3510
2727
  const at = this.iso();
3511
2728
  const orchestrator = this.orchestratorNow();
3512
- let pausedBy = row.autoPausedBy;
3513
- let notice;
3514
2729
  const res = this.store.tx(() => {
3515
2730
  const queued = this.store.entries(row.id, { states: ["queued"] });
3516
2731
  const candidates = allow ? autoCandidates(queued, row.id) : [];
3517
- const decision = decideAutoContinue({
3518
- auto: row.auto,
3519
- ...row.autoPausedBy !== void 0 ? { pausedBy: row.autoPausedBy } : {},
3520
- ...row.autoLimit !== void 0 ? { limit: row.autoLimit } : {},
3521
- runs: row.autoRuns
3522
- }, candidates, nowMs, this.autoLimits);
2732
+ const decision = decideAutoContinue({ runs: row.autoRuns }, candidates, nowMs, this.autoLimits);
3523
2733
  if (decision.continue) {
3524
- const taken = takeWithinBytes(candidates.slice(0, 20), RESPONSE_BUDGET_BYTES);
2734
+ const taken = takeWithinBytes(candidates.slice(0, 20), maxBytes);
3525
2735
  const updated = markDelivered(taken, taken.map((e) => e.message.id), at);
3526
2736
  for (const e of updated) this.store.saveEntry(row.id, e);
3527
2737
  this.store.updateSession(row.id, {
@@ -3534,36 +2744,24 @@ var Daemon = class {
3534
2744
  remaining: queued.length - taken.length
3535
2745
  };
3536
2746
  }
3537
- if (decision.pause !== void 0) {
3538
- pausedBy = decision.pause;
3539
- notice = this.pauseNotice(row, decision.pause, at);
3540
- this.store.insertMessage(notice, row.id, at);
3541
- this.store.updateSession(row.id, {
3542
- autoPausedAt: at,
3543
- autoPausedBy: decision.pause
3544
- });
3545
- }
3546
2747
  if (endOfTurn) this.store.updateSession(row.id, {
3547
2748
  status: "idle",
3548
2749
  turnHops: 0
3549
2750
  });
3550
2751
  return {
3551
2752
  messages: [],
3552
- remaining: queued.length + (notice ? 1 : 0)
2753
+ remaining: queued.length
3553
2754
  };
3554
2755
  });
3555
- if (notice) this.emitMessage(notice, row.id);
3556
- 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");
3557
2757
  return {
3558
2758
  ...res,
3559
- auto: row.auto,
3560
- paused: pausedBy !== void 0,
3561
- ...pausedBy !== void 0 ? { pausedBy } : {},
3562
2759
  orchestrator
3563
2760
  };
3564
2761
  }
3565
2762
  turnEnd(p) {
3566
2763
  const row = this.requireOnline(p.sessionId);
2764
+ this.woken.delete(p.sessionId);
3567
2765
  if (row.status === "waiting_on_question") return this.continueWith(row, false, false);
3568
2766
  return this.continueWith(row, p.allowContinue, true);
3569
2767
  }
@@ -3571,23 +2769,22 @@ var Daemon = class {
3571
2769
  * An idle-wake listener asks for work. The newest listener of a session wins: an older one gets
3572
2770
  * `superseded` and stops. A busy session is not woken; its messages wait for the end of the turn.
3573
2771
  */
3574
- turnWake(p) {
2772
+ turnWake(conn, p) {
3575
2773
  const row = this.requireOnline(p.sessionId);
3576
2774
  const known = this.listeners.get(row.id);
3577
2775
  if (known?.retired.includes(p.listenerId)) return {
3578
2776
  messages: [],
3579
2777
  remaining: this.store.unreadCount(row.id),
3580
- auto: row.auto,
3581
- paused: row.autoPausedBy !== void 0,
3582
- ...row.autoPausedBy !== void 0 ? { pausedBy: row.autoPausedBy } : {},
3583
2778
  orchestrator: this.orchestratorNow(),
3584
2779
  superseded: true
3585
2780
  };
2781
+ const wasConnected = this.listenerConnected(row.id);
3586
2782
  if (known?.current !== p.listenerId) {
3587
2783
  const retired = known ? [...known.retired, known.current].slice(-64) : [];
3588
2784
  this.listeners.set(row.id, {
3589
2785
  current: p.listenerId,
3590
- retired
2786
+ retired,
2787
+ conn
3591
2788
  });
3592
2789
  if (known) this.emit({
3593
2790
  event: "session.updated",
@@ -3596,9 +2793,12 @@ var Daemon = class {
3596
2793
  change: "updated"
3597
2794
  }
3598
2795
  }, row.id);
3599
- }
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);
3600
2800
  return {
3601
- ...this.continueWith(row, row.status === "idle", false),
2801
+ ...d,
3602
2802
  superseded: false
3603
2803
  };
3604
2804
  }
@@ -3606,16 +2806,15 @@ var Daemon = class {
3606
2806
  this.requireSession(p.sessionId);
3607
2807
  return this.readInboxOf(p.sessionId, p.unreadOnly, p.limit);
3608
2808
  }
3609
- /** A mailbox's messages, oldest first, marked read. The owner's mailbox has no session row. */
3610
- readInboxOf(id, unreadOnly, limit, newest = false) {
2809
+ /** A mailbox's messages, oldest first, marked read. */
2810
+ readInboxOf(id, unreadOnly, limit) {
3611
2811
  const at = this.iso();
3612
2812
  return this.store.tx(() => {
3613
2813
  const entries = this.store.entries(id, unreadOnly ? { states: ["queued"] } : {});
3614
2814
  const res = readInbox(entries, {
3615
2815
  unreadOnly,
3616
2816
  limit,
3617
- maxBytes: RESPONSE_BUDGET_BYTES,
3618
- newest
2817
+ maxBytes: RESPONSE_BUDGET_BYTES
3619
2818
  }, at);
3620
2819
  const changed = new Set(res.returned.map((e) => e.message.id));
3621
2820
  for (const e of res.entries) if (changed.has(e.message.id)) this.store.saveEntry(id, e);
@@ -3679,8 +2878,8 @@ var Daemon = class {
3679
2878
  default: throw new ConvenoError(RpcErrorCode.MethodNotFound, `Method not found: ${req.method}`);
3680
2879
  }
3681
2880
  }
3682
- sendToRemote(message, target) {
3683
- this.relay.sendRemote(target, message);
2881
+ sendToRemote(message, target, hops) {
2882
+ this.relay.sendRemote(target, message, hops);
3684
2883
  return {
3685
2884
  message,
3686
2885
  delivery: target.deliveryTier,
@@ -3694,19 +2893,22 @@ var Daemon = class {
3694
2893
  relayHost() {
3695
2894
  return {
3696
2895
  log: this.log,
3697
- localSessions: () => this.store.allSessions().filter((r) => r.status !== "offline").map((r) => this.view(r)),
3698
- 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) => {
3699
2901
  if (m.kind === "system") return "not_allowed";
3700
2902
  const row = this.store.getSession(to);
3701
2903
  if (!row) return "session_gone";
3702
2904
  if (row.status === "offline") return "session_offline";
3703
2905
  if (this.store.hasMessage(m.id)) return void 0;
3704
2906
  if (this.store.unreadCount(row.id) >= 1e3) return "mailbox_full";
3705
- this.store.insertMessage(m, row.id, this.iso());
2907
+ this.store.insertMessage(m, row.id, this.iso(), hops);
3706
2908
  this.emitMessage(m, row.id);
3707
2909
  },
3708
2910
  notify: (to, event, detail) => {
3709
- if (to !== OWNER_SESSION_ID && !this.store.getSession(to)) return;
2911
+ if (!this.store.getSession(to)) return;
3710
2912
  const m = {
3711
2913
  id: newMessageId(),
3712
2914
  from: DAEMON_SENDER_ID,
@@ -3724,34 +2926,18 @@ var Daemon = class {
3724
2926
  }
3725
2927
  };
3726
2928
  }
3727
- /**
3728
- * Prune rules for an offline session, in order:
3729
- * 1. With unread messages waiting, keep it for PRUNE_UNREAD_AFTER_MS, then delete it and its mail.
3730
- * 2. Replaced by a newer live session with the same name, CLI and repo: delete after
3731
- * PRUNE_SUPERSEDED_AFTER_MS.
3732
- * 3. Otherwise delete after PRUNE_OFFLINE_AFTER_MS.
3733
- * Besides these rules, `workspaceGone` forgets an offline session whose folder has been gone a while.
3734
- */
3735
- shouldPrune(row, all, nowMs) {
3736
- const offlineMs = nowMs - Date.parse(row.lastSeenAt);
3737
- if (this.store.unreadCount(row.id) > 0) return offlineMs >= PRUNE_UNREAD_AFTER_MS;
3738
- const place = (r) => r.repoRoot ?? r.cwd;
3739
- 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);
3740
2932
  }
3741
2933
  sweep() {
3742
- this.tickets.sweep();
3743
2934
  const nowMs = this.now().getTime();
3744
- if (nowMs - this.ownerPrunedMs >= OWNER_PRUNE_EVERY_MS) {
3745
- this.ownerPrunedMs = nowMs;
3746
- this.store.pruneMailbox(OWNER_SESSION_ID, 500, (/* @__PURE__ */ new Date(nowMs - OWNER_READ_KEEP_MS)).toISOString());
3747
- }
2935
+ this.removeOffline(OFFLINE_GRACE_MS);
2936
+ this.retryDaemonWakes(nowMs);
3748
2937
  let online = 0;
3749
2938
  const rows = this.store.allSessions();
3750
2939
  for (const row of rows) {
3751
- if (row.status === "offline") {
3752
- if (this.shouldPrune(row, rows, nowMs) || this.workspaceGone(row, nowMs)) this.forgetRows([row]);
3753
- continue;
3754
- }
2940
+ if (row.status === "offline") continue;
3755
2941
  const lastSeenMs = Math.max(Date.parse(row.lastSeenAt), this.startedMs);
3756
2942
  const verdict = evaluateLiveness({
3757
2943
  lastSeenMs,
@@ -3764,6 +2950,14 @@ var Daemon = class {
3764
2950
  else if (nowMs - this.idleSince >= this.idleExitMs) this.requestIdleExit();
3765
2951
  }
3766
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
+ }
3767
2961
  const unauthorizedMessage = "Finish the handshake first: call hello, then auth. Both use the token in daemon.token in the Conveno data directory.";
3768
2962
  /** Start the relay client. A broken relay state is logged and leaves the daemon local-only. */
3769
2963
  function startRelay(daemon, opts, relayOpts) {
@@ -3808,10 +3002,8 @@ async function startDaemon(opts) {
3808
3002
  close().then(() => opts.onIdleExit?.());
3809
3003
  }, () => {
3810
3004
  close().then(() => opts.onShutdown?.());
3811
- }, daemonLog, opts.authTimeoutMs ?? 5e3, opts.pathExists ?? existsSync, opts.autoLimits ?? autoLimitsFromEnv(process.env), opts.transcripts, opts.transcriptEnv, processIo, opts.notifier ?? createNotifier({
3812
- settingsPath: paths.settings,
3813
- onError: (what, e) => daemonLog.error(`notify: ${what}`, e)
3814
- }));
3005
+ }, daemonLog, opts.authTimeoutMs ?? 5e3, opts.autoLimits ?? autoLimitsFromEnv(process.env), processIo, opts.platform, opts.wakers ?? {});
3006
+ daemon.removeAllOffline();
3815
3007
  const srv = createServer((socket) => daemon.attach(socket));
3816
3008
  server = srv;
3817
3009
  await new Promise((resolve, reject) => {
@@ -3826,8 +3018,8 @@ async function startDaemon(opts) {
3826
3018
  function close() {
3827
3019
  closing ??= (async () => {
3828
3020
  if (timer) clearInterval(timer);
3021
+ daemon.stopping = true;
3829
3022
  walker?.close();
3830
- daemon.closeNotifier();
3831
3023
  daemon.relay?.stop();
3832
3024
  const stopped = new Promise((resolve) => srv.close(() => resolve()));
3833
3025
  for (const c of daemon.conns) c.socket.destroy();
@@ -3845,7 +3037,10 @@ async function startDaemon(opts) {
3845
3037
  testRelay: {
3846
3038
  host: () => daemon.relayHost(),
3847
3039
  set: (relay) => {
3848
- daemon.relay = relay;
3040
+ daemon.relay = relay && {
3041
+ sessionsChanged: () => {},
3042
+ ...relay
3043
+ };
3849
3044
  }
3850
3045
  }
3851
3046
  };
@@ -3856,264 +3051,11 @@ async function startDaemon(opts) {
3856
3051
  throw e;
3857
3052
  }
3858
3053
  }
3859
- // ../adapters/copilot/dist/transcript.js
3860
- /**
3861
- * GitHub Copilot CLI keeps each session in `~/.copilot/session-state/<session-id>/` (COPILOT_HOME
3862
- * replaces `~/.copilot`): `events.jsonl`, an append-only stream of `{ type, data, id, timestamp }`
3863
- * records, and `workspace.yaml` with `id`, `cwd`, `created_at` and `updated_at`.
3864
- *
3865
- * GitHub does not document this layout. It is taken from community write-ups of Copilot CLI 1.0.11
3866
- * and later (the events.jsonl reference gist
3867
- * https://gist.github.com/RockNoggin/8cc87f640ce5e3d284298a6db21f7523 and
3868
- * https://github.com/microsoft/What-I-Did-Copilot/blob/main/docs/architecture.md) and the open
3869
- * request for documentation, github/copilot-cli#3551. The reference bundle in
3870
- * reference/bundles/copilot-cli is a closed binary whose strings do not show the layout, so this
3871
- * reader is not checked against a real install. It skips what it does not recognise.
3872
- */
3873
- const copilotHome = (env) => env.env.COPILOT_HOME?.trim() || join(env.home, ".copilot");
3874
- const unquote = (s) => s.trim().replace(/^(["'])(.*)\1$/, "$2");
3875
- /** The `cwd:` value of a workspace.yaml, which is flat `key: value` lines. */
3876
- function yamlCwd(yaml) {
3877
- const m = /^cwd:[ \t]*(.+)$/m.exec(yaml);
3878
- return m?.[1] ? unquote(m[1]) : void 0;
3879
- }
3880
- async function sessionCwd(dir) {
3881
- try {
3882
- const cwd = yamlCwd(await readFile(join(dir, "workspace.yaml"), "utf8"));
3883
- if (cwd) return cwd;
3884
- } catch {}
3885
- try {
3886
- const head = await readHeadLine(join(dir, "events.jsonl"), 262144);
3887
- const ev = head ? JSON.parse(head) : null;
3888
- const data = isRecord(ev) && ev.type === "session.start" ? ev.data : void 0;
3889
- const context = isRecord(data) && isRecord(data.context) ? data.context : void 0;
3890
- return asString(context?.cwd);
3891
- } catch {
3892
- return;
3893
- }
3894
- }
3895
- const textOf = (v) => {
3896
- if (typeof v === "string") return v;
3897
- if (Array.isArray(v)) return v.map(textOf).filter(Boolean).join("\n");
3898
- if (isRecord(v)) return asString(v.text) ?? asString(v.content) ?? "";
3899
- return "";
3900
- };
3901
- /** Normalize one events.jsonl record. Exported for tests. */
3902
- function parseCopilotEvent(obj) {
3903
- const data = isRecord(obj.data) ? obj.data : {};
3904
- if (data.agentId !== void 0) return [];
3905
- const at = toIso(obj.timestamp);
3906
- const stamp = at ? { at } : {};
3907
- switch (obj.type) {
3908
- case "user.message": {
3909
- const text = asString(data.content) ?? "";
3910
- return text === "" ? [] : [{
3911
- role: "user",
3912
- text,
3913
- ...stamp
3914
- }];
3915
- }
3916
- case "assistant.message": {
3917
- const out = [];
3918
- const text = asString(data.content) ?? "";
3919
- if (text !== "") out.push({
3920
- role: "assistant",
3921
- text,
3922
- ...stamp
3923
- });
3924
- if (Array.isArray(data.toolRequests)) for (const r of data.toolRequests) {
3925
- if (!isRecord(r)) continue;
3926
- out.push({
3927
- role: "tool",
3928
- text: describeToolCall(asString(r.name) ?? "tool", r.arguments ?? r.intentionSummary),
3929
- ...stamp
3930
- });
3931
- }
3932
- return out;
3933
- }
3934
- case "tool.execution_complete": {
3935
- const result = isRecord(data.result) ? data.result : {};
3936
- const text = textOf(result.content) || textOf(result.detailedContent);
3937
- return text === "" ? [] : [{
3938
- role: "tool",
3939
- text,
3940
- ...stamp
3941
- }];
3942
- }
3943
- default: return [];
3944
- }
3945
- }
3946
- /** Find the session directory, or the reason there is none. */
3947
- async function locateCopilotSession(q, env) {
3948
- const root = join(copilotHome(env), "session-state");
3949
- if (q.cliSessionId && /^[A-Za-z0-9_-]{1,200}$/.test(q.cliSessionId)) {
3950
- const dir = join(root, q.cliSessionId);
3951
- if (await stat(join(dir, "events.jsonl")).then(() => true, () => false)) return { dir };
3952
- }
3953
- const since = Date.parse(q.startedAt);
3954
- const floor = Number.isFinite(since) ? since - 5e3 : 0;
3955
- for (const e of await entriesNewestFirst(root)) {
3956
- if (!e.dir || e.mtimeMs < floor) continue;
3957
- if (!await stat(join(e.path, "events.jsonl")).then(() => true, () => false)) continue;
3958
- const cwd = await sessionCwd(e.path);
3959
- if (cwd !== void 0 && samePath(cwd, q.cwd, env.platform)) return { dir: e.path };
3960
- }
3961
- return { error: "no session in session-state for this working directory since it started" };
3962
- }
3963
- const copilotTranscript = { async read(q, env) {
3964
- try {
3965
- const found = await locateCopilotSession(q, env);
3966
- if ("error" in found) return notFound("Copilot", found.error);
3967
- const { entries, more } = await tailJsonl(join(found.dir, "events.jsonl"), q.lastTurns, parseCopilotEvent);
3968
- return {
3969
- ok: true,
3970
- entries,
3971
- more
3972
- };
3973
- } catch (e) {
3974
- return notFound("Copilot", e instanceof Error ? e.message : "read failed");
3975
- }
3976
- } };
3977
- // ../adapters/grok/dist/transcript.js
3978
- /**
3979
- * Grok Build (xAI) keeps a session at
3980
- * `$GROK_HOME/sessions/<encoded cwd>/<session id>/chat_history.jsonl`, `$GROK_HOME` defaulting to
3981
- * `~/.grok`. The cwd directory name is the URL-encoded working directory; one over 255 bytes is
3982
- * `<slug>-<blake3 hex16>` and holds a `.cwd` file with the real path.
3983
- * reference/src/grok-build/crates/codegen/xai-dirs/src/lib.rs (grok home),
3984
- * xai-grok-config/src/paths.rs (`encode_cwd_dirname`, `sessions_cwd_dir_in`),
3985
- * xai-grok-shell/src/session/persistence.rs (`session_dir_in`).
3986
- *
3987
- * Each line of chat_history.jsonl is a `ConversationItem` tagged by `type`: `user`, `assistant`,
3988
- * `tool_result`, `system`, `reasoning`, `backend_tool_call`
3989
- * (xai-grok-sampling-types/src/conversation.rs). Items carry no timestamp.
3990
- */
3991
- const grokHome = (env) => env.env.GROK_HOME?.trim() || join(env.home, ".grok");
3992
- /** `urlencoding::encode`: everything but the unreserved characters `A-Za-z0-9-_.~` is percent-encoded. */
3993
- function encodeCwdDirname(cwd) {
3994
- return encodeURIComponent(cwd).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
3995
- }
3996
- const readText = (p) => readFile(p, "utf8").then((t) => t, () => void 0);
3997
- const textParts = (content) => {
3998
- if (typeof content === "string") return content;
3999
- if (!Array.isArray(content)) return "";
4000
- return content.map((p) => isRecord(p) && p.type === "text" ? asString(p.text) ?? "" : "").filter(Boolean).join("\n");
4001
- };
4002
- /** The user's own words: the CLI wraps the typed text in `<user_query>`. */
4003
- const unwrapQuery = (text) => {
4004
- return (/<user_query>([\s\S]*?)(?:<\/user_query>|$)/.exec(text)?.[1] ?? text).trim();
4005
- };
4006
- /** Normalize one chat_history.jsonl line. Exported for tests. */
4007
- function parseGrokItem(obj) {
4008
- switch (obj.type) {
4009
- case "user": {
4010
- const reason = obj.synthetic_reason;
4011
- if (reason !== void 0 && reason !== null && reason !== "human") return [];
4012
- const text = unwrapQuery(textParts(obj.content));
4013
- return text === "" ? [] : [{
4014
- role: "user",
4015
- text
4016
- }];
4017
- }
4018
- case "assistant": {
4019
- const out = [];
4020
- const text = asString(obj.content) ?? "";
4021
- if (text !== "") out.push({
4022
- role: "assistant",
4023
- text
4024
- });
4025
- if (Array.isArray(obj.tool_calls)) {
4026
- for (const c of obj.tool_calls) if (isRecord(c)) out.push({
4027
- role: "tool",
4028
- text: describeToolCall(asString(c.name) ?? "tool", c.arguments)
4029
- });
4030
- }
4031
- return out;
4032
- }
4033
- case "tool_result": {
4034
- const text = asString(obj.content) ?? "";
4035
- return text === "" ? [] : [{
4036
- role: "tool",
4037
- text
4038
- }];
4039
- }
4040
- default: return [];
4041
- }
4042
- }
4043
- /** The directory of sessions for a working directory, or undefined. */
4044
- async function cwdDir(root, cwd) {
4045
- const direct = join(root, encodeCwdDirname(cwd));
4046
- if (await stat(direct).then((s) => s.isDirectory(), () => false)) return direct;
4047
- let names;
4048
- try {
4049
- names = await readdir(root);
4050
- } catch {
4051
- return;
4052
- }
4053
- for (const name of names) {
4054
- const dir = join(root, name);
4055
- if ((await readText(join(dir, ".cwd")))?.trim() === cwd) return dir;
4056
- }
4057
- }
4058
- /** Find the chat_history.jsonl for a session, or the reason there is none. */
4059
- async function locateGrokHistory(q, env) {
4060
- const dir = await cwdDir(join(grokHome(env), "sessions"), q.cwd);
4061
- if (dir === void 0) return { error: "no Grok sessions for this working directory" };
4062
- if (q.cliSessionId && /^[A-Za-z0-9_-]{1,200}$/.test(q.cliSessionId)) {
4063
- const path = join(dir, q.cliSessionId, "chat_history.jsonl");
4064
- if (await stat(path).then(() => true, () => false)) return { path };
4065
- }
4066
- const since = Date.parse(q.startedAt);
4067
- const floor = Number.isFinite(since) ? since - 5e3 : 0;
4068
- let best;
4069
- for (const e of await entriesNewestFirst(dir)) {
4070
- if (!e.dir) continue;
4071
- const path = join(e.path, "chat_history.jsonl");
4072
- const s = await stat(path).catch(() => void 0);
4073
- if (s && s.mtimeMs >= floor && (!best || s.mtimeMs > best.mtimeMs)) best = {
4074
- path,
4075
- mtimeMs: s.mtimeMs
4076
- };
4077
- }
4078
- if (best) return { path: best.path };
4079
- return { error: "no Grok session in this working directory since it started" };
4080
- }
4081
- const grokTranscript = { async read(q, env) {
4082
- try {
4083
- const found = await locateGrokHistory(q, env);
4084
- if ("error" in found) return notFound("Grok", found.error);
4085
- const { entries, more } = await tailJsonl(found.path, q.lastTurns, parseGrokItem);
4086
- return {
4087
- ok: true,
4088
- entries,
4089
- more
4090
- };
4091
- } catch (e) {
4092
- return notFound("Grok", e instanceof Error ? e.message : "read failed");
4093
- }
4094
- } };
4095
- // ../daemon/src/transcripts.ts
4096
- /**
4097
- * The transcript reader of each CLI the daemon can peek into. A CLI missing here answers
4098
- * "peek not supported for <cli> yet". Cursor and Antigravity are listed with the reason, so the
4099
- * message says why.
4100
- */
4101
- function defaultTranscriptReaders() {
4102
- return {
4103
- claude: claudeTranscript,
4104
- codex: codexTranscript,
4105
- opencode: openCodeTranscript,
4106
- copilot: copilotTranscript,
4107
- grok: grokTranscript,
4108
- cursor: unsupportedTranscript("cursor", "its chat storage is not documented"),
4109
- antigravity: unsupportedTranscript("antigravity", "its conversation store is not documented")
4110
- };
4111
- }
4112
3054
  // ../daemon/src/bin.ts
4113
3055
  async function main() {
4114
3056
  const handle = await startDaemon({
4115
3057
  dataDir: dataDir(process.platform, process.env, homedir()),
4116
- transcripts: defaultTranscriptReaders(),
3058
+ wakers: { codex: codexAdapter.daemonWake },
4117
3059
  onIdleExit: () => {
4118
3060
  process.stderr.write("convenod: no sessions for a while, exiting.\n");
4119
3061
  process.exit(0);