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

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,6 +1,6 @@
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";
2
+ import { n as runAcpHostFromFile, r as stopRequestPath, t as killProcessTree } from "./dist-4iJnF07i.js";
3
+ import { Lt as readSpawnRecord, Xt as spawnRecordPath } from "./dist-CRj_cuHc.js";
4
4
  import { a as parseFlags, n as COMMANDS } from "./args-C1eX8Ixk.js";
5
5
  import { a as fail, n as cmd } from "./fmt-C2SsP5Y0.js";
6
6
  // src/acp.ts
@@ -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-Du1hwaux.js";
3
+ import { qt as runWaker } from "./dist-CRj_cuHc.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,
package/dist/bin.js CHANGED
@@ -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-D2CAJsq-.js")).runHookEntry(argv.slice(1));
29
+ if (isHook) code = await (await import("./hook-entry-ajdMBSpY.js")).runHookEntry(argv.slice(1));
30
30
  else {
31
- const [{ main }, { createRuntimeCtx }] = await Promise.all([import("./main-EqfI0btx.js"), import("./runtime-BDNmkbsS.js")]);
31
+ const [{ main }, { createRuntimeCtx }] = await Promise.all([import("./main-WIfawg60.js"), import("./runtime-BKPod_ZQ.js")]);
32
32
  code = await main(argv, createRuntimeCtx());
33
33
  }
34
34
  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-BjATai4T.js";
4
+ import { $ as generateSessionName, $t as statusAfterLiveness, A as clientProof, An as isSocketPathTooLong, At as proofsMatch, B as defaultProcessIo, Bn as sanitizeLine, C as autoCandidates, D as claimOrchestrator, Dn as defaultSocketPath, E as bindAccountDevice, En as createLineDecoder, F as currentAccessToken, Fn as newMessageId, Ft as readInbox, I as daemonProof, In as newSessionId, It as readSettings, K as evaluateLiveness, L as dataDir, Ln as parseIpcRequest, Mn as makeEventNotification, Mt as readAccountTokens, Nn as makeResult, Nt as readAncestry, On as encodeFrame, Ot as planSpawn, P as createWmiWalker, Pn as newDeviceId, R as dataPaths, Rn as parseRelayFrame, Sn as RpcErrorCode, St as pendingForInjection, T as baseName, Tn as SessionId, V as detectRepo, Vn as socketPathTooLongMessage, Vt as requeueEntries, W as effectiveHolder, Wt as resolveRecipient, X as formatContinuation, Z as formatHookContext, _n as Message, bn as PROTOCOL_VERSION, et as holderAfterDeparture, gt as oneWindowPerHost, ht as newAuthNonce, i as ConvenoError, in as turnHops, jn as makeError, k as clearOrchestrator, m as ackEntries, mn as EVENT_NAMES, n as AccountError, nn as takeWithinChars, ot as isOnline, pn as DeviceId, pt as markDelivered, rn as tooManyUnreadMessage, sn as validateRename, st as jwtClaim, tn as takeWithinBytes, u as RESPONSE_BUDGET_BYTES, w as autoLimitsFromEnv, xn as RelayPayload, yn as OWNER_SESSION_ID, z as decideAutoContinue, zn as safeParse } from "./dist-CRj_cuHc.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-DeN0jR3I.js";
10
10
  import { execFileSync } from "node:child_process";
11
11
  import { DatabaseSync } from "node:sqlite";
12
12
  // ../daemon/src/lifecycle.ts
