@conveno/cli 0.2.0-rc.5 → 0.2.0-rc.7

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.
Files changed (33) hide show
  1. package/README.md +22 -30
  2. package/dist/acp-9pRRszwU.js +82 -0
  3. package/dist/agy-relay-C-nqvieJ.js +137 -0
  4. package/dist/args-C7Agak9f.js +321 -0
  5. package/dist/bin.js +2 -2
  6. package/dist/{ctx-CDLE-2f2.js → ctx-tYftvhz_.js} +2 -3
  7. package/dist/daemon.js +410 -1423
  8. package/dist/daemonError-DNAKEyRT.js +66 -0
  9. package/dist/{dist-TrWRppjR.js → dist-D2hMvcZu.js} +592 -1216
  10. package/dist/dist-D9Gu-mQm.js +547 -0
  11. package/dist/dist-DOGlDbRb.js +504 -0
  12. package/dist/{dist-BPPOKmbH.js → dist-DOKVrSIw.js} +39 -148
  13. package/dist/dist-Dd31Fg0h.js +671 -0
  14. package/dist/{dist-CEJ2-wxh.js → dist-ftx5RNCp.js} +4 -17
  15. package/dist/{dist-E3XvoT1Q.js → dist-iFaY42Bs.js} +1 -1
  16. package/dist/{doctor-CzIGTeNT.js → doctor-BYa-MApu.js} +109 -102
  17. package/dist/fmt-C2SsP5Y0.js +96 -0
  18. package/dist/{hook-CLB_muZS.js → hook-CQeSn-w4.js} +7 -5
  19. package/dist/hook-entry-BXmSN--S.js +2490 -0
  20. package/dist/hook-entry-CgiSN-Oj.js +1 -0
  21. package/dist/main-seh-HPZO.js +971 -0
  22. package/dist/pick-DoyocW55.js +9 -0
  23. package/dist/{run-CYH0CRbp.js → run-B-WfNtCX.js} +627 -1998
  24. package/dist/{runtime-B1Pb9Qqg.js → runtime-Bnjh9BQ8.js} +119 -210
  25. package/dist/{dist-C8JRuLiZ.js → toml-patch-DGzVRdd1.js} +20 -1890
  26. package/dist/watch-Dr2RdyGo.js +185 -0
  27. package/package.json +15 -15
  28. package/dist/acp-BD7Oaerg.js +0 -142
  29. package/dist/args-BRB8QEQM.js +0 -554
  30. package/dist/dist-DcmKjrmu.js +0 -271
  31. package/dist/hook-entry-BlvSoNMm.js +0 -1289
  32. package/dist/hook-entry-CRDh36pe.js +0 -1
  33. package/dist/main-CsCsyq2G.js +0 -1645
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-DOGlDbRb.js";
4
+ import { $ as jwtClaim, $t as EVENT_NAMES, A as daemonProof, At as resolveRecipient, B as evaluateLiveness, Cn as safeParse, Et as requeueEntries, F as detectRepo, G as formatHookContext, Ht as takeWithinChars, J as holderAfterDeparture, Kt as validateRename, M as dataPaths, N as decideAutoContinue, O as createWmiWalker, P as defaultProcessIo, Q as isOnline, Qt as DeviceId, R as effectiveHolder, S as claimOrchestrator, Sn as parseRelayFrame, T as clientProof, Tn as socketPathTooLongMessage, Ut as tooManyUnreadMessage, Vt as takeWithinBytes, W as formatContinuation, Wt as turnHops, _n as makeResult, _t as readAccountTokens, an as PROTOCOL_VERSION, b as baseName, bn as newSessionId, bt as readInbox, dn as defaultSocketPath, fn as encodeFrame, gn as makeEventNotification, hn as makeError, ht as proofsMatch, in as OWNER_SESSION_ID, j as dataDir, k as currentAccessToken, l as RESPONSE_BUDGET_BYTES, ln as SessionId, lt as pendingForInjection, mn as isSocketPathTooLong, n as AccountError, nn as Message, nt as markDelivered, on as RelayPayload, p as ackEntries, pt as planSpawn, q as generateSessionName, r as ConvenoError, rt as newAuthNonce, sn as RpcErrorCode, un as createLineDecoder, v as autoCandidates, vn as newDeviceId, vt as readAncestry, w as clearOrchestrator, wn as sanitizeLine, x as bindAccountDevice, xn as parseIpcRequest, y as autoLimitsFromEnv, yn as newMessageId, zt as statusAfterLiveness } from "./dist-D2hMvcZu.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-iFaY42Bs.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,27 @@ 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.7";
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
+ /** A wake still not a turn after this long counts as unread in status (see `stalledWoken`). */
1965
+ const WOKEN_STALL_MS = 3e4;
1966
+ const WAKE_RETRY_MAX_MS = 3e5;
2691
1967
  /** Sender id on `system` messages made by the daemon itself (no session sent them). */
2692
1968
  const DAEMON_SENDER_ID = SessionId.parse("0".repeat(26));
