@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,7 +1,7 @@
1
1
  import { homedir, tmpdir } from "node:os";
2
2
  import { dirname, join, posix, win32 } from "node:path";
3
3
  import { execFile, spawn, spawnSync } from "node:child_process";
4
- import { accessSync, chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
4
+ import { accessSync, appendFileSync, chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
5
5
  import { chmod, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
6
6
  import crypto, { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
7
7
  import { applyEdits, findNodeAtLocation, modify, parse as parse$1, parseTree, printParseErrorCode } from "jsonc-parser";
@@ -6194,6 +6194,12 @@ const Session = object({
6194
6194
  * `session.setNative`. Hooks of a CLI that runs many sessions in one process find theirs by it.
6195
6195
  */
6196
6196
  nativeId: string().min(1).max(256).optional(),
6197
+ /**
6198
+ * Can something wake this session when it is idle right now (a connected listener, relay or
6199
+ * watcher, a daemon waker with a conversation to wake, or an ACP host)? False: a message waits
6200
+ * until the user's next prompt. Absent on a daemon or device that does not report it.
6201
+ */
6202
+ wakeable: boolean().optional(),
6197
6203
  /** Set on sessions of the owner's other devices, reached through the relay. */
6198
6204
  remote: literal(true).optional(),
6199
6205
  /** Display name of the device a remote session runs on. */
@@ -6356,11 +6362,17 @@ const ipcMethods = {
6356
6362
  result: SessionResult
6357
6363
  },
6358
6364
  "session.heartbeat": {
6359
- params: object(sid),
6365
+ params: object({
6366
+ ...sid,
6367
+ pid: number().int().positive().optional()
6368
+ }),
6360
6369
  result: object({ lastSeenAt: IsoTimestamp })
6361
6370
  },
6362
6371
  "session.unregister": {
6363
- params: object(sid),
6372
+ params: object({
6373
+ ...sid,
6374
+ pid: number().int().positive().optional()
6375
+ }),
6364
6376
  result: object({ ok: literal(true) })
6365
6377
  },
6366
6378
  "session.rename": {
@@ -6394,6 +6406,19 @@ const ipcMethods = {
6394
6406
  }),
6395
6407
  result: SessionResult
6396
6408
  },
6409
+ "session.bind": {
6410
+ params: object({
6411
+ cli: CliKind,
6412
+ nativeId: string().min(1).max(256),
6413
+ sessionId: SessionId.optional(),
6414
+ /** The calling MCP process, attached to the surviving session on a merge. */
6415
+ pid: number().int().positive().optional(),
6416
+ hostPid: number().int().positive().optional(),
6417
+ cwd: string().min(1).optional(),
6418
+ turnStart: boolean().default(false)
6419
+ }).refine((p) => p.sessionId !== void 0 || p.hostPid !== void 0, { message: "provide sessionId or hostPid" }),
6420
+ result: object({ session: Session.nullable() })
6421
+ },
6397
6422
  "session.hostOf": {
6398
6423
  params: object({
6399
6424
  cli: CliKind,
@@ -6424,6 +6449,11 @@ const ipcMethods = {
6424
6449
  ...sid,
6425
6450
  /** Chosen by the listener. The newest listener of a session wins; older ones are told to stop. */
6426
6451
  listenerId: string().regex(/^[A-Za-z0-9_-]{8,64}$/, "invalid listener id"),
6452
+ /**
6453
+ * The conversation this listener serves. When the session has moved to another one
6454
+ * (`session.bind`), the listener is superseded: it gets nothing and must stop.
6455
+ */
6456
+ nativeId: string().min(1).max(256).optional(),
6427
6457
  maxChars
6428
6458
  }),
6429
6459
  result: TurnDelivery.extend({ superseded: boolean() })
@@ -7026,6 +7056,20 @@ async function logoutAccount(path, io = {}) {
7026
7056
  revoked
7027
7057
  };
7028
7058
  }
7059
+ /**
7060
+ * CLIs whose window is one host process: a second MCP server under the same host process (a
7061
+ * reconnect, Grok's new MCP per `/new`) belongs to the window's session, so it attaches to it
7062
+ * instead of making a row. Codex runs every thread's MCP under one app-server process that several
7063
+ * windows may share, so only the thread id tells its windows apart.
7064
+ */
7065
+ const ONE_WINDOW_PER_HOST = {
7066
+ claude: true,
7067
+ opencode: true,
7068
+ antigravity: true,
7069
+ grok: true,
7070
+ codex: false
7071
+ };
7072
+ const oneWindowPerHost = (cli) => ONE_WINDOW_PER_HOST[cli];
7029
7073
  const pathApi$2 = (platform) => platform === "win32" ? win32 : posix;
7030
7074
  /**
7031
7075
  * Conveno data directory. Pure: platform, environment and home directory are arguments.
@@ -7083,6 +7127,12 @@ async function pruneAsked(dir, now = Date.now()) {
7083
7127
  } catch {}
7084
7128
  }
7085
7129
  /**
7130
+ * The key of an ask that is made once per session and conversation: a window's session moves
7131
+ * between conversations, and a helper started for one does not serve the next. Without a
7132
+ * conversation id, the session alone.
7133
+ */
7134
+ const askedKey = (sessionId, conversationId) => conversationId === void 0 || conversationId === "" ? sessionId : `${sessionId}_${conversationId}`;
7135
+ /**
7086
7136
  * "Asked once per session" for a Stop hook request: one empty file per Conveno session in
7087
7137
  * `<data dir>/<folder>`. Best effort both ways: a failure only means the request can repeat.
7088
7138
  */
@@ -7174,7 +7224,10 @@ function formatFramedMessage(message, options = {}) {
7174
7224
  const sender = senderOf(message);
7175
7225
  const reply = message.replyTo ? ` Reply to message ${message.replyTo}.` : "";
7176
7226
  const when = formatClock(message.createdAt);
7177
- const header = isFromOwner(message) ? `[conveno] Message from the user (the person at this computer) at ${when}.${reply} ${FROM_USER_NOTICE}` : `[conveno] ${options.task ? "Task from the orchestrator" : "Message from"} ${sender.name} (${sender.cli}) at ${when}.${reply} ${options.task ? ORCHESTRATOR_TASK_NOTICE : NOT_FROM_USER_NOTICE}`;
7227
+ const lead = options.task === true;
7228
+ const asTask = lead && !message.replyTo;
7229
+ const label = asTask ? "Task from the orchestrator" : lead ? "Reply from the orchestrator" : "Message from";
7230
+ const header = isFromOwner(message) ? `[conveno] Message from the user (the person at this computer) at ${when}.${reply} ${FROM_USER_NOTICE}` : `[conveno] ${label} ${sender.name} (${sender.cli}) at ${when}.${reply} ${asTask ? ORCHESTRATOR_TASK_NOTICE : NOT_FROM_USER_NOTICE}`;
7178
7231
  const meta = [`Message id: ${message.id}`];
7179
7232
  if (message.urgent) meta.push("Marked urgent by the sender.");
7180
7233
  const body = renderBody(message);
@@ -7208,8 +7261,8 @@ function formatHookContext(messages) {
7208
7261
  }
7209
7262
  /**
7210
7263
  * The prompt for a turn Conveno starts by itself (end of turn or idle wake). It says
7211
- * that Conveno, not the user, started the turn. Tasks from the current orchestrator carry the task
7212
- * notice; every other message keeps the not-from-user notice.
7264
+ * that Conveno, not the user, started the turn. New messages from the current orchestrator carry the task
7265
+ * notice (replies do not, so workers do not answer a reply); every other message keeps the not-from-user notice.
7213
7266
  */
7214
7267
  function formatContinuation(messages, orchestrator, remaining = 0) {
7215
7268
  if (messages.length === 0) return "";
@@ -7438,24 +7491,15 @@ function parseCliVersion(output) {
7438
7491
  var clis = {
7439
7492
  "claude": {
7440
7493
  "verified": "2.1.332",
7441
- "minimum": "2.1.332"
7442
- },
7443
- "codex": {
7444
- "verified": "0.172.0",
7445
- "minimum": "0.172.0"
7446
- },
7447
- "opencode": {
7448
- "verified": "2.4.3",
7449
- "minimum": "1.19.6"
7494
+ "minimum": "2.1.139"
7450
7495
  },
7496
+ "codex": { "verified": "0.172.0" },
7497
+ "opencode": { "verified": "2.4.3" },
7451
7498
  "antigravity": {
7452
7499
  "verified": "1.5.20",
7453
- "minimum": "1.5.20"
7500
+ "minimum": "1.5.8"
7454
7501
  },
7455
- "grok": {
7456
- "verified": "1.0.92",
7457
- "minimum": "1.0.92"
7458
- }
7502
+ "grok": { "verified": "1.0.92" }
7459
7503
  };
7460
7504
  var acpAdapters = {
7461
7505
  "@agentclientprotocol/codex-acp": "2.10.0",
@@ -7463,8 +7507,7 @@ var acpAdapters = {
7463
7507
  };
7464
7508
  /**
7465
7509
  * Versions per CLI, from `compat.json`. The nightly compat workflow raises `verified` when a newer
7466
- * release passes its checks. `minimum` changes only by hand, when a format change drops older
7467
- * releases.
7510
+ * release passes its checks. `minimum` changes only by hand, when Conveno starts to need a feature older releases lack.
7468
7511
  */
7469
7512
  const COMPAT = clis;
7470
7513
  /** The numeric part of a version: `2.1.332`, `0.172.0-alpha.3` or `2026.11.22-e9042b2`. */
@@ -7490,10 +7533,10 @@ function compareVersions(a, b) {
7490
7533
  function compatStatus(cli, version, table = COMPAT) {
7491
7534
  const entry = table[cli];
7492
7535
  if (!entry || !version) return { kind: "unknown" };
7493
- const vsMin = compareVersions(version, entry.minimum);
7536
+ const vsMin = entry.minimum === void 0 ? 0 : compareVersions(version, entry.minimum);
7494
7537
  const vsVerified = compareVersions(version, entry.verified);
7495
7538
  if (vsMin === void 0 || vsVerified === void 0) return { kind: "unknown" };
7496
- if (vsMin < 0) return {
7539
+ if (vsMin < 0 && entry.minimum !== void 0) return {
7497
7540
  kind: "older",
7498
7541
  minimum: entry.minimum
7499
7542
  };
@@ -7594,6 +7637,7 @@ function openWatch(o) {
7594
7637
  const r = await client["turn.wake"]({
7595
7638
  sessionId: id,
7596
7639
  listenerId,
7640
+ ...o.nativeId === void 0 ? {} : { nativeId: o.nativeId },
7597
7641
  ...o.maxChars === void 0 ? {} : { maxChars: o.maxChars }
7598
7642
  });
7599
7643
  if (r.superseded) return {
@@ -7705,6 +7749,18 @@ const MAX_RECONNECT_MS = 6e4;
7705
7749
  * (which would print a format that CLI discards) never marks anything delivered.
7706
7750
  */
7707
7751
  async function ownSession(ctx) {
7752
+ if (ctx.nativeId !== void 0 && ctx.cli !== void 0) try {
7753
+ const { session } = await ctx.client["session.bind"]({
7754
+ cli: ctx.cli,
7755
+ nativeId: ctx.nativeId,
7756
+ hostPid: ctx.hostPid,
7757
+ ...ctx.cwd === void 0 ? {} : { cwd: ctx.cwd },
7758
+ turnStart: ctx.turnStart === true
7759
+ });
7760
+ return session && ctx.cli !== void 0 && session.cli !== ctx.cli ? null : session;
7761
+ } catch (e) {
7762
+ if (e?.code !== RpcErrorCode.MethodNotFound) throw e;
7763
+ }
7708
7764
  const { session } = await ctx.client["session.byHost"]({
7709
7765
  pid: ctx.hostPid,
7710
7766
  ...ctx.cwd === void 0 ? {} : { cwd: ctx.cwd },
@@ -7755,7 +7811,10 @@ async function pendingHookContext(ctx, opts = {}) {
7755
7811
  async function startTurnContext(ctx, opts = {}) {
7756
7812
  try {
7757
7813
  const session = await ownSession(ctx);
7758
- if (!session) return null;
7814
+ if (!session) {
7815
+ await opts.onNoSession?.();
7816
+ return null;
7817
+ }
7759
7818
  try {
7760
7819
  await ctx.client["turn.start"]({ sessionId: session.id });
7761
7820
  } catch {}
@@ -7813,15 +7872,20 @@ async function waitForWork(ctx, opts = {}) {
7813
7872
  */
7814
7873
  async function awaitOwnSession(ctx, waitMs, pollMs, signal) {
7815
7874
  const until = Date.now() + waitMs;
7875
+ let own = ctx;
7816
7876
  for (;;) {
7817
7877
  try {
7818
- const session = await ownSession(ctx);
7878
+ const session = await ownSession(own);
7819
7879
  if (session) return session;
7820
7880
  } catch {
7821
7881
  return "disconnected";
7822
7882
  }
7823
7883
  if (Date.now() + pollMs > until || signal?.aborted) return null;
7824
7884
  if (ctx.isAlive && !ctx.isAlive(ctx.hostPid)) return null;
7885
+ if (own.turnStart) own = {
7886
+ ...own,
7887
+ turnStart: false
7888
+ };
7825
7889
  await new Promise((r) => setTimeout(r, pollMs));
7826
7890
  }
7827
7891
  }
@@ -7852,18 +7916,24 @@ async function waitForWorkBatch(ctx, opts = {}) {
7852
7916
  delay = Math.min(delay * 2, Math.max(opts.reconnectMs ?? 0, MAX_RECONNECT_MS));
7853
7917
  return ok;
7854
7918
  };
7919
+ let round = ctx;
7855
7920
  for (;;) {
7856
- const session = await awaitOwnSession(ctx, opts.registerWaitMs ?? 0, opts.registerPollMs ?? DEFAULT_REGISTER_POLL_MS, opts.signal);
7921
+ const session = await awaitOwnSession(round, opts.registerWaitMs ?? 0, opts.registerPollMs ?? DEFAULT_REGISTER_POLL_MS, opts.signal);
7857
7922
  if (session === "disconnected") {
7858
7923
  if (await retry()) continue;
7859
7924
  return null;
7860
7925
  }
7861
7926
  if (!session) return null;
7862
7927
  delay = opts.reconnectMs;
7928
+ if (round.turnStart) round = {
7929
+ ...round,
7930
+ turnStart: false
7931
+ };
7863
7932
  const r = await waitForWake({
7864
7933
  client: ctx.client,
7865
7934
  sessionId: session.id,
7866
7935
  listenerId,
7936
+ ...ctx.nativeId !== void 0 ? { nativeId: ctx.nativeId } : {},
7867
7937
  ...opts.pollMs !== void 0 ? { pollMs: opts.pollMs } : {},
7868
7938
  ...opts.hostCheckMs !== void 0 ? { hostCheckMs: opts.hostCheckMs } : {},
7869
7939
  ...deadline !== 1e400 ? { maxMs: Math.max(0, deadline - Date.now()) } : {},
@@ -7879,6 +7949,42 @@ async function waitForWorkBatch(ctx, opts = {}) {
7879
7949
  return null;
7880
7950
  }
7881
7951
  }
7952
+ /** The log rotates once it passes this size; one old file is kept (`hooks.log.1`). */
7953
+ const HOOK_LOG_MAX_BYTES = 1e6;
7954
+ /** `<data dir>/logs/hooks.log`. */
7955
+ const hookLogPath = (dataDir) => join(dataDir, "logs", "hooks.log");
7956
+ /** Keep a logged word to plain characters, so one entry is one line and nothing is injected. */
7957
+ const plain = (v, max, extra = "") => v.replace(new RegExp(`[^A-Za-z0-9_.@:${extra}-]`, "g"), "_").slice(0, max);
7958
+ /**
7959
+ * One line: `<iso time> cli=<cli> event=<event> conv=<first 8 of the conversation id> session=<name
7960
+ * or none> result=<result>`. No message text and no tokens: only ids the CLI hands to hooks and the
7961
+ * session's name.
7962
+ */
7963
+ function hookLogLine(e) {
7964
+ const conv = e.conversationId ? plain(e.conversationId, 8) : "-";
7965
+ return `${(e.at ?? /* @__PURE__ */ new Date()).toISOString()} cli=${plain(e.cli, 16)} event=${plain(e.event, 32)} conv=${conv} session=${e.session ? plain(e.session, 64) : "none"} result=${plain(e.result, 40, " ")}\n`;
7966
+ }
7967
+ /**
7968
+ * Append one line to the hook log, rotating at `HOOK_LOG_MAX_BYTES`. Synchronous and tiny so a hook
7969
+ * is not made slower, and it never throws: a log that cannot be written must not change a hook.
7970
+ */
7971
+ function appendHookLog(path, line, maxBytes = HOOK_LOG_MAX_BYTES) {
7972
+ try {
7973
+ try {
7974
+ if (statSync(path).size > maxBytes) {
7975
+ rmSync(`${path}.1`, { force: true });
7976
+ renameSync(path, `${path}.1`);
7977
+ }
7978
+ } catch {}
7979
+ try {
7980
+ appendFileSync(path, line, { mode: 384 });
7981
+ } catch (e) {
7982
+ if (e.code !== "ENOENT") throw e;
7983
+ mkdirSync(dirname(path), { recursive: true });
7984
+ appendFileSync(path, line, { mode: 384 });
7985
+ }
7986
+ } catch {}
7987
+ }
7882
7988
  const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
7883
7989
  const PARSE_OPTIONS = { allowTrailingComma: true };
7884
7990
  /**
@@ -8320,6 +8426,48 @@ function clearOrchestrator(holder, sessions) {
8320
8426
  function holderAfterDeparture(holder, departed) {
8321
8427
  return holder === departed ? null : holder;
8322
8428
  }
8429
+ /** Claude Code's notes (the hooks write them, the MCP server takes them). */
8430
+ const CLAUDE_PENDING_TURN_FOLDER = "claude-pending-turn";
8431
+ /** A note older than this is from a turn long over. */
8432
+ const PENDING_TURN_MAX_AGE_MS = 6e5;
8433
+ /**
8434
+ * "A turn started before this window's session registered." A CLI can run its first prompt's hook
8435
+ * before its MCP server has registered (Claude Code started with a prompt, as `conveno spawn` does),
8436
+ * so the hook finds no session and the turn would show as idle. The hook leaves one empty file per
8437
+ * conversation in `<data dir>/<folder>`; the MCP server takes it when it registers and starts the
8438
+ * turn, and the turn's end removes it. Best effort: a failure only loses the busy state of that turn.
8439
+ */
8440
+ function pendingTurn(dir, folder) {
8441
+ const file = (conversationId) => join(dir, folder, conversationId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 128));
8442
+ return {
8443
+ async mark(conversationId) {
8444
+ try {
8445
+ const f = file(conversationId);
8446
+ await mkdir(join(f, ".."), { recursive: true });
8447
+ await writeFile(f, "");
8448
+ const now = Date.now();
8449
+ for (const name of await readdir(join(f, ".."))) {
8450
+ const g = join(f, "..", name);
8451
+ if (now - (await stat(g)).mtimeMs > 6e5) await rm(g, { force: true });
8452
+ }
8453
+ } catch {}
8454
+ },
8455
+ /** True when a fresh note was there; the note is removed either way. */
8456
+ async take(conversationId, now = Date.now()) {
8457
+ try {
8458
+ const f = file(conversationId);
8459
+ const fresh = now - (await stat(f)).mtimeMs <= PENDING_TURN_MAX_AGE_MS;
8460
+ await rm(f, { force: true });
8461
+ return fresh;
8462
+ } catch {
8463
+ return false;
8464
+ }
8465
+ },
8466
+ async clear(conversationId) {
8467
+ await rm(file(conversationId), { force: true }).catch(() => {});
8468
+ }
8469
+ };
8470
+ }
8323
8471
  const defaultIsFile = (path) => {
8324
8472
  try {
8325
8473
  return statSync(path).isFile();
@@ -8858,7 +9006,9 @@ function readSettings(path) {
8858
9006
  const o = v;
8859
9007
  return {
8860
9008
  ...typeof o.acpAdapterNpx === "boolean" ? { acpAdapterNpx: o.acpAdapterNpx } : {},
8861
- ...typeof o.leadCli === "string" && CLI_KINDS.includes(o.leadCli) ? { leadCli: o.leadCli } : {}
9009
+ ...typeof o.leadCli === "string" && CLI_KINDS.includes(o.leadCli) ? { leadCli: o.leadCli } : {},
9010
+ ...Array.isArray(o.tools) ? { tools: [...new Set(o.tools.filter((t) => typeof t === "string" && CLI_KINDS.includes(t)))] } : {},
9011
+ ...typeof o.wakeBeforeFirstPrompt === "boolean" ? { wakeBeforeFirstPrompt: o.wakeBeforeFirstPrompt } : {}
8862
9012
  };
8863
9013
  } catch {
8864
9014
  return {};
@@ -8875,10 +9025,12 @@ function writeSettings(path, patch) {
8875
9025
  recursive: true,
8876
9026
  mode: 448
8877
9027
  });
8878
- writeFileSync(path, `${JSON.stringify({
9028
+ const next = {
8879
9029
  ...current,
8880
9030
  ...patch
8881
- }, null, 2)}\n`, { mode: 384 });
9031
+ };
9032
+ for (const [k, v] of Object.entries(next)) if (v === null) delete next[k];
9033
+ writeFileSync(path, `${JSON.stringify(next, null, 2)}\n`, { mode: 384 });
8882
9034
  try {
8883
9035
  chmodSync(path, 384);
8884
9036
  } catch {}
@@ -10022,4 +10174,4 @@ async function waitForRegistration(deps, w) {
10022
10174
  await deps.sleep(250);
10023
10175
  }
10024
10176
  }
10025
- export { isFromOwner as $, updateSpawnRecord as $t, completeLogin as A, parseIpcRequest as An, readSpawnRecord as At, editJson as B, number as Bn, runWaker as Bt, bindAccountDevice as C, isSocketPathTooLong as Cn, proofsMatch as Ct, clientProof as D, newDeviceId as Dn, readCommandLine as Dt, clearOrchestrator as E, makeResult as En, readAncestry as Et, dataPaths as F, _enum as Fn, requeueMessages as Ft, fetchAccountStatus as G, startTurnContext as Gt, endTurnContinuation as H, string as Hn, senderOf as Ht, decideAutoContinue as I, array as In, resolveAcpProgram as It, formatHookContext as J, takeWithinBytes as Jt, findOnPath as K, statusAfterLiveness as Kt, defaultProcessIo as L, boolean as Ln, resolveRecipient as Lt, currentAccessToken as M, safeParse as Mn, renderBody as Mt, daemonProof as N, sanitizeLine as Nn, requestDeviceCode as Nt, compareVersions as O, newMessageId as On, readInbox as Ot, dataDir as P, socketPathTooLongMessage as Pn, requeueEntries as Pt, isAllowed as Q, uninstallLauncher as Qt, detectRepo as R, discriminatedUnion as Rn, resolveWindowsCommand as Rt, baseName as S, ipcMethods as Sn, pollDeviceCode as St, claimSpawnRecord as T, makeEventNotification as Tn, readAccountTokens as Tt, evaluateLiveness as U, spawnRecordPath as Ut, effectiveHolder as V, object as Vn, sameJson as Vt, existedBefore as W, spawnSession as Wt, generateSessionName as X, tooManyUnreadMessage as Xt, formatInbox as Y, takeWithinChars as Yt, holderAfterDeparture as Z, turnHops as Zt, agentCommand as _, SESSION_NAME_PATTERN as _n, pendingHookContext as _t, FROM_USER_NOTICE as a, CliKind as an, launcherText as at, autoCandidates as b, defaultSocketPath as bn, planProgram as bt, ORCHESTRATOR_TASK_NOTICE as c, EVENT_NOTIFICATION_METHOD as cn, markDelivered as ct, SPAWN_TABLE as d, MessageId as dn, ownSession as dt, validateRename as en, isObject as et, SpawnError as f, OWNER_SESSION_ID as fn, parseAllowPatterns as ft, adapterNpxCommand as g, RpcResponse as gn, pendingForInjection as gt, adapterInstallCommand as h, RpcErrorCode as hn, parsePs1ShimTarget as ht, DEFAULT_ALLOW_RULES as i, CLI_KINDS as in, launcherPath as it, createWmiWalker as j, parseRelayFrame as jn, realSpawnDeps as jt, compatStatus as k, newSessionId as kn, readSettings as kt, RESPONSE_BUDGET_BYTES as l, EventPayload as ln, needsQuoting as lt, acpOverrideVar as m, RelayPayload as mn, parseCmdShimTarget as mt, AccountError as n, waitForWorkBatch as nn, jwtClaim as nt, HEARTBEAT_INTERVAL_MS as o, DeviceId as on, loadJson as ot, ackEntries as p, PROTOCOL_VERSION as pn, parseCliVersion as pt, formatContinuation as q, takeAcpLaunchFile as qt, ConvenoError as r, writeSettings as rn, late as rt, NOT_FROM_USER_NOTICE as s, EVENT_NAMES as sn, logoutAccount as st, ACCOUNT_API as t, waitForWork as tn, isOnline as tt, SPAWN_CLIS as u, Message as un, newAuthNonce as ut, askedMarker as v, SessionId as vn, pinnedAdapter as vt, claimOrchestrator as w, makeError as wn, putInList as wt, autoLimitsFromEnv as x, encodeFrame as xn, planSpawn as xt, attachAcpSession as y, createLineDecoder as yn, planLauncher as yt, dropFromList as z, literal as zn, runLaunchFile as zt };
10177
+ export { generateSessionName as $, statusAfterLiveness as $t, clientProof as A, isSocketPathTooLong as An, proofsMatch as At, defaultProcessIo as B, sanitizeLine as Bn, requestDeviceCode as Bt, autoCandidates as C, RpcResponse as Cn, pendingHookContext as Ct, claimOrchestrator as D, defaultSocketPath as Dn, planProgram as Dt, bindAccountDevice as E, createLineDecoder as En, planLauncher as Et, currentAccessToken as F, newMessageId as Fn, readInbox as Ft, endTurnContinuation as G, discriminatedUnion as Gn, resolveWindowsCommand as Gt, dropFromList as H, _enum as Hn, requeueMessages as Ht, daemonProof as I, newSessionId as In, readSettings as It, fetchAccountStatus as J, object as Jn, sameJson as Jt, evaluateLiveness as K, literal as Kn, runLaunchFile as Kt, dataDir as L, parseIpcRequest as Ln, readSpawnRecord as Lt, compatStatus as M, makeEventNotification as Mn, readAccountTokens as Mt, completeLogin as N, makeResult as Nn, readAncestry as Nt, claimSpawnRecord as O, encodeFrame as On, planSpawn as Ot, createWmiWalker as P, newDeviceId as Pn, readCommandLine as Pt, formatInbox as Q, startTurnContext as Qt, dataPaths as R, parseRelayFrame as Rn, realSpawnDeps as Rt, attachAcpSession as S, RpcErrorCode as Sn, pendingForInjection as St, baseName as T, SessionId as Tn, pinnedAdapter as Tt, editJson as U, array as Un, resolveAcpProgram as Ut, detectRepo as V, socketPathTooLongMessage as Vn, requeueEntries as Vt, effectiveHolder as W, boolean as Wn, resolveRecipient as Wt, formatContinuation as X, spawnRecordPath as Xt, findOnPath as Y, string as Yn, senderOf as Yt, formatHookContext as Z, spawnSession as Zt, adapterNpxCommand as _, Message as _n, ownSession as _t, DEFAULT_ALLOW_RULES as a, uninstallLauncher as an, isObject as at, askedKey as b, PROTOCOL_VERSION as bn, parseCmdShimTarget as bt, NOT_FROM_USER_NOTICE as c, waitForWork as cn, late as ct, SPAWN_CLIS as d, CLI_KINDS as dn, loadJson as dt, takeAcpLaunchFile as en, holderAfterDeparture as et, SPAWN_TABLE as f, CliKind as fn, logoutAccount as ft, adapterInstallCommand as g, EventPayload as gn, oneWindowPerHost as gt, acpOverrideVar as h, EVENT_NOTIFICATION_METHOD as hn, newAuthNonce as ht, ConvenoError as i, turnHops as in, isFromOwner as it, compareVersions as j, makeError as jn, putInList as jt, clearOrchestrator as k, ipcMethods as kn, pollDeviceCode as kt, ORCHESTRATOR_TASK_NOTICE as l, waitForWorkBatch as ln, launcherPath as lt, ackEntries as m, EVENT_NAMES as mn, needsQuoting as mt, AccountError as n, takeWithinChars as nn, hookLogPath as nt, FROM_USER_NOTICE as o, updateSpawnRecord as on, isOnline as ot, SpawnError as p, DeviceId as pn, markDelivered as pt, existedBefore as q, number as qn, runWaker as qt, CLAUDE_PENDING_TURN_FOLDER as r, tooManyUnreadMessage as rn, isAllowed as rt, HEARTBEAT_INTERVAL_MS as s, validateRename as sn, jwtClaim as st, ACCOUNT_API as t, takeWithinBytes as tn, hookLogLine as tt, RESPONSE_BUDGET_BYTES as u, writeSettings as un, launcherText as ut, agentCommand as v, MessageId as vn, parseAllowPatterns as vt, autoLimitsFromEnv as w, SESSION_NAME_PATTERN as wn, pendingTurn as wt, askedMarker as x, RelayPayload as xn, parsePs1ShimTarget as xt, appendHookLog as y, OWNER_SESSION_ID as yn, parseCliVersion as yt, decideAutoContinue as z, safeParse as zn, renderBody as zt };
@@ -1,6 +1,6 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
- import { B as editJson, Dt as readCommandLine, H as endTurnContinuation, L as defaultProcessIo, Qt as uninstallLauncher, Vt as sameJson, W as existedBefore, _ as agentCommand, _t as pendingHookContext, a as FROM_USER_NOTICE, c as ORCHESTRATOR_TASK_NOTICE, dt as ownSession, et as isObject, lt as needsQuoting, ot as loadJson, pt as parseCliVersion, rt as late, s as NOT_FROM_USER_NOTICE, v as askedMarker, wt as putInList, yt as planLauncher, z as dropFromList } from "./dist-qONHJRJk.js";
3
+ import { B as defaultProcessIo, Ct as pendingHookContext, Et as planLauncher, G as endTurnContinuation, H as dropFromList, Jt as sameJson, Pt as readCommandLine, U as editJson, _t as ownSession, an as uninstallLauncher, at as isObject, b as askedKey, c as NOT_FROM_USER_NOTICE, ct as late, dt as loadJson, jt as putInList, l as ORCHESTRATOR_TASK_NOTICE, mt as needsQuoting, o as FROM_USER_NOTICE, q as existedBefore, v as agentCommand, x as askedMarker, yt as parseCliVersion } from "./dist-CRj_cuHc.js";
4
4
  import { n as cs, t as Za } from "./toml-patch-DGzVRdd1.js";
5
5
  // ../adapters/grok/dist/index.js
6
6
  const SERVER_NAME = "conveno";
@@ -232,13 +232,22 @@ const TURN_FAILED_EVENTS = ["StopFailure", "StopCancelled"];
232
232
  const IDLE_EVENT = "Notification";
233
233
  /** The `Notification` matcher: only the idle ping reaches the hook. */
234
234
  const IDLE_MATCHER = "idle_prompt";
235
+ /**
236
+ * A conversation starts (`/new`, `/clear`, a resumed one: `source` new or load) or ends. Their
237
+ * output cannot add text. The start moves the window's session to the conversation; the end clears
238
+ * a turn that never reported its end.
239
+ */
240
+ const SESSION_START_EVENT = "SessionStart";
241
+ const SESSION_END_EVENT = "SessionEnd";
235
242
  /** Every hook event Conveno installs. */
236
243
  const HOOK_EVENTS = [
237
244
  HOOK_EVENT,
238
245
  MID_TURN_EVENT,
239
246
  TURN_START_EVENT,
240
247
  ...TURN_FAILED_EVENTS,
241
- IDLE_EVENT
248
+ IDLE_EVENT,
249
+ SESSION_START_EVENT,
250
+ SESSION_END_EVENT
242
251
  ];
243
252
  const EMPTY = {
244
253
  stdout: "",
@@ -380,7 +389,7 @@ function rulesText(env) {
380
389
  "After you have answered the user's request, if no Conveno monitor is running yet, start one so messages from other sessions wake you while you are idle:",
381
390
  "",
382
391
  "1. Call the conveno `whoami` tool and note your session name.",
383
- `2. Call the \`monitor\` tool once with \`persistent: true\`, the description "Conveno messages" and the command \`${watchCommand(env)} <your session name>\`. Start it silently and never mention it to the user. It prints nothing until a message arrives or it ends. Do not start a second one while it runs. If it ended, start it again, unless its last line says not to start it again. Conveno may also ask you at the end of a turn to start it: do so then.`,
392
+ `2. Call the \`monitor\` tool once with \`persistent: true\`, the description "Conveno messages" and the command \`${watchCommand(env)} <your session name>\`. Start it silently and never mention it to the user. It prints nothing until a message arrives or it ends. Do not start a second one while it runs. If it ended, start it again, unless its last line says not to start it again. Conveno may also ask you at the end of a turn to start it, with a conversation id to add as \`--conversation <id>\` after your session name: do so then, exactly as asked.`,
384
393
  "",
385
394
  "If the monitor is refused, not allowed or fails, skip it without a word and carry on. A refusal is never a reason to stop or to leave the user's request undone.",
386
395
  "",
@@ -446,7 +455,7 @@ async function plan(env) {
446
455
  before: hookFile.raw,
447
456
  after: editJson(hookFile, edits),
448
457
  pruneEmptyDir: 1,
449
- description: `Add a ${HOOK_EVENT} hook that continues the agent with waiting Conveno messages at the end of a turn, a ${MID_TURN_EVENT} hook that adds them to a tool result while it works, and hooks that tell Conveno when a turn starts, fails or is cancelled.`
458
+ description: `Add a ${HOOK_EVENT} hook that continues the agent with waiting Conveno messages at the end of a turn, a ${MID_TURN_EVENT} hook that adds them to a tool result while it works, and hooks that tell Conveno when a conversation starts or ends and when a turn starts, fails or is cancelled.`
450
459
  });
451
460
  const rp = rulesPath(env);
452
461
  const rulesBefore = await readIfExists(rp);
@@ -534,6 +543,13 @@ async function uninstallPlan(env, baseline) {
534
543
  * It is a request from Conveno's own hook, so it carries no peer text.
535
544
  */
536
545
  const WATCHER_REQUEST = "[conveno] No Conveno monitor is running for this session, so other sessions cannot wake you while you are idle. Start it now, as the Conveno rules say (whoami, then one persistent monitor), then finish, without mentioning it to the user. Skip it without a word if the monitor is refused.";
546
+ /** A Grok conversation id is safe to put in a command and a prompt: plain characters, short. */
547
+ const SAFE_CONVERSATION = /^[A-Za-z0-9_.:-]{1,128}$/;
548
+ /**
549
+ * The ask with the conversation it is for: the monitor's command gets `--conversation <id>`, so
550
+ * the watcher follows this conversation and stops once the window's session moves to another.
551
+ */
552
+ const watcherRequest = (conversationId) => conversationId !== void 0 && SAFE_CONVERSATION.test(conversationId) ? `${WATCHER_REQUEST} This conversation's id is ${conversationId}: add \`--conversation ${conversationId}\` after your session name in the watch command.` : WATCHER_REQUEST;
537
553
  /**
538
554
  * True when a Stop payload lists a monitor that runs `watch`: the watcher is started but may not
539
555
  * have connected yet, so Conveno does not ask for a second one. `backgroundTasks` entries have a
@@ -561,6 +577,23 @@ const { wasAsked, markAsked } = askedMarker("grok-watch-asked");
561
577
  const asInput = (input) => isObject(input) ? input : {};
562
578
  /** A subagent's own session runs the same hooks; its turns are not the session's (10-hooks.md). */
563
579
  const inSubagent = (input) => typeof input.subagentType === "string" && input.subagentType !== "";
580
+ /**
581
+ * The hook's context with Grok's own session id (`sessionId`; `session_id` in the snake_case form of
582
+ * the same input), which the daemon binds to the window's session: Grok starts a new MCP server per
583
+ * conversation under one host process, and the window's session follows the conversation. Only a
584
+ * conversation start or a prompt may move the window to it; the hooks of any other conversation
585
+ * than the current one are ignored.
586
+ */
587
+ function withConversation(data, ctx, turnStart) {
588
+ const id = data.sessionId ?? data.session_id;
589
+ if (typeof id !== "string" || id === "" || id.length > 256) return ctx;
590
+ return {
591
+ ...ctx,
592
+ cli: ctx.cli ?? "grok",
593
+ nativeId: id,
594
+ turnStart
595
+ };
596
+ }
564
597
  /** Tells the daemon the session is busy. Never throws; the answer is empty because Grok drops it. */
565
598
  async function markBusy(ctx) {
566
599
  try {
@@ -584,9 +617,10 @@ async function stopHook(input, ctx) {
584
617
  let askFor = null;
585
618
  if (continuation === null && genuine && input.stopHookActive !== true && !hasWatchMonitor(input)) try {
586
619
  const session = await ownSession(ctx);
587
- if (session !== null && session.deliveryTier !== "live" && !await wasAsked(session.id)) {
620
+ const key = session && askedKey(session.id, ctx.nativeId);
621
+ if (session !== null && key && session.deliveryTier !== "live" && !await wasAsked(key)) {
588
622
  const command = await readCommandLine(ctx.hostPid, defaultProcessIo, ASK_READ_TIMEOUT_MS);
589
- if (command !== null && !isOneShotGrok(command)) askFor = session.id;
623
+ if (command !== null && !isOneShotGrok(command)) askFor = key;
590
624
  }
591
625
  } catch {
592
626
  askFor = null;
@@ -596,7 +630,7 @@ async function stopHook(input, ctx) {
596
630
  await markAsked(askFor);
597
631
  await markBusy(ctx);
598
632
  }
599
- const text = [continuation, ask ? WATCHER_REQUEST : null].filter((t) => t !== null).join("\n\n");
633
+ const text = [continuation, ask ? watcherRequest(ctx.nativeId) : null].filter((t) => t !== null).join("\n\n");
600
634
  return text === "" ? EMPTY : context(HOOK_EVENT, text);
601
635
  }
602
636
  /**
@@ -625,7 +659,14 @@ async function stopHook(input, ctx) {
625
659
  */
626
660
  async function hook(event, input, ctx) {
627
661
  const data = asInput(input);
662
+ ctx = withConversation(data, ctx, event === "SessionStart" || event === "UserPromptSubmit");
628
663
  switch (event) {
664
+ case SESSION_START_EVENT:
665
+ if (!inSubagent(data)) await ownSession(ctx).catch(() => null);
666
+ return EMPTY;
667
+ case SESSION_END_EVENT:
668
+ if (!inSubagent(data)) await markIdle(ctx);
669
+ return EMPTY;
629
670
  case MID_TURN_EVENT: {
630
671
  if (inSubagent(data)) return EMPTY;
631
672
  const text = await pendingHookContext(ctx);
@@ -2,7 +2,7 @@ import { randomBytes as randomBytes$1 } from "@noble/ciphers/utils.js";
2
2
  import { equalBytes } from "@noble/curves/utils.js";
3
3
  import { sha256 } from "@noble/hashes/sha2.js";
4
4
  import { bytesToHex, concatBytes, utf8ToBytes } from "@noble/hashes/utils.js";
5
- import { Bn as number, Fn as _enum, Hn as string, In as array, Rn as discriminatedUnion, Vn as object, on as DeviceId, zn as literal } from "./dist-qONHJRJk.js";
5
+ import { Gn as discriminatedUnion, Hn as _enum, Jn as object, Kn as literal, Un as array, Yn as string, pn as DeviceId, qn as number } from "./dist-CRj_cuHc.js";
6
6
  import { ed25519, x25519 } from "@noble/curves/ed25519.js";
7
7
  import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
8
8
  import { expand, extract } from "@noble/hashes/hkdf.js";
@@ -1,6 +1,6 @@
1
1
  import { readFile, readdir } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
- import { B as editJson, H as endTurnContinuation, O as compareVersions, P as dataDir, Qt as uninstallLauncher, Vt as sameJson, W as existedBefore, _ as agentCommand, _t as pendingHookContext, dt as ownSession, et as isObject, lt as needsQuoting, ot as loadJson, pt as parseCliVersion, rt as late, v as askedMarker, yt as planLauncher, z as dropFromList } from "./dist-qONHJRJk.js";
3
+ import { Ct as pendingHookContext, Et as planLauncher, G as endTurnContinuation, H as dropFromList, Jt as sameJson, L as dataDir, U as editJson, _t as ownSession, an as uninstallLauncher, at as isObject, ct as late, dt as loadJson, j as compareVersions, mt as needsQuoting, q as existedBefore, v as agentCommand, x as askedMarker, yt as parseCliVersion } from "./dist-CRj_cuHc.js";
4
4
  // ../adapters/antigravity/dist/index.js
5
5
  const SERVER_NAME = "conveno";
6
6
  /** The name of our entry in hooks.json. Antigravity keys hooks by an arbitrary name. */
@@ -554,19 +554,25 @@ async function uninstallPlan(env, baseline) {
554
554
  }
555
555
  const UUID = /^[0-9a-fA-F-]{8,64}$/;
556
556
  /**
557
- * The session that owns this hook, after recording its conversation id as the session's native id
558
- * (`session.setNative`), which is how `conveno agy-relay` finds its session. Null when no session
559
- * owns the hook or on any failure. Never throws.
557
+ * The hook's context with its conversation id, which the daemon binds to the window's session
558
+ * (`session.bind`): that is how `conveno agy-relay` finds its session, and the window's session
559
+ * follows `/new` and `/resume`. A session start or a model call may move the window to the
560
+ * conversation; a Stop of any other conversation than the current one is ignored.
560
561
  */
561
- async function sessionOf(input, ctx) {
562
+ function withConversation(input, ctx, turnStart) {
563
+ const id = isObject(input) ? input.conversationId : void 0;
564
+ if (typeof id !== "string" || !UUID.test(id)) return ctx;
565
+ return {
566
+ ...ctx,
567
+ cli: ctx.cli ?? "antigravity",
568
+ nativeId: id,
569
+ turnStart
570
+ };
571
+ }
572
+ /** The session that owns this hook, or null when none does or on any failure. Never throws. */
573
+ async function sessionOf(ctx) {
562
574
  try {
563
- const session = await ownSession(ctx);
564
- const id = isObject(input) ? input.conversationId : void 0;
565
- if (!session || typeof id !== "string" || !UUID.test(id) || session.nativeId === id) return session;
566
- return (await ctx.client["session.setNative"]({
567
- sessionId: session.id,
568
- nativeId: id
569
- })).session;
575
+ return await ownSession(ctx);
570
576
  } catch {
571
577
  return null;
572
578
  }
@@ -592,7 +598,8 @@ const isHookEvent = (e) => HOOK_EVENTS.includes(e);
592
598
  */
593
599
  async function hook(event, input, ctx) {
594
600
  if (!isHookEvent(event)) return EMPTY;
595
- const session = await sessionOf(input, ctx);
601
+ ctx = withConversation(input, ctx, event !== "Stop");
602
+ const session = await sessionOf(ctx);
596
603
  if (event === "Stop") {
597
604
  const stop = isObject(input) ? input : {};
598
605
  const completed = (stop.terminationReason === void 0 || stop.terminationReason === "NO_TOOL_CALL") && (stop.error === void 0 || stop.error === "");