@@ -1866,6 +1866,10 @@ var Store = class {
1866
1866
  updateSession(id, fields) {
1867
1867
  const sets = [];
1868
1868
  const vals = [];
1869
+ if (fields.pid !== void 0) {
1870
+ sets.push("pid = ?");
1871
+ vals.push(fields.pid);
1872
+ }
1869
1873
  if (fields.nativeId !== void 0) {
1870
1874
  sets.push("native_id = ?");
1871
1875
  vals.push(fields.nativeId);
@@ -1917,6 +1921,10 @@ var Store = class {
1917
1921
  hasMessage(id) {
1918
1922
  return this.all("SELECT 1 AS x FROM messages WHERE id = ?", id).length > 0;
1919
1923
  }
1924
+ /** Move every mailbox entry of `from` to `to`. An entry `to` already has stays as it is. */
1925
+ moveMailbox(from, to) {
1926
+ this.run("UPDATE OR IGNORE mailbox SET session_id = ? WHERE session_id = ?", to, from);
1927
+ }
1920
1928
  /** Remove a session, its mailbox, and any message no mailbox refers to any more. */
1921
1929
  deleteSession(id) {
1922
1930
  this.run("DELETE FROM mailbox WHERE session_id = ?", id);
@@ -1944,7 +1952,7 @@ var Store = class {
1944
1952
  }
1945
1953
  };
1946
1954
  // ../daemon/src/server.ts
1947
- const DAEMON_VERSION = "0.2.0-rc.11";
1955
+ const DAEMON_VERSION = "0.2.0-rc.12";
1948
1956
  /** A connection that has not finished the handshake by then is closed. */
1949
1957
  const AUTH_TIMEOUT_MS = 5e3;
1950
1958
  /** Unread messages one session may hold. */
@@ -2018,6 +2026,14 @@ var Daemon = class {
2018
2026
  startedMs;
2019
2027
  /** When each session went offline, for the removal grace. In memory only. */
2020
2028
  offlineSince = /* @__PURE__ */ new Map();
2029
+ /**
2030
+ * The MCP processes attached to each session (a window can have several: a reconnect, a thread's
2031
+ * second server). In memory only: a daemon that restarted learns them again, because every
2032
+ * process sends its pid with each heartbeat, and the session's own `pid` seeds the set.
2033
+ */
2034
+ attached = /* @__PURE__ */ new Map();
2035
+ /** When a hook last touched each session (a turn start or end, a delivery, a bind). In memory only. */
2036
+ hookAt = /* @__PURE__ */ new Map();
2021
2037
  constructor(store, token, now, isAlive, idleExitMs, requestIdleExit, requestShutdown, log, authTimeoutMs = AUTH_TIMEOUT_MS, autoLimits = autoLimitsFromEnv({}), processIo = defaultProcessIo, platform = process.platform, wakers = {}, settingsPath) {
2022
2038
  this.store = store;
2023
2039
  this.token = token;
@@ -2113,14 +2129,15 @@ var Daemon = class {
2113
2129
  case "hello": return this.hello(conn, req.params);
2114
2130
  case "auth": return this.auth(conn, req.params);
2115
2131
  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);
2132
+ case "session.heartbeat": return this.heartbeat(req.params.sessionId, req.params.pid);
2133
+ case "session.unregister": return this.unregister(req.params.sessionId, req.params.pid);
2118
2134
  case "session.rename": return this.rename(req.params);
2119
2135
  case "session.setStatus": return this.setStatus(req.params);
2120
2136
  case "session.list": return this.list(req.params);
2121
2137
  case "session.byHost": return this.byHost(req.params);
2122
2138
  case "session.hostOf": return this.hostOf(req.params);
2123
2139
  case "session.setNative": return this.setNative(req.params);
2140
+ case "session.bind": return this.bind(req.params);
2124
2141
  case "turn.start": return this.turnStart(req.params.sessionId);
2125
2142
  case "turn.end": return this.turnEnd(req.params);
2126
2143
  case "turn.wake": return this.turnWake(conn, req.params);
@@ -2185,10 +2202,14 @@ var Daemon = class {
2185
2202
  /** The wire view of a session. Its `deliveryTier` is the live one (`tierFor`). */
2186
2203
  view(row) {
2187
2204
  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));
2205
+ const tier = this.tierFor(row);
2206
+ return {
2207
+ ...toSession({
2208
+ ...row,
2209
+ deliveryTier: tier
2210
+ }, holder?.id === row.id, this.store.unreadCount(row.id) + this.stalledWoken(row.id)),
2211
+ wakeable: tier === "live" || tier === "acp"
2212
+ };
2192
2213
  }
2193
2214
  /** The orchestrator as routing sees it: the holder, if it is online. */
2194
2215
  orchestratorNow() {
@@ -2227,7 +2248,34 @@ var Daemon = class {
2227
2248
  const found = await detectRepo(p.cwd, { exists: (path) => existsSync(path) });
2228
2249
  return found.root ? { root: found.root } : void 0;
2229
2250
  }
2251
+ /**
2252
+ * The session an MCP server of a one-window-per-host CLI attaches to: the online, non-ACP
2253
+ * session of the same CLI under the same host process (and in the same folder, for OpenCode,
2254
+ * whose server hosts every folder).
2255
+ */
2256
+ attachTarget(p) {
2257
+ if (p.acp || p.hostPid === void 0 || !oneWindowPerHost(p.cli)) return void 0;
2258
+ 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)));
2259
+ }
2260
+ /** The MCP pids attached to a session; seeded with the pid it registered with. */
2261
+ attachedOf(row) {
2262
+ let set = this.attached.get(row.id);
2263
+ if (!set) {
2264
+ set = new Set(row.pid === void 0 ? [] : [row.pid]);
2265
+ this.attached.set(row.id, set);
2266
+ }
2267
+ return set;
2268
+ }
2269
+ touchHook(id) {
2270
+ this.hookAt.set(id, this.now().getTime());
2271
+ }
2230
2272
  register(p, repo) {
2273
+ const window = this.attachTarget(p);
2274
+ if (window) {
2275
+ if (p.pid !== void 0) this.attachedOf(window).add(p.pid);
2276
+ this.store.updateSession(window.id, { lastSeenAt: this.iso() });
2277
+ return { session: this.view(this.store.getSession(window.id) ?? window) };
2278
+ }
2231
2279
  const id = newSessionId();
2232
2280
  const at = this.iso();
2233
2281
  const row = this.store.tx(() => {
@@ -2262,6 +2310,7 @@ var Daemon = class {
2262
2310
  this.store.insertSession(r);
2263
2311
  return r;
2264
2312
  });
2313
+ this.attachedOf(row);
2265
2314
  this.emitSession(row.id, "registered");
2266
2315
  this.claimPreferredLead(row);
2267
2316
  return { session: this.view(this.store.getSession(row.id) ?? row) };
@@ -2272,17 +2321,20 @@ var Daemon = class {
2272
2321
  */
2273
2322
  claimPreferredLead(row) {
2274
2323
  if (this.settingsPath === void 0) return;
2275
- if (readSettings(this.settingsPath).leadCli !== row.cli) return;
2324
+ const settings = readSettings(this.settingsPath);
2325
+ if (settings.leadCli !== row.cli) return;
2326
+ if (settings.tools && !settings.tools.includes(row.cli)) return;
2276
2327
  if (this.orchestratorNow() !== null) return;
2277
2328
  this.claim(row.id);
2278
2329
  }
2279
2330
  async registerAsync(p) {
2280
2331
  return this.register(p, await this.detect(p));
2281
2332
  }
2282
- heartbeat(sessionId) {
2333
+ heartbeat(sessionId, pid) {
2283
2334
  const row = this.requireSession(sessionId);
2284
2335
  const at = this.iso();
2285
2336
  if (row.status !== "offline") {
2337
+ if (pid !== void 0) this.attachedOf(row).add(pid);
2286
2338
  this.store.updateSession(sessionId, { lastSeenAt: at });
2287
2339
  return { lastSeenAt: at };
2288
2340
  }
@@ -2292,6 +2344,7 @@ var Daemon = class {
2292
2344
  status: "idle",
2293
2345
  lastSeenAt: at
2294
2346
  });
2347
+ if (pid !== void 0) this.attachedOf(row).add(pid);
2295
2348
  this.offlineSince.delete(sessionId);
2296
2349
  this.emitSession(sessionId, "updated");
2297
2350
  return { lastSeenAt: at };
@@ -2305,6 +2358,8 @@ var Daemon = class {
2305
2358
  });
2306
2359
  this.listeners.delete(sessionId);
2307
2360
  this.woken.delete(sessionId);
2361
+ this.attached.delete(sessionId);
2362
+ this.hookAt.delete(sessionId);
2308
2363
  this.offlineSince.set(sessionId, this.now().getTime());
2309
2364
  this.emitSession(sessionId, change);
2310
2365
  if (after !== before) this.emit({
@@ -2315,8 +2370,22 @@ var Daemon = class {
2315
2370
  }
2316
2371
  });
2317
2372
  }
2318
- unregister(sessionId) {
2319
- if (this.requireSession(sessionId).status !== "offline") this.depart(sessionId, "unregistered");
2373
+ /**
2374
+ * With `pid`, that MCP process detaches and the session stays online while another is attached;
2375
+ * the session departs with its last one. Without `pid` it departs at once.
2376
+ */
2377
+ unregister(sessionId, pid) {
2378
+ const row = this.requireSession(sessionId);
2379
+ if (row.status === "offline") return { ok: true };
2380
+ if (pid !== void 0) {
2381
+ const set = this.attachedOf(row);
2382
+ set.delete(pid);
2383
+ if (set.size > 0) {
2384
+ if (row.pid === pid) this.store.updateSession(sessionId, { pid: [...set][0] });
2385
+ return { ok: true };
2386
+ }
2387
+ }
2388
+ this.depart(sessionId, "unregistered");
2320
2389
  return { ok: true };
2321
2390
  }
2322
2391
  rename(p) {
@@ -2381,6 +2450,7 @@ var Daemon = class {
2381
2450
  }
2382
2451
  const holders = this.pidHolders(rows, pid, cwd, live);
2383
2452
  const only = holders.length === 1 ? holders[0] : void 0;
2453
+ if (only) this.touchHook(only.id);
2384
2454
  return { session: only ? this.view(only) : null };
2385
2455
  }
2386
2456
  /** Sessions whose host is `pid` (in `cwd`, when given), online ones first. */
@@ -2428,6 +2498,102 @@ var Daemon = class {
2428
2498
  this.daemonWake(row.id);
2429
2499
  return { session: this.view(this.requireSession(row.id)) };
2430
2500
  }
2501
+ /**
2502
+ * The session of the window a hook runs in, among the online sessions of its CLI: the one under
2503
+ * its host process (and in its folder, when the hook says which). Codex shares one host process
2504
+ * between windows, so there it prefers a session that has no conversation yet, and takes a bound
2505
+ * one only when it is the only one. Null when it is ambiguous or none matches.
2506
+ */
2507
+ windowRow(rows, p) {
2508
+ if (p.hostPid === void 0) return void 0;
2509
+ const { cwd } = p;
2510
+ const cands = rows.filter((r) => r.hostPid === p.hostPid && (cwd === void 0 || samePath(r.cwd, cwd, this.platform)));
2511
+ if (oneWindowPerHost(p.cli)) return cands.length === 1 ? cands[0] : void 0;
2512
+ const unbound = cands.filter((r) => r.nativeId === void 0);
2513
+ if (unbound.length > 0) return unbound.length === 1 ? unbound[0] : void 0;
2514
+ return cands.length === 1 ? cands[0] : void 0;
2515
+ }
2516
+ /**
2517
+ * Bind a conversation to the window's session (see `session.bind` in the protocol). The session
2518
+ * that holds the id wins; a caller with a session of its own is merged into it. Otherwise only a
2519
+ * turn start moves the window to the conversation, and a conversation that is not the window's
2520
+ * current one is ignored by every other hook. Replaces `setNative` for hooks and MCP servers.
2521
+ */
2522
+ bind(p) {
2523
+ const caller = p.sessionId === void 0 ? void 0 : this.requireOnline(p.sessionId);
2524
+ if (caller && caller.cli !== p.cli) return { session: null };
2525
+ const rows = this.store.allSessions().filter((r) => r.status !== "offline" && r.cli === p.cli);
2526
+ let holder = rows.find((r) => r.nativeId === p.nativeId);
2527
+ if (holder && !caller && p.hostPid !== void 0) {
2528
+ const pids = [...holder.hostPid === void 0 ? [] : [holder.hostPid], ...holder.hostPids ?? []];
2529
+ if (pids.length > 0 && !pids.includes(p.hostPid)) {
2530
+ const mine = rows.filter((r) => r.hostPid === p.hostPid);
2531
+ if (mine.length === 1 && mine[0]?.id !== holder.id) holder = void 0;
2532
+ }
2533
+ }
2534
+ if (holder) {
2535
+ if (caller && caller.id !== holder.id) return { session: this.merge(caller, holder, p.pid) };
2536
+ if (!caller) this.touchHook(holder.id);
2537
+ return { session: this.view(holder) };
2538
+ }
2539
+ const row = caller ?? this.windowRow(rows, p);
2540
+ if (!row) return { session: null };
2541
+ if (!caller) this.touchHook(row.id);
2542
+ if (row.nativeId !== void 0 && !p.turnStart) return { session: null };
2543
+ const others = rows.filter((r) => r.id !== row.id && r.nativeId === p.nativeId);
2544
+ const moved = row.nativeId !== void 0;
2545
+ const stale = moved && row.status === "busy";
2546
+ this.store.tx(() => {
2547
+ for (const o of others) this.store.updateSession(o.id, { nativeId: null });
2548
+ this.store.updateSession(row.id, {
2549
+ nativeId: p.nativeId,
2550
+ ...stale ? {
2551
+ status: "idle",
2552
+ turnHops: 0
2553
+ } : {}
2554
+ });
2555
+ });
2556
+ if (moved) {
2557
+ this.listeners.delete(row.id);
2558
+ this.woken.delete(row.id);
2559
+ }
2560
+ for (const o of others) this.emitSession(o.id, "updated");
2561
+ this.emitSession(row.id, "updated");
2562
+ this.daemonWake(row.id);
2563
+ return { session: this.view(this.requireSession(row.id)) };
2564
+ }
2565
+ /**
2566
+ * Fold the session of an MCP process into the session that holds its conversation: the process
2567
+ * attaches to the survivor, the mail and the lead role move to it, and the caller's row goes.
2568
+ */
2569
+ merge(from, into, pid) {
2570
+ const pids = this.attachedOf(into);
2571
+ for (const q of this.attachedOf(from)) pids.add(q);
2572
+ if (pid !== void 0) pids.add(pid);
2573
+ const lead = this.store.holder() === from.id;
2574
+ this.store.tx(() => {
2575
+ this.store.moveMailbox(from.id, into.id);
2576
+ if (lead) this.store.setHolder(into.id);
2577
+ this.store.updateSession(into.id, { lastSeenAt: this.iso() });
2578
+ this.store.deleteSession(from.id);
2579
+ });
2580
+ this.listeners.delete(from.id);
2581
+ this.woken.delete(from.id);
2582
+ this.attached.delete(from.id);
2583
+ this.hookAt.delete(from.id);
2584
+ this.offlineSince.delete(from.id);
2585
+ this.relay?.sessionsChanged();
2586
+ if (lead) this.emit({
2587
+ event: "orchestrator.changed",
2588
+ data: {
2589
+ orchestrator: into.id,
2590
+ previous: from.id
2591
+ }
2592
+ });
2593
+ this.emitSession(into.id, "updated");
2594
+ this.daemonWake(into.id);
2595
+ return this.view(this.requireSession(into.id));
2596
+ }
2431
2597
  /** Delete offline sessions and their mail. \`graceMs\` 0 removes every one at once. */
2432
2598
  removeOffline(graceMs) {
2433
2599
  const nowMs = this.now().getTime();
@@ -2446,6 +2612,8 @@ var Daemon = class {
2446
2612
  this.wokenAt.delete(r.id);
2447
2613
  this.wakersOff.delete(r.id);
2448
2614
  this.offlineSince.delete(r.id);
2615
+ this.attached.delete(r.id);
2616
+ this.hookAt.delete(r.id);
2449
2617
  }
2450
2618
  }
2451
2619
  claim(sessionId) {
@@ -2754,6 +2922,7 @@ var Daemon = class {
2754
2922
  */
2755
2923
  turnStart(sessionId) {
2756
2924
  const row = this.requireOnline(sessionId);
2925
+ this.touchHook(sessionId);
2757
2926
  const fromWake = this.woken.has(sessionId) && row.status === "busy";
2758
2927
  this.woken.delete(sessionId);
2759
2928
  this.store.updateSession(sessionId, fromWake ? { status: "busy" } : {
@@ -2804,6 +2973,7 @@ var Daemon = class {
2804
2973
  remaining: queued.length
2805
2974
  };
2806
2975
  });
2976
+ if (res.messages.length > 0) this.touchHook(row.id);
2807
2977
  if (res.messages.length > 0 ? row.status !== "busy" : endOfTurn && row.status !== "idle") this.emitSession(row.id, "updated");
2808
2978
  return {
2809
2979
  ...res,
@@ -2812,6 +2982,7 @@ var Daemon = class {
2812
2982
  }
2813
2983
  turnEnd(p) {
2814
2984
  const row = this.requireOnline(p.sessionId);
2985
+ this.touchHook(p.sessionId);
2815
2986
  this.woken.delete(p.sessionId);
2816
2987
  if (row.status === "waiting_on_question") return this.continueWith(row, false, false);
2817
2988
  return this.continueWith(row, p.allowContinue, true, RESPONSE_BUDGET_BYTES, p.maxChars);
@@ -2822,6 +2993,12 @@ var Daemon = class {
2822
2993
  */
2823
2994
  turnWake(conn, p) {
2824
2995
  const row = this.requireOnline(p.sessionId);
2996
+ if (p.nativeId !== void 0 && row.nativeId !== void 0 && p.nativeId !== row.nativeId) return {
2997
+ messages: [],
2998
+ remaining: this.store.unreadCount(row.id),
2999
+ orchestrator: this.orchestratorNow(),
3000
+ superseded: true
3001
+ };
2825
3002
  const known = this.listeners.get(row.id);
2826
3003
  if (known?.retired.includes(p.listenerId)) return {
2827
3004
  messages: [],
@@ -2877,6 +3054,7 @@ var Daemon = class {
2877
3054
  }
2878
3055
  deliver(p) {
2879
3056
  this.requireSession(p.sessionId);
3057
+ this.touchHook(p.sessionId);
2880
3058
  const at = this.iso();
2881
3059
  return this.store.tx(() => {
2882
3060
  const pending = pendingForInjection(this.store.entries(p.sessionId, { states: ["queued"] }));
@@ -2986,6 +3164,17 @@ var Daemon = class {
2986
3164
  removeAllOffline() {
2987
3165
  this.removeOffline(0);
2988
3166
  }
3167
+ /** A busy session no hook has touched for `STUCK_BUSY_MS` is idle: its turn end never came. */
3168
+ clearStuckBusy(row, nowMs) {
3169
+ if (row.status !== "busy") return;
3170
+ if (nowMs - (this.hookAt.get(row.id) ?? Math.max(Date.parse(row.startedAt), this.startedMs)) <= 18e5) return;
3171
+ this.store.updateSession(row.id, {
3172
+ status: "idle",
3173
+ turnHops: 0
3174
+ });
3175
+ this.woken.delete(row.id);
3176
+ this.emitSession(row.id, "updated");
3177
+ }
2989
3178
  sweep() {
2990
3179
  const nowMs = this.now().getTime();
2991
3180
  this.removeOffline(OFFLINE_GRACE_MS);
@@ -2999,8 +3188,16 @@ var Daemon = class {
2999
3188
  lastSeenMs,
3000
3189
  hostPid: row.hostPid
3001
3190
  }, nowMs, this.isAlive);
3002
- if (statusAfterLiveness(row.status, verdict) === "offline") this.depart(row.id, "offline");
3003
- else online++;
3191
+ if (statusAfterLiveness(row.status, verdict) === "offline") {
3192
+ this.depart(row.id, "offline");
3193
+ continue;
3194
+ }
3195
+ online++;
3196
+ const pids = this.attached.get(row.id);
3197
+ if (pids) {
3198
+ for (const q of [...pids]) if (!this.isAlive(q)) pids.delete(q);
3199
+ }
3200
+ this.clearStuckBusy(row, nowMs);
3004
3201
  }
3005
3202
  if (online > 0) this.idleSince = nowMs;
3006
3203
  else if (nowMs - this.idleSince >= this.idleExitMs) this.requestIdleExit();
@@ -1,4 +1,4 @@
1
- import { t as ClientError } from "./dist-n6XMTlyN.js";
1
+ import { t as ClientError } from "./dist-B3YYLzKS.js";
2
2
  import { n as cmd, s as plainError } from "./fmt-C2SsP5Y0.js";
3
3
  // src/daemonError.ts
4
4
  /**
@@ -1,5 +1,5 @@
1
- import { n as connect } from "./dist-n6XMTlyN.js";
2
- import { $t as updateSpawnRecord, Q as isAllowed, an as CliKind, ft as parseAllowPatterns, hn as RpcErrorCode, i as DEFAULT_ALLOW_RULES, q as formatContinuation, qt as takeAcpLaunchFile, r as ConvenoError, vn as SessionId } from "./dist-qONHJRJk.js";
1
+ import { n as connect } from "./dist-B3YYLzKS.js";
2
+ import { Sn as RpcErrorCode, Tn as SessionId, X as formatContinuation, a as DEFAULT_ALLOW_RULES, en as takeAcpLaunchFile, fn as CliKind, i as ConvenoError, on as updateSpawnRecord, rt as isAllowed, vt as parseAllowPatterns } from "./dist-CRj_cuHc.js";
3
3
  import { randomBytes } from "node:crypto";
4
4
  import { existsSync, rmSync } from "node:fs";
5
5
  import { Readable, Writable } from "node:stream";
@@ -71,7 +71,7 @@ var ToolTracker = class {
71
71
  return u.sessionUpdate === "tool_call" ? next.title ?? next.kind ?? "tool" : void 0;
72
72
  }
73
73
  };
74
- const HOST_VERSION = "0.2.0-rc.11";
74
+ const HOST_VERSION = "0.2.0-rc.12";
75
75
  /** A stop request file: `conveno stop` writes it next to the spawn record. */
76
76
  const stopRequestPath = (recordPath) => recordPath.replace(/\.json$/, ".stop");
77
77
  function withTimeout(p, ms, what) {
@@ -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 { Cn as isSocketPathTooLong, Ct as proofsMatch, D as clientProof, F as dataPaths, N as daemonProof, P as dataDir, Pn as socketPathTooLongMessage, Sn as ipcMethods, bn as defaultSocketPath, gn as RpcResponse, hn as RpcErrorCode, ln as EventPayload, pn as PROTOCOL_VERSION, r as ConvenoError, ut as newAuthNonce, xn as encodeFrame, yn as createLineDecoder } from "./dist-qONHJRJk.js";
6
+ import { A as clientProof, An as isSocketPathTooLong, At as proofsMatch, Cn as RpcResponse, Dn as defaultSocketPath, En as createLineDecoder, I as daemonProof, L as dataDir, On as encodeFrame, R as dataPaths, Sn as RpcErrorCode, Vn as socketPathTooLongMessage, bn as PROTOCOL_VERSION, gn as EventPayload, ht as newAuthNonce, i as ConvenoError, kn as ipcMethods } from "./dist-CRj_cuHc.js";
7
7
  // ../client/dist/index.js
8
8
  const DEFAULT_REQUEST_TIMEOUT_MS = 5e3;
9
9
  const DEFAULT_START_TIMEOUT_MS = 1e4;
@@ -17,6 +17,7 @@ const CLIENT_METHODS = [
17
17
  "session.byHost",
18
18
  "session.hostOf",
19
19
  "session.setNative",
20
+ "session.bind",
20
21
  "turn.start",
21
22
  "turn.end",
22
23
  "turn.wake",
@@ -2,7 +2,7 @@ import { execFile, spawn } from "node:child_process";
2
2
  import { readFileSync, statSync } from "node:fs";
3
3
  import { readFile } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
- import { Gt as startTurnContext, H as endTurnContinuation, K as findOnPath, _t as pendingHookContext, bt as planProgram, dt as ownSession, pt as parseCliVersion, xt as planSpawn } from "./dist-qONHJRJk.js";
5
+ import { Ct as pendingHookContext, Dt as planProgram, G as endTurnContinuation, Ot as planSpawn, Qt as startTurnContext, Y as findOnPath, yt as parseCliVersion } from "./dist-CRj_cuHc.js";
6
6
  import { n as cs, t as Za } from "./toml-patch-DGzVRdd1.js";
7
7
  // ../adapters/codex/dist/index.js
8
8
  const SERVER_NAME = "conveno";
@@ -607,7 +607,7 @@ const EMPTY = {
607
607
  * continuation would otherwise wait for the user. Conveno's wake limit bounds the chain.
608
608
  */
609
609
  async function hook(event, input, ctx) {
610
- await recordThreadId(input, ctx);
610
+ ctx = withThread(input, ctx, event);
611
611
  if (event === "Stop") {
612
612
  const reason = await endTurnContinuation(ctx);
613
613
  if (reason === null) return EMPTY;
@@ -632,22 +632,21 @@ async function hook(event, input, ctx) {
632
632
  }
633
633
  /**
634
634
  * The hook's `session_id` is the Codex thread id, the id `codex queue --thread` takes. Codex
635
- * sessions can share one app-server process, so the host pid alone may not tell them apart: tell
636
- * the daemon the thread id so it can wake this session by it. Best effort; an older daemon
637
- * without `session.setNative` just keeps the pid lookup.
635
+ * threads can share one app-server process, so the host pid alone may not tell windows apart: the
636
+ * daemon binds the thread to the window's session (`session.bind`), and wakes the session by it.
637
+ * A session start or a prompt may move the window to the thread; a Stop of any other thread than
638
+ * the session's current one is ignored. With several windows on one process the daemon may not
639
+ * know which one the hook is in; the thread's own MCP server binds it on its first tool call.
638
640
  */
639
- async function recordThreadId(input, ctx) {
641
+ function withThread(input, ctx, event) {
640
642
  const threadId = asObject(input).session_id;
641
- if (typeof threadId !== "string" || threadId === "") return;
642
- try {
643
- const session = await ownSession(ctx);
644
- if (!session) return;
645
- const call = ctx.client["session.setNative"];
646
- if (typeof call === "function") await call({
647
- sessionId: session.id,
648
- nativeId: threadId
649
- });
650
- } catch {}
643
+ if (typeof threadId !== "string" || threadId === "") return ctx;
644
+ return {
645
+ ...ctx,
646
+ cli: ctx.cli ?? "codex",
647
+ nativeId: threadId,
648
+ turnStart: event === "SessionStart" || event === "UserPromptSubmit"
649
+ };
651
650
  }
652
651
  /** How long `codex queue` may take (it probes the shared local app-server) before we give up. */
653
652
  const QUEUE_TIMEOUT_MS = 2e4;