@conveno/cli 0.2.0-rc.12 → 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.
@@ -2,7 +2,7 @@ import { execFile, spawn } from "node:child_process";
2
2
  import { readFileSync, statSync } from "node:fs";
3
3
  import { readFile } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
- import { Ct as pendingHookContext, Dt as planProgram, G as endTurnContinuation, Ot as planSpawn, Qt as startTurnContext, Y as findOnPath, yt as parseCliVersion } from "./dist-CRj_cuHc.js";
5
+ import { Ct as parseCliVersion, Dt as pendingHookContext, K as endTurnContinuation, Mt as planProgram, Nt as planSpawn, X as findOnPath, in as startTurnContext, xt as ownSession } from "./dist-DnNuDzEA.js";
6
6
  import { n as cs, t as Za } from "./toml-patch-DGzVRdd1.js";
7
7
  // ../adapters/codex/dist/index.js
8
8
  const SERVER_NAME = "conveno";
@@ -95,6 +95,7 @@ const EVENT_NAME = {
95
95
  session_start: "SessionStart",
96
96
  user_prompt_submit: "UserPromptSubmit",
97
97
  stop: "Stop",
98
+ session_end: "SessionEnd",
98
99
  permission_request: "PermissionRequest"
99
100
  };
100
101
  /** A hook key is `<file>:<event>:<group>:<handler>`; null for any other shape. */
@@ -354,12 +355,16 @@ function renameHooks(toml, rename) {
354
355
  const HOOK_EVENTS = [
355
356
  "SessionStart",
356
357
  "UserPromptSubmit",
357
- "Stop"
358
+ "Stop",
359
+ "SessionEnd"
358
360
  ];
359
361
  /** Older versions also installed a PermissionRequest hook; uninstall still removes it. */
360
362
  const LEGACY_HOOK_EVENTS = ["PermissionRequest"];
361
363
  /** Seconds. The hook gives up after 2 s on its own; this leaves room for Node startup. Same as Claude. */
362
364
  const HOOK_TIMEOUT_SECONDS = 5;
365
+ /** Codex runs SessionEnd while a thread unloads and caps it at 3 s (default 1 s). */
366
+ const SESSION_END_TIMEOUT_SECONDS = 3;
367
+ const timeoutFor = (event) => event === "SessionEnd" ? SESSION_END_TIMEOUT_SECONDS : HOOK_TIMEOUT_SECONDS;
363
368
  const codexDir = (env) => env.env.CODEX_HOME || join(env.home, ".codex");
364
369
  const configPath = (env) => join(codexDir(env), "config.toml");
365
370
  const hooksPath = (env) => join(codexDir(env), "hooks.json");
@@ -471,7 +476,7 @@ async function planHooks(env) {
471
476
  next[event] = withOursReplaced(groups, event, { hooks: [{
472
477
  type: "command",
473
478
  command,
474
- timeout: HOOK_TIMEOUT_SECONDS
479
+ timeout: timeoutFor(event)
475
480
  }] });
476
481
  }
477
482
  if (!changed) return [];
@@ -491,7 +496,7 @@ async function planHooks(env) {
491
496
  ...doc,
492
497
  hooks: next
493
498
  }),
494
- description: `Add SessionStart, UserPromptSubmit and Stop hooks that deliver Conveno messages on the next turn and at the end of a turn. Codex asks you to trust new hooks: review them with /hooks.`
499
+ description: `Add SessionStart, UserPromptSubmit, Stop and SessionEnd hooks that deliver Conveno messages on the next turn and at the end of a turn, and take a closed window offline. Codex asks you to trust new hooks: review them with /hooks.`
495
500
  }];
496
501
  }
497
502
  async function uninstallHooks(env) {
@@ -522,7 +527,7 @@ async function uninstallHooks(env) {
522
527
  path,
523
528
  before,
524
529
  after: json(after),
525
- description: "Remove the Conveno SessionStart, UserPromptSubmit, and Stop hooks."
530
+ description: "Remove the Conveno SessionStart, UserPromptSubmit, Stop, and SessionEnd hooks."
526
531
  }];
