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

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-CuStS_nO.js";
3
+ import { Ut as spawnRecordPath, jt as readSpawnRecord, m as acpTurnsPath } from "./dist-DUqXHTRg.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-DP6eq6qr.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-ByyF0srt.js"), import("./runtime-BS-SUGVR.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-DUqXHTRg.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-BmpWfYuM.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-CfwMkSGH.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,40 @@ 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
+ }
2173
+ /**
2174
+ * Messages a session received (it has a mailbox entry) or sent, newest first, optionally only
2175
+ * those older than `before`. Message ids are ULIDs, so id order is time order.
2176
+ */
2177
+ messagesOf(sessionId, limit, before) {
2178
+ return this.all(`SELECT m.json FROM messages m
2179
+ WHERE (m.id IN (SELECT message_id FROM mailbox WHERE session_id = ?)
2180
+ OR json_extract(m.json, '$.from') = ?)
2181
+ ${before ? "AND m.id < ?" : ""}
2182
+ ORDER BY m.id DESC LIMIT ?`, ...before ? [
2183
+ sessionId,
2184
+ sessionId,
2185
+ before,
2186
+ limit
2187
+ ] : [
2188
+ sessionId,
2189
+ sessionId,
2190
+ limit
2191
+ ]).map((r) => Message.parse(JSON.parse(r.json)));
2192
+ }
2159
2193
  /** Mailbox entries of one session, optionally limited to the given states or message ids. */
2160
2194
  entries(sessionId, filter = {}) {
2161
2195
  let sql = `SELECT m.json, b.state, b.queued_at, b.delivered_at, b.read_at, b.acked_at, b.hops
@@ -2181,6 +2215,10 @@ var Store = class {
2181
2215
  const TICKET_TTL_MS = 864e5;
2182
2216
  /** A permission ticket outlives the hook that asked for it by little: the hook gives up in 90 s. */
2183
2217
  const PERMISSION_TICKET_TTL_MS = 3e5;
2218
+ const OWNER = {
2219
+ id: OWNER_SESSION_ID,
2220
+ name: "you"
2221
+ };
2184
2222
  const fail = (code, message) => {
2185
2223
  throw new ConvenoError(code, message);
2186
2224
  };
@@ -2199,13 +2237,14 @@ var TicketService = class {
2199
2237
  }
2200
2238
  create(p) {
2201
2239
  const asker = this.requireOnline(p.sessionId);
2202
- const target = this.host.resolve(p.to ?? "orchestrator");
2240
+ const toOwner = p.to === "you" || p.to === OWNER_SESSION_ID;
2241
+ const target = toOwner ? OWNER : this.host.resolve(p.to ?? "orchestrator");
2203
2242
  if (target.id === asker.id) fail(RpcErrorCode.InvalidParams, p.to === void 0 || p.to === "orchestrator" ? "You are the orchestrator, so there is no one above you to ask. Ask the user directly." : "A session cannot ask itself. Name another session in `to`.");
2204
2243
  return this.open(asker, target, {
2205
2244
  kind: "question",
2206
2245
  question: p.question,
2207
2246
  options: p.options,
2208
- toRef: p.to === void 0 || p.to === "orchestrator" ? ORCHESTRATOR_ALIAS : target.id,
2247
+ toRef: toOwner ? "you" : p.to === void 0 || p.to === "orchestrator" ? ORCHESTRATOR_ALIAS : target.id,
2209
2248
  ttlMs: TICKET_TTL_MS
2210
2249
  });
2211
2250
  }
@@ -2244,7 +2283,7 @@ var TicketService = class {
2244
2283
  };
2245
2284
  this.host.store.tx(() => {
2246
2285
  this.store.insert(ticket, t.toRef);
2247
- this.host.queue(message, target, true);
2286
+ if (target.id !== OWNER_SESSION_ID) this.host.queue(message, target, true);
2248
2287
  });
2249
2288
  this.host.emit({
2250
2289
  event: "ticket.created",
@@ -2281,7 +2320,7 @@ var TicketService = class {
2281
2320
  if (ticket.kind === "question" && asker) {
2282
2321
  message = {
2283
2322
  id: newMessageId(),
2284
- from: me?.id ?? this.host.daemonSender,
2323
+ from: me?.id ?? OWNER_SESSION_ID,
2285
2324
  to: asker.id,
2286
2325
  kind: "answer",
2287
2326
  body: {
@@ -2290,10 +2329,8 @@ var TicketService = class {
2290
2329
  },
2291
2330
  urgent: true,
2292
2331
  createdAt: at,
2293
- ...me ? {
2294
- fromName: me.name,
2295
- fromCli: me.cli
2296
- } : {}
2332
+ fromName: me?.name ?? "you",
2333
+ ...me ? { fromCli: me.cli } : {}
2297
2334
  };
2298
2335
  this.host.queue(message, asker, false);
2299
2336
  messageId = message.id;
@@ -2304,11 +2341,7 @@ var TicketService = class {
2304
2341
  this.host.emit({
2305
2342
  event: "ticket.answered",
2306
2343
  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);
2344
+ }, [ticket.fromSession, ticket.toSession]);
2312
2345
  return { ticket: done };
2313
2346
  }
2314
2347
  list(p, client) {
@@ -2357,7 +2390,7 @@ var TicketService = class {
2357
2390
  kind: "system",
2358
2391
  body: {
2359
2392
  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.`
2393
+ detail: `Your question to ${ticket.toSession === OWNER_SESSION_ID ? "the user" : target?.name ?? "the orchestrator"} (ticket ${ticket.id}) got no answer and has expired. Ask again, or decide yourself.`
2361
2394
  },
