@conveno/cli 0.2.0-rc.2 → 0.2.0-rc.3

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.
@@ -0,0 +1,142 @@
1
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { i as stopRequestPath, n as parseTurns, r as runAcpHostFromFile, t as killProcessTree } from "./dist-BiAm0SS8.js";
3
+ import { Ut as spawnRecordPath, jt as readSpawnRecord, m as acpTurnsPath } from "./dist-M9Gs7e_K.js";
4
+ import { i as parseFlags, l as fail, o as cmd, t as COMMANDS, u as localStamp } from "./args-DEYV4Ran.js";
5
+ // src/acp.ts
6
+ /** How long `conveno stop` waits for a worker to end by itself before it ends the process tree. */
7
+ const STOP_WAIT_MS = 1e4;
8
+ /** `conveno acp-host <launch file>`: what `conveno spawn --acp` runs in the background. Not for people. */
9
+ async function runAcpHostCmd(ctx, argv) {
10
+ const [file] = argv;
11
+ if (!file) return fail(ctx, {
12
+ what: "conveno acp-host needs a launch file",
13
+ detail: ["It is started by conveno spawn --acp."],
14
+ fix: `Run ${cmd(ctx.theme, "conveno spawn <cli> --acp")} instead.`,
15
+ exit: 2,
16
+ ref: "e_usage"
17
+ });
18
+ try {
19
+ return await runAcpHostFromFile(file, {
20
+ dataDir: ctx.dataDir,
21
+ ...ctx.socketPath ? { socketPath: ctx.socketPath } : {},
22
+ ...ctx.daemonEntry ? { daemonEntry: ctx.daemonEntry } : {}
23
+ });
24
+ } catch (e) {
25
+ return fail(ctx, {
26
+ what: "The ACP host could not start",
27
+ detail: [e instanceof Error ? e.message : String(e)],
28
+ fix: `Run ${cmd(ctx.theme, "conveno spawn <cli> --acp")} again.`,
29
+ exit: 1,
30
+ ref: "e_spawn"
31
+ });
32
+ }
33
+ }
34
+ function findWorker(ctx, name, command) {
35
+ if (!name) return fail(ctx, {
36
+ what: `conveno ${command} needs a worker name`,
37
+ fix: `Run ${cmd(ctx.theme, "conveno status")} to see the names.`,
38
+ exit: 2,
39
+ ref: "e_usage"
40
+ });
41
+ const rec = /^[a-z0-9][a-z0-9._@-]{0,63}$/.test(name) ? readSpawnRecord(spawnRecordPath(ctx.dataDir, name)) : void 0;
42
+ if (!rec) return fail(ctx, {
43
+ what: `No running worker named "${name}"`,
44
+ detail: ["Only sessions started by conveno spawn or spawn_session on this machine are workers."],
45
+ fix: `Run ${cmd(ctx.theme, "conveno status")} to see the names.`,
46
+ exit: 1,
47
+ ref: "e_not_found"
48
+ });
49
+ return rec;
50
+ }
51
+ /**
52
+ * `conveno stop <worker>`. An ACP worker gets a stop request: its host sends `session/cancel` for
53
+ * a running turn, ends the agent, reports to the spawner and takes the session offline. A headless
54
+ * one-shot run is ended. A worker in a terminal is the user's to close.
55
+ */
56
+ async function runStop(ctx, argv) {
57
+ const spec = COMMANDS.find((c) => c.name === "stop");
58
+ if (!spec) return 2;
59
+ const parsed = parseFlags(ctx, spec, argv);
60
+ if (typeof parsed === "number") return parsed;
61
+ const [name] = parsed.positionals;
62
+ const rec = findWorker(ctx, name, "stop");
63
+ if (typeof rec === "number") return rec;
64
+ const t = ctx.theme;
65
+ if (!rec.headless) return fail(ctx, {
66
+ what: `${rec.name} runs in a terminal`,
67
+ detail: ["Conveno does not close a terminal you can see."],
68
+ fix: "Exit the CLI in that terminal.",
69
+ exit: 1,
70
+ ref: "e_spawn"
71
+ });
72
+ const alive = () => rec.pid !== void 0 && ctx.isAlive(rec.pid);
73
+ if (rec.acp) {
74
+ writeFileSync(stopRequestPath(spawnRecordPath(ctx.dataDir, rec.name)), "", { mode: 384 });
75
+ const end = Date.now() + STOP_WAIT_MS;
76
+ while (alive() && Date.now() < end) await new Promise((r) => setTimeout(r, 100));
77
+ }
78
+ if (alive() && rec.pid !== void 0) killProcessTree(rec.pid, ctx.platform);
79
+ if (rec.agentPid !== void 0 && ctx.isAlive(rec.agentPid)) killProcessTree(rec.agentPid, ctx.platform);
80
+ ctx.out(`${t.status("ok")} ${t.bold(`Stopped ${rec.name}`)}\n`);
81
+ return 0;
82
+ }
83
+ const ROLE_LABEL = {
84
+ user: "prompt",
85
+ assistant: "agent",
86
+ tool: "tool",
87
+ system: "conveno"
88
+ };
89
+ /**
90
+ * `conveno attach <worker>`: print the recent turns of an ACP worker and follow new ones until it
91
+ * stops or Ctrl+C. Read-only: nothing typed here reaches the worker; message it with send instead.
92
+ */
93
+ async function runAttach(ctx, argv) {
94
+ const spec = COMMANDS.find((c) => c.name === "attach");
95
+ if (!spec) return 2;
96
+ const parsed = parseFlags(ctx, spec, argv);
97
+ if (typeof parsed === "number") return parsed;
98
+ const t = ctx.theme;
99
+ const [name] = parsed.positionals;
100
+ const rec = findWorker(ctx, name, "attach");
101
+ if (typeof rec === "number") return rec;
102
+ if (!rec.acp) return fail(ctx, {
103
+ what: `${rec.name} is not driven over ACP`,
104
+ detail: ["attach follows workers started with conveno spawn --acp."],
105
+ fix: "Watch it in its terminal, or read its log in the data folder.",
106
+ exit: 1,
107
+ ref: "e_spawn"
108
+ });
109
+ const linesFlag = parsed.values.lines;
110
+ const lines = typeof linesFlag === "string" ? Number(linesFlag) : 20;
111
+ if (!Number.isInteger(lines) || lines < 0) return fail(ctx, {
112
+ what: "--lines takes a whole number",
113
+ fix: `Run ${cmd(t, "conveno attach <worker> --lines 50")}.`,
114
+ exit: 2,
115
+ ref: "e_usage"
116
+ });
117
+ const path = acpTurnsPath(ctx.dataDir, rec.name);
118
+ const read = () => existsSync(path) ? parseTurns(readFileSync(path, "utf8")) : [];
119
+ const show = (e) => {
120
+ const head = t.paint("quiet", `${localStamp(e.at)} ${ROLE_LABEL[e.role]}`);
121
+ ctx.out(`${head}\n${e.text}\n\n`);
122
+ };
123
+ let last = 0;
124
+ const first = read();
125
+ for (const e of first.slice(-lines)) show(e);
126
+ last = first.at(-1)?.seq ?? 0;
127
+ if (parsed.values["no-follow"] === true) return 0;
128
+ ctx.err(t.paint("quiet", `Following ${rec.name}. Read-only; Ctrl+C to leave.\n`));
129
+ const record = spawnRecordPath(ctx.dataDir, rec.name);
130
+ for (;;) {
131
+ await new Promise((r) => setTimeout(r, 300));
132
+ for (const e of read()) if (e.seq > last) {
133
+ show(e);
134
+ last = e.seq;
135
+ }
136
+ if (!existsSync(record)) {
137
+ ctx.err(t.paint("quiet", `${rec.name} stopped.\n`));
138
+ return 0;
139
+ }
140
+ }
141
+ }
142
+ export { runAcpHostCmd, runAttach, runStop };
package/dist/bin.js CHANGED
@@ -9,7 +9,7 @@ import { join } from "node:path";
9
9
  * bundle and zod is most of the time a hook spends starting. Node checks each entry against the
