@conveno/cli 0.2.0-rc.11 → 0.2.0-rc.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -64,7 +64,7 @@ A worker started with `conveno spawn` wakes on every message, whatever the CLI.
64
64
 
65
65
  ## Compatibility
66
66
 
67
- Vendors change config and hook formats without notice. `conveno doctor` compares each detected CLI with the versions Conveno was checked against: a newer one is a warning, one older than the minimum is a problem with an upgrade hint. A nightly workflow installs the latest release of every supported CLI and checks that it accepts what `conveno init` writes, then raises the checked version or opens an issue. The table of versions and the details are in the [repository README](https://github.com/0xPixelNinja/conveno#compatibility).
67
+ Vendors change config and hook formats without notice. `conveno doctor` compares each detected CLI with the versions Conveno was checked against: a newer one is not flagged, and one older than a known minimum (a release that lacks something Conveno needs) is a warning with an upgrade hint. A version never makes doctor exit 1. A nightly workflow installs the latest release of every supported CLI and checks that it accepts what `conveno init` writes, then raises the checked version or opens an issue. The table of versions and the details are in the [repository README](https://github.com/0xPixelNinja/conveno#compatibility).
68
68
 
69
69
  ## How it works
70
70
 
@@ -1,7 +1,7 @@
1
1
  import { writeFileSync } from "node:fs";
2
- import { n as runAcpHostFromFile, r as stopRequestPath, t as killProcessTree } from "./dist-Rdj5ogAX.js";
3
- import { At as readSpawnRecord, Ut as spawnRecordPath } from "./dist-qONHJRJk.js";
4
- import { a as parseFlags, n as COMMANDS } from "./args-C1eX8Ixk.js";
2
+ import { n as runAcpHostFromFile, r as stopRequestPath, t as killProcessTree } from "./dist-BkhKEexU.js";
3
+ import { Ut as readSpawnRecord, nn as spawnRecordPath } from "./dist-DnNuDzEA.js";
4
+ import { a as parseFlags, n as COMMANDS } from "./args-C4rVCVXx.js";
5
5
  import { a as fail, n as cmd } from "./fmt-C2SsP5Y0.js";
6
6
  // src/acp.ts
7
7
  /** How long `conveno stop` waits for a worker to end by itself before it ends the process tree. */
@@ -1,6 +1,6 @@
1
1
  import { execFile } from "node:child_process";
2
- import { t as RELAY_SUBCOMMAND } from "./dist-KWlFKO7H.js";
3
- import { Bt as runWaker } from "./dist-qONHJRJk.js";
2
+ import { t as RELAY_SUBCOMMAND } from "./dist-D4sb5RQD.js";
3
+ import { $t as runWaker } from "./dist-DnNuDzEA.js";
4
4
  import { n as connectOpts } from "./ctx-tYftvhz_.js";
5
5
  // src/agy-relay.ts
6
6
  /**
@@ -117,6 +117,7 @@ async function runAgyRelay(ctx, argv, deps = {}) {
117
117
  client: c,
118
118
  sessionId: session.id,
119
119
  signal,
120
+ nativeId: conversationId,
120
121
  ...hostPid ? { isHostAlive: () => ctx.isAlive(hostPid) } : {},
121
122
  inject: (text, messages) => sendToConversation({
122
123
  platform: ctx.platform,
@@ -156,7 +156,7 @@ const COMMANDS = [
156
156
  allow: {
157
157
  type: "string",
158
158
  value: "<kinds>",
159
- help: "Background: tool calls to approve, such as read,search or execute:npm test*"
159
+ help: "Background: tool calls to approve, such as read,search or execute:npm test*. Comma or space separated; repeat the flag to add more"
160
160
  },
161
161
  yes: {
162
162
  type: "boolean",
@@ -169,6 +169,8 @@ const COMMANDS = [
169
169
  "it becomes its next prompt: right away when it is idle, else when its turn ends.",
170
170
  "--window opens the real CLI in a new terminal instead, so you can watch it and take over.",
171
171
  "In the background, tool calls that need approval are denied unless --allow covers them.",
172
+ "Example: --allow read,search (also --allow read search, or --allow read --allow search).",
173
+ "Conveno's own tools, such as send, are always allowed.",
172
174
  "claude and codex need an ACP adapter installed. End a worker with conveno stop.",
173
175
  "Waits until the session registers, then prints its name.",
174
176
  "Without a terminal of your own it needs --yes, and exits 2 without it.",
package/dist/bin.js CHANGED
@@ -2,6 +2,19 @@
2
2
  import { enableCompileCache } from "node:module";
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
5
+ // src/hook-skip.ts
6
+ /**
7
+ * Whether `conveno <argv>` is a hook that must exit 0 at once, with no output:
8
+ * - an ACP worker's agent (`CONVENO_ACP_WORKER`, set by the ACP host): the host drives its turns
9
+ * and delivery itself, and a hook's process walk could reach the lead's session instead;
10
+ * - Claude hooks run by Grok, which imports `~/.claude/settings.json` and sets `GROK_HOOK_EVENT`
11
+ * on every hook process. Claude Code never sets it. Grok's own hooks (`hook grok ...`) still run.
12
+ */
13
+ function hookSkipped(argv, env) {
14
+ if (argv[0] !== "hook") return false;
15
+ if (env.CONVENO_ACP_WORKER) return true;
16
+ return argv[1] === "claude" && Boolean(env.GROK_HOOK_EVENT);
17
+ }
5
18
  // src/bin.ts
6
19
  /**
7
20
  * Cache V8's compiled code for Conveno's files and its dependencies, in the user's own data
@@ -20,15 +33,16 @@ function startCompileCache() {
20
33
  startCompileCache();
21
34
  const argv = process.argv.slice(2);
22
35
  const isHook = argv[0] === "hook";
36
+ if (hookSkipped(argv, process.env)) process.exit(0);
23
37
  for (const stream of [process.stdout, process.stderr]) stream.on("error", (err) => {
24
38
  if (err.code === "EPIPE") process.exit(0);
25
39
  throw err;
26
40
  });
27
41
  try {
28
42
  let code;
29
- if (isHook) code = await (await import("./hook-entry-D2CAJsq-.js")).runHookEntry(argv.slice(1));
43
+ if (isHook) code = await (await import("./hook-entry-jOfjq-0A.js")).runHookEntry(argv.slice(1));
30
44
  else {
31
- const [{ main }, { createRuntimeCtx }] = await Promise.all([import("./main-EqfI0btx.js"), import("./runtime-BDNmkbsS.js")]);
45
+ const [{ main }, { createRuntimeCtx }] = await Promise.all([import("./main-I2RMN7XN.js"), import("./runtime-CPmrhPFJ.js")]);
32
46
  code = await main(argv, createRuntimeCtx());
33
47
  }
34
48
  if (isHook) process.exit(code);
package/dist/daemon.js CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import { homedir, hostname, userInfo } from "node:os";
3
- import { t as codexAdapter } from "./dist-DEjU_KXC.js";
4
- import { An as parseIpcRequest, C as bindAccountDevice, Cn as isSocketPathTooLong, Ct as proofsMatch, D as clientProof, Dn as newDeviceId, E as clearOrchestrator, En as makeResult, Et as readAncestry, F as dataPaths, I as decideAutoContinue, J as formatHookContext, Jt as takeWithinBytes, Kt as statusAfterLiveness, L as defaultProcessIo, Lt as resolveRecipient, M as currentAccessToken, Mn as safeParse, N as daemonProof, Nn as sanitizeLine, On as newMessageId, Ot as readInbox, P as dataDir, Pn as socketPathTooLongMessage, Pt as requeueEntries, R as detectRepo, S as baseName, Tn as makeEventNotification, Tt as readAccountTokens, U as evaluateLiveness, V as effectiveHolder, X as generateSessionName, Xt as tooManyUnreadMessage, Yt as takeWithinChars, Z as holderAfterDeparture, Zt as turnHops, b as autoCandidates, bn as defaultSocketPath, ct as markDelivered, en as validateRename, fn as OWNER_SESSION_ID, gt as pendingForInjection, hn as RpcErrorCode, j as createWmiWalker, jn as parseRelayFrame, kn as newSessionId, kt as readSettings, l as RESPONSE_BUDGET_BYTES, mn as RelayPayload, n as AccountError, nt as jwtClaim, on as DeviceId, p as ackEntries, pn as PROTOCOL_VERSION, q as formatContinuation, r as ConvenoError, sn as EVENT_NAMES, tt as isOnline, un as Message, ut as newAuthNonce, vn as SessionId, w as claimOrchestrator, wn as makeError, x as autoLimitsFromEnv, xn as encodeFrame, xt as planSpawn, yn as createLineDecoder } from "./dist-qONHJRJk.js";
3
+ import { t as codexAdapter } from "./dist-C9Z1EMlM.js";
4
+ import { A as clearOrchestrator, An as SESSION_ENDED_TEXT, B as decideAutoContinue, Bn as makeResult, Bt as readInbox, Cn as Message, D as bindAccountDevice, Dn as RelayPayload, E as baseName, En as PROTOCOL_VERSION, Et as pendingForInjection, F as createWmiWalker, Fn as encodeFrame, Ft as proofsMatch, G as effectiveHolder, Gn as parseRelayFrame, H as detectRepo, Hn as newMessageId, Ht as readSettings, I as currentAccessToken, Jn as socketPathTooLongMessage, Kn as safeParse, L as daemonProof, Ln as isSocketPathTooLong, Lt as readAccountTokens, Mn as SessionId, Nn as createLineDecoder, Nt as planSpawn, O as claimOrchestrator, On as RpcErrorCode, Pn as defaultSocketPath, Q as formatHookContext, R as dataDir, Rn as makeError, Rt as readAncestry, T as autoLimitsFromEnv, Tn as OWNER_SESSION_ID, Un as newSessionId, V as defaultProcessIo, Vn as newDeviceId, Wn as parseIpcRequest, Xt as resolveRecipient, Z as formatContinuation, _t as markDelivered, a as ConvenoError, an as statusAfterLiveness, bn as EVENT_NAMES, bt as oneWindowPerHost, cn as takeWithinChars, d as RESPONSE_BUDGET_BYTES, dt as jwtClaim, et as generateSessionName, h as ackEntries, j as clientProof, ln as tooManyUnreadMessage, pn as validateRename, q as evaluateLiveness, qn as sanitizeLine, qt as requeueEntries, r as AccountError, sn as takeWithinBytes, tt as holderAfterDeparture, un as turnHops, ut as isOnline, w as autoCandidates, yn as DeviceId, yt as newAuthNonce, z as dataPaths, zn as makeEventNotification } from "./dist-DnNuDzEA.js";
5
5
  import { randomBytes } from "node:crypto";
6
6
  import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
7
7
  import { connect, createServer } from "node:net";
8
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-Dg2IY9OA.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-CoRBNycn.js";
10
10
  import { execFileSync } from "node:child_process";
11
11
  import { DatabaseSync } from "node:sqlite";
12
12
  // ../daemon/src/lifecycle.ts
@@ -1691,6 +1691,10 @@ const MIGRATIONS = [
1691
1691
  ALTER TABLE sessions ADD COLUMN native_id TEXT;
1692
1692
  CREATE INDEX sessions_native_id ON sessions (native_id);
1693
1693
  `
1694
+ },
1695
+ {
1696
+ name: "008_variant",
1697
+ sql: "ALTER TABLE sessions ADD COLUMN variant TEXT;"
1694
1698
  }
1695
1699
  ];
1696
1700
  const str = (v) => typeof v === "string" ? v : void 0;
@@ -1749,6 +1753,7 @@ function toSessionRow(r) {
1749
1753
  if (spawnedBy !== void 0) row.spawnedBy = spawnedBy;
1750
1754
  const nativeId = str(r.native_id);
1751
1755
  if (nativeId !== void 0) row.nativeId = nativeId;
1756
+ if (r.variant === "app") row.variant = "app";
1752
1757
  return row;
1753
1758
  }
1754
1759
  /** Wire-format session for a stored row. */
@@ -1779,6 +1784,7 @@ function toSession(row, isOrchestrator, unreadCount) {
1779
1784
  if (row.statusText !== void 0) s.statusText = row.statusText;
1780
1785
  if (row.spawnedBy !== void 0) s.spawnedBy = row.spawnedBy;
1781
1786
  if (row.nativeId !== void 0) s.nativeId = row.nativeId;
1787
+ if (row.variant !== void 0) s.variant = row.variant;
1782
1788
  return s;
1783
1789
  }
1784
1790
  function toEntry(r) {
@@ -1852,8 +1858,8 @@ var Store = class {
1852
1858
  insertSession(s) {
1853
1859
  this.run(`INSERT INTO sessions (id, name, cli, cli_version, device_id, cwd, repo_root, repo_remote_hash,
1854
1860
  pid, host_pid, host_pids, status, status_text, delivery_tier, spawned_by, spawned, spawn_depth,
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);
1861
+ auto_runs, turn_hops, started_at, last_seen_at, variant)
1862
+ 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, s.variant ?? null);
1857
1863
  }
1858
1864
  getSession(id) {
1859
1865
  const r = this.all("SELECT * FROM sessions WHERE id = ?", id)[0];
@@ -1866,6 +1872,22 @@ var Store = class {
1866
1872
  updateSession(id, fields) {
1867
1873
  const sets = [];
1868
1874
  const vals = [];
1875
+ if (fields.cwd !== void 0) {
1876
+ sets.push("cwd = ?");
1877
+ vals.push(fields.cwd);
1878
+ }
1879
+ if (fields.repoRoot !== void 0) {
1880
+ sets.push("repo_root = ?", "repo_remote_hash = NULL");
1881
+ vals.push(fields.repoRoot);
1882
+ }
1883
+ if (fields.variant !== void 0) {
1884
+ sets.push("variant = ?");
1885
+ vals.push(fields.variant);
1886
+ }
1887
+ if (fields.pid !== void 0) {
1888
+ sets.push("pid = ?");
1889
+ vals.push(fields.pid);
1890
+ }
1869
1891
  if (fields.nativeId !== void 0) {
1870
1892
  sets.push("native_id = ?");
1871
1893
  vals.push(fields.nativeId);
@@ -1917,6 +1939,10 @@ var Store = class {
1917
1939
  hasMessage(id) {
1918
1940
  return this.all("SELECT 1 AS x FROM messages WHERE id = ?", id).length > 0;
1919
1941
  }
1942
+ /** Move every mailbox entry of `from` to `to`. An entry `to` already has stays as it is. */
1943
+ moveMailbox(from, to) {
1944
+ this.run("UPDATE OR IGNORE mailbox SET session_id = ? WHERE session_id = ?", to, from);
1945
+ }
1920
1946
  /** Remove a session, its mailbox, and any message no mailbox refers to any more. */
1921
1947
  deleteSession(id) {
1922
1948
  this.run("DELETE FROM mailbox WHERE session_id = ?", id);
@@ -1944,7 +1970,7 @@ var Store = class {
1944
1970
  }
1945
1971
  };
1946
1972
  // ../daemon/src/server.ts
1947
- const DAEMON_VERSION = "0.2.0-rc.11";
1973
+ const DAEMON_VERSION = "0.2.0-rc.13";
1948
1974
  /** A connection that has not finished the handshake by then is closed. */
1949
1975
  const AUTH_TIMEOUT_MS = 5e3;
1950
1976
  /** Unread messages one session may hold. */
@@ -2018,6 +2044,19 @@ var Daemon = class {
2018
2044
  startedMs;
2019
2045
  /** When each session went offline, for the removal grace. In memory only. */
2020
2046
  offlineSince = /* @__PURE__ */ new Map();
2047
+ /**
2048
+ * The MCP processes attached to each session (a window can have several: a reconnect, a thread's
2049
+ * second server). In memory only: a daemon that restarted learns them again, because every
2050
+ * process sends its pid with each heartbeat, and the session's own `pid` seeds the set.
2051
+ */
2052
+ attached = /* @__PURE__ */ new Map();
2053
+ /** When a hook last touched each session (a turn start or end, a delivery, a bind). In memory only. */
2054
+ hookAt = /* @__PURE__ */ new Map();
2055
+ /**
2056
+ * Sessions retired by an unregister without a pid (a Codex SessionEnd hook, an ACP host exiting).
2057
+ * Their heartbeats are refused, so a leftover MCP process cannot bring them back online.
2058
+ */
2059
+ retired = /* @__PURE__ */ new Set();
2021
2060
  constructor(store, token, now, isAlive, idleExitMs, requestIdleExit, requestShutdown, log, authTimeoutMs = AUTH_TIMEOUT_MS, autoLimits = autoLimitsFromEnv({}), processIo = defaultProcessIo, platform = process.platform, wakers = {}, settingsPath) {
2022
2061
  this.store = store;
2023
2062
  this.token = token;
@@ -2113,14 +2152,17 @@ var Daemon = class {
2113
2152
  case "hello": return this.hello(conn, req.params);
2114
2153
  case "auth": return this.auth(conn, req.params);
2115
2154
  case "session.register": return this.registerAsync(req.params);
2116
- case "session.heartbeat": return this.heartbeat(req.params.sessionId);
2117
- case "session.unregister": return this.unregister(req.params.sessionId);
2155
+ case "session.heartbeat": return this.heartbeat(req.params.sessionId, req.params.pid);
2156
+ case "session.unregister": return this.unregister(req.params.sessionId, req.params.pid);
2157
+ case "session.remove": return this.remove(req.params.sessionId);
2118
2158
  case "session.rename": return this.rename(req.params);
2119
2159
  case "session.setStatus": return this.setStatus(req.params);
2120
2160
  case "session.list": return this.list(req.params);
2121
2161
  case "session.byHost": return this.byHost(req.params);
2122
2162
  case "session.hostOf": return this.hostOf(req.params);
2123
2163
  case "session.setNative": return this.setNative(req.params);
2164
+ case "session.bind": return this.bind(req.params);
2165
+ case "session.setCwd": return this.setCwd(req.params);
2124
2166
  case "turn.start": return this.turnStart(req.params.sessionId);
2125
2167
  case "turn.end": return this.turnEnd(req.params);
2126
2168
  case "turn.wake": return this.turnWake(conn, req.params);
@@ -2185,10 +2227,14 @@ var Daemon = class {
2185
2227
  /** The wire view of a session. Its `deliveryTier` is the live one (`tierFor`). */
2186
2228
  view(row) {
2187
2229
  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));
2230
+ const tier = this.tierFor(row);
2231
+ return {
2232
+ ...toSession({
2233
+ ...row,
2234
+ deliveryTier: tier
2235
+ }, holder?.id === row.id, this.store.unreadCount(row.id) + this.stalledWoken(row.id)),
2236
+ wakeable: tier === "live" || tier === "acp"
2237
+ };
2192
2238
  }
2193
2239
  /** The orchestrator as routing sees it: the holder, if it is online. */
2194
2240
  orchestratorNow() {
@@ -2227,7 +2273,34 @@ var Daemon = class {
2227
2273
  const found = await detectRepo(p.cwd, { exists: (path) => existsSync(path) });
2228
2274
  return found.root ? { root: found.root } : void 0;
2229
2275
  }
2276
+ /**
2277
+ * The session an MCP server of a one-window-per-host CLI attaches to: the online, non-ACP
2278
+ * session of the same CLI under the same host process (and in the same folder, for OpenCode,
2279
+ * whose server hosts every folder).
2280
+ */
2281
+ attachTarget(p) {
2282
+ if (p.acp || p.hostPid === void 0 || !oneWindowPerHost(p.cli)) return void 0;
2283
+ return this.store.allSessions().find((r) => r.status !== "offline" && r.cli === p.cli && r.deliveryTier !== "acp" && r.hostPid === p.hostPid && (p.cli !== "opencode" || samePath(r.cwd, p.cwd, this.platform)));
2284
+ }
2285
+ /** The MCP pids attached to a session; seeded with the pid it registered with. */
2286
+ attachedOf(row) {
2287
+ let set = this.attached.get(row.id);
2288
+ if (!set) {
2289
+ set = new Set(row.pid === void 0 ? [] : [row.pid]);
2290
+ this.attached.set(row.id, set);
2291
+ }
2292
+ return set;
2293
+ }
2294
+ touchHook(id) {
2295
+ this.hookAt.set(id, this.now().getTime());
2296
+ }
2230
2297
  register(p, repo) {
2298
+ const window = this.attachTarget(p);
2299
+ if (window) {
2300
+ if (p.pid !== void 0) this.attachedOf(window).add(p.pid);
2301
+ this.store.updateSession(window.id, { lastSeenAt: this.iso() });
2302
+ return { session: this.view(this.store.getSession(window.id) ?? window) };
2303
+ }
2231
2304
  const id = newSessionId();
2232
2305
  const at = this.iso();
2233
2306
  const row = this.store.tx(() => {
@@ -2251,6 +2324,7 @@ var Daemon = class {
2251
2324
  lastSeenAt: at
2252
2325
  };
2253
2326
  if (p.cliVersion !== void 0) r.cliVersion = p.cliVersion;
2327
+ if (p.variant !== void 0) r.variant = p.variant;
2254
2328
  if (repo) {
2255
2329
  r.repoRoot = repo.root;
2256
2330
  if (repo.remoteUrlHash !== void 0) r.repoRemoteUrlHash = repo.remoteUrlHash;
@@ -2262,6 +2336,7 @@ var Daemon = class {
2262
2336
  this.store.insertSession(r);
2263
2337
  return r;
2264
2338
  });
2339
+ this.attachedOf(row);
2265
2340
  this.emitSession(row.id, "registered");
2266
2341
  this.claimPreferredLead(row);
2267
2342
  return { session: this.view(this.store.getSession(row.id) ?? row) };
@@ -2272,17 +2347,21 @@ var Daemon = class {
2272
2347
  */
2273
2348
  claimPreferredLead(row) {
2274
2349
  if (this.settingsPath === void 0) return;
2275
- if (readSettings(this.settingsPath).leadCli !== row.cli) return;
2350
+ const settings = readSettings(this.settingsPath);
2351
+ if (settings.leadCli !== row.cli) return;
2352
+ if (settings.tools && !settings.tools.includes(row.cli)) return;
2276
2353
  if (this.orchestratorNow() !== null) return;
2277
2354
  this.claim(row.id);
2278
2355
  }
2279
2356
  async registerAsync(p) {
2280
2357
  return this.register(p, await this.detect(p));
2281
2358
  }
2282
- heartbeat(sessionId) {
2359
+ heartbeat(sessionId, pid) {
2283
2360
  const row = this.requireSession(sessionId);
2361
+ if (this.retired.has(sessionId)) throw new ConvenoError(RpcErrorCode.NotFound, `Session "${row.name}" ${SESSION_ENDED_TEXT}.`);
2284
2362
  const at = this.iso();
2285
2363
  if (row.status !== "offline") {
2364
+ if (pid !== void 0) this.attachedOf(row).add(pid);
2286
2365
  this.store.updateSession(sessionId, { lastSeenAt: at });
2287
2366
  return { lastSeenAt: at };
2288
2367
  }
@@ -2292,6 +2371,7 @@ var Daemon = class {
2292
2371
  status: "idle",
2293
2372
  lastSeenAt: at
2294
2373
  });
2374
+ if (pid !== void 0) this.attachedOf(row).add(pid);
2295
2375
  this.offlineSince.delete(sessionId);
2296
2376
  this.emitSession(sessionId, "updated");
2297
2377
  return { lastSeenAt: at };
@@ -2305,6 +2385,8 @@ var Daemon = class {
2305
2385
  });
2306
2386
  this.listeners.delete(sessionId);
2307
2387
  this.woken.delete(sessionId);
2388
+ this.attached.delete(sessionId);
2389
+ this.hookAt.delete(sessionId);
2308
2390
  this.offlineSince.set(sessionId, this.now().getTime());
2309
2391
  this.emitSession(sessionId, change);
2310
2392
  if (after !== before) this.emit({
@@ -2315,8 +2397,63 @@ var Daemon = class {
2315
2397
  }
2316
2398
  });
2317
2399
  }
2318
- unregister(sessionId) {
2319
- if (this.requireSession(sessionId).status !== "offline") this.depart(sessionId, "unregistered");
2400
+ /**
2401
+ * With `pid`, that MCP process detaches and the session stays online while another is attached;
2402
+ * the session departs with its last one. Without `pid` it departs at once.
2403
+ */
2404
+ unregister(sessionId, pid) {
2405
+ const row = this.requireSession(sessionId);
2406
+ if (row.status === "offline") return { ok: true };
2407
+ if (pid !== void 0) {
2408
+ const set = this.attachedOf(row);
2409
+ set.delete(pid);
2410
+ if (set.size > 0) {
2411
+ if (row.pid === pid) this.store.updateSession(sessionId, { pid: [...set][0] });
2412
+ return { ok: true };
2413
+ }
2414
+ }
2415
+ if (pid === void 0) this.retired.add(sessionId);
2416
+ this.depart(sessionId, "unregistered");
2417
+ return { ok: true };
2418
+ }
2419
+ /**
2420
+ * Delete a session and its mail (the app's "Remove this session"). The lead role goes with it.
2421
+ * A window that is still open registers again on its next heartbeat or tool call.
2422
+ */
2423
+ remove(sessionId) {
2424
+ const row = this.requireSession(sessionId);
2425
+ const shown = {
2426
+ ...this.view(row),
2427
+ status: "offline"
2428
+ };
2429
+ const before = this.store.holder();
2430
+ const after = holderAfterDeparture(before, sessionId);
2431
+ this.store.tx(() => {
2432
+ if (after !== before) this.store.setHolder(after);
2433
+ this.store.deleteSession(sessionId);
2434
+ });
2435
+ this.listeners.delete(sessionId);
2436
+ this.woken.delete(sessionId);
2437
+ this.wokenAt.delete(sessionId);
2438
+ this.wakersOff.delete(sessionId);
2439
+ this.offlineSince.delete(sessionId);
2440
+ this.attached.delete(sessionId);
2441
+ this.hookAt.delete(sessionId);
2442
+ this.emit({
2443
+ event: "session.updated",
2444
+ data: {
2445
+ session: shown,
2446
+ change: "unregistered"
2447
+ }
2448
+ });
2449
+ this.relay?.sessionsChanged();
2450
+ if (after !== before) this.emit({
2451
+ event: "orchestrator.changed",
2452
+ data: {
2453
+ orchestrator: after,
2454
+ previous: before
2455
+ }
2456
+ });
2320
2457
  return { ok: true };
2321
2458
  }
2322
2459
  rename(p) {
@@ -2381,6 +2518,7 @@ var Daemon = class {
2381
2518
  }
2382
2519
  const holders = this.pidHolders(rows, pid, cwd, live);
2383
2520
  const only = holders.length === 1 ? holders[0] : void 0;
2521
+ if (only) this.touchHook(only.id);
2384
2522
  return { session: only ? this.view(only) : null };
2385
2523
  }
2386
2524
  /** Sessions whose host is `pid` (in `cwd`, when given), online ones first. */
@@ -2428,6 +2566,158 @@ var Daemon = class {
2428
2566
  this.daemonWake(row.id);
2429
2567
  return { session: this.view(this.requireSession(row.id)) };
2430
2568
  }
2569
+ /**
2570
+ * A desktop app session learns its workspace from a hook: the app starts Conveno in its install
2571
+ * folder, so the row moves to the folder the user has open. A name made from the old folder
2572
+ * follows it; a name the user chose stays. Only an app session moves (`variant` on the call may
2573
+ * mark one); a CLI row keeps the folder it registered with.
2574
+ */
2575
+ async setCwd(p) {
2576
+ const row = this.requireOnline(p.sessionId);
2577
+ if (!(row.variant === "app" || p.variant === "app")) return { session: this.view(row) };
2578
+ const found = samePath(row.cwd, p.cwd, this.platform) ? void 0 : await detectRepo(p.cwd, { exists: (path) => existsSync(path) });
2579
+ const cur = this.requireOnline(p.sessionId);
2580
+ const fields = {};
2581
+ if (cur.variant !== "app") fields.variant = "app";
2582
+ if (found && !samePath(cur.cwd, p.cwd, this.platform)) {
2583
+ const oldBase = baseName(cur.repoRoot ?? cur.cwd);
2584
+ const prefix = generateSessionName(cur.cli, oldBase, []).replace(/1$/, "");
2585
+ const auto = cur.name.startsWith(prefix) && /^\d+$/.test(cur.name.slice(prefix.length));
2586
+ fields.cwd = p.cwd;
2587
+ fields.repoRoot = found.root ?? null;
2588
+ if (auto) {
2589
+ const others = this.named(this.store.allSessions().filter((r) => r.id !== cur.id));
2590
+ fields.name = generateSessionName(cur.cli, baseName(found.root ?? p.cwd), others);
2591
+ }
2592
+ }
2593
+ if (Object.keys(fields).length > 0) {
2594
+ this.store.updateSession(cur.id, fields);
2595
+ this.emitSession(cur.id, "updated");
2596
+ }
2597
+ return { session: this.view(this.requireSession(cur.id)) };
2598
+ }
2599
+ /**
2600
+ * The session of the window a hook runs in, among the online sessions of its CLI: the one under
2601
+ * its host process (and in its folder, when the hook says which). Codex shares one host process
2602
+ * between windows, so there it prefers a session that has no conversation yet, and takes a bound
2603
+ * one only when it is the only one. Null when it is ambiguous or none matches.
2604
+ */
2605
+ windowRow(rows, p) {
2606
+ if (p.hostPid === void 0) return void 0;
2607
+ const { cwd } = p;
2608
+ const cands = rows.filter((r) => r.hostPid === p.hostPid && (cwd === void 0 || samePath(r.cwd, cwd, this.platform)));
2609
+ if (oneWindowPerHost(p.cli)) return cands.length === 1 ? cands[0] : void 0;
2610
+ const unbound = cands.filter((r) => r.nativeId === void 0);
2611
+ if (unbound.length > 0) return unbound.length === 1 ? unbound[0] : void 0;
2612
+ return cands.length === 1 ? cands[0] : void 0;
2613
+ }
2614
+ /**
2615
+ * `session.bind` from a hook that has only its parent pid. Answers without the hook walking the
2616
+ * process tree when the conversation settles it: exactly one online session of the CLI holds the
2617
+ * id, and the hook's parent is that session's host, or the hook starts no turn (a Stop or an
2618
+ * idle never moves a window), or that session is already busy. A conversation no window could
2619
+ * take (no session online, or a hook that is no turn start and every session has a
2620
+ * conversation) answers none. Anything else needs the host pid: `needsHost`. So only the turn
2621
+ * start of an idle conversation walks.
2622
+ */
2623
+ bindWithoutHost(rows, p) {
2624
+ if (rows.length === 0) return { session: null };
2625
+ const holders = rows.filter((r) => r.nativeId === p.nativeId);
2626
+ const [holder] = holders;
2627
+ if (holders.length === 1 && holder) {
2628
+ const pids = [...holder.hostPid === void 0 ? [] : [holder.hostPid], ...holder.hostPids ?? []];
2629
+ if (p.ppid !== void 0 && pids.includes(p.ppid) || !p.turnStart || holder.status === "busy") {
2630
+ this.touchHook(holder.id);
2631
+ return { session: this.view(holder) };
2632
+ }
2633
+ } else if (holders.length === 0 && !p.turnStart && rows.every((r) => r.nativeId !== void 0)) return { session: null };
2634
+ return {
2635
+ session: null,
2636
+ needsHost: true
2637
+ };
2638
+ }
2639
+ /**
2640
+ * Bind a conversation to the window's session (see `session.bind` in the protocol). The session
2641
+ * that holds the id wins; a caller with a session of its own is merged into it. Otherwise only a
2642
+ * turn start moves the window to the conversation, and a conversation that is not the window's
2643
+ * current one is ignored by every other hook. Replaces `setNative` for hooks and MCP servers.
2644
+ */
2645
+ bind(p) {
2646
+ const caller = p.sessionId === void 0 ? void 0 : this.requireOnline(p.sessionId);
2647
+ if (caller && caller.cli !== p.cli) return { session: null };
2648
+ const rows = this.store.allSessions().filter((r) => r.status !== "offline" && r.cli === p.cli);
2649
+ if (!caller && p.hostPid === void 0) return this.bindWithoutHost(rows, p);
2650
+ let holder = rows.find((r) => r.nativeId === p.nativeId);
2651
+ if (holder && !caller && p.hostPid !== void 0) {
2652
+ const pids = [...holder.hostPid === void 0 ? [] : [holder.hostPid], ...holder.hostPids ?? []];
2653
+ if (pids.length > 0 && !pids.includes(p.hostPid)) {
2654
+ const mine = rows.filter((r) => r.hostPid === p.hostPid);
2655
+ if (mine.length === 1 && mine[0]?.id !== holder.id) holder = void 0;
2656
+ }
2657
+ }
2658
+ if (holder) {
2659
+ if (caller && caller.id !== holder.id) return { session: this.merge(caller, holder, p.pid) };
2660
+ if (!caller) this.touchHook(holder.id);
2661
+ return { session: this.view(holder) };
2662
+ }
2663
+ const row = caller ?? this.windowRow(rows, p);
2664
+ if (!row) return { session: null };
2665
+ if (!caller) this.touchHook(row.id);
2666
+ if (row.nativeId !== void 0 && !p.turnStart) return { session: null };
2667
+ const others = rows.filter((r) => r.id !== row.id && r.nativeId === p.nativeId);
2668
+ const moved = row.nativeId !== void 0;
2669
+ const stale = moved && row.status === "busy";
2670
+ this.store.tx(() => {
2671
+ for (const o of others) this.store.updateSession(o.id, { nativeId: null });
2672
+ this.store.updateSession(row.id, {
2673
+ nativeId: p.nativeId,
2674
+ ...stale ? {
2675
+ status: "idle",
2676
+ turnHops: 0
2677
+ } : {}
2678
+ });
2679
+ });
2680
+ if (moved) {
2681
+ this.listeners.delete(row.id);
2682
+ this.woken.delete(row.id);
2683
+ }
2684
+ for (const o of others) this.emitSession(o.id, "updated");
2685
+ this.emitSession(row.id, "updated");
2686
+ this.daemonWake(row.id);
2687
+ return { session: this.view(this.requireSession(row.id)) };
2688
+ }
2689
+ /**
2690
+ * Fold the session of an MCP process into the session that holds its conversation: the process
2691
+ * attaches to the survivor, the mail and the lead role move to it, and the caller's row goes.
2692
+ */
2693
+ merge(from, into, pid) {
2694
+ const pids = this.attachedOf(into);
2695
+ for (const q of this.attachedOf(from)) pids.add(q);
2696
+ if (pid !== void 0) pids.add(pid);
2697
+ const lead = this.store.holder() === from.id;
2698
+ this.store.tx(() => {
2699
+ this.store.moveMailbox(from.id, into.id);
2700
+ if (lead) this.store.setHolder(into.id);
2701
+ this.store.updateSession(into.id, { lastSeenAt: this.iso() });
2702
+ this.store.deleteSession(from.id);
2703
+ });
2704
+ this.listeners.delete(from.id);
2705
+ this.woken.delete(from.id);
2706
+ this.attached.delete(from.id);
2707
+ this.hookAt.delete(from.id);
2708
+ this.offlineSince.delete(from.id);
2709
+ this.relay?.sessionsChanged();
2710
+ if (lead) this.emit({
2711
+ event: "orchestrator.changed",
2712
+ data: {
2713
+ orchestrator: into.id,
2714
+ previous: from.id
2715
+ }
2716
+ });
2717
+ this.emitSession(into.id, "updated");
2718
+ this.daemonWake(into.id);
2719
+ return this.view(this.requireSession(into.id));
2720
+ }
2431
2721
  /** Delete offline sessions and their mail. \`graceMs\` 0 removes every one at once. */
2432
2722
  removeOffline(graceMs) {
2433
2723
  const nowMs = this.now().getTime();
@@ -2446,6 +2736,8 @@ var Daemon = class {
2446
2736
  this.wokenAt.delete(r.id);
2447
2737
  this.wakersOff.delete(r.id);
2448
2738
  this.offlineSince.delete(r.id);
2739
+ this.attached.delete(r.id);
2740
+ this.hookAt.delete(r.id);
2449
2741
  }
2450
2742
  }
2451
2743
  claim(sessionId) {
@@ -2754,6 +3046,7 @@ var Daemon = class {
2754
3046
  */
2755
3047
  turnStart(sessionId) {
2756
3048
  const row = this.requireOnline(sessionId);
3049
+ this.touchHook(sessionId);
2757
3050
  const fromWake = this.woken.has(sessionId) && row.status === "busy";
2758
3051
  this.woken.delete(sessionId);
2759
3052
  this.store.updateSession(sessionId, fromWake ? { status: "busy" } : {
@@ -2804,6 +3097,7 @@ var Daemon = class {
2804
3097
  remaining: queued.length
2805
3098
  };
2806
3099
  });
3100
+ if (res.messages.length > 0) this.touchHook(row.id);
2807
3101
  if (res.messages.length > 0 ? row.status !== "busy" : endOfTurn && row.status !== "idle") this.emitSession(row.id, "updated");
2808
3102
  return {
2809
3103
  ...res,
@@ -2812,6 +3106,7 @@ var Daemon = class {
2812
3106
  }
2813
3107
  turnEnd(p) {
2814
3108
  const row = this.requireOnline(p.sessionId);
3109
+ this.touchHook(p.sessionId);
2815
3110
  this.woken.delete(p.sessionId);
2816
3111
  if (row.status === "waiting_on_question") return this.continueWith(row, false, false);
2817
3112
  return this.continueWith(row, p.allowContinue, true, RESPONSE_BUDGET_BYTES, p.maxChars);
@@ -2822,6 +3117,12 @@ var Daemon = class {
2822
3117
  */
2823
3118
  turnWake(conn, p) {
2824
3119
  const row = this.requireOnline(p.sessionId);
3120
+ if (p.nativeId !== void 0 && row.nativeId !== void 0 && p.nativeId !== row.nativeId) return {
3121
+ messages: [],
3122
+ remaining: this.store.unreadCount(row.id),
3123
+ orchestrator: this.orchestratorNow(),
3124
+ superseded: true
3125
+ };
2825
3126
  const known = this.listeners.get(row.id);
2826
3127
  if (known?.retired.includes(p.listenerId)) return {
2827
3128
  messages: [],
@@ -2877,6 +3178,7 @@ var Daemon = class {
2877
3178
  }
2878
3179
  deliver(p) {
2879
3180
  this.requireSession(p.sessionId);
3181
+ this.touchHook(p.sessionId);
2880
3182
  const at = this.iso();
2881
3183
  return this.store.tx(() => {
2882
3184
  const pending = pendingForInjection(this.store.entries(p.sessionId, { states: ["queued"] }));
@@ -2986,6 +3288,17 @@ var Daemon = class {
2986
3288
  removeAllOffline() {
2987
3289
  this.removeOffline(0);
2988
3290
  }
3291
+ /** A busy session no hook has touched for `STUCK_BUSY_MS` is idle: its turn end never came. */
3292
+ clearStuckBusy(row, nowMs) {
3293
+ if (row.status !== "busy") return;
3294
+ if (nowMs - (this.hookAt.get(row.id) ?? Math.max(Date.parse(row.startedAt), this.startedMs)) <= 18e5) return;
3295
+ this.store.updateSession(row.id, {
3296
+ status: "idle",
3297
+ turnHops: 0
3298
+ });
3299
+ this.woken.delete(row.id);
3300
+ this.emitSession(row.id, "updated");
3301
+ }
2989
3302
  sweep() {
2990
3303
  const nowMs = this.now().getTime();
2991
3304
  this.removeOffline(OFFLINE_GRACE_MS);
@@ -2999,8 +3312,16 @@ var Daemon = class {
2999
3312
  lastSeenMs,
3000
3313
  hostPid: row.hostPid
3001
3314
  }, nowMs, this.isAlive);
3002
- if (statusAfterLiveness(row.status, verdict) === "offline") this.depart(row.id, "offline");
3003
- else online++;
3315
+ if (statusAfterLiveness(row.status, verdict) === "offline") {
3316
+ this.depart(row.id, "offline");
3317
+ continue;
3318
+ }
3319
+ online++;
3320
+ const pids = this.attached.get(row.id);
3321
+ if (pids) {
3322
+ for (const q of [...pids]) if (!this.isAlive(q)) pids.delete(q);
3323
+ }
3324
+ this.clearStuckBusy(row, nowMs);
3004
3325
  }
3005
3326
  if (online > 0) this.idleSince = nowMs;
3006
3327
  else if (nowMs - this.idleSince >= this.idleExitMs) this.requestIdleExit();