2362
2395
  urgent: false,
2363
2396
  createdAt: at
@@ -2434,17 +2467,13 @@ var TicketService = class {
2434
2467
  }
2435
2468
  };
2436
2469
  // ../daemon/src/server.ts
2437
- const DAEMON_VERSION = "0.2.0-rc.2";
2470
+ const DAEMON_VERSION = "0.2.0-rc.4";
2438
2471
  /** A connection that has not finished the handshake by then is closed. */
2439
2472
  const AUTH_TIMEOUT_MS = 5e3;
2440
2473
  /** Unread messages one session may hold. */
2441
2474
  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
- */
2475
+ const OWNER_READ_KEEP_MS = 2592e6;
2476
+ const OWNER_PRUNE_EVERY_MS = 36e5;
2448
2477
  const PRUNE_OFFLINE_AFTER_MS = 864e5;
2449
2478
  /**
2450
2479
  * An offline session that a newer live session has replaced (same name, CLI and repo) is deleted
@@ -2496,6 +2525,7 @@ var Daemon = class {
2496
2525
  listeners = /* @__PURE__ */ new Map();
2497
2526
  idleSince;
2498
2527
  startedMs;
2528
+ ownerPrunedMs = 0;
2499
2529
  tickets;
2500
2530
  constructor(store, token, now, isAlive, idleExitMs, requestIdleExit, requestShutdown, log, authTimeoutMs = AUTH_TIMEOUT_MS, pathExists = existsSync, autoLimits = autoLimitsFromEnv({}), transcripts = {}, transcriptEnv = {
2501
2531
  home: homedir(),
@@ -2525,7 +2555,7 @@ var Daemon = class {
2525
2555
  requireSession: (id) => this.requireSession(id),
2526
2556
  resolve: (to) => this.resolveOnline(to),
2527
2557
  holder: () => effectiveHolder(store.holder(), this.named(store.allSessions()))?.id ?? null,
2528
- queue: (message, row, limit) => this.queueMessage(message, row, limit),
2558
+ queue: (message, to, limit) => this.queueMessage(message, to, limit),
2529
2559
  emit: (payload, onlyTo) => this.emit(payload, onlyTo),
2530
2560
  daemonSender: DAEMON_SENDER_ID
2531
2561
  });
@@ -2623,6 +2653,10 @@ var Daemon = class {
2623
2653
  case "daemon.shutdown": return { ok: true };
2624
2654
  case "orchestrator.claim": return this.claim(req.params.sessionId);
2625
2655
  case "message.send": return this.sendMessage(req.params);
2656
+ case "message.history": return this.messageHistory(conn, req.params);
2657
+ case "owner.inbox": return this.ownerInbox(conn, req.params);
2658
+ case "owner.ack": return this.ownerAck(conn, req.params);
2659
+ case "owner.send": return this.ownerSend(conn, req.params);
2626
2660
  case "message.inbox": return this.inbox(req.params);
2627
2661
  case "message.deliver": return this.deliver(req.params);
2628
2662
  case "message.ack": return this.ack(req.params);
@@ -2694,17 +2728,21 @@ var Daemon = class {
2694
2728
  const found = resolveRecipient(to, this.named(rows), this.store.holder());
2695
2729
  return rows.find((r) => r.id === found.id);
2696
2730
  }
2697
- /** Queue a message for a session and tell its subscriber. `limit` applies the unread cap. */
2731
+ /**
2732
+ * Queue a message for a session, or for the owner, and tell its subscriber. `limit` applies the
2733
+ * unread cap.
2734
+ */
2698
2735
  queueMessage(message, row, limit) {
2699
2736
  if (limit && this.store.unreadCount(row.id) >= 1e3) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(row.name, MAX_UNREAD_PER_SESSION));
2700
2737
  this.store.insertMessage(message, row.id, message.createdAt);
2701
2738
  this.emitMessage(message, row.id);
2702
2739
  }
2703
2740
  emit(payload, onlyTo) {
2741
+ const only = onlyTo === void 0 || Array.isArray(onlyTo) ? onlyTo : [onlyTo];
2704
2742
  for (const c of this.conns) {
2705
2743
  const sub = c.sub;
2706
2744
  if (!sub?.topics.has(payload.event)) continue;
2707
- if (onlyTo !== void 0 && sub.sessionId !== onlyTo) continue;
2745
+ if (only !== void 0 && sub.sessionId !== void 0 && !only.includes(sub.sessionId)) continue;
2708
2746
  this.send(c, makeEventNotification(payload));
2709
2747
  }
2710
2748
  }
@@ -3049,35 +3087,68 @@ var Daemon = class {
3049
3087
  const sender = this.requireSession(p.sessionId);
3050
3088
  if (sender.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${sender.name}" is offline. Register the session again before sending.`);
3051
3089
  if (p.kind === "system") throw new ConvenoError(RpcErrorCode.InvalidParams, "Messages of kind \"system\" are made by the Conveno daemon only. Send kind \"text\" instead.");
3090
+ return this.deliverFrom({
3091
+ id: sender.id,
3092
+ name: sender.name,
3093
+ cli: sender.cli,
3094
+ hops: sender.status === "busy" ? sender.turnHops : 0
3095
+ }, p);
3096
+ }
3097
+ /** The recipient names the owner: `you`, or the id of a message the owner sent. */
3098
+ isOwnerRecipient(to) {
3099
+ return to === "you" || to === OWNER_SESSION_ID;
3100
+ }
3101
+ /**
3102
+ * Route one message from `sender` (a session, or the owner) to a session, the owner, or a
3103
+ * session on another device. The owner is not a session: a message to `you` waits in the owner's
3104
+ * mailbox, which no hook or wake ever reads.
3105
+ */
3106
+ deliverFrom(sender, p) {
3052
3107
  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.`);
3108
+ const at = this.iso();
3053
3109
  const rows = this.store.allSessions();
3110
+ const make = (to) => ({
3111
+ id: newMessageId(),
3112
+ from: sender.id,
3113
+ to,
3114
+ kind: p.kind,
3115
+ body: p.body,
3116
+ urgent: p.urgent,
3117
+ createdAt: at,
3118
+ fromName: sender.name,
3119
+ ...sender.cli !== void 0 ? { fromCli: sender.cli } : {},
3120
+ ...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
3121
+ });
3122
+ if (this.isOwnerRecipient(p.to)) {
3123
+ if (sender.id === OWNER_SESSION_ID) throw new ConvenoError(RpcErrorCode.InvalidParams, "You cannot send a message to yourself.");
3124
+ const message = make("you");
3125
+ this.store.tx(() => this.queueMessage(message, {
3126
+ id: OWNER_SESSION_ID,
3127
+ name: "you"
3128
+ }, true));
3129
+ return {
3130
+ message,
3131
+ delivery: "inbox",
3132
+ deliveredTo: {
3133
+ id: OWNER_SESSION_ID,
3134
+ name: "you"
3135
+ }
3136
+ };
3137
+ }
3054
3138
  let target;
3055
3139
  try {
3056
3140
  target = resolveRecipient(p.to, this.named(rows), this.store.holder());
3057
3141
  } catch (e) {
3058
3142
  const remote = e instanceof ConvenoError && e.code === RpcErrorCode.NotFound ? this.relay?.resolveRemote(p.to) : void 0;
3059
3143
  if (!remote) throw e;
3060
- return this.sendToRemote(sender, remote, p);
3144
+ return this.sendToRemote(make(p.to), remote);
3061
3145
  }
3062
3146
  const targetRow = rows.find((r) => r.id === target.id);
3063
3147
  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
- };
3148
+ const message = make(p.to);
3077
3149
  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
3150
  this.store.tx(() => {
3080
- this.store.insertMessage(message, targetRow.id, at, hops);
3151
+ this.store.insertMessage(message, targetRow.id, at, sender.hops);
3081
3152
  if (enableAuto) this.store.updateSession(targetRow.id, { auto: true });
3082
3153
  });
3083
3154
  if (enableAuto) {
@@ -3094,6 +3165,50 @@ var Daemon = class {
3094
3165
  }
3095
3166
  };
3096
3167
  }
3168
+ requireCli(conn, what) {
3169
+ if (conn.client !== "cli") throw new ConvenoError(RpcErrorCode.Unauthorized, `Only the conveno command and app can ${what}. A session cannot act as the owner.`);
3170
+ }
3171
+ ownerInbox(conn, p) {
3172
+ this.requireCli(conn, "read the owner's messages");
3173
+ return this.readInboxOf(OWNER_SESSION_ID, p.unreadOnly, p.limit, true);
3174
+ }
3175
+ messageHistory(conn, p) {
3176
+ this.requireCli(conn, "read a session's message history");
3177
+ if (!(p.session === OWNER_SESSION_ID || this.store.getSession(p.session) !== void 0 || (this.relay?.remoteSessions?.() ?? []).some((s) => s.id === p.session))) throw new ConvenoError(RpcErrorCode.NotFound, `No session with id ${p.session}.`);
3178
+ const rows = this.store.messagesOf(p.session, p.limit + 1, p.before);
3179
+ const more = rows.length > p.limit;
3180
+ return {
3181
+ messages: rows.slice(0, p.limit).reverse(),
3182
+ more
3183
+ };
3184
+ }
3185
+ ownerAck(conn, p) {
3186
+ this.requireCli(conn, "mark the owner's messages as handled");
3187
+ return this.ackFor(OWNER_SESSION_ID, p.ids);
3188
+ }
3189
+ ownerSend(conn, p) {
3190
+ this.requireCli(conn, "send as the owner");
3191
+ if (!this.isOwnerRecipient(p.to) && this.relay?.resolveRemote(p.to)) {
3192
+ let local = true;
3193
+ try {
3194
+ resolveRecipient(p.to, this.named(this.store.allSessions()), this.store.holder());
3195
+ } catch {
3196
+ local = false;
3197
+ }
3198
+ if (!local) throw new ConvenoError(RpcErrorCode.InvalidParams, "Sending to another machine from the app isn't supported yet. Message a session on this machine instead.");
3199
+ }
3200
+ return this.deliverFrom({
3201
+ id: OWNER_SESSION_ID,
3202
+ name: "you",
3203
+ hops: 0
3204
+ }, {
3205
+ to: p.to,
3206
+ kind: "text",
3207
+ body: { text: p.text },
3208
+ urgent: p.urgent,
3209
+ ...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
3210
+ });
3211
+ }
3097
3212
  /** `live` for a session in auto mode whose CLI can be woken; otherwise the CLI's own tier. */
3098
3213
  tierFor(row) {
3099
3214
  const running = row.auto && row.autoPausedBy === void 0;
@@ -3278,16 +3393,21 @@ var Daemon = class {
3278
3393
  }
3279
3394
  inbox(p) {
3280
3395
  this.requireSession(p.sessionId);
3396
+ return this.readInboxOf(p.sessionId, p.unreadOnly, p.limit);
3397
+ }
3398
+ /** A mailbox's messages, oldest first, marked read. The owner's mailbox has no session row. */
3399
+ readInboxOf(id, unreadOnly, limit, newest = false) {
3281
3400
  const at = this.iso();
3282
3401
  return this.store.tx(() => {
3283
- const entries = this.store.entries(p.sessionId, p.unreadOnly ? { states: ["queued"] } : {});
3402
+ const entries = this.store.entries(id, unreadOnly ? { states: ["queued"] } : {});
3284
3403
  const res = readInbox(entries, {
3285
- unreadOnly: p.unreadOnly,
3286
- limit: p.limit,
3287
- maxBytes: RESPONSE_BUDGET_BYTES
3404
+ unreadOnly,
3405
+ limit,
3406
+ maxBytes: RESPONSE_BUDGET_BYTES,
3407
+ newest
3288
3408
  }, at);
3289
3409
  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);
3410
+ for (const e of res.entries) if (changed.has(e.message.id)) this.store.saveEntry(id, e);
3291
3411
  return {
3292
3412
  messages: res.returned.map((e) => e.message),
3293
3413
  unreadCount: res.unreadCount
@@ -3310,19 +3430,24 @@ var Daemon = class {
3310
3430
  }
3311
3431
  ack(p) {
3312
3432
  this.requireSession(p.sessionId);
3433
+ return this.ackFor(p.sessionId, p.ids);
3434
+ }
3435
+ ackFor(id, ids) {
3313
3436
  const at = this.iso();
3314
3437
  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);
3438
+ const entries = this.store.entries(id, { ids });
3439
+ const res = ackEntries(entries, ids, at);
3440
+ for (const e of res.entries) this.store.saveEntry(id, e);
3318
3441
  return { acked: res.acked };
3319
3442
  });
3320
3443
  }
3321
3444
  subscribe(conn, p) {
3322
- this.requireSession(p.sessionId);
3445
+ if (p.sessionId === void 0) {
3446
+ if (conn.client !== "cli") throw new ConvenoError(RpcErrorCode.Unauthorized, "Pass sessionId to subscribe. Only the conveno command and app can subscribe to every event.");
3447
+ } else this.requireSession(p.sessionId);
3323
3448
  const topics = p.topics ?? [...EVENT_NAMES];
3324
3449
  conn.sub = {
3325
- sessionId: p.sessionId,
3450
+ ...p.sessionId !== void 0 ? { sessionId: p.sessionId } : {},
3326
3451
  topics: new Set(topics)
3327
3452
  };
3328
3453
  return { subscribed: topics };
@@ -3343,19 +3468,7 @@ var Daemon = class {
3343
3468
  default: throw new ConvenoError(RpcErrorCode.MethodNotFound, `Method not found: ${req.method}`);
3344
3469
  }
3345
3470
  }
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
- };
3471
+ sendToRemote(message, target) {
3359
3472
  this.relay.sendRemote(target, message);
3360
3473
  return {
3361
3474
  message,
@@ -3382,7 +3495,7 @@ var Daemon = class {
3382
3495
  this.emitMessage(m, row.id);
3383
3496
  },
3384
3497
  notify: (to, event, detail) => {
3385
- if (!this.store.getSession(to)) return;
3498
+ if (to !== OWNER_SESSION_ID && !this.store.getSession(to)) return;
3386
3499
  const m = {
3387
3500
  id: newMessageId(),
3388
3501
  from: DAEMON_SENDER_ID,
@@ -3417,6 +3530,10 @@ var Daemon = class {
3417
3530
  sweep() {
3418
3531
  this.tickets.sweep();
3419
3532
  const nowMs = this.now().getTime();
3533
+ if (nowMs - this.ownerPrunedMs >= OWNER_PRUNE_EVERY_MS) {
3534
+ this.ownerPrunedMs = nowMs;
3535
+ this.store.pruneMailbox(OWNER_SESSION_ID, 500, (/* @__PURE__ */ new Date(nowMs - OWNER_READ_KEEP_MS)).toISOString());
3536
+ }
3420
3537
  let online = 0;
3421
3538
  const rows = this.store.allSessions();
3422
3539
  for (const row of rows) {
@@ -3508,7 +3625,13 @@ async function startDaemon(opts) {
3508
3625
  return {
3509
3626
  socketPath,
3510
3627
  close,
3511
- sweep: () => daemon.sweep()
3628
+ sweep: () => daemon.sweep(),
3629
+ testRelay: {
3630
+ host: () => daemon.relayHost(),
3631
+ set: (relay) => {
3632
+ daemon.relay = relay;
3633
+ }
3634
+ }
3512
3635
  };
3513
3636
  } catch (e) {
3514
3637
  server?.close();