527
532
  }
528
533
  function serverSpec(env, existing) {
@@ -608,6 +613,7 @@ const EMPTY = {
608
613
  */
609
614
  async function hook(event, input, ctx) {
610
615
  ctx = withThread(input, ctx, event);
616
+ if (event === "SessionEnd") return retireThread(ctx);
611
617
  if (event === "Stop") {
612
618
  const reason = await endTurnContinuation(ctx);
613
619
  if (reason === null) return EMPTY;
@@ -631,6 +637,20 @@ async function hook(event, input, ctx) {
631
637
  };
632
638
  }
633
639
  /**
640
+ * The thread unloaded (its window closed, or the TUI left it 60 s ago). If it is the session's
641
+ * current conversation, the session departs: the thread's MCP may outlive it (Windows, when Codex
642
+ * cannot kill the process tree) and would keep the row online. A thread the window already left
643
+ * binds to nothing (`turnStart` is false), so the window's session stays. No delivery.
644
+ */
645
+ async function retireThread(ctx) {
646
+ if (ctx.nativeId === void 0) return EMPTY;
647
+ try {
648
+ const session = await ownSession(ctx);
649
+ if (session) await ctx.client["session.unregister"]({ sessionId: session.id });
650
+ } catch {}
651
+ return EMPTY;
652
+ }
653
+ /**
634
654
  * The hook's `session_id` is the Codex thread id, the id `codex queue --thread` takes. Codex
635
655
  * threads can share one app-server process, so the host pid alone may not tell windows apart: the
636
656
  * daemon binds the thread to the window's session (`session.bind`), and wakes the session by it.
@@ -858,6 +878,7 @@ const STATE_EVENTS = {
858
878
  SessionStart: "session_start",
859
879
  UserPromptSubmit: "user_prompt_submit",
860
880
  Stop: "stop",
881
+ SessionEnd: "session_end",
861
882
  PermissionRequest: "permission_request"
862
883
  };
863
884
  /**
@@ -3,7 +3,7 @@ import { mkdir, open, readFile, rm, stat } from "node:fs/promises";
3
3
  import { createConnection } from "node:net";
4
4
  import { homedir } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
- import { A as clientProof, An as isSocketPathTooLong, At as proofsMatch, Cn as RpcResponse, Dn as defaultSocketPath, En as createLineDecoder, I as daemonProof, L as dataDir, On as encodeFrame, R as dataPaths, Sn as RpcErrorCode, Vn as socketPathTooLongMessage, bn as PROTOCOL_VERSION, gn as EventPayload, ht as newAuthNonce, i as ConvenoError, kn as ipcMethods } from "./dist-CRj_cuHc.js";
6
+ import { En as PROTOCOL_VERSION, Fn as encodeFrame, Ft as proofsMatch, In as ipcMethods, Jn as socketPathTooLongMessage, L as daemonProof, Ln as isSocketPathTooLong, Nn as createLineDecoder, On as RpcErrorCode, Pn as defaultSocketPath, R as dataDir, Sn as EventPayload, a as ConvenoError, j as clientProof, kn as RpcResponse, yt as newAuthNonce, z as dataPaths } from "./dist-DnNuDzEA.js";
7
7
  // ../client/dist/index.js
8
8
  const DEFAULT_REQUEST_TIMEOUT_MS = 5e3;
9
9
  const DEFAULT_START_TIMEOUT_MS = 1e4;
@@ -12,6 +12,7 @@ const CLIENT_METHODS = [
12
12
  "session.register",
13
13
  "session.heartbeat",
14
14
  "session.unregister",
15
+ "session.remove",
15
16
  "session.rename",
16
17
  "session.setStatus",
17
18
  "session.byHost",
@@ -147,6 +148,8 @@ var Connection = class {
147
148
  pending = /* @__PURE__ */ new Map();
148
149
  decoder = createLineDecoder();
149
150
  closed = false;
151
+ /** The daemon's version, from its `hello` answer. */
152
+ daemonVersion;
150
153
  constructor(socket, timeoutMs, onEvent = () => {}) {
151
154
  this.socket = socket;
152
155
  this.timeoutMs = timeoutMs;
@@ -254,6 +257,7 @@ async function handshake(socketPath, tokenPath, kind, timeoutMs, onEvent) {
254
257
  });
255
258
  if (!proofsMatch(hello.proof, daemonProof(token, nonce))) throw new ClientError(`The process on ${socketPath} is not the Conveno daemon. Stop it, or remove the socket, and try again.`, { kind: "not_daemon" });
256
259
  await typedCall(conn, "auth", { proof: clientProof(token, hello.challenge) });
260
+ conn.daemonVersion = hello.daemonVersion;
257
261
  return conn;
258
262
  } catch (e) {
259
263
  await conn.close();
@@ -468,6 +472,10 @@ async function connect(opts) {
468
472
  onEvent: (handler) => link.onEvent(handler),
469
473
  close: () => link.close()
470
474
  };
475
+ Object.defineProperty(client, "daemonVersion", {
476
+ get: () => link.conn.daemonVersion,
477
+ enumerable: true
478
+ });
471
479
  for (const method of CLIENT_METHODS) client[method] = (params) => link.call(method, params);
472
480
  return client;
473
481
  }
@@ -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 { 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";
5
+ import { $n as literal, Qn as discriminatedUnion, Xn as array, Yn as _enum, er as number, nr as string, tr as object, yn as DeviceId } from "./dist-DnNuDzEA.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 { 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";
3
+ import { Ct as parseCliVersion, Dt as pendingHookContext, J as existedBefore, K as endTurnContinuation, M as compareVersions, R as dataDir, S as askedMarker, U as dropFromList, W as editJson, dn as uninstallLauncher, en as sameJson, ft as late, ht as loadJson, jt as planLauncher, lt as isObject, vt as needsQuoting, xt as ownSession, y as agentCommand } from "./dist-DnNuDzEA.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. */
@@ -577,6 +577,40 @@ async function sessionOf(ctx) {
577
577
  return null;
578
578
  }
579
579
  }
580
+ /** The folder the hook says the agent works in: the first of `workspacePaths`, else `cwd`. */
581
+ function workspaceOf(input) {
582
+ if (!isObject(input)) return void 0;
583
+ const paths = input.workspacePaths;
584
+ const first = Array.isArray(paths) ? paths[0] : void 0;
585
+ const dir = typeof first === "string" && first !== "" ? first : input.cwd;
586
+ return typeof dir === "string" && dir !== "" ? dir : void 0;
587
+ }
588
+ /**
589
+ * Is the transcript in the Antigravity desktop app's product folder (`antigravity/`), not the CLI's
590
+ * (`antigravity-cli/`) or the IDE's (`antigravity-ide/`)? A second signal next to the process chain.
591
+ */
592
+ function appTranscript(input) {
593
+ const t = isObject(input) ? input.transcriptPath : void 0;
594
+ return typeof t === "string" && t.split(/[\\/]/).includes("antigravity");
595
+ }
596
+ /**
597
+ * The desktop app starts Conveno in its install folder; a hook knows the workspace. Tell the daemon
598
+ * when an app session works elsewhere, and the row moves there. A CLI row is never sent: it already
599
+ * runs in the folder the user opened. Never throws.
600
+ */
601
+ async function followWorkspace(input, ctx, session) {
602
+ const app = session.variant === "app" || appTranscript(input);
603
+ const dir = workspaceOf(input);
604
+ if (!app || dir === void 0) return;
605
+ if (session.variant === "app" && dir === session.cwd) return;
606
+ try {
607
+ await ctx.client["session.setCwd"]({
608
+ sessionId: session.id,
609
+ cwd: dir,
610
+ ...session.variant === "app" ? {} : { variant: "app" }
611
+ });
612
+ } catch {}
613
+ }
580
614
  /** What the Stop hook asks once per turn while no relay is connected. */
581
615
  /** The relay request is asked once per Conveno session (a one-shot `agy -p` run counts each retry as a new turn). */
582
616
  const relayAsk = askedMarker("agy-relay-asked");
@@ -600,6 +634,7 @@ async function hook(event, input, ctx) {
600
634
  if (!isHookEvent(event)) return EMPTY;
601
635
  ctx = withConversation(input, ctx, event !== "Stop");
602
636
  const session = await sessionOf(ctx);
637
+ if (session !== null) await followWorkspace(input, ctx, session);
603
638
  if (event === "Stop") {
604
639
  const stop = isObject(input) ? input : {};
605
640
  const completed = (stop.terminationReason === void 0 || stop.terminationReason === "NO_TOOL_CALL") && (stop.error === void 0 || stop.error === "");
@@ -646,6 +681,7 @@ const antigravityAdapter = {
646
681
  detect,
647
682
  plan,
648
683
  optional: [relayOption],
684
+ doctorNotes: async () => ["The Antigravity app shares the CLI's settings, so Conveno is set up in both. App sessions show as \"Antigravity app\"."],
649
685
  uninstallPlan,
650
686
  hook
651
687
  };
@@ -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(),
@@ -6232,11 +6239,15 @@ const AuthParams = object({
6232
6239
  proof: Sha256Hex });
6233
6240
  const sid = { sessionId: SessionId };
6234
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");
6235
6244
  const RegisterParams = object({
6236
6245
  /** Requested name. If omitted the daemon assigns one such as `claude@repo-1`. */
6237
6246
  name: SessionNameInput.optional(),
6238
6247
  cli: CliKind,
6239
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(),
6240
6251
  cwd: string().min(1),
6241
6252
  repo: RepoInfo.optional(),
6242
6253
  pid: number().int().positive().optional(),
@@ -6348,6 +6359,8 @@ function makeEventNotification(payload) {
6348
6359
  params: payload
6349
6360
  };
6350
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";
6351
6364
  const ipcMethods = {
6352
6365
  hello: {
6353
6366
  params: HelloParams,
@@ -6375,6 +6388,10 @@ const ipcMethods = {
6375
6388
  }),
6376
6389
  result: object({ ok: literal(true) })
6377
6390
  },
6391
+ "session.remove": {
6392
+ params: object({ ...sid }),
6393
+ result: object({ ok: literal(true) })
6394
+ },
6378
6395
  "session.rename": {
6379
6396
  params: object({
6380
6397
  ...sid,
@@ -6414,10 +6431,27 @@ const ipcMethods = {
6414
6431
  /** The calling MCP process, attached to the surviving session on a merge. */
6415
6432
  pid: number().int().positive().optional(),
6416
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(),
6417
6440
  cwd: string().min(1).optional(),
6418
6441
  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() })
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
6421
6455
  },
6422
6456
  "session.hostOf": {
6423
6457
  params: object({
@@ -7744,25 +7778,63 @@ async function runWaker(o) {
7744
7778
  /** Longest wait between two tries to reach the daemon again (`reconnectMs`). */
7745
7779
  const MAX_RECONNECT_MS = 6e4;
7746
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
+ /**
7747
7800
  * The session that owns the hook's host process, when it is a session of the hook's own CLI. Every
7748
7801
  * helper below goes through here before taking messages, so a hook running inside another CLI
7749
7802
  * (which would print a format that CLI discards) never marks anything delivered.
7750
7803
  */
7751
7804
  async function ownSession(ctx) {
7752
7805
  if (ctx.nativeId !== void 0 && ctx.cli !== void 0) try {
7753
- const { session } = await ctx.client["session.bind"]({
7806
+ const base = {
7754
7807
  cli: ctx.cli,
7755
7808
  nativeId: ctx.nativeId,
7756
- hostPid: ctx.hostPid,
7757
7809
  ...ctx.cwd === void 0 ? {} : { cwd: ctx.cwd },
7758
7810
  turnStart: ctx.turnStart === true
7759
- });
7760
- return session && ctx.cli !== void 0 && session.cli !== ctx.cli ? null : session;
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;
7761
7831
  } catch (e) {
7762
7832
  if (e?.code !== RpcErrorCode.MethodNotFound) throw e;
7763
7833
  }
7834
+ const pid = await hostPidOf(ctx);
7835
+ if (pid === void 0) return null;
7764
7836
  const { session } = await ctx.client["session.byHost"]({
7765
- pid: ctx.hostPid,
7837
+ pid,
7766
7838
  ...ctx.cwd === void 0 ? {} : { cwd: ctx.cwd },
7767
7839
  ...ctx.nativeId === void 0 ? {} : { nativeId: ctx.nativeId }
7768
7840
  });
@@ -7881,7 +7953,7 @@ async function awaitOwnSession(ctx, waitMs, pollMs, signal) {
7881
7953
  return "disconnected";
7882
7954
  }
7883
7955
  if (Date.now() + pollMs > until || signal?.aborted) return null;
7884
- if (ctx.isAlive && !ctx.isAlive(ctx.hostPid)) return null;
7956
+ if (!await hostAlive(ctx)) return null;
7885
7957
  if (own.turnStart) own = {
7886
7958
  ...own,
7887
7959
  turnStart: false
@@ -7897,7 +7969,7 @@ async function pauseWhileAlive(ctx, ms, stepMs, deadline, signal) {
7897
7969
  const until = Math.min(Date.now() + ms, deadline);
7898
7970
  for (;;) {
7899
7971
  if (signal?.aborted || Date.now() >= deadline) return false;
7900
- if (ctx.isAlive && !ctx.isAlive(ctx.hostPid)) return false;
7972
+ if (!await hostAlive(ctx)) return false;
7901
7973
  const left = until - Date.now();
7902
7974
  if (left <= 0) return true;
7903
7975
  await new Promise((r) => setTimeout(r, Math.min(left, stepMs)));
@@ -7906,7 +7978,8 @@ async function pauseWhileAlive(ctx, ms, stepMs, deadline, signal) {
7906
7978
  /** `waitForWork`, returning the whole batch and its session (for a requeue). */
7907
7979
  async function waitForWorkBatch(ctx, opts = {}) {
7908
7980
  const deadline = opts.maxMs === void 0 ? 1e400 : Date.now() + opts.maxMs;
7909
- const { isAlive, hostPid } = ctx;
7981
+ const { isAlive } = ctx;
7982
+ const hostPid = isAlive ? await hostPidOf(ctx) : void 0;
7910
7983
  const listenerId = opts.listenerId ?? randomBytes(12).toString("base64url");
7911
7984
  let delay = opts.reconnectMs;
7912
7985
  /** After a lost connection: wait, then go round again. False when the listener must stop. */
@@ -7939,7 +8012,7 @@ async function waitForWorkBatch(ctx, opts = {}) {
7939
8012
  ...deadline !== 1e400 ? { maxMs: Math.max(0, deadline - Date.now()) } : {},
7940
8013
  ...opts.signal !== void 0 ? { signal: opts.signal } : {},
7941
8014
  ...opts.maxChars !== void 0 ? { maxChars: opts.maxChars } : {},
7942
- ...isAlive ? { isHostAlive: () => isAlive(hostPid) } : {}
8015
+ ...isAlive && hostPid !== void 0 ? { isHostAlive: () => isAlive(hostPid) } : {}
7943
8016
  });
7944
8017
  if (r.ok) return {
7945
8018
  sessionId: session.id,
@@ -7955,14 +8028,16 @@ const HOOK_LOG_MAX_BYTES = 1e6;
7955
8028
  const hookLogPath = (dataDir) => join(dataDir, "logs", "hooks.log");
7956
8029
  /** Keep a logged word to plain characters, so one entry is one line and nothing is injected. */
7957
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)));
7958
8033
  /**
7959
8034
  * 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
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
7961
8036
  * session's name.
7962
8037
  */
7963
8038
  function hookLogLine(e) {
7964
8039
  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`;
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`;
7966
8041
  }
7967
8042
  /**
7968
8043
  * Append one line to the hook log, rotating at `HOOK_LOG_MAX_BYTES`. Synchronous and tiny so a hook
@@ -8657,6 +8732,12 @@ function parseProcStat(stat) {
8657
8732
  const ppid = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
8658
8733
  return Number.isInteger(ppid) && ppid >= 0 ? ppid : void 0;
8659
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
+ }
8660
8741
  const norm = (text) => text.replaceAll("\\", "/").toLowerCase();
8661
8742
  /** Split a command line into tokens, keeping quoted parts together and dropping the quotes. */
8662
8743
  function tokens(command) {
@@ -8809,6 +8890,22 @@ async function readTable(io, timeoutMs) {
8809
8890
  return out === null ? null : parseProcessTable(out);
8810
8891
  }
8811
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
+ /**
8812
8909
  * The command line of a process as one string, or null when the OS does not say (the process is
8813
8910
  * gone, or the query was denied). A null answer means "unknown", never "not the daemon".
8814
8911
  */
@@ -9459,6 +9556,7 @@ async function runLaunchFile(path) {
9459
9556
  const child = spawn(spec.file, spec.args, {
9460
9557
  cwd: spec.cwd,
9461
9558
  stdio: "inherit",
9559
+ env: Object.fromEntries(Object.entries(process.env).filter(([k]) => k !== "CONVENO_ACP_WORKER")),
9462
9560
  ...spec.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
9463
9561
  });
9464
9562
  child.once("error", (e) => {
@@ -10174,4 +10272,4 @@ async function waitForRegistration(deps, w) {
10174
10272
  await deps.sleep(250);
10175
10273
  }
10176
10274
  }
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 };
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 };
@@ -1,5 +1,5 @@
1
1
  import { appendFileSync } from "node:fs";
2
- import { tt as hookLogLine, y as appendHookLog } from "./dist-CRj_cuHc.js";
2
+ import { b as appendHookLog, nt as hookLogLine } from "./dist-DnNuDzEA.js";
3
3
  import { n as connectOpts } from "./ctx-tYftvhz_.js";
4
4
  // src/hook.ts
5
5
  /**
@@ -85,6 +85,14 @@ function conversationIn(input) {
85
85
  }
86
86
  /** After a timeout, the hook gets this many more timeouts' worth of time to finish recording. */
87
87
  const FINISH_GRACE_FACTOR = 2;
88
+ /**
89
+ * Every CLI kills a hook 5 s after it starts (`HOOK_TIMEOUT_SECONDS` in each adapter). The budget
90
+ * and the finish grace together stay under this, so the process ends by itself with its outcome
91
+ * logged instead of being killed mid-write. The rest is left for process start-up.
92
+ */
93
+ const HOOK_TOTAL_MAX_MS = 4800;
94
+ /** How long a timed-out hook may keep running to record its turn: capped so budget + grace fits. */
95
+ const finishGraceMs = (timeoutMs) => Math.max(0, Math.min(timeoutMs * FINISH_GRACE_FACTOR, HOOK_TOTAL_MAX_MS - timeoutMs));
88
96
  /** How long before the hook's timeout its messages count as too late to print. */
89
97
  const DEADLINE_MARGIN_MS = 300;
90
98
  /**
@@ -103,10 +111,15 @@ async function runHook(ctx, argv) {
103
111
  if (!adapter || !event) return 0;
104
112
  const listener = adapter.listenEvents?.includes(event) === true;
105
113
  const deadline = listener ? void 0 : Date.now() + ctx.hookTimeoutMs - DEADLINE_MARGIN_MS;
106
- const t0 = ctx.timingLog && !listener ? Date.now() : void 0;
114
+ const started = Date.now();
115
+ const t0 = ctx.timingLog && !listener ? started : void 0;
107
116
  const trace = { delivered: 0 };
108
117
  let conversation;
109
118
  let timedOut = false;
119
+ let workDone = false;
120
+ let hostMs;
121
+ let hostResolved = false;
122
+ let hostMissing = false;
110
123
  let client;
111
124
  let timer;
112
125
  const early = ctx.hostLookup ? void 0 : ctx.ancestry(HOOK_ANCESTRY_TIMEOUT_MS);
@@ -122,19 +135,37 @@ async function runHook(ctx, argv) {
122
135
  const [input, connected] = await Promise.all([readInput(), ctx.connect(connectOpts(ctx, false))]);
123
136
  client = ctx.hookLog ? traced(connected, trace) : connected;
124
137
  if (ctx.hookLog) conversation = conversationIn(input);
125
- const hostPid = await findHostPid(ctx, connected, adapter.cli, () => early ?? ctx.ancestry(1200));
126
- if (hostPid === void 0) {
127
- await adapter.hookWithoutSession?.(event, input).catch(() => {});
128
- return NOTHING;
129
- }
130
- return adapter.hook(event, input, {
138
+ let hostPid;
139
+ const resolveHostPid = () => {
140
+ hostPid ??= (async () => {
141
+ const t = Date.now();
142
+ try {
143
+ const pid = await findHostPid(ctx, connected, adapter.cli, () => early ?? ctx.ancestry(1200));
144
+ if (pid === void 0) hostMissing = true;
145
+ return pid;
146
+ } finally {
147
+ hostMs = Date.now() - t;
148
+ hostResolved = true;
149
+ }
150
+ })();
151
+ return hostPid;
152
+ };
153
+ const out = await adapter.hook(event, input, {
131
154
  client,
132
- hostPid,
155
+ resolveHostPid,
156
+ ...ctx.hostLookup ? { ppid: ctx.hostLookup.ppid } : {},
133
157
  cli: adapter.cli,
134
158
  isAlive: ctx.isAlive,
135
159
  ...deadline === void 0 ? {} : { deadline }
136
160
  });
161
+ if (hostResolved && hostMissing) await adapter.hookWithoutSession?.(event, input).catch(() => {});
162
+ return out;
137
163
  })();
164
+ work.then(() => {
165
+ workDone = true;
166
+ }, () => {
167
+ workDone = true;
168
+ });
138
169
  const timeout = listener ? new Promise(() => void 0) : new Promise((resolve) => {
139
170
  timer = setTimeout(() => {
140
171
  timedOut = true;
@@ -144,19 +175,22 @@ async function runHook(ctx, argv) {
144
175
  let code = 0;
145
176
  try {
146
177
  const out = await Promise.race([work, timeout]);
147
- if (out === NOTHING && !listener) await Promise.race([work.catch(() => void 0), new Promise((r) => setTimeout(r, ctx.hookTimeoutMs * FINISH_GRACE_FACTOR))]);
178
+ if (out === NOTHING && !listener) await Promise.race([work.catch(() => void 0), new Promise((r) => setTimeout(r, finishGraceMs(ctx.hookTimeoutMs)))]);
148
179
  if (out.stdout) ctx.out(out.stdout.endsWith("\n") ? out.stdout : `${out.stdout}\n`);
149
180
  if (listener && out.stderr) ctx.err(out.stderr.endsWith("\n") ? out.stderr : `${out.stderr}\n`);
150
181
  if (listener) code = out.exitCode;
151
182
  } catch {} finally {
152
183
  if (ctx.hookLog) {
153
- const result = timedOut ? "timeout" : trace.error ?? (trace.delivered > 0 ? `delivered ${trace.delivered}` : trace.turn ?? "nothing");
184
+ const done = trace.error ?? (trace.delivered > 0 ? `delivered ${trace.delivered}` : trace.turn ?? "nothing");
185
+ const result = timedOut ? workDone ? `${done} late` : "timeout" : done;
154
186
  appendHookLog(ctx.hookLog, hookLogLine({
155
187
  cli: adapter.cli,
156
188
  event,
157
189
  conversationId: conversation,
158
190
  session: trace.session,
159
- result
191
+ result,
192
+ hostMs,
193
+ ms: Date.now() - started
160
194
  }));
161
195
  }
162
196
  if (t0 !== void 0 && ctx.timingLog) {
@@ -1,13 +1,13 @@
1
1
  import { homedir } from "node:os";
2
- import { n as antigravityAdapter } from "./dist-Du1hwaux.js";
2
+ import { n as antigravityAdapter } from "./dist-D4sb5RQD.js";
3
3
  import { isAbsolute, join } from "node:path";
4
- import { Ct as pendingHookContext, G as endTurnContinuation, Ht as requeueMessages, It as readSettings, L as dataDir, Nt as readAncestry, Qt as startTurnContext, R as dataPaths, _t as ownSession, cn as waitForWork, ln as waitForWorkBatch, nt as hookLogPath, r as CLAUDE_PENDING_TURN_FOLDER, wt as pendingTurn, yt as parseCliVersion } from "./dist-CRj_cuHc.js";
4
+ import { Ct as parseCliVersion, Dt as pendingHookContext, Ht as readSettings, Jt as requeueMessages, K as endTurnContinuation, Ot as pendingTurn, R as dataDir, Rt as readAncestry, hn as waitForWorkBatch, i as CLAUDE_PENDING_TURN_FOLDER, in as startTurnContext, it as hostAlive, mn as waitForWork, rt as hookLogPath, xt as ownSession, z as dataPaths } from "./dist-DnNuDzEA.js";
5
5
  import { readFile } from "node:fs/promises";
6
6
  import { applyEdits, modify, parse, printParseErrorCode } from "jsonc-parser";
7
- import { t as codexAdapter } from "./dist-BjATai4T.js";
8
- import { t as grokAdapter } from "./dist-DF0nL8wE.js";
9
- import { n as connect } from "./dist-B3YYLzKS.js";
10
- import { t as runHook } from "./hook-ByduyOom.js";
7
+ import { t as codexAdapter } from "./dist-C9Z1EMlM.js";
8
+ import { t as grokAdapter } from "./dist-B14ldKRS.js";
9
+ import { n as connect } from "./dist-Ca3P7aN-.js";
10
+ import { t as runHook } from "./hook-C60hXJdg.js";
11
11
  // ../adapters/claude/dist/index.js
12
12
  const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
13
13
  /** Read a JSON object file. Missing or blank files give `{}`; anything else that is not a JSON object throws. */
@@ -467,7 +467,7 @@ async function mayListen(ctx, input) {
467
467
  for (let i = 0; i < 20; i++) {
468
468
  const session = await ownSession(ctx).catch(() => null);
469
469
  if (session) return session.spawned;
470
- if (ctx.isAlive && !ctx.isAlive(ctx.hostPid)) return false;
470
+ if (!await hostAlive(ctx)) return false;
471
471
  await new Promise((r) => setTimeout(r, 500));
472
472
  }
473
473
  return false;
@@ -537,7 +537,7 @@ async function hook$1(event, input, ctx) {
537
537
  maxChars: WAKE_MAX_CHARS
538
538
  });
539
539
  if (r === null) return EMPTY$1;
540
- if (ctx.isAlive && !ctx.isAlive(ctx.hostPid)) {
540
+ if (!await hostAlive(ctx)) {
541
541
  await requeueMessages(ctx.client, r.sessionId, r.batch.messages);
542
542
  return EMPTY$1;
543
543
  }
@@ -1330,7 +1330,7 @@ function createHookCtx() {
1330
1330
  launcherPaths
1331
1331
  },
1332
1332
  isAlive: isProcessAlive,
1333
- hookTimeoutMs: 2e3,
1333
+ hookTimeoutMs: process.platform === "win32" ? 3500 : 2e3,
1334
1334
  ...process.env.CONVENO_HOOK_TIMING_LOG ? {
1335
1335
  timingLog: process.env.CONVENO_HOOK_TIMING_LOG,
1336
1336
  uptimeMs: () => process.uptime() * 1e3
@@ -0,0 +1 @@
1
+ export { i as runHookEntry } from "./hook-entry-WlJSM5aD.js";