@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.
@@ -1,10 +1,10 @@
1
1
  import { Box, Text, render, useApp, useInput, useStdin, useStdout } from "ink";
2
2
  import { n as connectOpts, t as adapterEnv } from "./ctx-tYftvhz_.js";
3
- import { t as daemonProblem } from "./daemonError-DraepwsB.js";
3
+ import { t as daemonProblem } from "./daemonError-0KnkgIRo.js";
4
4
  import { a as fail, n as cmd, s as plainError, u as tilde } from "./fmt-C2SsP5Y0.js";
5
5
  import { createContext, useContext, useEffect, useImperativeHandle, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
6
- import { A as completeLogin, At as readSpawnRecord, F as dataPaths, G as fetchAccountStatus, K as findOnPath, Nt as requestDeviceCode, St as pollDeviceCode, Tt as readAccountTokens, Ut as spawnRecordPath, Wt as spawnSession, _n as SESSION_NAME_PATTERN, jt as realSpawnDeps, k as compatStatus, kt as readSettings, n as AccountError, rn as writeSettings, st as logoutAccount, xt as planSpawn } from "./dist-qONHJRJk.js";
7
- import { C as openInBrowser, D as showCode$1, S as stopDaemonIfRunning, _ as unifiedDiff, a as applyOptions, c as collectPlans, d as refreshManifest, f as renewedApprovals, g as applyChanges, h as StaleError, l as detectAll, n as inspect, o as approvalWrites, r as partState, s as approvedBySetup, t as runUninstall, u as pendingOptions, v as PAIR_TIMEOUT_MS } from "./uninstall-Blt-KHI5.js";
6
+ import { Bt as requestDeviceCode, It as readSettings, J as fetchAccountStatus, Lt as readSpawnRecord, M as compatStatus, Mt as readAccountTokens, N as completeLogin, Ot as planSpawn, R as dataPaths, Rt as realSpawnDeps, Xt as spawnRecordPath, Y as findOnPath, Zt as spawnSession, ft as logoutAccount, kt as pollDeviceCode, n as AccountError, un as writeSettings, wn as SESSION_NAME_PATTERN } from "./dist-CRj_cuHc.js";
7
+ import { A as showCode$1, E as openInBrowser, T as stopDaemonIfRunning, _ as saveChoice, a as applyOptions, b as unifiedDiff, c as collectPlans, d as refreshManifest, f as renewedApprovals, g as connectedTools, h as chosenTools, l as detectAll, n as inspect, o as approvalWrites, r as partState, s as approvedBySetup, t as runUninstall, u as pendingOptions, v as StaleError, x as PAIR_TIMEOUT_MS, y as applyChanges } from "./uninstall-MaS5t1CK.js";
8
8
  import { i as tokens, n as detectColorLevel, r as detectUnicode } from "./dist-BRjg9CLd.js";
9
9
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
10
10
  import { readFileSync, statSync, writeFileSync } from "node:fs";
@@ -12,7 +12,7 @@ import { Readable } from "node:stream";
12
12
  import { basename, posix, win32 } from "node:path";
13
13
  import { spawn } from "node:child_process";
14
14
  import { homedir } from "node:os";
15
- import { r as stopRequestPath, t as killProcessTree } from "./dist-Rdj5ogAX.js";
15
+ import { r as stopRequestPath, t as killProcessTree } from "./dist-4iJnF07i.js";
16
16
  // src/tui/home/deps.ts
17
17
  /**
18
18
  * What home does outside the store: sign in and out, and take Conveno away. Real in the app, fake
@@ -570,14 +570,10 @@ function Choices({ items, multi = false, value, onChange, onSubmit, focusIndex,
570
570
  else if (input === " ") toggle(focus);
571
571
  else if (key.return) submit(focus);
572
572
  }, { isActive });
573
- const mark = multi ? k.ascii ? {
573
+ const mark = multi ? {
574
574
  on: "[x]",
575
575
  off: "[ ]",
576
576
  no: "[-]"
577
- } : {
578
- on: "●",
579
- off: "○",
580
- no: "–"
581
577
  } : void 0;
582
578
  const pointer = k.ascii ? ">" : "›";
583
579
  const labelW = Math.max(0, ...items.map((i) => [...i.label].length));
@@ -587,7 +583,7 @@ function Choices({ items, multi = false, value, onChange, onSubmit, focusIndex,
587
583
  const focused = i === focus && !item.disabled;
588
584
  const picked = value.includes(item.id);
589
585
  const lead = focused ? pointer : " ";
590
- const room = Math.max(0, full - 2 - (mark ? k.ascii ? 4 : 2 : 0));
586
+ const room = Math.max(0, full - 2 - (mark ? 4 : 0));
591
587
  const label = cut(item.label, Math.min(labelW, room), k.ascii);
592
588
  const hintRoom = room - [...label].length - 2;
593
589
  const labelProps = item.disabled ? tint(k.c.quiet) : focused ? {
@@ -612,7 +608,10 @@ function Choices({ items, multi = false, value, onChange, onSubmit, focusIndex,
612
608
  children: `${lead} `
613
609
  }),
614
610
  mark ? /* @__PURE__ */ jsx(Text, {
615
- ...item.disabled ? k.quiet : picked ? tint(k.c.entry) : k.quiet,
611
+ ...item.disabled ? k.quiet : picked ? {
612
+ ...tint(k.c.entry),
613
+ ...strong(k)
614
+ } : k.quiet,
616
615
  children: `${item.disabled ? mark.no : picked ? mark.on : mark.off} `
617
616
  }) : null,
618
617
  /* @__PURE__ */ jsx(Text, {
@@ -1188,11 +1187,16 @@ function reasonOf(e, fallback = "That did not work.") {
1188
1187
  const line = (e instanceof Error ? e.message : typeof e === "string" ? e : "").split("\n")[0]?.trim();
1189
1188
  return line ? line : fallback;
1190
1189
  }
1191
- /** The state of a session in one or two words: working, idle, waking up, waiting for you. */
1190
+ /**
1191
+ * The state of a session in one or two words: working, idle, waking up, on next prompt, waiting for
1192
+ * you. A message waits for "waking up" only when something can wake the session; one that cannot
1193
+ * (`wakeable` false, such as a window nothing listens in yet) gets it at its next prompt.
1194
+ */
1192
1195
  function stateWord(s) {
1193
1196
  if (s.status === "busy") return "working";
1194
1197
  if (s.status === "waiting_on_question") return "waiting for you";
1195
- return (s.unreadCount ?? 0) > 0 ? "waking up" : "idle";
1198
+ if ((s.unreadCount ?? 0) === 0) return "idle";
1199
+ return s.wakeable === false ? "on next prompt" : "waking up";
1196
1200
  }
1197
1201
  /** What a card says on its last line: the state, and the computer for a remote session. */
1198
1202
  function stateLine(s) {
@@ -1217,6 +1221,7 @@ function problemsOf(setup) {
1217
1221
  if (!h.fixId) continue;
1218
1222
  const cli = h.fixId.split(":")[1] ?? "";
1219
1223
  const check = setup.clis.find((c) => c.cli === cli);
1224
+ if (check?.chosen === false) continue;
1220
1225
  out.push({
1221
1226
  fixId: h.fixId,
1222
1227
  label: check?.label ?? toolName$1(cli)
@@ -3219,26 +3224,11 @@ function installPlan(cli, platform) {
3219
3224
  }
3220
3225
  }
3221
3226
  /**
3222
- * Update route, only for opencode below 2.4. `opencode upgrade` moves within the installed major
3223
- * version; OpenCode 1 needs `--major` to reach 2 (reference/src/opencode cmd/upgrade.ts). An
3224
- * unreadable version gets no update.
3227
+ * Update route. No tool needs one now: any OpenCode 1.x or 2.x works, so nothing is offered. Kept
3228
+ * as the one place to add a route again if a tool ever gets a floor.
3225
3229
  */
3226
- function updatePlan(cli, installedVersion) {
3227
- if (cli !== "opencode" || installedVersion === void 0) return { available: false };
3228
- const m = /^v?(\d+)\.(\d+)/.exec(installedVersion.trim());
3229
- if (!m) return { available: false };
3230
- const major = Number(m[1]);
3231
- const minor = Number(m[2]);
3232
- if (major > 2 || major === 2 && minor >= 4) return { available: false };
3233
- const args = major < 2 ? ["upgrade", "--major"] : ["upgrade"];
3234
- return {
3235
- available: true,
3236
- steps: [{
3237
- file: "opencode",
3238
- args,
3239
- display: `opencode ${args.join(" ")}`
3240
- }]
3241
- };
3230
+ function updatePlan(_cli, _installedVersion) {
3231
+ return { available: false };
3242
3232
  }
3243
3233
  /** Real process I/O. */
3244
3234
  function realInstallDeps() {
@@ -3548,9 +3538,13 @@ function healthFrom(input) {
3548
3538
  level: "error",
3549
3539
  text: "Conveno can't be reached"
3550
3540
  });
3551
- const installed = input.clis.filter((c) => c.status !== "not-installed");
3552
- const good = installed.filter((c) => c.status === "ready").length;
3553
- out.push(installed.length === 0 ? {
3541
+ const mine = input.clis.filter((c) => c.chosen !== false);
3542
+ const installed = mine.filter((c) => c.status !== "not-installed" || c.connected);
3543
+ const good = installed.filter((c) => c.status === "ready" || c.status === "not-installed").length;
3544
+ out.push(mine.length === 0 ? {
3545
+ level: "warn",
3546
+ text: "No AI tools chosen yet"
3547
+ } : installed.length === 0 ? {
3554
3548
  level: "warn",
3555
3549
  text: "No supported CLI found on this machine"
3556
3550
  } : {
@@ -3592,7 +3586,18 @@ function healthFrom(input) {
3592
3586
  }
3593
3587
  /** The same facts as `conveno doctor`, as friendly rows. Never throws. */
3594
3588
  async function loadSetup(ctx) {
3595
- const clis = (await Promise.all(ctx.adapters.map((a) => inspect(ctx, a)))).map((r) => checkFromRow(r, ctx.compat));
3589
+ const rows = await Promise.all(ctx.adapters.map((a) => inspect(ctx, a)));
3590
+ const chosen = new Set(await chosenTools(ctx));
3591
+ const connected = new Set(await connectedTools(ctx));
3592
+ const clis = rows.map((r) => {
3593
+ const check = checkFromRow(r, ctx.compat);
3594
+ return {
3595
+ ...check,
3596
+ chosen: chosen.has(r.adapter.cli),
3597
+ ...connected.has(r.adapter.cli) ? { connected: true } : {},
3598
+ ...check.status === "not-installed" && connected.has(r.adapter.cli) ? { note: "connected, but the program is not on this computer" } : {}
3599
+ };
3600
+ });
3596
3601
  let daemon = "stopped";
3597
3602
  let sync;
3598
3603
  try {
@@ -3655,7 +3660,7 @@ async function planFor(ctx, fixId) {
3655
3660
  installed: false,
3656
3661
  configPaths: []
3657
3662
  }));
3658
- if (detection.installed) found.push({
3663
+ if (detection.installed || parsed.kind === "uninstall") found.push({
3659
3664
  adapter,
3660
3665
  detection
3661
3666
  });
@@ -3806,8 +3811,7 @@ async function detectTools(ctx) {
3806
3811
  ...o.defaultYes ? { defaultYes: true } : {}
3807
3812
  });
3808
3813
  }
3809
- let connected = false;
3810
- if (detection.installed) connected = await adapter.plan(env, {}).then((p) => p.length === 0).catch(() => false);
3814
+ const connected = await adapter.plan(env, {}).then((p) => p.length === 0).catch(() => false);
3811
3815
  const major = Number.parseInt((detection.version ?? "").replace(/^v/i, ""), 10) < 2;
3812
3816
  return {
3813
3817
  cli,
@@ -3928,8 +3932,9 @@ function createOnboardingDeps(ctx) {
3928
3932
  update: (cli, io) => updateTool(ctx, cli, io),
3929
3933
  connect: (cli, accept, io) => changeTool(ctx, cli, fixIdWith(cli, accept), "connect", io),
3930
3934
  disconnect: (cli, io) => changeTool(ctx, cli, `uninstall:${cli}`, "remove Conveno from", io),
3931
- setLead: async (cli) => {
3932
- writeSettings(dataPaths(ctx.platform, ctx.dataDir).settings, { leadCli: cli });
3935
+ chosen: () => chosenTools(ctx),
3936
+ saveChoice: async (tools, lead) => {
3937
+ saveChoice(ctx, tools, lead);
3933
3938
  },
3934
3939
  signedIn: async () => await readAccountTokens(tokenFile(ctx)).catch(() => null) !== null,
3935
3940
  signIn: async ({ signal, onCode }) => {
@@ -4140,14 +4145,12 @@ const pushLog = (r, lines) => ({
4140
4145
  function reduce(s, a) {
4141
4146
  switch (a.type) {
4142
4147
  case "loaded": {
4143
- const installed = a.tools.filter((t) => t.installed);
4144
- const connected = a.tools.filter((t) => t.connected);
4145
- const initial = s.start === "tools" && connected.length > 0 ? connected : installed;
4148
+ const known = new Set(a.tools.map((t) => t.cli));
4146
4149
  return {
4147
4150
  ...s,
4148
4151
  tools: a.tools,
4149
4152
  signedIn: a.signedIn,
4150
- picked: initial.map((t) => t.cli)
4153
+ picked: a.chosen.filter((c) => known.has(c))
4151
4154
  };
4152
4155
  }
4153
4156
  case "begin": return s.step === "welcome" && s.tools ? {
@@ -4424,7 +4427,8 @@ function Line({ tone, children }) {
4424
4427
  const list = (names) => names.length <= 1 ? names[0] ?? "" : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
4425
4428
  function toolHint(t) {
4426
4429
  const parts = [];
4427
- if (!t.installed) parts.push(t.installable ? "not installed · I can install it" : "not installed");
4430
+ if (!t.installed && t.connected) parts.push("already connected · not on this computer");
4431
+ else if (!t.installed) parts.push(t.installable ? "not installed · I can install it" : "not installed");
4428
4432
  else if (t.connected) parts.push("already connected");
4429
4433
  else parts.push("on this computer");
4430
4434
  if (t.installed && t.update) parts.push("needs an update");
@@ -4800,18 +4804,27 @@ function Onboarding({ deps, start, onDone }) {
4800
4804
  }, []);
4801
4805
  useEffect(() => {
4802
4806
  const d = depsRef.current;
4803
- Promise.all([d.detect(), d.signedIn().catch(() => false)]).then(([tools, signedIn]) => {
4807
+ Promise.all([
4808
+ d.detect(),
4809
+ d.signedIn().catch(() => false),
4810
+ d.chosen().catch(() => [])
4811
+ ]).then(([tools, signedIn, chosen]) => {
4804
4812
  if (live.current) dispatch({
4805
4813
  type: "loaded",
4806
4814
  tools,
4807
- signedIn
4815
+ signedIn,
4816
+ chosen
4808
4817
  });
4809
4818
  });
4810
4819
  }, []);
4811
4820
  useEffect(() => {
4812
- if (s.step !== "working" || led.current) return;
4821
+ if (s.step !== "account" && s.step !== "finish") return;
4822
+ if (led.current) return;
4813
4823
  led.current = true;
4814
- if (s.lead) depsRef.current.setLead(s.lead).catch(() => {});
4824
+ const tools = connectedRows(s).map((r) => r.cli);
4825
+ if (tools.length === 0) return;
4826
+ const lead = s.lead && tools.includes(s.lead) ? s.lead : void 0;
4827
+ depsRef.current.saveChoice(tools, lead).catch(() => {});
4815
4828
  }, [s]);
4816
4829
  useEffect(() => {
4817
4830
  if (s.step !== "working") return;
@@ -4,18 +4,18 @@ import { homedir } from "node:os";
4
4
  import { delimiter, join, win32 } from "node:path";
5
5
  import { createInterface } from "node:readline";
6
6
  import { fileURLToPath } from "node:url";
7
- import { n as antigravityAdapter } from "./dist-KWlFKO7H.js";
8
- import { a as opencodeAdapter, o as claudeAdapter, r as readAllStdin } from "./hook-entry-BYvXWDJv.js";
9
- import { t as codexAdapter } from "./dist-DEjU_KXC.js";
10
- import { t as grokAdapter } from "./dist-Y0JDSJP_.js";
7
+ import { n as antigravityAdapter } from "./dist-Du1hwaux.js";
8
+ import { a as opencodeAdapter, o as claudeAdapter, r as readAllStdin } from "./hook-entry-DWa1oppt.js";
9
+ import { t as codexAdapter } from "./dist-BjATai4T.js";
10
+ import { t as grokAdapter } from "./dist-DF0nL8wE.js";
11
11
  import { t as createTheme } from "./dist-BRjg9CLd.js";
12
- import { n as connect$1 } from "./dist-n6XMTlyN.js";
13
- import { Bn as number, Dt as readCommandLine, Et as readAncestry, Fn as _enum, Hn as string, In as array, Ln as boolean, P as dataDir, R as detectRepo, Rt as resolveWindowsCommand, S as baseName, T as claimSpawnRecord, Wt as spawnSession, Y as formatInbox, at as launcherText, dn as MessageId, en as validateRename, f as SpawnError, fn as OWNER_SESSION_ID, hn as RpcErrorCode, ht as parsePs1ShimTarget, in as CLI_KINDS, it as launcherPath, jt as realSpawnDeps, lt as needsQuoting, mt as parseCmdShimTarget, o as HEARTBEAT_INTERVAL_MS, r as ConvenoError, s as NOT_FROM_USER_NOTICE, u as SPAWN_CLIS, vn as SessionId, xt as planSpawn, y as attachAcpSession } from "./dist-qONHJRJk.js";
14
- import "./dist-Dg2IY9OA.js";
12
+ import { n as connect$1 } from "./dist-B3YYLzKS.js";
13
+ import { Gt as resolveWindowsCommand, Hn as _enum, L as dataDir, Nt as readAncestry, O as claimSpawnRecord, Ot as planSpawn, Pt as readCommandLine, Q as formatInbox, Rt as realSpawnDeps, S as attachAcpSession, Sn as RpcErrorCode, T as baseName, Tn as SessionId, Un as array, V as detectRepo, Wn as boolean, Yn as string, Zt as spawnSession, bt as parseCmdShimTarget, c as NOT_FROM_USER_NOTICE, d as SPAWN_CLIS, dn as CLI_KINDS, i as ConvenoError, lt as launcherPath, mt as needsQuoting, p as SpawnError, qn as number, s as HEARTBEAT_INTERVAL_MS, sn as validateRename, ut as launcherText, vn as MessageId, wt as pendingTurn, xt as parsePs1ShimTarget, yn as OWNER_SESSION_ID } from "./dist-CRj_cuHc.js";
14
+ import "./dist-DeN0jR3I.js";
15
15
  import { access } from "node:fs/promises";
16
16
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
17
17
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
18
- // ../daemon/dist/server-Dh2GFVxr.js
18
+ // ../daemon/dist/server-p7RFPs-_.js
19
19
  /** `kill(pid, 0)` liveness: EPERM means the process exists but belongs to someone else. */
20
20
  function defaultIsAlive(pid) {
21
21
  try {
@@ -28,7 +28,7 @@ function defaultIsAlive(pid) {
28
28
  `${OWNER_SESSION_ID}`;
29
29
  SessionId.parse("0".repeat(26));
30
30
  // ../mcp/dist/index.js
31
- const SERVER_VERSION = "0.2.0-rc.11";
31
+ const SERVER_VERSION = "0.2.0-rc.12";
32
32
  const ok = (text) => ({ content: [{
33
33
  type: "text",
34
34
  text
@@ -140,25 +140,20 @@ function createServer(opts) {
140
140
  /** This server acts as a session an ACP host registered, and leaves its lifecycle to the host. */
141
141
  let attached = false;
142
142
  /**
143
- * OpenCode 2.x serves several sessions from one MCP process. Each OpenCode session that calls a
144
- * tool gets its own Conveno session; the first one takes over the session this process
145
- * registered at start, the others register fresh and heartbeat on their own.
143
+ * The id Conveno acts as. It starts as the session this process registered, and changes to the
144
+ * surviving session when `session.bind` merges this process's session into the one that already
145
+ * holds its conversation (Codex runs one MCP server per thread, so a thread the window already
146
+ * has may be registered a second time). Heartbeats, tool calls and unregister all use it.
146
147
  */
147
- const byOpencode = /* @__PURE__ */ new Map();
148
- const extraBeats = /* @__PURE__ */ new Map();
149
- let baseOwner;
150
- /** Stop an extra session's heartbeat and forget it, so a closed OpenCode session goes offline. */
151
- const release = (ocId, id) => {
152
- const beat = extraBeats.get(id);
153
- if (beat) clearInterval(beat);
154
- extraBeats.delete(id);
155
- byOpencode.delete(ocId);
156
- };
157
- const register = async (extra = false, ocId) => {
148
+ let actingId;
149
+ /** The conversation this process last bound, so a tool call binds only when it changes. */
150
+ let boundConversation;
151
+ let binding = Promise.resolve();
152
+ const register = async () => {
158
153
  const repo = await detectRepo(cwd, { exists: pathExists });
159
154
  const cliVersion = process.env.CONVENO_CLI_VERSION?.trim().slice(0, 64);
160
155
  const { hostPid, hostPids } = await host;
161
- const record = extra ? void 0 : claimSpawnRecord(spawnDataDir, cli, hostPids);
156
+ const record = claimSpawnRecord(spawnDataDir, cli, hostPids);
162
157
  if (record?.acp) {
163
158
  attached = true;
164
159
  return attachAcpSession(client, spawnDataDir, record);
@@ -175,31 +170,53 @@ function createServer(opts) {
175
170
  ...spawnedBy.success ? { spawnedBy: spawnedBy.data } : {},
176
171
  ...record ? { spawned: true } : {}
177
172
  };
178
- const res = await (record ? client["session.register"]({
173
+ let session = (await (record ? client["session.register"]({
179
174
  ...params,
180
175
  name: record.name
181
176
  }).catch((err) => {
182
177
  if (err instanceof ConvenoError && err.code === RpcErrorCode.Conflict) return client["session.register"](params);
183
178
  throw err;
184
- }) : client["session.register"](params));
185
- const id = res.session.id;
179
+ }) : client["session.register"](params))).session;
180
+ actingId = session.id;
181
+ boundConversation = session.nativeId;
186
182
  const claudeId = cli === "claude" ? process.env.CLAUDE_CODE_SESSION_ID?.trim() : void 0;
187
- if (!extra && claudeId) await client["session.setNative"]({
188
- sessionId: id,
189
- nativeId: claudeId
190
- }).catch(() => {});
183
+ if (claudeId && session.nativeId === void 0) {
184
+ const bound = await bindTo(claudeId, session);
185
+ if (bound) session = bound;
186
+ if (await pendingTurn(spawnDataDir, "claude-pending-turn").take(claudeId)) await client["turn.start"]({ sessionId: session.id }).catch(() => {});
187
+ }
191
188
  const beat = setInterval(() => {
192
- client["session.heartbeat"]({ sessionId: id }).catch((err) => {
193
- if (extra && ocId !== void 0 && isSessionGone(err)) release(ocId, id);
194
- });
189
+ if (actingId) client["session.heartbeat"]({
190
+ sessionId: actingId,
191
+ pid: process.pid
192
+ }).catch(() => {});
195
193
  }, HEARTBEAT_INTERVAL_MS);
196
194
  beat.unref();
197
- if (extra) extraBeats.set(id, beat);
198
- else {
199
- if (timer) clearInterval(timer);
200
- timer = beat;
195
+ if (timer) clearInterval(timer);
196
+ timer = beat;
197
+ return session;
198
+ };
199
+ /**
200
+ * Bind this process's session to a conversation. The daemon may answer with another session, the
201
+ * one that already holds it; this process acts as that one from then on. Best effort: without
202
+ * the answer the session stays as it is.
203
+ */
204
+ const bindTo = async (conversation, me) => {
205
+ try {
206
+ const { session } = await client["session.bind"]({
207
+ cli,
208
+ nativeId: conversation,
209
+ sessionId: me.id,
210
+ pid: process.pid,
211
+ turnStart: true
212
+ });
213
+ if (!session) return void 0;
214
+ boundConversation = conversation;
215
+ actingId = session.id;
216
+ return session;
217
+ } catch {
218
+ return;
201
219
  }
202
- return res.session;
203
220
  };
204
221
  const ensure = () => {
205
222
  if (!registering) {
@@ -211,20 +228,15 @@ function createServer(opts) {
211
228
  }
212
229
  return registering;
213
230
  };
214
- /** Forget a dead session so the next ensure() registers again. Only drops `dead`, not a newer one. */
215
- const forget = (dead) => {
216
- if (registering === dead) registering = void 0;
217
- };
218
231
  const shutdown = () => {
219
232
  shutting ??= (async () => {
220
233
  if (timer) clearInterval(timer);
221
234
  timer = void 0;
222
235
  const s = await registering?.catch(() => void 0);
223
- if (s && !attached) await client["session.unregister"]({ sessionId: s.id }).catch(() => void 0);
224
- for (const beat of extraBeats.values()) clearInterval(beat);
225
- extraBeats.clear();
226
- const others = await Promise.all([...byOpencode.values()].map((p) => p.catch(() => void 0)));
227
- for (const o of others) if (o && o.id !== s?.id) await client["session.unregister"]({ sessionId: o.id }).catch(() => void 0);
236
+ if (s && !attached) await client["session.unregister"]({
237
+ sessionId: actingId ?? s.id,
238
+ pid: process.pid
239
+ }).catch(() => void 0);
228
240
  })();
229
241
  return shutting;
230
242
  };
@@ -239,44 +251,38 @@ function createServer(opts) {
239
251
  await closeTransport();
240
252
  await shutdown();
241
253
  };
242
- /** The Conveno session for an OpenCode session id; without one, this process's own session. */
243
- const sessionFor = (ocId) => {
244
- if (!ocId) return ensure();
245
- let p = byOpencode.get(ocId);
246
- if (!p) {
247
- const takeBase = baseOwner === void 0;
248
- if (takeBase) baseOwner = ocId;
249
- const made = (takeBase ? ensure() : register(true, ocId)).then(async (s) => {
250
- await client["session.setNative"]({
251
- sessionId: s.id,
252
- nativeId: ocId
253
- });
254
- return s;
255
- });
256
- p = made;
257
- byOpencode.set(ocId, made);
258
- made.catch(() => {
259
- if (byOpencode.get(ocId) === made) byOpencode.delete(ocId);
260
- if (takeBase && baseOwner === ocId) baseOwner = void 0;
261
- });
262
- }
263
- return p;
254
+ /**
255
+ * The session a tool call acts as. A call that names its conversation (`_meta`) is a turn start
256
+ * in it: when it differs from the one this process last bound, the window's session moves to it
257
+ * (and a session of another process that already holds it takes this one over).
258
+ */
259
+ const sessionFor = async (conversation) => {
260
+ const me = await ensure();
261
+ if (!conversation || attached || conversation === boundConversation) return me;
262
+ const turn = binding.then(async () => {
263
+ const current = await ensure();
264
+ if (conversation === boundConversation) return current;
265
+ const bound = await bindTo(conversation, current);
266
+ if (bound) registering = Promise.resolve(bound);
267
+ return bound ?? current;
268
+ });
269
+ binding = turn.catch(() => void 0);
270
+ return turn;
264
271
  };
265
272
  /** Drop a dead session so the next call registers again. */
266
- const forgetFor = (ocId, dead) => {
267
- if (!ocId) {
268
- forget(dead);
269
- return;
270
- }
271
- if (byOpencode.get(ocId) === dead) byOpencode.delete(ocId);
272
- if (baseOwner === ocId) {
273
- baseOwner = void 0;
274
- registering = void 0;
275
- }
273
+ const forgetSession = () => {
274
+ registering = void 0;
275
+ boundConversation = void 0;
276
+ actingId = void 0;
276
277
  };
277
- /** OpenCode puts the calling session's id in the request's `_meta`. */
278
- const opencodeId = (extra) => {
279
- const v = extra?._meta?.["ai.opencode/sessionID"];
278
+ /**
279
+ * The conversation a tool call comes from, in the request's `_meta`: Codex `threadId`, OpenCode
280
+ * `ai.opencode/sessionID`, Antigravity `antigravity.google/root_conversation_id`.
281
+ */
282
+ const conversationOf = (extra) => {
283
+ const meta = extra?._meta;
284
+ const key = cli === "codex" ? "threadId" : cli === "opencode" ? "ai.opencode/sessionID" : cli === "antigravity" ? "antigravity.google/root_conversation_id" : void 0;
285
+ const v = key === void 0 ? void 0 : meta?.[key];
280
286
  return typeof v === "string" && v.length > 0 && v.length <= 256 ? v : void 0;
281
287
  };
282
288
  /**
@@ -287,16 +293,15 @@ function createServer(opts) {
287
293
  const tool = (body) => async (...given) => {
288
294
  const extra = given.length > 1 ? given[given.length - 1] : void 0;
289
295
  const args = given.length > 1 ? given[0] : {};
290
- const oc = opencodeId(extra ?? given[0]);
291
- const first = sessionFor(oc);
296
+ const conversation = conversationOf(extra ?? given[0]);
292
297
  try {
293
- return ok(await body(await first, args));
298
+ return ok(await body(await sessionFor(conversation), args));
294
299
  } catch (err) {
295
300
  if (!isSessionGone(err)) return fail(err);
296
- forgetFor(oc, first);
301
+ forgetSession();
297
302
  }
298
303
  try {
299
- return ok(await body(await sessionFor(oc), args));
304
+ return ok(await body(await sessionFor(conversation), args));
300
305
  } catch (err) {
301
306
  return isSessionGone(err) ? fail(/* @__PURE__ */ new Error(SESSION_LOST_TEXT)) : fail(err);
302
307
  }