10
10
  * file's contents and its own version, and a cache that cannot be written is ignored.
11
11
  */
12
- function useCompileCache() {
12
+ function startCompileCache() {
13
13
  if (process.env.NODE_DISABLE_COMPILE_CACHE || process.env.NODE_COMPILE_CACHE) return;
14
14
  try {
15
15
  const env = process.env;
@@ -17,7 +17,7 @@ function useCompileCache() {
17
17
  enableCompileCache(join(base, "conveno", "compile-cache"));
18
18
  } catch {}
19
19
  }
20
- useCompileCache();
20
+ startCompileCache();
21
21
  const argv = process.argv.slice(2);
22
22
  const isHook = argv[0] === "hook";
23
23
  for (const stream of [process.stdout, process.stderr]) stream.on("error", (err) => {
@@ -26,9 +26,9 @@ for (const stream of [process.stdout, process.stderr]) stream.on("error", (err)
26
26
  });
27
27
  try {
28
28
  let code;
29
- if (isHook) code = await (await import("./hook-entry-jDI9wAt-.js")).runHookEntry(argv.slice(1));
29
+ if (isHook) code = await (await import("./hook-entry-B8Iiwe99.js")).runHookEntry(argv.slice(1));
30
30
  else {
31
- const [{ main }, { createRuntimeCtx }] = await Promise.all([import("./main-DyHE7TAz.js"), import("./runtime-DPrz7M0s.js")]);
31
+ const [{ main }, { createRuntimeCtx }] = await Promise.all([import("./main-Cf0q06gR.js"), import("./runtime-BPG36vYD.js")]);
32
32
  code = await main(argv, createRuntimeCtx());
33
33
  }
34
34
  if (isHook) process.exit(code);
@@ -0,0 +1,18 @@
1
+ // src/ctx.ts
2
+ const adapterEnv = (ctx, opts = {}) => ({
3
+ home: ctx.home,
4
+ platform: ctx.platform,
5
+ cwd: ctx.cwd,
6
+ exec: ctx.exec,
7
+ conveno: ctx.conveno,
8
+ env: ctx.env,
9
+ ...opts.permissionRelay ? { permissionRelay: true } : {}
10
+ });
11
+ const connectOpts = (ctx, autoStart) => ({
12
+ kind: "cli",
13
+ dataDir: ctx.dataDir,
14
+ autoStart,
15
+ ...ctx.socketPath ? { socketPath: ctx.socketPath } : {},
16
+ ...ctx.daemonEntry ? { daemonEntry: ctx.daemonEntry } : {}
17
+ });
18
+ export { connectOpts as n, adapterEnv as t };
package/dist/daemon.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import { homedir, hostname, userInfo } from "node:os";
3
- import { $t as turnHops, A as currentAccessToken, An as encodeFrame, B as effectiveHolder, Bn as parseIpcRequest, C as claimOrchestrator, Ct as proofsMatch, E as clientProof, En as Ticket, Et as readAncestry, F as defaultProcessIo, Fn as makeResult, H as entriesNewestFirst, Hn as safeParse, Ht as samePath, I as describeToolCall, In as newDeviceId, Jt as tailJsonl, Kt as statusAfterLiveness, L as detectRepo, Ln as newMessageId, M as dataDir, Mn as isSocketPathTooLong, N as dataPaths, Nn as makeError, On as createLineDecoder, Ot as readHeadLine, P as decideAutoContinue, Pn as makeEventNotification, Q as holderAfterDeparture, Qt as tooManyUnreadMessage, Rn as newSessionId, Rt as resolveRecipient, S as bindAccountDevice, T as classifyPermission, Tt as readAccountTokens, U as evaluateLiveness, Un as sanitizeLine, Vn as parseRelayFrame, Wn as socketPathTooLongMessage, Xt as takeWithinBytes, Z as generateSessionName, Zt as toIso, _ as asString, _n as PROTOCOL_VERSION, _t as pendingForInjection, at as jwtClaim, b as autoLimitsFromEnv, cn as DeviceId, ct as markDelivered, d as ackEntries, dt as notFound, en as unsupportedTranscript, fn as HUMAN_ANSWERER, gn as PERMISSION_ANSWERS, gt as pauseLabel, hn as ORCHESTRATOR_ALIAS, j as daemonProof, k as createWmiWalker, kn as defaultSocketPath, kt as readInbox, ln as EVENT_NAMES, lt as nameMatchesPattern, n as AccountError, nn as validateRename, p as acpTranscript, pn as Message, r as ConvenoError, rt as isRecord, s as RESPONSE_BUDGET_BYTES, tt as isOnline, ut as newAuthNonce, vn as RelayPayload, x as baseName, xn as SessionId, xt as planSpawn, y as autoCandidates, yn as RpcErrorCode, zn as newTicketId } from "./dist-_sq6DmrE.js";
3
+ import { $t as turnHops, A as currentAccessToken, An as defaultSocketPath, B as effectiveHolder, Bn as newTicketId, C as claimOrchestrator, Ct as proofsMatch, Dn as Ticket, E as clientProof, Et as readAncestry, F as defaultProcessIo, Fn as makeEventNotification, Gn as socketPathTooLongMessage, H as entriesNewestFirst, Hn as parseRelayFrame, Ht as samePath, I as describeToolCall, In as makeResult, Jt as tailJsonl, Kt as statusAfterLiveness, L as detectRepo, Ln as newDeviceId, M as dataDir, N as dataPaths, Nn as isSocketPathTooLong, Ot as readHeadLine, P as decideAutoContinue, Pn as makeError, Q as holderAfterDeparture, Qt as tooManyUnreadMessage, Rn as newMessageId, Rt as resolveRecipient, S as bindAccountDevice, Sn as SessionId, T as classifyPermission, Tt as readAccountTokens, U as evaluateLiveness, Un as safeParse, Vn as parseIpcRequest, Wn as sanitizeLine, Xt as takeWithinBytes, Z as generateSessionName, Zt as toIso, _ as asString, _n as PERMISSION_ANSWERS, _t as pendingForInjection, at as jwtClaim, b as autoLimitsFromEnv, bn as RpcErrorCode, cn as DeviceId, ct as markDelivered, d as ackEntries, dt as notFound, en as unsupportedTranscript, fn as HUMAN_ANSWERER, gn as OWNER_SESSION_ID, gt as pauseLabel, hn as ORCHESTRATOR_ALIAS, j as daemonProof, jn as encodeFrame, k as createWmiWalker, kn as createLineDecoder, kt as readInbox, ln as EVENT_NAMES, lt as nameMatchesPattern, n as AccountError, nn as validateRename, p as acpTranscript, pn as Message, r as ConvenoError, rt as isRecord, s as RESPONSE_BUDGET_BYTES, tt as isOnline, ut as newAuthNonce, vn as PROTOCOL_VERSION, x as baseName, xt as planSpawn, y as autoCandidates, yn as RelayPayload, zn as newSessionId } from "./dist-M9Gs7e_K.js";
4
4
  import { randomBytes } from "node:crypto";
5
5
  import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
6
6
  import { connect, createServer } from "node:net";
7
7
  import { dirname, join, posix, win32 } from "node:path";
8
8
  import { n as redactWithReport } from "./dist-DcmKjrmu.js";
9
- import { _ as sasMatches, a as JoinerPairing, b as signRelayHello, c as decodePairMessage, d as forkPoint, f as generateIdentity, g as publicRecord, h as parseIdentity, i as InviterPairing, l as deviceFingerprint, m as openEnvelope, n as ENVELOPE_MAX_AGE_MS, o as appendRevoke, p as headMatches, r as ENVELOPE_MAX_FUTURE_MS, s as chainHead, t as CryptoError, u as encodePairMessage, v as sealEnvelope, x as verifyChain, y as serializeIdentity } from "./dist-hYvLf29C.js";
9
+ import { _ as sasMatches, a as JoinerPairing, b as signRelayHello, c as decodePairMessage, d as forkPoint, f as generateIdentity, g as publicRecord, h as parseIdentity, i as InviterPairing, l as deviceFingerprint, m as openEnvelope, n as ENVELOPE_MAX_AGE_MS, o as appendRevoke, p as headMatches, r as ENVELOPE_MAX_FUTURE_MS, s as chainHead, t as CryptoError, u as encodePairMessage, v as sealEnvelope, x as verifyChain, y as serializeIdentity } from "./dist-DIJhGLVn.js";
10
10
  import { execFileSync } from "node:child_process";
11
11
  import { DatabaseSync } from "node:sqlite";
12
- import { c as claudeTranscript, i as codexTranscript, t as openCodeTranscript } from "./dist-BVE5ihb8.js";
12
+ import { c as claudeTranscript, i as codexTranscript, t as openCodeTranscript } from "./dist-B7znzc5U.js";
13
13
  import { readFile, readdir, stat } from "node:fs/promises";
14
14
  // ../daemon/src/lifecycle.ts
15
15
  /** Thrown when another Conveno daemon already owns the lock file or answers on the socket. */
@@ -2156,6 +2156,20 @@ var Store = class {
2156
2156
  this.run("DELETE FROM messages WHERE id NOT IN (SELECT message_id FROM mailbox)");
2157
2157
  this.run("DELETE FROM sessions WHERE id = ?", id);
2158
2158
  }
2159
+ /**
2160
+ * Trim a mailbox nobody else cleans up: delete handled entries (anything but queued) that are
2161
+ * beyond the newest `keep` entries or were last touched before `olderThanIso`. Queued entries
2162
+ * stay. Returns how many were deleted.
2163
+ */
2164
+ pruneMailbox(sessionId, keep, olderThanIso) {
2165
+ const res = this.db.prepare(`DELETE FROM mailbox WHERE session_id = ? AND state <> 'queued' AND (
2166
+ message_id NOT IN (SELECT message_id FROM mailbox WHERE session_id = ?
2167
+ ORDER BY message_id DESC LIMIT ?)
2168
+ OR COALESCE(read_at, delivered_at, queued_at) < ?)`).run(sessionId, sessionId, keep, olderThanIso);
2169
+ const n = Number(res.changes);
2170
+ if (n > 0) this.run("DELETE FROM messages WHERE id NOT IN (SELECT message_id FROM mailbox)");
2171
+ return n;
2172
+ }
2159
2173
  /** Mailbox entries of one session, optionally limited to the given states or message ids. */
2160
2174
  entries(sessionId, filter = {}) {
2161
2175
  let sql = `SELECT m.json, b.state, b.queued_at, b.delivered_at, b.read_at, b.acked_at, b.hops
@@ -2181,6 +2195,10 @@ var Store = class {
2181
2195
  const TICKET_TTL_MS = 864e5;
2182
2196
  /** A permission ticket outlives the hook that asked for it by little: the hook gives up in 90 s. */
2183
2197
  const PERMISSION_TICKET_TTL_MS = 3e5;
2198
+ const OWNER = {
2199
+ id: OWNER_SESSION_ID,
2200
+ name: "you"
2201
+ };
2184
2202
  const fail = (code, message) => {
2185
2203
  throw new ConvenoError(code, message);
2186
2204
  };
@@ -2199,13 +2217,14 @@ var TicketService = class {
2199
2217
  }
2200
2218
  create(p) {
2201
2219
  const asker = this.requireOnline(p.sessionId);
2202
- const target = this.host.resolve(p.to ?? "orchestrator");
2220
+ const toOwner = p.to === "you" || p.to === OWNER_SESSION_ID;
2221
+ const target = toOwner ? OWNER : this.host.resolve(p.to ?? "orchestrator");
2203
2222
  if (target.id === asker.id) fail(RpcErrorCode.InvalidParams, p.to === void 0 || p.to === "orchestrator" ? "You are the orchestrator, so there is no one above you to ask. Ask the user directly." : "A session cannot ask itself. Name another session in `to`.");
2204
2223
  return this.open(asker, target, {
2205
2224
  kind: "question",
2206
2225
  question: p.question,
2207
2226
  options: p.options,
2208
- toRef: p.to === void 0 || p.to === "orchestrator" ? ORCHESTRATOR_ALIAS : target.id,
2227
+ toRef: toOwner ? "you" : p.to === void 0 || p.to === "orchestrator" ? ORCHESTRATOR_ALIAS : target.id,
2209
2228
  ttlMs: TICKET_TTL_MS
2210
2229
  });
2211
2230
  }
@@ -2244,7 +2263,7 @@ var TicketService = class {
2244
2263
  };
2245
2264
  this.host.store.tx(() => {
2246
2265
  this.store.insert(ticket, t.toRef);
2247
- this.host.queue(message, target, true);
2266
+ if (target.id !== OWNER_SESSION_ID) this.host.queue(message, target, true);
2248
2267
  });
2249
2268
  this.host.emit({
2250
2269
  event: "ticket.created",
@@ -2281,7 +2300,7 @@ var TicketService = class {
2281
2300
  if (ticket.kind === "question" && asker) {
2282
2301
  message = {
2283
2302
  id: newMessageId(),
2284
- from: me?.id ?? this.host.daemonSender,
2303
+ from: me?.id ?? OWNER_SESSION_ID,
2285
2304
  to: asker.id,
2286
2305
  kind: "answer",
2287
2306
  body: {
@@ -2290,10 +2309,8 @@ var TicketService = class {
2290
2309
  },
2291
2310
  urgent: true,
2292
2311
  createdAt: at,
2293
- ...me ? {
2294
- fromName: me.name,
2295
- fromCli: me.cli
2296
- } : {}
2312
+ fromName: me?.name ?? "you",
2313
+ ...me ? { fromCli: me.cli } : {}
2297
2314
  };
2298
2315
  this.host.queue(message, asker, false);
2299
2316
  messageId = message.id;
@@ -2304,11 +2321,7 @@ var TicketService = class {
2304
2321
  this.host.emit({
2305
2322
  event: "ticket.answered",
2306
2323
  data: { ticket: done }
2307
- }, ticket.fromSession);
2308
- if (ticket.toSession !== ticket.fromSession) this.host.emit({
2309
- event: "ticket.answered",
2310
- data: { ticket: done }
2311
- }, ticket.toSession);
2324
+ }, [ticket.fromSession, ticket.toSession]);
2312
2325
  return { ticket: done };
2313
2326
  }
2314
2327
  list(p, client) {
@@ -2357,7 +2370,7 @@ var TicketService = class {
2357
2370
  kind: "system",
2358
2371
  body: {
2359
2372
  event: "ticket.expired",
2360
- detail: `Your question to ${target?.name ?? "the orchestrator"} (ticket ${ticket.id}) got no answer and has expired. Ask again, or decide yourself.`
2373
+ 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.`
2361
2374
  },
2362
2375
  urgent: false,
2363
2376
  createdAt: at
@@ -2434,17 +2447,13 @@ var TicketService = class {
2434
2447
  }
2435
2448
  };
2436
2449
  // ../daemon/src/server.ts
2437
- const DAEMON_VERSION = "0.2.0-rc.2";
2450
+ const DAEMON_VERSION = "0.2.0-rc.3";
2438
2451
  /** A connection that has not finished the handshake by then is closed. */
2439
2452
  const AUTH_TIMEOUT_MS = 5e3;
2440
2453
  /** Unread messages one session may hold. */
2441
2454
  const MAX_UNREAD_PER_SESSION = 1e3;
2442
- /**
2443
- * How long an offline session stays listed (`conveno status --all`) before the sweep deletes it.
2444
- * A closed session does not come back after a day: it returns only while its host process is alive,
2445
- * and a new run of the CLI registers as a new session. 24 h keeps a working day's history visible
2446
- * without piling up months of test sessions. It applies only when nothing is waiting for it.
2447
- */
2455
+ const OWNER_READ_KEEP_MS = 2592e6;
2456
+ const OWNER_PRUNE_EVERY_MS = 36e5;
2448
2457
  const PRUNE_OFFLINE_AFTER_MS = 864e5;
2449
2458
  /**
2450
2459
  * An offline session that a newer live session has replaced (same name, CLI and repo) is deleted
@@ -2496,6 +2505,7 @@ var Daemon = class {
2496
2505
  listeners = /* @__PURE__ */ new Map();
2497
2506
  idleSince;
2498
2507
  startedMs;
2508
+ ownerPrunedMs = 0;
2499
2509
  tickets;
2500
2510
  constructor(store, token, now, isAlive, idleExitMs, requestIdleExit, requestShutdown, log, authTimeoutMs = AUTH_TIMEOUT_MS, pathExists = existsSync, autoLimits = autoLimitsFromEnv({}), transcripts = {}, transcriptEnv = {
2501
2511
  home: homedir(),
@@ -2525,7 +2535,7 @@ var Daemon = class {
2525
2535
  requireSession: (id) => this.requireSession(id),
2526
2536
  resolve: (to) => this.resolveOnline(to),
2527
2537
  holder: () => effectiveHolder(store.holder(), this.named(store.allSessions()))?.id ?? null,
2528
- queue: (message, row, limit) => this.queueMessage(message, row, limit),
2538
+ queue: (message, to, limit) => this.queueMessage(message, to, limit),
2529
2539
  emit: (payload, onlyTo) => this.emit(payload, onlyTo),
2530
2540
  daemonSender: DAEMON_SENDER_ID
2531
2541
  });
@@ -2623,6 +2633,9 @@ var Daemon = class {
2623
2633
  case "daemon.shutdown": return { ok: true };
2624
2634
  case "orchestrator.claim": return this.claim(req.params.sessionId);
2625
2635
  case "message.send": return this.sendMessage(req.params);
2636
+ case "owner.inbox": return this.ownerInbox(conn, req.params);
2637
+ case "owner.ack": return this.ownerAck(conn, req.params);
2638
+ case "owner.send": return this.ownerSend(conn, req.params);
2626
2639
  case "message.inbox": return this.inbox(req.params);
2627
2640
  case "message.deliver": return this.deliver(req.params);
2628
2641
  case "message.ack": return this.ack(req.params);
@@ -2694,17 +2707,21 @@ var Daemon = class {
2694
2707
  const found = resolveRecipient(to, this.named(rows), this.store.holder());
2695
2708
  return rows.find((r) => r.id === found.id);
2696
2709
  }
2697
- /** Queue a message for a session and tell its subscriber. `limit` applies the unread cap. */
2710
+ /**
2711
+ * Queue a message for a session, or for the owner, and tell its subscriber. `limit` applies the
2712
+ * unread cap.
2713
+ */
2698
2714
  queueMessage(message, row, limit) {
2699
2715
  if (limit && this.store.unreadCount(row.id) >= 1e3) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(row.name, MAX_UNREAD_PER_SESSION));
2700
2716
  this.store.insertMessage(message, row.id, message.createdAt);
2701
2717
  this.emitMessage(message, row.id);
2702
2718
  }
2703
2719
  emit(payload, onlyTo) {
2720
+ const only = onlyTo === void 0 || Array.isArray(onlyTo) ? onlyTo : [onlyTo];
2704
2721
  for (const c of this.conns) {
2705
2722
  const sub = c.sub;
2706
2723
  if (!sub?.topics.has(payload.event)) continue;
2707
- if (onlyTo !== void 0 && sub.sessionId !== onlyTo) continue;
2724
+ if (only !== void 0 && sub.sessionId !== void 0 && !only.includes(sub.sessionId)) continue;
2708
2725
  this.send(c, makeEventNotification(payload));
2709
2726
  }
2710
2727
  }
@@ -3049,35 +3066,68 @@ var Daemon = class {
3049
3066
  const sender = this.requireSession(p.sessionId);
3050
3067
  if (sender.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${sender.name}" is offline. Register the session again before sending.`);
3051
3068
  if (p.kind === "system") throw new ConvenoError(RpcErrorCode.InvalidParams, "Messages of kind \"system\" are made by the Conveno daemon only. Send kind \"text\" instead.");
3069
+ return this.deliverFrom({
3070
+ id: sender.id,
3071
+ name: sender.name,
3072
+ cli: sender.cli,
3073
+ hops: sender.status === "busy" ? sender.turnHops : 0
3074
+ }, p);
3075
+ }
3076
+ /** The recipient names the owner: `you`, or the id of a message the owner sent. */
3077
+ isOwnerRecipient(to) {
3078
+ return to === "you" || to === OWNER_SESSION_ID;
3079
+ }
3080
+ /**
3081
+ * Route one message from `sender` (a session, or the owner) to a session, the owner, or a
3082
+ * session on another device. The owner is not a session: a message to `you` waits in the owner's
3083
+ * mailbox, which no hook or wake ever reads.
3084
+ */
3085
+ deliverFrom(sender, p) {
3052
3086
  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.`);
3087
+ const at = this.iso();
3053
3088
  const rows = this.store.allSessions();
3089
+ const make = (to) => ({
3090
+ id: newMessageId(),
3091
+ from: sender.id,
3092
+ to,
3093
+ kind: p.kind,
3094
+ body: p.body,
3095
+ urgent: p.urgent,
3096
+ createdAt: at,
3097
+ fromName: sender.name,
3098
+ ...sender.cli !== void 0 ? { fromCli: sender.cli } : {},
3099
+ ...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
3100
+ });
3101
+ if (this.isOwnerRecipient(p.to)) {
3102
+ if (sender.id === OWNER_SESSION_ID) throw new ConvenoError(RpcErrorCode.InvalidParams, "You cannot send a message to yourself.");
3103
+ const message = make("you");
3104
+ this.store.tx(() => this.queueMessage(message, {
3105
+ id: OWNER_SESSION_ID,
3106
+ name: "you"
3107
+ }, true));
3108
+ return {
3109
+ message,
3110
+ delivery: "inbox",
3111
+ deliveredTo: {
3112
+ id: OWNER_SESSION_ID,
3113
+ name: "you"
3114
+ }
3115
+ };
3116
+ }
3054
3117
  let target;
3055
3118
  try {
3056
3119
  target = resolveRecipient(p.to, this.named(rows), this.store.holder());
3057
3120
  } catch (e) {
3058
3121
  const remote = e instanceof ConvenoError && e.code === RpcErrorCode.NotFound ? this.relay?.resolveRemote(p.to) : void 0;
3059
3122
  if (!remote) throw e;
3060
- return this.sendToRemote(sender, remote, p);
3123
+ return this.sendToRemote(make(p.to), remote);
3061
3124
  }
3062
3125
  const targetRow = rows.find((r) => r.id === target.id);
3063
3126
  if (this.store.unreadCount(targetRow.id) >= 1e3) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(targetRow.name, MAX_UNREAD_PER_SESSION));
3064
- const at = this.iso();
3065
- const message = {
3066
- id: newMessageId(),
3067
- from: sender.id,
3068
- to: p.to,
3069
- kind: p.kind,
3070
- body: p.body,
3071
- urgent: p.urgent,
3072
- createdAt: at,
3073
- fromName: sender.name,
3074
- fromCli: sender.cli,
3075
- ...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
3076
- };
3127
+ const message = make(p.to);
3077
3128
  const enableAuto = sender.id !== targetRow.id && effectiveHolder(this.store.holder(), this.named(rows))?.id === sender.id && !targetRow.auto && !targetRow.autoExplicit;
3078
- const hops = sender.status === "busy" ? sender.turnHops : 0;
3079
3129
  this.store.tx(() => {
3080
- this.store.insertMessage(message, targetRow.id, at, hops);
3130
+ this.store.insertMessage(message, targetRow.id, at, sender.hops);
3081
3131
  if (enableAuto) this.store.updateSession(targetRow.id, { auto: true });
3082
3132
  });
3083
3133
  if (enableAuto) {
@@ -3094,6 +3144,40 @@ var Daemon = class {
3094
3144
  }
3095
3145
  };
3096
3146
  }
3147
+ requireCli(conn, what) {
3148
+ if (conn.client !== "cli") throw new ConvenoError(RpcErrorCode.Unauthorized, `Only the conveno command and app can ${what}. A session cannot act as the owner.`);
3149
+ }
3150
+ ownerInbox(conn, p) {
3151
+ this.requireCli(conn, "read the owner's messages");
3152
+ return this.readInboxOf(OWNER_SESSION_ID, p.unreadOnly, p.limit, true);
3153
+ }
3154
+ ownerAck(conn, p) {
3155
+ this.requireCli(conn, "mark the owner's messages as handled");
3156
+ return this.ackFor(OWNER_SESSION_ID, p.ids);
3157
+ }
3158
+ ownerSend(conn, p) {
3159
+ this.requireCli(conn, "send as the owner");
3160
+ if (!this.isOwnerRecipient(p.to) && this.relay?.resolveRemote(p.to)) {
3161
+ let local = true;
3162
+ try {
3163
+ resolveRecipient(p.to, this.named(this.store.allSessions()), this.store.holder());
3164
+ } catch {
3165
+ local = false;
3166
+ }
3167
+ 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.");
3168
+ }
3169
+ return this.deliverFrom({
3170
+ id: OWNER_SESSION_ID,
3171
+ name: "you",
3172
+ hops: 0
3173
+ }, {
3174
+ to: p.to,
3175
+ kind: "text",
3176
+ body: { text: p.text },
3177
+ urgent: p.urgent,
3178
+ ...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
3179
+ });
3180
+ }
3097
3181
  /** `live` for a session in auto mode whose CLI can be woken; otherwise the CLI's own tier. */
3098
3182
  tierFor(row) {
3099
3183
  const running = row.auto && row.autoPausedBy === void 0;
@@ -3278,16 +3362,21 @@ var Daemon = class {
3278
3362
  }
3279
3363
  inbox(p) {
3280
3364
  this.requireSession(p.sessionId);
3365
+ return this.readInboxOf(p.sessionId, p.unreadOnly, p.limit);
3366
+ }
3367
+ /** A mailbox's messages, oldest first, marked read. The owner's mailbox has no session row. */
3368
+ readInboxOf(id, unreadOnly, limit, newest = false) {
3281
3369
  const at = this.iso();
3282
3370
  return this.store.tx(() => {
3283
- const entries = this.store.entries(p.sessionId, p.unreadOnly ? { states: ["queued"] } : {});
3371
+ const entries = this.store.entries(id, unreadOnly ? { states: ["queued"] } : {});
3284
3372
  const res = readInbox(entries, {
3285
- unreadOnly: p.unreadOnly,
3286
- limit: p.limit,
3287
- maxBytes: RESPONSE_BUDGET_BYTES
3373
+ unreadOnly,
3374
+ limit,
3375
+ maxBytes: RESPONSE_BUDGET_BYTES,
3376
+ newest
3288
3377
  }, at);
3289
3378
  const changed = new Set(res.returned.map((e) => e.message.id));
3290
- for (const e of res.entries) if (changed.has(e.message.id)) this.store.saveEntry(p.sessionId, e);
3379
+ for (const e of res.entries) if (changed.has(e.message.id)) this.store.saveEntry(id, e);
3291
3380
  return {
3292
3381
  messages: res.returned.map((e) => e.message),
3293
3382
  unreadCount: res.unreadCount
@@ -3310,19 +3399,24 @@ var Daemon = class {
3310
3399
  }
3311
3400
  ack(p) {
3312
3401
  this.requireSession(p.sessionId);
3402
+ return this.ackFor(p.sessionId, p.ids);
3403
+ }
3404
+ ackFor(id, ids) {
3313
3405
  const at = this.iso();
3314
3406
  return this.store.tx(() => {
3315
- const entries = this.store.entries(p.sessionId, { ids: p.ids });
3316
- const res = ackEntries(entries, p.ids, at);
3317
- for (const e of res.entries) this.store.saveEntry(p.sessionId, e);
3407
+ const entries = this.store.entries(id, { ids });
3408
+ const res = ackEntries(entries, ids, at);
3409
+ for (const e of res.entries) this.store.saveEntry(id, e);
3318
3410
  return { acked: res.acked };
3319
3411
  });
3320
3412
  }
3321
3413
  subscribe(conn, p) {
3322
- this.requireSession(p.sessionId);
3414
+ if (p.sessionId === void 0) {
3415
+ if (conn.client !== "cli") throw new ConvenoError(RpcErrorCode.Unauthorized, "Pass sessionId to subscribe. Only the conveno command and app can subscribe to every event.");
3416
+ } else this.requireSession(p.sessionId);
3323
3417
  const topics = p.topics ?? [...EVENT_NAMES];
3324
3418
  conn.sub = {
3325
- sessionId: p.sessionId,
3419
+ ...p.sessionId !== void 0 ? { sessionId: p.sessionId } : {},
3326
3420
  topics: new Set(topics)
3327
3421
  };
3328
3422
  return { subscribed: topics };
@@ -3343,19 +3437,7 @@ var Daemon = class {
3343
3437
  default: throw new ConvenoError(RpcErrorCode.MethodNotFound, `Method not found: ${req.method}`);
3344
3438
  }
3345
3439
  }
3346
- sendToRemote(sender, target, p) {
3347
- const message = {
3348
- id: newMessageId(),
3349
- from: sender.id,
3350
- to: p.to,
3351
- kind: p.kind,
3352
- body: p.body,
3353
- urgent: p.urgent,
3354
- createdAt: this.iso(),
3355
- fromName: sender.name,
3356
- fromCli: sender.cli,
3357
- ...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
3358
- };
3440
+ sendToRemote(message, target) {
3359
3441
  this.relay.sendRemote(target, message);
3360
3442
  return {
3361
3443
  message,
@@ -3382,7 +3464,7 @@ var Daemon = class {
3382
3464
  this.emitMessage(m, row.id);
3383
3465
  },
3384
3466
  notify: (to, event, detail) => {
3385
- if (!this.store.getSession(to)) return;
3467
+ if (to !== OWNER_SESSION_ID && !this.store.getSession(to)) return;
3386
3468
  const m = {
3387
3469
  id: newMessageId(),
3388
3470
  from: DAEMON_SENDER_ID,
@@ -3417,6 +3499,10 @@ var Daemon = class {
3417
3499
  sweep() {
3418
3500
  this.tickets.sweep();
3419
3501
  const nowMs = this.now().getTime();
3502
+ if (nowMs - this.ownerPrunedMs >= OWNER_PRUNE_EVERY_MS) {
3503
+ this.ownerPrunedMs = nowMs;
3504
+ this.store.pruneMailbox(OWNER_SESSION_ID, 500, (/* @__PURE__ */ new Date(nowMs - OWNER_READ_KEEP_MS)).toISOString());
3505
+ }
3420
3506
  let online = 0;
3421
3507
  const rows = this.store.allSessions();
3422
3508
  for (const row of rows) {
@@ -3508,7 +3594,13 @@ async function startDaemon(opts) {
3508
3594
  return {
3509
3595
  socketPath,
3510
3596
  close,
3511
- sweep: () => daemon.sweep()
3597
+ sweep: () => daemon.sweep(),
3598
+ testRelay: {
3599
+ host: () => daemon.relayHost(),
3600
+ set: (relay) => {
3601
+ daemon.relay = relay;
3602
+ }
3603
+ }
3512
3604
  };
3513
3605
  } catch (e) {
3514
3606
  server?.close();
@@ -3,7 +3,7 @@ import { mkdir, open, readFile, rm, stat } from "node:fs/promises";
3
3
  import { createConnection } from "node:net";
4
4
  import { homedir } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
- import { An as encodeFrame, Ct as proofsMatch, E as clientProof, M as dataDir, Mn as isSocketPathTooLong, N as dataPaths, On as createLineDecoder, Wn as socketPathTooLongMessage, _n as PROTOCOL_VERSION, bn as RpcResponse, dn as EventPayload, j as daemonProof, jn as ipcMethods, kn as defaultSocketPath, r as ConvenoError, ut as newAuthNonce, yn as RpcErrorCode } from "./dist-_sq6DmrE.js";
6
+ import { An as defaultSocketPath, Ct as proofsMatch, E as clientProof, Gn as socketPathTooLongMessage, M as dataDir, Mn as ipcMethods, N as dataPaths, Nn as isSocketPathTooLong, bn as RpcErrorCode, dn as EventPayload, j as daemonProof, jn as encodeFrame, kn as createLineDecoder, r as ConvenoError, ut as newAuthNonce, vn as PROTOCOL_VERSION, xn as RpcResponse } from "./dist-M9Gs7e_K.js";
7
7
  // ../client/dist/index.js
8
8
  const DEFAULT_REQUEST_TIMEOUT_MS = 5e3;
9
9
  const DEFAULT_START_TIMEOUT_MS = 1e4;
@@ -28,6 +28,9 @@ const CLIENT_METHODS = [
28
28
  "message.inbox",
29
29
  "message.deliver",
30
30
  "message.ack",
31
+ "owner.inbox",
32
+ "owner.ack",
33
+ "owner.send",
31
34
  "session.setCliInfo",
32
35
  "session.setPeekable",
33
36
  "session.peek",
@@ -54,6 +57,7 @@ const CLIENT_METHODS = [
54
57
  */
55
58
  const NOT_REPLAYABLE = /* @__PURE__ */ new Set([
56
59
  "message.send",
60
+ "owner.send",
57
61
  "session.register",
58
62
  "daemon.shutdown",
59
63
  "turn.end",
@@ -1,4 +1,4 @@
1
- import { Ft as relayPermission, Gt as startTurnContext, H as entriesNewestFirst, Ht as samePath, I as describeToolCall, Jt as tailJsonl, Mt as readTailLines, Ot as readHeadLine, Pt as recordCliInfo, V as endTurnContinuation, X as formatPermissionDecision, Zt as toIso, _ as asString, dt as notFound, it as isTranscriptPath, pt as parseCliVersion, qt as subdirsNewestFirst, rn as waitForWork, rt as isRecord, vt as pendingHookContext, yt as pickNewestSince } from "./dist-_sq6DmrE.js";
1
+ import { Ft as relayPermission, Gt as startTurnContext, H as entriesNewestFirst, Ht as samePath, I as describeToolCall, Jt as tailJsonl, Mt as readTailLines, Ot as readHeadLine, Pt as recordCliInfo, V as endTurnContinuation, X as formatPermissionDecision, Zt as toIso, _ as asString, dt as notFound, it as isTranscriptPath, pt as parseCliVersion, qt as subdirsNewestFirst, rn as waitForWork, rt as isRecord, vt as pendingHookContext, yt as pickNewestSince } from "./dist-M9Gs7e_K.js";
2
2
  import { isAbsolute, join } from "node:path";
3
3
  import { readFile, stat } from "node:fs/promises";
4
4
  import { applyEdits, modify, parse, printParseErrorCode } from "jsonc-parser";