2693
1969
  const CLI_TIER = {
@@ -2697,11 +1973,6 @@ const CLI_TIER = {
2697
1973
  copilot: "next_turn",
2698
1974
  antigravity: "next_turn"
2699
1975
  };
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
1976
  var Daemon = class {
2706
1977
  store;
2707
1978
  token;
@@ -2712,27 +1983,43 @@ var Daemon = class {
2712
1983
  requestShutdown;
2713
1984
  log;
2714
1985
  authTimeoutMs;
2715
- pathExists;
2716
1986
  autoLimits;
2717
- transcripts;
2718
- transcriptEnv;
2719
1987
  processIo;
2720
- notifier;
1988
+ platform;
1989
+ wakers;
2721
1990
  conns = /* @__PURE__ */ new Set();
2722
1991
  /** Reaches the owner's other devices; set by startDaemon unless disabled. */
2723
1992
  relay;
2724
1993
  deviceId;
2725
- /** The newest idle-wake listener of each session, and the ids it replaced. In memory only. */
1994
+ /**
1995
+ * The newest idle-wake listener of each session, the ids it replaced, and the connection it
1996
+ * asked on. The session counts as wakeable while that connection is open. In memory only.
1997
+ */
2726
1998
  listeners = /* @__PURE__ */ new Map();
1999
+ /**
2000
+ * Messages the last wake handed each session, until its turn starts or ends. A requeue of
2001
+ * these makes the session idle again. In memory only.
2002
+ */
2003
+ woken = /* @__PURE__ */ new Map();
2004
+ /** Sessions a daemon waker is working on, so one session gets one wake at a time. */
2005
+ daemonWaking = /* @__PURE__ */ new Set();
2006
+ /** Daemon wakes to try again (after \`failed\` or the wake limit), by session. In memory only. */
2007
+ wakeRetry = /* @__PURE__ */ new Map();
2008
+ /** Set when the daemon shuts down: closing connections must not touch the store any more. */
2009
+ stopping = false;
2010
+ /**
2011
+ * Sessions whose daemon waker answered \`unsupported\` (no \`queue\` in that binary, an ephemeral
2012
+ * thread): not asked again for them while the daemon runs, so a new daemon checks afresh. Other
2013
+ * sessions of the same CLI are still woken.
2014
+ */
2015
+ wakersOff = /* @__PURE__ */ new Set();
2016
+ /** When each session's last daemon wake was handed over, to tell a wake that never became a turn. */
2017
+ wokenAt = /* @__PURE__ */ new Map();
2727
2018
  idleSince;
2728
2019
  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) {
2020
+ /** When each session went offline, for the removal grace. In memory only. */
2021
+ offlineSince = /* @__PURE__ */ new Map();
2022
+ constructor(store, token, now, isAlive, idleExitMs, requestIdleExit, requestShutdown, log, authTimeoutMs = AUTH_TIMEOUT_MS, autoLimits = autoLimitsFromEnv({}), processIo = defaultProcessIo, platform = process.platform, wakers = {}) {
2736
2023
  this.store = store;
2737
2024
  this.token = token;
2738
2025
  this.now = now;
@@ -2742,31 +2029,15 @@ var Daemon = class {
2742
2029
  this.requestShutdown = requestShutdown;
2743
2030
  this.log = log;
2744
2031
  this.authTimeoutMs = authTimeoutMs;
2745
- this.pathExists = pathExists;
2746
2032
  this.autoLimits = autoLimits;
2747
- this.transcripts = transcripts;
2748
- this.transcriptEnv = transcriptEnv;
2749
2033
  this.processIo = processIo;
2750
- this.notifier = notifier;
2034
+ this.platform = platform;
2035
+ this.wakers = wakers;
2751
2036
  this.deviceId = store.deviceId();
2752
2037
  this.startedMs = now().getTime();
2753
2038
  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
2039
  }
2766
2040
  iso = () => this.now().toISOString();
2767
- closeNotifier() {
2768
- this.notifier.close();
2769
- }
2770
2041
  attach(socket) {
2771
2042
  const conn = {
2772
2043
  socket,
@@ -2785,6 +2056,7 @@ var Daemon = class {
2785
2056
  socket.on("close", () => {
2786
2057
  clearTimeout(authTimer);
2787
2058
  this.conns.delete(conn);
2059
+ this.listenerGone(conn);
2788
2060
  });
2789
2061
  socket.on("error", () => socket.destroy());
2790
2062
  }
@@ -2846,33 +2118,22 @@ var Daemon = class {
2846
2118
  case "session.rename": return this.rename(req.params);
2847
2119
  case "session.setStatus": return this.setStatus(req.params);
2848
2120
  case "session.list": return this.list(req.params);
2849
- case "session.byHost": return this.byHost(req.params.pid, req.params.cwd);
2121
+ case "session.byHost": return this.byHost(req.params);
2850
2122
  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);
2123
+ case "session.setNative": return this.setNative(req.params);
2853
2124
  case "turn.start": return this.turnStart(req.params.sessionId);
2854
2125
  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);
2126
+ case "turn.wake": return this.turnWake(conn, req.params);
2859
2127
  case "daemon.shutdown": return { ok: true };
2860
2128
  case "orchestrator.claim": return this.claim(req.params.sessionId);
2129
+ case "orchestrator.clear": return this.clearLead(conn);
2861
2130
  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
2131
  case "owner.send": return this.ownerSend(conn, req.params);
2866
2132
  case "message.inbox": return this.inbox(req.params);
2867
2133
  case "message.deliver": return this.deliver(req.params);
2868
2134
  case "message.ack": return this.ack(req.params);
2135
+ case "message.requeue": return this.requeue(req.params);
2869
2136
  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
2137
  case "relay.status":
2877
2138
  case "devices.list":
2878
2139
  case "devices.pair":
@@ -2921,28 +2182,18 @@ var Daemon = class {
2921
2182
  if (row.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${row.name}" is offline. Register the session again.`);
2922
2183
  return row;
2923
2184
  }
2185
+ /** The wire view of a session. Its `deliveryTier` is the live one (`tierFor`). */
2924
2186
  view(row) {
2925
- return toSession(row, effectiveHolder(this.store.holder(), this.named([row]))?.id === row.id, this.store.unreadCount(row.id));
2187
+ const holder = effectiveHolder(this.store.holder(), this.named([row]));
2188
+ return toSession({
2189
+ ...row,
2190
+ deliveryTier: this.tierFor(row)
2191
+ }, holder?.id === row.id, this.store.unreadCount(row.id) + this.stalledWoken(row.id));
2926
2192
  }
2927
2193
  /** The orchestrator as routing sees it: the holder, if it is online. */
2928
2194
  orchestratorNow() {
2929
2195
  return effectiveHolder(this.store.holder(), this.named(this.store.allSessions()))?.id ?? null;
2930
2196
  }
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
2197
  emit(payload, onlyTo) {
2947
2198
  const only = onlyTo === void 0 || Array.isArray(onlyTo) ? onlyTo : [onlyTo];
2948
2199
  for (const c of this.conns) {
@@ -2963,11 +2214,13 @@ var Daemon = class {
2963
2214
  });
2964
2215
  this.relay?.sessionsChanged();
2965
2216
  }
2217
+ /** Every message that lands in a local mailbox goes through here. */
2966
2218
  emitMessage(m, recipient) {
2967
2219
  this.emit({
2968
2220
  event: "message.received",
2969
2221
  data: { message: m }
2970
2222
  }, recipient);
2223
+ this.daemonWake(recipient);
2971
2224
  }
2972
2225
  async detect(p) {
2973
2226
  if (p.repo) return p.repo;
@@ -2992,8 +2245,6 @@ var Daemon = class {
2992
2245
  deliveryTier: p.acp ? "acp" : CLI_TIER[p.cli] ?? "inbox",
2993
2246
  spawned: p.spawned,
2994
2247
  spawnDepth: parent ? parent.spawnDepth + 1 : 0,
2995
- auto: p.auto ?? (p.spawned || p.spawnedBy !== void 0),
2996
- autoExplicit: false,
2997
2248
  autoRuns: [],
2998
2249
  turnHops: 0,
2999
2250
  startedAt: at,
@@ -3030,6 +2281,7 @@ var Daemon = class {
3030
2281
  status: "idle",
3031
2282
  lastSeenAt: at
3032
2283
  });
2284
+ this.offlineSince.delete(sessionId);
3033
2285
  this.emitSession(sessionId, "updated");
3034
2286
  return { lastSeenAt: at };
3035
2287
  }
@@ -3041,6 +2293,8 @@ var Daemon = class {
3041
2293
  if (after !== before) this.store.setHolder(after);
3042
2294
  });
3043
2295
  this.listeners.delete(sessionId);
2296
+ this.woken.delete(sessionId);
2297
+ this.offlineSince.set(sessionId, this.now().getTime());
3044
2298
  this.emitSession(sessionId, change);
3045
2299
  if (after !== before) this.emit({
3046
2300
  event: "orchestrator.changed",
@@ -3079,7 +2333,7 @@ var Daemon = class {
3079
2333
  }
3080
2334
  list(p) {
3081
2335
  const rows = this.store.allSessions().filter((r) => {
3082
- if (!p.includeOffline && r.status === "offline") return false;
2336
+ if (r.status === "offline" && !p.includeOffline) return false;
3083
2337
  if (p.cli && r.cli !== p.cli) return false;
3084
2338
  if (p.repo && r.repoRoot !== p.repo && baseName(r.repoRoot ?? r.cwd) !== p.repo) return false;
3085
2339
  return true;
@@ -3095,15 +2349,33 @@ var Daemon = class {
3095
2349
  * Exact equality only, with no walk to farther ancestors, so a hook from a CLI that has no
3096
2350
  * session matches nothing. Two sessions under one CLI process are ambiguous, so the result is
3097
2351
  * 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
2352
+ * those registered in the same folder (separators, trailing slash, case
3099
2353
  * on Windows), so several folders on one OpenCode 2.x server stay apart. Two sessions in one
3100
2354
  * folder still match nothing.
3101
2355
  */
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)));
2356
+ byHost(p) {
2357
+ const { pid, cwd, nativeId } = p;
2358
+ const rows = this.store.allSessions().filter((r) => p.includeOffline || r.status !== "offline");
2359
+ const live = (list) => {
2360
+ const online = list.filter((r) => r.status !== "offline");
2361
+ return online.length > 0 ? online : list;
2362
+ };
2363
+ if (nativeId !== void 0) {
2364
+ const own = live(rows.filter((r) => r.nativeId === nativeId))[0];
2365
+ if (!own) return { session: null };
2366
+ const pids = [...own.hostPid === void 0 ? [] : [own.hostPid], ...own.hostPids ?? []];
2367
+ if (pids.length === 0 || pids.includes(pid)) return { session: this.view(own) };
2368
+ const mine = this.pidHolders(rows, pid, cwd, live);
2369
+ return { session: this.view(mine.length === 1 ? mine[0] : own) };
2370
+ }
2371
+ const holders = this.pidHolders(rows, pid, cwd, live);
3104
2372
  const only = holders.length === 1 ? holders[0] : void 0;
3105
2373
  return { session: only ? this.view(only) : null };
3106
2374
  }
2375
+ /** Sessions whose host is `pid` (in `cwd`, when given), online ones first. */
2376
+ pidHolders(rows, pid, cwd, live) {
2377
+ return live(rows.filter((r) => r.hostPid === pid && (cwd === void 0 || samePath(r.cwd, cwd, this.platform))));
2378
+ }
3107
2379
  /**
3108
2380
  * Walk up from a hook's parent pid to its host CLI, for a hook that would otherwise read the
3109
2381
  * process table itself. With no online session of the hook's CLI there is nothing the hook could
@@ -3129,122 +2401,41 @@ var Daemon = class {
3129
2401
  };
3130
2402
  }
3131
2403
  /**
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.
2404
+ * A hook records the CLI's own id for its session. One online session holds an id at a time,
2405
+ * so a CLI that reuses an id for a new session (a resumed thread) moves it there.
3138
2406
  */
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
2407
+ setNative(p) {
2408
+ const row = this.requireOnline(p.sessionId);
2409
+ if (row.nativeId === p.nativeId) return { session: this.view(row) };
2410
+ const others = this.store.allSessions().filter((r) => r.id !== row.id && r.nativeId === p.nativeId);
2411
+ this.store.tx(() => {
2412
+ for (const o of others) this.store.updateSession(o.id, { nativeId: null });
2413
+ this.store.updateSession(row.id, { nativeId: p.nativeId });
3151
2414
  });
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
- };
2415
+ for (const o of others) this.emitSession(o.id, "updated");
2416
+ this.emitSession(row.id, "updated");
2417
+ this.daemonWake(row.id);
2418
+ return { session: this.view(this.requireSession(row.id)) };
3229
2419
  }
3230
- forgetRows(rows) {
3231
- if (rows.length === 0) return;
2420
+ /** Delete offline sessions and their mail. \`graceMs\` 0 removes every one at once. */
2421
+ removeOffline(graceMs) {
2422
+ const nowMs = this.now().getTime();
2423
+ const gone = this.store.allSessions().filter((r) => {
2424
+ if (r.status !== "offline") return false;
2425
+ const since = this.offlineSince.get(r.id) ?? Date.parse(r.lastSeenAt);
2426
+ return nowMs - since >= graceMs;
2427
+ });
2428
+ if (gone.length === 0) return;
3232
2429
  this.store.tx(() => {
3233
- for (const r of rows) this.store.deleteSession(r.id);
2430
+ for (const r of gone) this.store.deleteSession(r.id);
3234
2431
  });
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);
2432
+ for (const r of gone) {
2433
+ this.listeners.delete(r.id);
2434
+ this.woken.delete(r.id);
2435
+ this.wokenAt.delete(r.id);
2436
+ this.wakersOff.delete(r.id);
2437
+ this.offlineSince.delete(r.id);
2438
+ }
3248
2439
  }
3249
2440
  claim(sessionId) {
3250
2441
  this.requireSession(sessionId);
@@ -3289,6 +2480,44 @@ var Daemon = class {
3289
2480
  previous: res.previous
3290
2481
  };
3291
2482
  }
2483
+ clearLead(conn) {
2484
+ this.requireCli(conn, "clear the lead");
2485
+ const holder = this.store.holder();
2486
+ const res = clearOrchestrator(holder, this.named(this.store.allSessions()));
2487
+ const at = this.iso();
2488
+ const sent = [];
2489
+ this.store.tx(() => {
2490
+ this.store.setHolder(null);
2491
+ for (const n of res.notices) {
2492
+ const m = {
2493
+ id: newMessageId(),
2494
+ from: DAEMON_SENDER_ID,
2495
+ to: n.to,
2496
+ kind: "system",
2497
+ body: {
2498
+ event: n.event,
2499
+ detail: n.detail
2500
+ },
2501
+ urgent: false,
2502
+ createdAt: at
2503
+ };
2504
+ this.store.insertMessage(m, n.to, at);
2505
+ sent.push(m);
2506
+ }
2507
+ });
2508
+ if (holder !== null) {
2509
+ this.emit({
2510
+ event: "orchestrator.changed",
2511
+ data: {
2512
+ orchestrator: null,
2513
+ previous: holder
2514
+ }
2515
+ });
2516
+ if (res.previous) this.emitSession(res.previous, "updated");
2517
+ for (const m of sent) this.emitMessage(m, m.to);
2518
+ }
2519
+ return { previous: res.previous };
2520
+ }
3292
2521
  sendMessage(p) {
3293
2522
  const sender = this.requireSession(p.sessionId);
3294
2523
  if (sender.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${sender.name}" is offline. Register the session again before sending.`);
@@ -3305,9 +2534,8 @@ var Daemon = class {
3305
2534
  return to === "you" || to === OWNER_SESSION_ID;
3306
2535
  }
3307
2536
  /**
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.
2537
+ * Route one message from \`sender\` (a session, or the owner) to a session, or to a session on
2538
+ * another device. The owner is not a session and has no inbox: a session cannot message \`you\`.
3311
2539
  */
3312
2540
  deliverFrom(sender, p) {
3313
2541
  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 +2553,19 @@ var Daemon = class {
3325
2553
  ...sender.cli !== void 0 ? { fromCli: sender.cli } : {},
3326
2554
  ...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
3327
2555
  });
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
- }
2556
+ 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
2557
  let target;
3350
2558
  try {
3351
2559
  target = resolveRecipient(p.to, this.named(rows), this.store.holder());
3352
2560
  } catch (e) {
3353
2561
  const remote = e instanceof ConvenoError && e.code === RpcErrorCode.NotFound ? this.relay?.resolveRemote(p.to) : void 0;
3354
2562
  if (!remote) throw e;
3355
- return this.sendToRemote(make(p.to), remote);
2563
+ return this.sendToRemote(make(p.to), remote, sender.hops);
3356
2564
  }
3357
2565
  const targetRow = rows.find((r) => r.id === target.id);
3358
2566
  if (this.store.unreadCount(targetRow.id) >= 1e3) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(targetRow.name, MAX_UNREAD_PER_SESSION));
3359
2567
  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
- }
2568
+ this.store.insertMessage(message, targetRow.id, at, sender.hops);
3369
2569
  this.emitMessage(message, targetRow.id);
3370
2570
  return {
3371
2571
  message,
@@ -3379,35 +2579,8 @@ var Daemon = class {
3379
2579
  requireCli(conn, what) {
3380
2580
  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
2581
  }
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
2582
  ownerSend(conn, p) {
3401
2583
  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
2584
  return this.deliverFrom({
3412
2585
  id: OWNER_SESSION_ID,
3413
2586
  name: "you",
@@ -3420,174 +2593,238 @@ var Daemon = class {
3420
2593
  ...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
3421
2594
  });
3422
2595
  }
3423
- /** `live` for a session in auto mode whose CLI can be woken; otherwise the CLI's own tier. */
2596
+ /**
2597
+ * \`acp\` for an ACP host. \`live\` while something can wake the session: a listener's connection
2598
+ * is open, or the session is busy in a turn a listener's CLI ends with its own hook (it continues
2599
+ * with what waits, then arms a new listener), or a daemon waker can reach it. Otherwise the CLI's
2600
+ * own tier.
2601
+ */
3424
2602
  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";
2603
+ if (row.deliveryTier === "acp") return "acp";
2604
+ if (this.listenerConnected(row.id)) return "live";
2605
+ if (row.status === "busy" && this.listeners.has(row.id)) return "live";
2606
+ if (this.daemonWakerFor(row)) return "live";
3428
2607
  return row.deliveryTier;
3429
2608
  }
2609
+ listenerConnected(id) {
2610
+ const conn = this.listeners.get(id)?.conn;
2611
+ return conn !== void 0 && this.conns.has(conn) && !conn.socket.destroyed;
2612
+ }
2613
+ /** A connection closed: a listener that asked on it no longer makes its session wakeable. */
2614
+ listenerGone(conn) {
2615
+ if (this.stopping) return;
2616
+ for (const [id, rec] of this.listeners) {
2617
+ if (rec.conn !== conn) continue;
2618
+ rec.conn = void 0;
2619
+ this.emitSession(id, "updated");
2620
+ }
2621
+ }
2622
+ daemonWakerFor(row) {
2623
+ if (row.nativeId === void 0 || this.wakersOff.has(row.id)) return void 0;
2624
+ return this.wakers[row.cli];
2625
+ }
3430
2626
  /**
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.
2627
+ * A message landed for \`id\`. When its CLI has a daemon waker, no listener is connected and the
2628
+ * session is idle, hand the waiting messages to the waker (under the wake limit, like
2629
+ * \`turn.wake\`, and under \`DAEMON_WAKE_BYTES\`, since they go on a command line). \`queued\`
2630
+ * and \`unknown\` keep them delivered (a wake that timed out may have landed: a requeue could
2631
+ * deliver them twice). \`failed\` and \`unsupported\` put them back; after \`failed\` or the wake
2632
+ * limit, the sweep tries again with a growing delay. One wake per session at a time.
3434
2633
  */
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
- }
2634
+ daemonWake(id) {
2635
+ if (this.daemonWaking.has(id)) return;
2636
+ const row = this.store.getSession(id);
2637
+ const wake = row?.status === "idle" && !this.listenerConnected(id) && this.daemonWakerFor(row);
2638
+ if (!row || !wake) {
2639
+ this.wakeRetry.delete(id);
2640
+ return;
3451
2641
  }
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 } : {}
2642
+ const d = this.continueWith(row, true, false, DAEMON_WAKE_BYTES);
2643
+ if (d.messages.length === 0) {
2644
+ const queued = this.store.entries(id, { states: ["queued"] });
2645
+ if (autoCandidates(queued, id).length > 0) this.scheduleWakeRetry(id);
2646
+ else this.wakeRetry.delete(id);
2647
+ return;
2648
+ }
2649
+ this.markWoken(id, d.messages);
2650
+ this.daemonWaking.add(id);
2651
+ const text = formatContinuation(d.messages, d.orchestrator, d.remaining);
2652
+ const session = this.view(this.requireSession(id));
2653
+ (async () => {
2654
+ let outcome;
2655
+ try {
2656
+ outcome = await wake({
2657
+ session,
2658
+ text,
2659
+ messages: d.messages,
2660
+ ...row.nativeId !== void 0 ? { nativeId: row.nativeId } : {}
2661
+ });
2662
+ } catch (e) {
2663
+ this.log.error(`${row.cli} waker failed`, e);
2664
+ outcome = "failed";
2665
+ }
2666
+ this.daemonWaking.delete(id);
2667
+ if (outcome === "queued" || outcome === "unknown" || this.stopping) {
2668
+ this.wakeRetry.delete(id);
2669
+ return;
2670
+ }
2671
+ if (outcome === "unsupported") {
2672
+ this.wakeRetry.delete(id);
2673
+ this.wakersOff.add(row.id);
2674
+ this.relay?.sessionsChanged();
2675
+ }
2676
+ if (this.store.getSession(id)?.status === "offline") {
2677
+ this.wakeRetry.delete(id);
2678
+ return;
2679
+ }
2680
+ this.requeueFor(id, d.messages.map((m) => m.id));
2681
+ if (outcome === "failed") this.scheduleWakeRetry(id);
2682
+ })();
2683
+ }
2684
+ /** Try a daemon wake of \`id\` again later, each time waiting twice as long, up to a cap. */
2685
+ scheduleWakeRetry(id) {
2686
+ const delayMs = Math.min((this.wakeRetry.get(id)?.delayMs ?? 0) * 2 || WAKE_RETRY_MS, WAKE_RETRY_MAX_MS);
2687
+ this.wakeRetry.set(id, {
2688
+ atMs: this.now().getTime() + delayMs,
2689
+ delayMs
2690
+ });
2691
+ }
2692
+ /** Run the daemon wakes whose retry is due. Called by the sweep. */
2693
+ retryDaemonWakes(nowMs) {
2694
+ for (const [id, r] of [...this.wakeRetry]) if (r.atMs <= nowMs) this.daemonWake(id);
2695
+ }
2696
+ markWoken(id, messages) {
2697
+ this.woken.set(id, new Set(messages.map((m) => m.id)));
2698
+ this.wokenAt.set(id, this.now().getTime());
2699
+ }
2700
+ /**
2701
+ * Messages a wake handed over that no turn took up: the CLI accepted them but the turn never
2702
+ * started (Codex keeps queued input while a turn is interrupted). Counted as unread so status
2703
+ * shows them. A turn start or end clears \`woken\`.
2704
+ */
2705
+ stalledWoken(id) {
2706
+ const at = this.wokenAt.get(id);
2707
+ if (at === void 0 || this.now().getTime() - at < WOKEN_STALL_MS) return 0;
2708
+ return this.woken.get(id)?.size ?? 0;
2709
+ }
2710
+ /**
2711
+ * Delivered messages go back to queued. When they are from the last wake and that wake made the
2712
+ * session busy, the wake never became a turn: the session is idle again and the wake does not
2713
+ * count against the limit.
2714
+ */
2715
+ requeue(p) {
2716
+ this.requireSession(p.sessionId);
2717
+ return this.requeueFor(p.sessionId, p.ids);
2718
+ }
2719
+ requeueFor(id, ids) {
2720
+ const woken = this.woken.get(id);
2721
+ const fromWake = woken !== void 0 && ids.some((m) => woken.has(m));
2722
+ const res = this.store.tx(() => {
2723
+ const r = requeueEntries(this.store.entries(id, { ids: [...ids] }), ids);
2724
+ for (const e of r.changed) this.store.saveEntry(id, e);
2725
+ const row = this.requireSession(id);
2726
+ const idle = fromWake && r.changed.length > 0 && row.status === "busy";
2727
+ if (idle) this.store.updateSession(id, {
2728
+ status: "idle",
2729
+ turnHops: 0,
2730
+ autoRuns: row.autoRuns.slice(0, -1)
3466
2731
  });
3467
- if (lift) this.store.resetQueuedHops(row.id);
2732
+ return {
2733
+ requeued: r.changed.length,
2734
+ idle
2735
+ };
3468
2736
  });
3469
- this.emitSession(row.id, "updated");
3470
- return { session: this.view(this.requireSession(row.id)) };
2737
+ if (fromWake) this.woken.delete(id);
2738
+ if (res.idle) this.emitSession(id, "updated");
2739
+ return { requeued: res.requeued };
3471
2740
  }
3472
2741
  /**
3473
2742
  * 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
2743
  */
3476
2744
  turnStart(sessionId) {
3477
- this.requireOnline(sessionId);
3478
- this.store.updateSession(sessionId, {
2745
+ const row = this.requireOnline(sessionId);
2746
+ const fromWake = this.woken.has(sessionId) && row.status === "busy";
2747
+ this.woken.delete(sessionId);
2748
+ this.store.updateSession(sessionId, fromWake ? { status: "busy" } : {
3479
2749
  status: "busy",
3480
2750
  turnHops: 0
3481
2751
  });
3482
2752
  this.emitSession(sessionId, "updated");
3483
2753
  return { session: this.view(this.requireSession(sessionId)) };
3484
2754
  }
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
2755
  /**
3504
- * Hand the session its waiting messages to continue with, if auto mode and its limit allow it.
2756
+ * Hand the session its waiting messages to continue with, if the wake limit allows it.
3505
2757
  * On a hand-over the session is busy and its turn carries the hops. With `endOfTurn`, nothing
3506
2758
  * handed over means the session is now idle. One transaction.
3507
2759
  */
3508
- continueWith(row, allow, endOfTurn) {
2760
+ continueWith(row, allow, endOfTurn, maxBytes = RESPONSE_BUDGET_BYTES, maxChars) {
3509
2761
  const nowMs = this.now().getTime();
3510
2762
  const at = this.iso();
3511
2763
  const orchestrator = this.orchestratorNow();
3512
- let pausedBy = row.autoPausedBy;
3513
- let notice;
3514
2764
  const res = this.store.tx(() => {
3515
2765
  const queued = this.store.entries(row.id, { states: ["queued"] });
3516
2766
  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);
2767
+ const decision = decideAutoContinue({ runs: row.autoRuns }, candidates, nowMs, this.autoLimits);
3523
2768
  if (decision.continue) {
3524
- const taken = takeWithinBytes(candidates.slice(0, 20), RESPONSE_BUDGET_BYTES);
2769
+ const fit = takeWithinBytes(candidates.slice(0, 20), maxBytes);
2770
+ const { taken, preview } = maxChars === void 0 ? { taken: fit } : takeWithinChars(fit, maxChars, (ms, cut) => formatContinuation(ms, orchestrator, queued.length - (cut ? 0 : ms.length)));
3525
2771
  const updated = markDelivered(taken, taken.map((e) => e.message.id), at);
3526
2772
  for (const e of updated) this.store.saveEntry(row.id, e);
3527
2773
  this.store.updateSession(row.id, {
3528
2774
  status: "busy",
3529
2775
  autoRuns: decision.runs,
3530
- turnHops: turnHops(taken)
2776
+ turnHops: turnHops(preview ? fit.slice(0, 1) : taken)
3531
2777
  });
2778
+ if (preview) return {
2779
+ messages: [preview],
2780
+ remaining: queued.length
2781
+ };
3532
2782
  return {
3533
2783
  messages: updated.map((e) => e.message),
3534
2784
  remaining: queued.length - taken.length
3535
2785
  };
3536
2786
  }
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
2787
  if (endOfTurn) this.store.updateSession(row.id, {
3547
2788
  status: "idle",
3548
2789
  turnHops: 0
3549
2790
  });
3550
2791
  return {
3551
2792
  messages: [],
3552
- remaining: queued.length + (notice ? 1 : 0)
2793
+ remaining: queued.length
3553
2794
  };
3554
2795
  });
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");
2796
+ if (res.messages.length > 0 ? row.status !== "busy" : endOfTurn && row.status !== "idle") this.emitSession(row.id, "updated");
3557
2797
  return {
3558
2798
  ...res,
3559
- auto: row.auto,
3560
- paused: pausedBy !== void 0,
3561
- ...pausedBy !== void 0 ? { pausedBy } : {},
3562
2799
  orchestrator
3563
2800
  };
3564
2801
  }
3565
2802
  turnEnd(p) {
3566
2803
  const row = this.requireOnline(p.sessionId);
2804
+ this.woken.delete(p.sessionId);
3567
2805
  if (row.status === "waiting_on_question") return this.continueWith(row, false, false);
3568
- return this.continueWith(row, p.allowContinue, true);
2806
+ return this.continueWith(row, p.allowContinue, true, RESPONSE_BUDGET_BYTES, p.maxChars);
3569
2807
  }
3570
2808
  /**
3571
2809
  * An idle-wake listener asks for work. The newest listener of a session wins: an older one gets
3572
2810
  * `superseded` and stops. A busy session is not woken; its messages wait for the end of the turn.
3573
2811
  */
3574
- turnWake(p) {
2812
+ turnWake(conn, p) {
3575
2813
  const row = this.requireOnline(p.sessionId);
3576
2814
  const known = this.listeners.get(row.id);
3577
2815
  if (known?.retired.includes(p.listenerId)) return {
3578
2816
  messages: [],
3579
2817
  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
2818
  orchestrator: this.orchestratorNow(),
3584
2819
  superseded: true
3585
2820
  };
2821
+ const wasConnected = this.listenerConnected(row.id);
3586
2822
  if (known?.current !== p.listenerId) {
3587
2823
  const retired = known ? [...known.retired, known.current].slice(-64) : [];
3588
2824
  this.listeners.set(row.id, {
3589
2825
  current: p.listenerId,
3590
- retired
2826
+ retired,
2827
+ conn
3591
2828
  });
3592
2829
  if (known) this.emit({
3593
2830
  event: "session.updated",
@@ -3596,9 +2833,12 @@ var Daemon = class {
3596
2833
  change: "updated"
3597
2834
  }
3598
2835
  }, row.id);
3599
- }
2836
+ } else known.conn = conn;
2837
+ if (!wasConnected) this.relay?.sessionsChanged();
2838
+ const d = this.continueWith(row, row.status === "idle", false, RESPONSE_BUDGET_BYTES, p.maxChars);
2839
+ if (d.messages.length > 0) this.markWoken(row.id, d.messages);
3600
2840
  return {
3601
- ...this.continueWith(row, row.status === "idle", false),
2841
+ ...d,
3602
2842
  superseded: false
3603
2843
  };
3604
2844
  }
@@ -3606,16 +2846,15 @@ var Daemon = class {
3606
2846
  this.requireSession(p.sessionId);
3607
2847
  return this.readInboxOf(p.sessionId, p.unreadOnly, p.limit);
3608
2848
  }
3609
- /** A mailbox's messages, oldest first, marked read. The owner's mailbox has no session row. */
3610
- readInboxOf(id, unreadOnly, limit, newest = false) {
2849
+ /** A mailbox's messages, oldest first, marked read. */
2850
+ readInboxOf(id, unreadOnly, limit) {
3611
2851
  const at = this.iso();
3612
2852
  return this.store.tx(() => {
3613
2853
  const entries = this.store.entries(id, unreadOnly ? { states: ["queued"] } : {});
3614
2854
  const res = readInbox(entries, {
3615
2855
  unreadOnly,
3616
2856
  limit,
3617
- maxBytes: RESPONSE_BUDGET_BYTES,
3618
- newest
2857
+ maxBytes: RESPONSE_BUDGET_BYTES
3619
2858
  }, at);
3620
2859
  const changed = new Set(res.returned.map((e) => e.message.id));
3621
2860
  for (const e of res.entries) if (changed.has(e.message.id)) this.store.saveEntry(id, e);
@@ -3630,9 +2869,14 @@ var Daemon = class {
3630
2869
  const at = this.iso();
3631
2870
  return this.store.tx(() => {
3632
2871
  const pending = pendingForInjection(this.store.entries(p.sessionId, { states: ["queued"] }));
3633
- const taken = takeWithinBytes(pending.slice(0, p.limit), RESPONSE_BUDGET_BYTES);
2872
+ const fit = takeWithinBytes(pending.slice(0, p.limit), RESPONSE_BUDGET_BYTES);
2873
+ const { taken, preview } = p.maxChars === void 0 ? { taken: fit } : takeWithinChars(fit, p.maxChars, (ms) => formatHookContext(ms));
3634
2874
  const updated = markDelivered(taken, taken.map((e) => e.message.id), at);
3635
2875
  for (const e of updated) this.store.saveEntry(p.sessionId, e);
2876
+ if (preview) return {
2877
+ messages: [preview],
2878
+ remaining: pending.length
2879
+ };
3636
2880
  return {
3637
2881
  messages: updated.map((e) => e.message),
3638
2882
  remaining: pending.length - taken.length
@@ -3679,8 +2923,8 @@ var Daemon = class {
3679
2923
  default: throw new ConvenoError(RpcErrorCode.MethodNotFound, `Method not found: ${req.method}`);
3680
2924
  }
3681
2925
  }
3682
- sendToRemote(message, target) {
3683
- this.relay.sendRemote(target, message);
2926
+ sendToRemote(message, target, hops) {
2927
+ this.relay.sendRemote(target, message, hops);
3684
2928
  return {
3685
2929
  message,
3686
2930
  delivery: target.deliveryTier,
@@ -3694,19 +2938,22 @@ var Daemon = class {
3694
2938
  relayHost() {
3695
2939
  return {
3696
2940
  log: this.log,
3697
- localSessions: () => this.store.allSessions().filter((r) => r.status !== "offline").map((r) => this.view(r)),
3698
- deliverLocal: (m, to) => {
2941
+ localSessions: () => this.store.allSessions().filter((r) => r.status !== "offline").map((r) => {
2942
+ const { nativeId: _n, ...s } = this.view(r);
2943
+ return s;
2944
+ }),
2945
+ deliverLocal: (m, to, hops = 0) => {
3699
2946
  if (m.kind === "system") return "not_allowed";
3700
2947
  const row = this.store.getSession(to);
3701
2948
  if (!row) return "session_gone";
3702
2949
  if (row.status === "offline") return "session_offline";
3703
2950
  if (this.store.hasMessage(m.id)) return void 0;
3704
2951
  if (this.store.unreadCount(row.id) >= 1e3) return "mailbox_full";
3705
- this.store.insertMessage(m, row.id, this.iso());
2952
+ this.store.insertMessage(m, row.id, this.iso(), hops);
3706
2953
  this.emitMessage(m, row.id);
3707
2954
  },
3708
2955
  notify: (to, event, detail) => {
3709
- if (to !== OWNER_SESSION_ID && !this.store.getSession(to)) return;
2956
+ if (!this.store.getSession(to)) return;
3710
2957
  const m = {
3711
2958
  id: newMessageId(),
3712
2959
  from: DAEMON_SENDER_ID,
@@ -3724,34 +2971,18 @@ var Daemon = class {
3724
2971
  }
3725
2972
  };
3726
2973
  }
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);
2974
+ /** Remove every offline session at once. The daemon does this when it starts. */
2975
+ removeAllOffline() {
2976
+ this.removeOffline(0);
3740
2977
  }
3741
2978
  sweep() {
3742
- this.tickets.sweep();
3743
2979
  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
- }
2980
+ this.removeOffline(OFFLINE_GRACE_MS);
2981
+ this.retryDaemonWakes(nowMs);
3748
2982
  let online = 0;
3749
2983
  const rows = this.store.allSessions();
3750
2984
  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
- }
2985
+ if (row.status === "offline") continue;
3755
2986
  const lastSeenMs = Math.max(Date.parse(row.lastSeenAt), this.startedMs);
3756
2987
  const verdict = evaluateLiveness({
3757
2988
  lastSeenMs,
@@ -3764,6 +2995,14 @@ var Daemon = class {
3764
2995
  else if (nowMs - this.idleSince >= this.idleExitMs) this.requestIdleExit();
3765
2996
  }
3766
2997
  };
2998
+ /** Do two directory paths name the same place, ignoring trailing separators (and case on Windows)? */
2999
+ function samePath(a, b, platform) {
3000
+ const norm = (p) => {
3001
+ const s = p.replace(/[\\/]+$/, "");
3002
+ return platform === "win32" ? s.replace(/\\/g, "/").toLowerCase() : s;
3003
+ };
3004
+ return norm(a) === norm(b);
3005
+ }
3767
3006
  const unauthorizedMessage = "Finish the handshake first: call hello, then auth. Both use the token in daemon.token in the Conveno data directory.";
3768
3007
  /** Start the relay client. A broken relay state is logged and leaves the daemon local-only. */
3769
3008
  function startRelay(daemon, opts, relayOpts) {
@@ -3808,10 +3047,8 @@ async function startDaemon(opts) {
3808
3047
  close().then(() => opts.onIdleExit?.());
3809
3048
  }, () => {
3810
3049
  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
- }));
3050
+ }, daemonLog, opts.authTimeoutMs ?? 5e3, opts.autoLimits ?? autoLimitsFromEnv(process.env), processIo, opts.platform, opts.wakers ?? {});
3051
+ daemon.removeAllOffline();
3815
3052
  const srv = createServer((socket) => daemon.attach(socket));
3816
3053
  server = srv;
3817
3054
  await new Promise((resolve, reject) => {
@@ -3826,8 +3063,8 @@ async function startDaemon(opts) {
3826
3063
  function close() {
3827
3064
  closing ??= (async () => {
3828
3065
  if (timer) clearInterval(timer);
3066
+ daemon.stopping = true;
3829
3067
  walker?.close();
3830
- daemon.closeNotifier();
3831
3068
  daemon.relay?.stop();
3832
3069
  const stopped = new Promise((resolve) => srv.close(() => resolve()));
3833
3070
  for (const c of daemon.conns) c.socket.destroy();
@@ -3845,7 +3082,10 @@ async function startDaemon(opts) {
3845
3082
  testRelay: {
3846
3083
  host: () => daemon.relayHost(),
3847
3084
  set: (relay) => {
3848
- daemon.relay = relay;
3085
+ daemon.relay = relay && {
3086
+ sessionsChanged: () => {},
3087
+ ...relay
3088
+ };
3849
3089
  }
3850
3090
  }
3851
3091
  };
@@ -3856,264 +3096,11 @@ async function startDaemon(opts) {
3856
3096
  throw e;
3857
3097
  }
3858
3098
  }
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
3099
  // ../daemon/src/bin.ts
4113
3100
  async function main() {
4114
3101
  const handle = await startDaemon({
4115
3102
  dataDir: dataDir(process.platform, process.env, homedir()),
4116
- transcripts: defaultTranscriptReaders(),
3103
+ wakers: { codex: codexAdapter.daemonWake },
4117
3104
  onIdleExit: () => {
4118
3105
  process.stderr.write("convenod: no sessions for a while, exiting.\n");
4119
3106
  process.exit(0);