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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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";
@@ -6158,12 +6158,19 @@ const RepoInfo = object({
6158
6158
  /** SHA-256 of the normalised `origin` URL; lets sessions on different machines match repos without exposing the URL. */
6159
6159
  remoteUrlHash: Sha256Hex.optional()
6160
6160
  });
6161
+ /**
6162
+ * A client of a CLI that is not the CLI itself: `app` is the Antigravity desktop app, which shares
6163
+ * agy's settings and so loads Conveno the same way.
6164
+ */
6165
+ const SessionVariant = literal("app");
6161
6166
  const Session = object({
6162
6167
  id: SessionId,
6163
6168
  /** `<device>:<name>` for a session on another device (`remote`). */
6164
6169
  name: union([SessionName, RemoteSessionName]),
6165
6170
  cli: CliKind,
6166
6171
  cliVersion: string().min(1).max(64).optional(),
6172
+ /** Set when the session is a desktop app of `cli` rather than the CLI. Screens say "Antigravity app". */
6173
+ variant: SessionVariant.optional(),
6167
6174
  deviceId: DeviceId,
6168
6175
  cwd: string().min(1),
6169
6176
  repo: RepoInfo.optional(),
@@ -6194,6 +6201,12 @@ const Session = object({
6194
6201
  * `session.setNative`. Hooks of a CLI that runs many sessions in one process find theirs by it.
6195
6202
  */
6196
6203
  nativeId: string().min(1).max(256).optional(),
6204
+ /**
6205
+ * Can something wake this session when it is idle right now (a connected listener, relay or
6206
+ * watcher, a daemon waker with a conversation to wake, or an ACP host)? False: a message waits
6207
+ * until the user's next prompt. Absent on a daemon or device that does not report it.
6208
+ */
6209
+ wakeable: boolean().optional(),
6197
6210
  /** Set on sessions of the owner's other devices, reached through the relay. */
6198
6211
  remote: literal(true).optional(),
6199
6212
  /** Display name of the device a remote session runs on. */
@@ -6226,11 +6239,15 @@ const AuthParams = object({
6226
6239
  proof: Sha256Hex });
6227
6240
  const sid = { sessionId: SessionId };
6228
6241
  const SessionResult = object({ session: Session });
6242
+ /** An absolute path (POSIX, drive or UNC) without control characters. */
6243
+ const AbsolutePath = string().min(1).max(1024).regex(/^(?:[A-Za-z]:[\\/]|\\\\|\/)/, "must be an absolute path").regex(/^[^\u0000-\u001f\u007f]*$/, "must not contain control characters");
6229
6244
  const RegisterParams = object({
6230
6245
  /** Requested name. If omitted the daemon assigns one such as `claude@repo-1`. */
6231
6246
  name: SessionNameInput.optional(),
6232
6247
  cli: CliKind,
6233
6248
  cliVersion: string().min(1).max(64).optional(),
6249
+ /** The session runs in a desktop app of `cli`. See `Session.variant`. */
6250
+ variant: SessionVariant.optional(),
6234
6251
  cwd: string().min(1),
6235
6252
  repo: RepoInfo.optional(),
6236
6253
  pid: number().int().positive().optional(),
@@ -6342,6 +6359,8 @@ function makeEventNotification(payload) {
6342
6359
  params: payload
6343
6360
  };
6344
6361
  }
6362
+ /** In the NotFound message for a heartbeat of a retired session. The MCP server exits on it. */
6363
+ const SESSION_ENDED_TEXT = "has ended and will not come back";
6345
6364
  const ipcMethods = {
6346
6365
  hello: {
6347
6366
  params: HelloParams,
@@ -6356,11 +6375,21 @@ const ipcMethods = {
6356
6375
  result: SessionResult
6357
6376
  },
6358
6377
  "session.heartbeat": {
6359
- params: object(sid),
6378
+ params: object({
6379
+ ...sid,
6380
+ pid: number().int().positive().optional()
6381
+ }),
6360
6382
  result: object({ lastSeenAt: IsoTimestamp })
6361
6383
  },
6362
6384
  "session.unregister": {
6363
- params: object(sid),
6385
+ params: object({
6386
+ ...sid,
6387
+ pid: number().int().positive().optional()
6388
+ }),
6389
+ result: object({ ok: literal(true) })
6390
+ },
6391
+ "session.remove": {
6392
+ params: object({ ...sid }),
6364
6393
  result: object({ ok: literal(true) })
6365
6394
  },
6366
6395
  "session.rename": {
@@ -6394,6 +6423,36 @@ const ipcMethods = {
6394
6423
  }),
6395
6424
  result: SessionResult
6396
6425
  },
6426
+ "session.bind": {
6427
+ params: object({
6428
+ cli: CliKind,
6429
+ nativeId: string().min(1).max(256),
6430
+ sessionId: SessionId.optional(),
6431
+ /** The calling MCP process, attached to the surviving session on a merge. */
6432
+ pid: number().int().positive().optional(),
6433
+ hostPid: number().int().positive().optional(),
6434
+ /**
6435
+ * A hook's direct parent pid, in place of `hostPid`, so the hook skips the process walk
6436
+ * when the daemon can tell without it. The answer is a session, none, or `needsHost`: the
6437
+ * hook then walks and asks again with `hostPid`.
6438
+ */
6439
+ ppid: number().int().positive().optional(),
6440
+ cwd: string().min(1).optional(),
6441
+ turnStart: boolean().default(false)
6442
+ }).refine((p) => p.sessionId !== void 0 || p.hostPid !== void 0 || p.ppid !== void 0, { message: "provide sessionId, hostPid or ppid" }),
6443
+ result: object({
6444
+ session: Session.nullable(),
6445
+ needsHost: boolean().optional()
6446
+ })
6447
+ },
6448
+ "session.setCwd": {
6449
+ params: object({
6450
+ ...sid,
6451
+ cwd: AbsolutePath,
6452
+ variant: SessionVariant.optional()
6453
+ }),
6454
+ result: SessionResult
6455
+ },
6397
6456
  "session.hostOf": {
6398
6457
  params: object({
6399
6458
  cli: CliKind,
@@ -6424,6 +6483,11 @@ const ipcMethods = {
6424
6483
  ...sid,
6425
6484
  /** Chosen by the listener. The newest listener of a session wins; older ones are told to stop. */
6426
6485
  listenerId: string().regex(/^[A-Za-z0-9_-]{8,64}$/, "invalid listener id"),
6486
+ /**
6487
+ * The conversation this listener serves. When the session has moved to another one
6488
+ * (`session.bind`), the listener is superseded: it gets nothing and must stop.
6489
+ */
6490
+ nativeId: string().min(1).max(256).optional(),
6427
6491
  maxChars
6428
6492
  }),
6429
6493
  result: TurnDelivery.extend({ superseded: boolean() })
@@ -7026,6 +7090,20 @@ async function logoutAccount(path, io = {}) {
7026
7090
  revoked
7027
7091
  };
7028
7092
  }
7093
+ /**
7094
+ * CLIs whose window is one host process: a second MCP server under the same host process (a
7095
+ * reconnect, Grok's new MCP per `/new`) belongs to the window's session, so it attaches to it
7096
+ * instead of making a row. Codex runs every thread's MCP under one app-server process that several
7097
+ * windows may share, so only the thread id tells its windows apart.
7098
+ */
7099
+ const ONE_WINDOW_PER_HOST = {
7100
+ claude: true,
7101
+ opencode: true,
7102
+ antigravity: true,
7103
+ grok: true,
7104
+ codex: false
7105
+ };
7106
+ const oneWindowPerHost = (cli) => ONE_WINDOW_PER_HOST[cli];
7029
7107
  const pathApi$2 = (platform) => platform === "win32" ? win32 : posix;
7030
7108
  /**
7031
7109
  * Conveno data directory. Pure: platform, environment and home directory are arguments.
@@ -7083,6 +7161,12 @@ async function pruneAsked(dir, now = Date.now()) {
7083
7161
  } catch {}
7084
7162
  }
7085
7163
  /**
7164
+ * The key of an ask that is made once per session and conversation: a window's session moves
7165
+ * between conversations, and a helper started for one does not serve the next. Without a
7166
+ * conversation id, the session alone.
7167
+ */
7168
+ const askedKey = (sessionId, conversationId) => conversationId === void 0 || conversationId === "" ? sessionId : `${sessionId}_${conversationId}`;
7169
+ /**
7086
7170
  * "Asked once per session" for a Stop hook request: one empty file per Conveno session in
7087
7171
  * `<data dir>/<folder>`. Best effort both ways: a failure only means the request can repeat.
7088
7172
  */
@@ -7174,7 +7258,10 @@ function formatFramedMessage(message, options = {}) {
7174
7258
  const sender = senderOf(message);
7175
7259
  const reply = message.replyTo ? ` Reply to message ${message.replyTo}.` : "";
7176
7260
  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}`;
7261
+ const lead = options.task === true;
7262
+ const asTask = lead && !message.replyTo;
7263
+ const label = asTask ? "Task from the orchestrator" : lead ? "Reply from the orchestrator" : "Message from";
7264
+ 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
7265
  const meta = [`Message id: ${message.id}`];
7179
7266
  if (message.urgent) meta.push("Marked urgent by the sender.");
7180
7267
  const body = renderBody(message);
@@ -7208,8 +7295,8 @@ function formatHookContext(messages) {
7208
7295
  }
7209
7296
  /**
7210
7297
  * 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.
7298
+ * that Conveno, not the user, started the turn. New messages from the current orchestrator carry the task
7299
+ * notice (replies do not, so workers do not answer a reply); every other message keeps the not-from-user notice.
7213
7300
  */
7214
7301
  function formatContinuation(messages, orchestrator, remaining = 0) {
7215
7302
  if (messages.length === 0) return "";
@@ -7438,24 +7525,15 @@ function parseCliVersion(output) {
7438
7525
  var clis = {
7439
7526
  "claude": {
7440
7527
  "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"
7528
+ "minimum": "2.1.139"
7450
7529
  },
7530
+ "codex": { "verified": "0.172.0" },
7531
+ "opencode": { "verified": "2.4.3" },
7451
7532
  "antigravity": {
7452
7533
  "verified": "1.5.20",
7453
- "minimum": "1.5.20"
7534
+ "minimum": "1.5.8"
7454
7535
  },
7455
- "grok": {
7456
- "verified": "1.0.92",
7457
- "minimum": "1.0.92"
7458
- }
7536
+ "grok": { "verified": "1.0.92" }
7459
7537
  };
7460
7538
  var acpAdapters = {
7461
7539
  "@agentclientprotocol/codex-acp": "2.10.0",
@@ -7463,8 +7541,7 @@ var acpAdapters = {
7463
7541
  };
7464
7542
  /**
7465
7543
  * 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.
7544
+ * release passes its checks. `minimum` changes only by hand, when Conveno starts to need a feature older releases lack.
7468
7545
  */
7469
7546
  const COMPAT = clis;
7470
7547
  /** The numeric part of a version: `2.1.332`, `0.172.0-alpha.3` or `2026.11.22-e9042b2`. */
@@ -7490,10 +7567,10 @@ function compareVersions(a, b) {
7490
7567
  function compatStatus(cli, version, table = COMPAT) {
7491
7568
  const entry = table[cli];
7492
7569
  if (!entry || !version) return { kind: "unknown" };
7493
- const vsMin = compareVersions(version, entry.minimum);
7570
+ const vsMin = entry.minimum === void 0 ? 0 : compareVersions(version, entry.minimum);
7494
7571
  const vsVerified = compareVersions(version, entry.verified);
7495
7572
  if (vsMin === void 0 || vsVerified === void 0) return { kind: "unknown" };
7496
- if (vsMin < 0) return {
7573
+ if (vsMin < 0 && entry.minimum !== void 0) return {
7497
7574
  kind: "older",
7498
7575
  minimum: entry.minimum
7499
7576
  };
@@ -7594,6 +7671,7 @@ function openWatch(o) {
7594
7671
  const r = await client["turn.wake"]({
7595
7672
  sessionId: id,
7596
7673
  listenerId,
7674
+ ...o.nativeId === void 0 ? {} : { nativeId: o.nativeId },
7597
7675
  ...o.maxChars === void 0 ? {} : { maxChars: o.maxChars }
7598
7676
  });
7599
7677
  if (r.superseded) return {
@@ -7700,13 +7778,63 @@ async function runWaker(o) {
7700
7778
  /** Longest wait between two tries to reach the daemon again (`reconnectMs`). */
7701
7779
  const MAX_RECONNECT_MS = 6e4;
7702
7780
  /**
7781
+ * The pid of the CLI above the hook: the one the context already knows, else the walk up the
7782
+ * process tree (`resolveHostPid`, which runs once). Undefined when no session of the CLI is online.
7783
+ */
7784
+ async function hostPidOf(ctx) {
7785
+ if (ctx.hostPid !== void 0) return ctx.hostPid;
7786
+ return ctx.resolveHostPid ? await ctx.resolveHostPid() : void 0;
7787
+ }
7788
+ /** Is the host CLI still running. True when there is no check or the host is not known. */
7789
+ async function hostAlive(ctx) {
7790
+ if (!ctx.isAlive) return true;
7791
+ const pid = await hostPidOf(ctx);
7792
+ return pid === void 0 || ctx.isAlive(pid);
7793
+ }
7794
+ /** The daemon cannot take `ppid` (an older one): fall back to the walk. */
7795
+ const noPpidSupport = (e) => {
7796
+ const code = e?.code;
7797
+ return code === RpcErrorCode.MethodNotFound || code === RpcErrorCode.InvalidParams;
7798
+ };
7799
+ /**
7703
7800
  * The session that owns the hook's host process, when it is a session of the hook's own CLI. Every
7704
7801
  * helper below goes through here before taking messages, so a hook running inside another CLI
7705
7802
  * (which would print a format that CLI discards) never marks anything delivered.
7706
7803
  */
7707
7804
  async function ownSession(ctx) {
7805
+ if (ctx.nativeId !== void 0 && ctx.cli !== void 0) try {
7806
+ const base = {
7807
+ cli: ctx.cli,
7808
+ nativeId: ctx.nativeId,
7809
+ ...ctx.cwd === void 0 ? {} : { cwd: ctx.cwd },
7810
+ turnStart: ctx.turnStart === true
7811
+ };
7812
+ let r;
7813
+ if (ctx.hostPid === void 0 && ctx.ppid !== void 0) try {
7814
+ r = await ctx.client["session.bind"]({
7815
+ ...base,
7816
+ ppid: ctx.ppid
7817
+ });
7818
+ } catch (e) {
7819
+ if (!noPpidSupport(e)) throw e;
7820
+ }
7821
+ if (!r || r.needsHost) {
7822
+ const hostPid = await hostPidOf(ctx);
7823
+ if (hostPid === void 0) return null;
7824
+ r = await ctx.client["session.bind"]({
7825
+ ...base,
7826
+ hostPid
7827
+ });
7828
+ }
7829
+ const { session } = r;
7830
+ return session && session.cli !== ctx.cli ? null : session;
7831
+ } catch (e) {
7832
+ if (e?.code !== RpcErrorCode.MethodNotFound) throw e;
7833
+ }
7834
+ const pid = await hostPidOf(ctx);
7835
+ if (pid === void 0) return null;
7708
7836
  const { session } = await ctx.client["session.byHost"]({
7709
- pid: ctx.hostPid,
7837
+ pid,
7710
7838
  ...ctx.cwd === void 0 ? {} : { cwd: ctx.cwd },
7711
7839
  ...ctx.nativeId === void 0 ? {} : { nativeId: ctx.nativeId }
7712
7840
  });
@@ -7755,7 +7883,10 @@ async function pendingHookContext(ctx, opts = {}) {
7755
7883
  async function startTurnContext(ctx, opts = {}) {
7756
7884
  try {
7757
7885
  const session = await ownSession(ctx);
7758
- if (!session) return null;
7886
+ if (!session) {
7887
+ await opts.onNoSession?.();
7888
+ return null;
7889
+ }
7759
7890
  try {
7760
7891
  await ctx.client["turn.start"]({ sessionId: session.id });
7761
7892
  } catch {}
@@ -7813,15 +7944,20 @@ async function waitForWork(ctx, opts = {}) {
7813
7944
  */
7814
7945
  async function awaitOwnSession(ctx, waitMs, pollMs, signal) {
7815
7946
  const until = Date.now() + waitMs;
7947
+ let own = ctx;
7816
7948
  for (;;) {
7817
7949
  try {
7818
- const session = await ownSession(ctx);
7950
+ const session = await ownSession(own);
7819
7951
  if (session) return session;
7820
7952
  } catch {
7821
7953
  return "disconnected";
7822
7954
  }
7823
7955
  if (Date.now() + pollMs > until || signal?.aborted) return null;
7824
- if (ctx.isAlive && !ctx.isAlive(ctx.hostPid)) return null;
7956
+ if (!await hostAlive(ctx)) return null;
7957
+ if (own.turnStart) own = {
7958
+ ...own,
7959
+ turnStart: false
7960
+ };
7825
7961
  await new Promise((r) => setTimeout(r, pollMs));
7826
7962
  }
7827
7963
  }
@@ -7833,7 +7969,7 @@ async function pauseWhileAlive(ctx, ms, stepMs, deadline, signal) {
7833
7969
  const until = Math.min(Date.now() + ms, deadline);
7834
7970
  for (;;) {
7835
7971
  if (signal?.aborted || Date.now() >= deadline) return false;
7836
- if (ctx.isAlive && !ctx.isAlive(ctx.hostPid)) return false;
7972
+ if (!await hostAlive(ctx)) return false;
7837
7973
  const left = until - Date.now();
7838
7974
  if (left <= 0) return true;
7839
7975
  await new Promise((r) => setTimeout(r, Math.min(left, stepMs)));
@@ -7842,7 +7978,8 @@ async function pauseWhileAlive(ctx, ms, stepMs, deadline, signal) {
7842
7978
  /** `waitForWork`, returning the whole batch and its session (for a requeue). */
7843
7979
  async function waitForWorkBatch(ctx, opts = {}) {
7844
7980
  const deadline = opts.maxMs === void 0 ? 1e400 : Date.now() + opts.maxMs;
7845
- const { isAlive, hostPid } = ctx;
7981
+ const { isAlive } = ctx;
7982
+ const hostPid = isAlive ? await hostPidOf(ctx) : void 0;
7846
7983
  const listenerId = opts.listenerId ?? randomBytes(12).toString("base64url");
7847
7984
  let delay = opts.reconnectMs;
7848
7985
  /** After a lost connection: wait, then go round again. False when the listener must stop. */
@@ -7852,24 +7989,30 @@ async function waitForWorkBatch(ctx, opts = {}) {
7852
7989
  delay = Math.min(delay * 2, Math.max(opts.reconnectMs ?? 0, MAX_RECONNECT_MS));
7853
7990
  return ok;
7854
7991
  };
7992
+ let round = ctx;
7855
7993
  for (;;) {
7856
- const session = await awaitOwnSession(ctx, opts.registerWaitMs ?? 0, opts.registerPollMs ?? DEFAULT_REGISTER_POLL_MS, opts.signal);
7994
+ const session = await awaitOwnSession(round, opts.registerWaitMs ?? 0, opts.registerPollMs ?? DEFAULT_REGISTER_POLL_MS, opts.signal);
7857
7995
  if (session === "disconnected") {
7858
7996
  if (await retry()) continue;
7859
7997
  return null;
7860
7998
  }
7861
7999
  if (!session) return null;
7862
8000
  delay = opts.reconnectMs;
8001
+ if (round.turnStart) round = {
8002
+ ...round,
8003
+ turnStart: false
8004
+ };
7863
8005
  const r = await waitForWake({
7864
8006
  client: ctx.client,
7865
8007
  sessionId: session.id,
7866
8008
  listenerId,
8009
+ ...ctx.nativeId !== void 0 ? { nativeId: ctx.nativeId } : {},
7867
8010
  ...opts.pollMs !== void 0 ? { pollMs: opts.pollMs } : {},
7868
8011
  ...opts.hostCheckMs !== void 0 ? { hostCheckMs: opts.hostCheckMs } : {},
7869
8012
  ...deadline !== 1e400 ? { maxMs: Math.max(0, deadline - Date.now()) } : {},
7870
8013
  ...opts.signal !== void 0 ? { signal: opts.signal } : {},
7871
8014
  ...opts.maxChars !== void 0 ? { maxChars: opts.maxChars } : {},
7872
- ...isAlive ? { isHostAlive: () => isAlive(hostPid) } : {}
8015
+ ...isAlive && hostPid !== void 0 ? { isHostAlive: () => isAlive(hostPid) } : {}
7873
8016
  });
7874
8017
  if (r.ok) return {
7875
8018
  sessionId: session.id,
@@ -7879,6 +8022,44 @@ async function waitForWorkBatch(ctx, opts = {}) {
7879
8022
  return null;
7880
8023
  }
7881
8024
  }
8025
+ /** The log rotates once it passes this size; one old file is kept (`hooks.log.1`). */
8026
+ const HOOK_LOG_MAX_BYTES = 1e6;
8027
+ /** `<data dir>/logs/hooks.log`. */
8028
+ const hookLogPath = (dataDir) => join(dataDir, "logs", "hooks.log");
8029
+ /** Keep a logged word to plain characters, so one entry is one line and nothing is injected. */
8030
+ const plain = (v, max, extra = "") => v.replace(new RegExp(`[^A-Za-z0-9_.@:${extra}-]`, "g"), "_").slice(0, max);
8031
+ /** A duration in whole ms, or `-` when there is none. */
8032
+ const num = (v) => v === void 0 || !Number.isFinite(v) ? "-" : String(Math.max(0, Math.round(v)));
8033
+ /**
8034
+ * One line: `<iso time> cli=<cli> event=<event> conv=<first 8 of the conversation id> session=<name
8035
+ * or none> result=<result> host_ms=<n or -> ms=<n or ->`. No message text and no tokens: only ids the CLI hands to hooks and the
8036
+ * session's name.
8037
+ */
8038
+ function hookLogLine(e) {
8039
+ const conv = e.conversationId ? plain(e.conversationId, 8) : "-";
8040
+ 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, " ")} host_ms=${num(e.hostMs)} ms=${num(e.ms)}\n`;
8041
+ }
8042
+ /**
8043
+ * Append one line to the hook log, rotating at `HOOK_LOG_MAX_BYTES`. Synchronous and tiny so a hook
8044
+ * is not made slower, and it never throws: a log that cannot be written must not change a hook.
8045
+ */
8046
+ function appendHookLog(path, line, maxBytes = HOOK_LOG_MAX_BYTES) {
8047
+ try {
8048
+ try {
8049
+ if (statSync(path).size > maxBytes) {
8050
+ rmSync(`${path}.1`, { force: true });
8051
+ renameSync(path, `${path}.1`);
8052
+ }
8053
+ } catch {}
8054
+ try {
8055
+ appendFileSync(path, line, { mode: 384 });
8056
+ } catch (e) {
8057
+ if (e.code !== "ENOENT") throw e;
8058
+ mkdirSync(dirname(path), { recursive: true });
8059
+ appendFileSync(path, line, { mode: 384 });
8060
+ }
8061
+ } catch {}
8062
+ }
7882
8063
  const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
7883
8064
  const PARSE_OPTIONS = { allowTrailingComma: true };
7884
8065
  /**
@@ -8320,6 +8501,48 @@ function clearOrchestrator(holder, sessions) {
8320
8501
  function holderAfterDeparture(holder, departed) {
8321
8502
  return holder === departed ? null : holder;
8322
8503
  }
8504
+ /** Claude Code's notes (the hooks write them, the MCP server takes them). */
8505
+ const CLAUDE_PENDING_TURN_FOLDER = "claude-pending-turn";
8506
+ /** A note older than this is from a turn long over. */
8507
+ const PENDING_TURN_MAX_AGE_MS = 6e5;
8508
+ /**
8509
+ * "A turn started before this window's session registered." A CLI can run its first prompt's hook
8510
+ * before its MCP server has registered (Claude Code started with a prompt, as `conveno spawn` does),
8511
+ * so the hook finds no session and the turn would show as idle. The hook leaves one empty file per
8512
+ * conversation in `<data dir>/<folder>`; the MCP server takes it when it registers and starts the
8513
+ * turn, and the turn's end removes it. Best effort: a failure only loses the busy state of that turn.
8514
+ */
8515
+ function pendingTurn(dir, folder) {
8516
+ const file = (conversationId) => join(dir, folder, conversationId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 128));
8517
+ return {
8518
+ async mark(conversationId) {
8519
+ try {
8520
+ const f = file(conversationId);
8521
+ await mkdir(join(f, ".."), { recursive: true });
8522
+ await writeFile(f, "");
8523
+ const now = Date.now();
8524
+ for (const name of await readdir(join(f, ".."))) {
8525
+ const g = join(f, "..", name);
8526
+ if (now - (await stat(g)).mtimeMs > 6e5) await rm(g, { force: true });
8527
+ }
8528
+ } catch {}
8529
+ },
8530
+ /** True when a fresh note was there; the note is removed either way. */
8531
+ async take(conversationId, now = Date.now()) {
8532
+ try {
8533
+ const f = file(conversationId);
8534
+ const fresh = now - (await stat(f)).mtimeMs <= PENDING_TURN_MAX_AGE_MS;
8535
+ await rm(f, { force: true });
8536
+ return fresh;
8537
+ } catch {
8538
+ return false;
8539
+ }
8540
+ },
8541
+ async clear(conversationId) {
8542
+ await rm(file(conversationId), { force: true }).catch(() => {});
8543
+ }
8544
+ };
8545
+ }
8323
8546
  const defaultIsFile = (path) => {
8324
8547
  try {
8325
8548
  return statSync(path).isFile();
@@ -8509,6 +8732,12 @@ function parseProcStat(stat) {
8509
8732
  const ppid = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
8510
8733
  return Number.isInteger(ppid) && ppid >= 0 ? ppid : void 0;
8511
8734
  }
8735
+ const ANTIGRAVITY_APP_EXE = /(?:^|[\\/"])antigravity(?:\.exe)?"?(?:\s|$)/i;
8736
+ const ANTIGRAVITY_APP_HUB = /--subclient_type[=\s]+hub\b/;
8737
+ /** Does the process chain run through the Antigravity desktop app? Needs command lines; false without them. */
8738
+ function isAntigravityApp(entries) {
8739
+ return entries.some((e) => e.command !== void 0 && (ANTIGRAVITY_APP_HUB.test(e.command) || ANTIGRAVITY_APP_EXE.test(e.command)));
8740
+ }
8512
8741
  const norm = (text) => text.replaceAll("\\", "/").toLowerCase();
8513
8742
  /** Split a command line into tokens, keeping quoted parts together and dropping the quotes. */
8514
8743
  function tokens(command) {
@@ -8661,6 +8890,22 @@ async function readTable(io, timeoutMs) {
8661
8890
  return out === null ? null : parseProcessTable(out);
8662
8891
  }
8663
8892
  /**
8893
+ * Every process with its command line, from the same one query the ancestry walk uses (the
8894
+ * Windows Script Host or CIM on Windows, `ps` elsewhere). Null when the table cannot be read.
8895
+ */
8896
+ async function readProcessList(io = defaultProcessIo, timeoutMs = 5e3) {
8897
+ try {
8898
+ const table = await readTable(io, timeoutMs);
8899
+ if (!table || table.size === 0) return null;
8900
+ return [...table].map(([pid, row]) => row.command === void 0 ? { pid } : {
8901
+ pid,
8902
+ command: row.command
8903
+ });
8904
+ } catch {
8905
+ return null;
8906
+ }
8907
+ }
8908
+ /**
8664
8909
  * The command line of a process as one string, or null when the OS does not say (the process is
8665
8910
  * gone, or the query was denied). A null answer means "unknown", never "not the daemon".
8666
8911
  */
@@ -8858,7 +9103,9 @@ function readSettings(path) {
8858
9103
  const o = v;
8859
9104
  return {
8860
9105
  ...typeof o.acpAdapterNpx === "boolean" ? { acpAdapterNpx: o.acpAdapterNpx } : {},
8861
- ...typeof o.leadCli === "string" && CLI_KINDS.includes(o.leadCli) ? { leadCli: o.leadCli } : {}
9106
+ ...typeof o.leadCli === "string" && CLI_KINDS.includes(o.leadCli) ? { leadCli: o.leadCli } : {},
9107
+ ...Array.isArray(o.tools) ? { tools: [...new Set(o.tools.filter((t) => typeof t === "string" && CLI_KINDS.includes(t)))] } : {},
9108
+ ...typeof o.wakeBeforeFirstPrompt === "boolean" ? { wakeBeforeFirstPrompt: o.wakeBeforeFirstPrompt } : {}
8862
9109
  };
8863
9110
  } catch {
8864
9111
  return {};
@@ -8875,10 +9122,12 @@ function writeSettings(path, patch) {
8875
9122
  recursive: true,
8876
9123
  mode: 448
8877
9124
  });
8878
- writeFileSync(path, `${JSON.stringify({
9125
+ const next = {
8879
9126
  ...current,
8880
9127
  ...patch
8881
- }, null, 2)}\n`, { mode: 384 });
9128
+ };
9129
+ for (const [k, v] of Object.entries(next)) if (v === null) delete next[k];
9130
+ writeFileSync(path, `${JSON.stringify(next, null, 2)}\n`, { mode: 384 });
8882
9131
  try {
8883
9132
  chmodSync(path, 384);
8884
9133
  } catch {}
@@ -9307,6 +9556,7 @@ async function runLaunchFile(path) {
9307
9556
  const child = spawn(spec.file, spec.args, {
9308
9557
  cwd: spec.cwd,
9309
9558
  stdio: "inherit",
9559
+ env: Object.fromEntries(Object.entries(process.env).filter(([k]) => k !== "CONVENO_ACP_WORKER")),
9310
9560
  ...spec.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
9311
9561
  });
9312
9562
  child.once("error", (e) => {
@@ -10022,4 +10272,4 @@ async function waitForRegistration(deps, w) {
10022
10272
  await deps.sleep(250);
10023
10273
  }
10024
10274
  }
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 };
10275
+ export { formatInbox as $, literal as $n, runWaker as $t, clearOrchestrator as A, SESSION_ENDED_TEXT as An, pinnedAdapter as At, decideAutoContinue as B, makeResult as Bn, readInbox as Bt, attachAcpSession as C, Message as Cn, parseCliVersion as Ct, bindAccountDevice as D, RelayPayload as Dn, pendingHookContext as Dt, baseName as E, PROTOCOL_VERSION as En, pendingForInjection as Et, createWmiWalker as F, encodeFrame as Fn, proofsMatch as Ft, effectiveHolder as G, parseRelayFrame as Gn, renderBody as Gt, detectRepo as H, newMessageId as Hn, readSettings as Ht, currentAccessToken as I, ipcMethods as In, putInList as It, existedBefore as J, socketPathTooLongMessage as Jn, requeueMessages as Jt, endTurnContinuation as K, safeParse as Kn, requestDeviceCode as Kt, daemonProof as L, isSocketPathTooLong as Ln, readAccountTokens as Lt, compareVersions as M, SessionId as Mn, planProgram as Mt, compatStatus as N, createLineDecoder as Nn, planSpawn as Nt, claimOrchestrator as O, RpcErrorCode as On, pendingTurn as Ot, completeLogin as P, defaultSocketPath as Pn, pollDeviceCode as Pt, formatHookContext as Q, discriminatedUnion as Qn, runLaunchFile as Qt, dataDir as R, makeError as Rn, readAncestry as Rt, askedMarker as S, EventPayload as Sn, parseAllowPatterns as St, autoLimitsFromEnv as T, OWNER_SESSION_ID as Tn, parsePs1ShimTarget as Tt, dropFromList as U, newSessionId as Un, readSpawnRecord as Ut, defaultProcessIo as V, newDeviceId as Vn, readProcessList as Vt, editJson as W, parseIpcRequest as Wn, realSpawnDeps as Wt, findOnPath as X, array as Xn, resolveRecipient as Xt, fetchAccountStatus as Y, _enum as Yn, resolveAcpProgram as Yt, formatContinuation as Z, boolean as Zn, resolveWindowsCommand as Zt, adapterInstallCommand as _, CLI_KINDS as _n, markDelivered as _t, ConvenoError as a, statusAfterLiveness as an, hostPidOf as at, appendHookLog as b, EVENT_NAMES as bn, oneWindowPerHost as bt, HEARTBEAT_INTERVAL_MS as c, takeWithinChars as cn, isFromOwner as ct, RESPONSE_BUDGET_BYTES as d, uninstallLauncher as dn, jwtClaim as dt, sameJson as en, number as er, generateSessionName as et, SPAWN_CLIS as f, updateSpawnRecord as fn, late as ft, acpOverrideVar as g, writeSettings as gn, logoutAccount as gt, ackEntries as h, waitForWorkBatch as hn, loadJson as ht, CLAUDE_PENDING_TURN_FOLDER as i, startTurnContext as in, hostAlive as it, clientProof as j, SESSION_NAME_PATTERN as jn, planLauncher as jt, claimSpawnRecord as k, RpcResponse as kn, pidAlive as kt, NOT_FROM_USER_NOTICE as l, tooManyUnreadMessage as ln, isObject as lt, SpawnError as m, waitForWork as mn, launcherText as mt, ACP_TOOL_KINDS as n, spawnRecordPath as nn, string as nr, hookLogLine as nt, DEFAULT_ALLOW_RULES as o, takeAcpLaunchFile as on, isAllowed as ot, SPAWN_TABLE as p, validateRename as pn, launcherPath as pt, evaluateLiveness as q, sanitizeLine as qn, requeueEntries as qt, AccountError as r, spawnSession as rn, hookLogPath as rt, FROM_USER_NOTICE as s, takeWithinBytes as sn, isAntigravityApp as st, ACCOUNT_API as t, senderOf as tn, object as tr, holderAfterDeparture as tt, ORCHESTRATOR_TASK_NOTICE as u, turnHops as un, isOnline as ut, adapterNpxCommand as v, CliKind as vn, needsQuoting as vt, autoCandidates as w, MessageId as wn, parseCmdShimTarget as wt, askedKey as x, EVENT_NOTIFICATION_METHOD as xn, ownSession as xt, agentCommand as y, DeviceId as yn, newAuthNonce as yt, dataPaths as z, makeEventNotification as zn, readCommandLine as zt };