@conveno/cli 0.2.0-rc.7 → 0.2.0-rc.9

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,8 +1,8 @@
1
- import { tmpdir } from "node:os";
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
4
  import { accessSync, chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
5
- import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
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";
8
8
  // ../../node_modules/.pnpm/ulid@3.0.2/node_modules/ulid/dist/node/index.js
@@ -7028,6 +7028,87 @@ async function logoutAccount(path, io = {}) {
7028
7028
  revoked
7029
7029
  };
7030
7030
  }
7031
+ const pathApi$2 = (platform) => platform === "win32" ? win32 : posix;
7032
+ /**
7033
+ * Conveno data directory. Pure: platform, environment and home directory are arguments.
7034
+ *
7035
+ * - linux and other posix: `$XDG_DATA_HOME/conveno` (absolute only), else `~/.local/share/conveno`
7036
+ * - darwin: `~/Library/Application Support/conveno`
7037
+ * - win32: `%LOCALAPPDATA%\conveno`, else `<home>\AppData\Local\conveno`
7038
+ */
7039
+ function dataDir(platform, env, homedir) {
7040
+ const p = pathApi$2(platform);
7041
+ const home = platform === "win32" ? env.USERPROFILE ?? homedir : env.HOME || homedir;
7042
+ if (platform === "win32") {
7043
+ const local = env.LOCALAPPDATA;
7044
+ if (local) return p.join(local, "conveno");
7045
+ if (!home) throw new Error("cannot determine LOCALAPPDATA or home directory for the data dir");
7046
+ return p.join(home, "AppData", "Local", "conveno");
7047
+ }
7048
+ if (platform === "darwin") {
7049
+ if (!home) throw new Error("cannot determine home directory for the data dir");
7050
+ return p.join(home, "Library", "Application Support", "conveno");
7051
+ }
7052
+ const xdg = env.XDG_DATA_HOME;
7053
+ if (xdg?.startsWith("/")) return p.join(xdg, "conveno");
7054
+ if (!home) throw new Error("cannot determine home directory for the data dir");
7055
+ return p.join(home, ".local", "share", "conveno");
7056
+ }
7057
+ /** Files and folders inside the data dir, joined with the platform's separator. */
7058
+ function dataPaths(platform, dir) {
7059
+ const p = pathApi$2(platform);
7060
+ return {
7061
+ dir,
7062
+ token: p.join(dir, "daemon.token"),
7063
+ database: p.join(dir, "conveno.db"),
7064
+ lock: p.join(dir, "daemon.lock"),
7065
+ backups: p.join(dir, "backups"),
7066
+ /** The CLI writes its error logs here, and the daemon writes `daemon.log`. */
7067
+ logs: p.join(dir, "logs"),
7068
+ daemonLog: p.join(dir, "logs", "daemon.log"),
7069
+ /** What the daemon printed to stdout and stderr, from the last time a client started it. */
7070
+ daemonStartLog: p.join(dir, "logs", "daemon-start.log"),
7071
+ manifest: p.join(dir, "install-manifest.json"),
7072
+ /** Conveno account tokens from `conveno login`, mode 0600. See account.ts. */
7073
+ account: p.join(dir, "account.json"),
7074
+ /** Choices the user made, such as whether ACP adapters may be fetched with npx. See settings.ts. */
7075
+ settings: p.join(dir, "settings.json")
7076
+ };
7077
+ }
7078
+ /** Best effort: deletes the markers in `dir` not touched for `ASKED_MAX_AGE_MS`. */
7079
+ async function pruneAsked(dir, now = Date.now()) {
7080
+ try {
7081
+ for (const name of await readdir(dir)) try {
7082
+ const f = join(dir, name);
7083
+ if (now - (await stat(f)).mtimeMs > 6048e5) await rm(f, { force: true });
7084
+ } catch {}
7085
+ } catch {}
7086
+ }
7087
+ /**
7088
+ * "Asked once per session" for a Stop hook request: one empty file per Conveno session in
7089
+ * `<data dir>/<folder>`. Best effort both ways: a failure only means the request can repeat.
7090
+ */
7091
+ function askedMarker(folder) {
7092
+ const file = (sessionId) => join(dataDir(process.platform, process.env, homedir()), folder, sessionId.replace(/[^A-Za-z0-9_-]/g, "_"));
7093
+ return {
7094
+ async wasAsked(sessionId) {
7095
+ try {
7096
+ await readFile(file(sessionId));
7097
+ return true;
7098
+ } catch {
7099
+ return false;
7100
+ }
7101
+ },
7102
+ async markAsked(sessionId) {
7103
+ try {
7104
+ const f = file(sessionId);
7105
+ await mkdir(join(f, ".."), { recursive: true });
7106
+ await writeFile(f, "");
7107
+ await pruneAsked(join(f, ".."));
7108
+ } catch {}
7109
+ }
7110
+ };
7111
+ }
7031
7112
  /** 32 random bytes as lowercase hex, for nonces and challenges. */
7032
7113
  const newAuthNonce = () => randomBytes(32).toString("hex");
7033
7114
  /** Proof the daemon sends in the `hello` result: HMAC-SHA256 of the client's nonce. */
@@ -7645,10 +7726,10 @@ async function ownSession(ctx, opts = {}) {
7645
7726
  return session;
7646
7727
  }
7647
7728
  const budget = (opts) => opts.maxChars === void 0 ? {} : { maxChars: opts.maxChars };
7648
- /** Past `opts.deadline`, or else the hook runner's own (`HookContext.deadline`). */
7729
+ /** Past `opts.deadline` or the hook runner's own (`HookContext.deadline`), whichever is first. */
7649
7730
  const late = (ctx, opts) => {
7650
- const d = opts.deadline ?? ctx.deadline;
7651
- return d !== void 0 && Date.now() > d;
7731
+ const d = Math.min(opts.deadline ?? 1e400, ctx.deadline ?? 1e400);
7732
+ return Date.now() > d;
7652
7733
  };
7653
7734
  /** `message.deliver` for `session`, framed for a hook; null when nothing or too late. */
7654
7735
  async function deliverFramed(ctx, session, opts) {
@@ -8072,6 +8153,99 @@ function existedBefore(baseline, path) {
8072
8153
  const root = parseTree(baseline.charCodeAt(0) === 65279 ? baseline.slice(1) : baseline, [], PARSE_OPTIONS);
8073
8154
  return root !== void 0 && findNodeAtLocation(root, path) !== void 0;
8074
8155
  }
8156
+ const MARKER = "Written by Conveno.";
8157
+ /**
8158
+ * Would `word` have to be quoted in a hook or allow-rule command? Grok never auto-allows a quoted
8159
+ * command, so a path that needs quotes cannot use the launcher. Shared with the Grok adapter's
8160
+ * quoting, so the two never disagree. Safe unquoted: letters, digits and `_@%+=:,./\-`, plus `~`
8161
+ * anywhere but first (8.3 short names such as `JOHNSM~1`): bash expands only a leading `~`, and
8162
+ * PowerShell and cmd read a mid-word `~` literally.
8163
+ */
8164
+ const needsQuoting = (word) => !/^(?!~)[A-Za-z0-9_@%+=:,./~-]+$/.test(word);
8165
+ const launcherFile = (platform) => platform === "win32" ? "conveno.cmd" : "conveno";
8166
+ /**
8167
+ * Where the launcher goes: `<data dir>/bin`, except on macOS, whose data dir
8168
+ * (`~/Library/Application Support/conveno`) has a space, so it is `~/.conveno/bin`.
8169
+ */
8170
+ const launcherPath = (platform, dataDir, home) => platform === "darwin" && home ? posix.join(home, ".conveno", "bin", launcherFile(platform)) : (platform === "win32" ? win32 : posix).join(dataDir, "bin", launcherFile(platform));
8171
+ /** The launcher's content: ASCII, CRLF on Windows, a POSIX shell script elsewhere. */
8172
+ function launcherText(platform, node, bin) {
8173
+ if (platform === "win32") {
8174
+ const q = (p) => `"${p.replace(/%/g, "%%")}"`;
8175
+ return `@rem ${MARKER} \`conveno uninstall\` removes this file.\r\n@${q(node)} ${q(bin)} %*\r\n`;
8176
+ }
8177
+ const q = (p) => `"${p.replace(/(["\\$`])/g, "\\$1")}"`;
8178
+ return `#!/bin/sh\n# ${MARKER} \`conveno uninstall\` removes this file.\nexec ${q(node)} ${q(bin)} "$@"\n`;
8179
+ }
8180
+ const slashed = (p, platform) => platform === "win32" ? p.replace(/\\/g, "/") : p;
8181
+ /** Without a usable launcher: the configured command, or node and the script for a Windows shim. */
8182
+ const fallback = (env) => {
8183
+ const { command, bin } = env.conveno;
8184
+ return command.length > 1 || !bin || env.platform !== "win32" ? command : ["node", bin];
8185
+ };
8186
+ /**
8187
+ * The command an agent runs for a Conveno helper of `cli`, as words (not yet quoted). Grok keeps a
8188
+ * plain `conveno` when the PATH one is this install. Antigravity on Windows prefers the PATH
8189
+ * `conveno.cmd`. In every other case it is the launcher, or the configured command when no launcher
8190
+ * is known.
8191
+ */
8192
+ function agentCommand(env, cli) {
8193
+ const l = env.conveno.launcher;
8194
+ if (!l) return env.conveno.command;
8195
+ if (cli === "antigravity" && env.platform === "win32" && l.onPath && l.cmdShim) return ["conveno.cmd"];
8196
+ if (l.onPath && !(cli === "antigravity" && env.platform === "win32")) return ["conveno"];
8197
+ if (l.spaced) return fallback(env);
8198
+ return [slashed(l.path, env.platform)];
8199
+ }
8200
+ /** Does `agentCommand` point at the launcher file. */
8201
+ const usesLauncher = (env, cli) => {
8202
+ const l = env.conveno.launcher;
8203
+ return l !== void 0 && !l.spaced && agentCommand(env, cli)[0] === slashed(l.path, env.platform);
8204
+ };
8205
+ /** Folders to drop with the launcher once empty: `bin`, and `~/.conveno` above it on macOS. */
8206
+ const pruneLevels = (path) => posix.basename(posix.dirname(posix.dirname(path.replace(/\\/g, "/")))) === ".conveno" ? 2 : 1;
8207
+ const read = (path) => readFile(path, "utf8").catch((e) => {
8208
+ if (e.code === "ENOENT" || e.code === "ENOTDIR") return null;
8209
+ throw e;
8210
+ });
8211
+ /** Write or refresh the launcher when `cli` runs it. Undefined: nothing to do. */
8212
+ async function planLauncher(env, cli) {
8213
+ const l = env.conveno.launcher;
8214
+ if (!l || !usesLauncher(env, cli)) return void 0;
8215
+ const before = await read(l.path);
8216
+ if (before === l.text) return void 0;
8217
+ return {
8218
+ component: "hooks",
8219
+ kind: before === null ? "add" : "update",
8220
+ parts: [{
8221
+ name: "Launcher",
8222
+ kind: before === null ? "add" : "update"
8223
+ }],
8224
+ path: l.path,
8225
+ before,
8226
+ after: l.text,
8227
+ pruneEmptyDir: pruneLevels(l.path),
8228
+ ...env.platform === "win32" ? {} : { mode: 493 },
8229
+ description: "Add a short launcher script in Conveno's data folder (~/.conveno/bin on macOS), so the agent runs a short command that starts this install."
8230
+ };
8231
+ }
8232
+ /** Remove the launcher when it is Conveno's own file. */
8233
+ async function uninstallLauncher(env) {
8234
+ const l = env.conveno.launcher;
8235
+ if (!l) return void 0;
8236
+ const before = await read(l.path);
8237
+ if (before === null || !before.includes(MARKER)) return void 0;
8238
+ return {
8239
+ component: "hooks",
8240
+ kind: "remove",
8241
+ path: l.path,
8242
+ before,
8243
+ after: "",
8244
+ description: "Remove Conveno's launcher script.",
8245
+ deleteFile: true,
8246
+ pruneEmptyDir: pruneLevels(l.path)
8247
+ };
8248
+ }
8075
8249
  const HEARTBEAT_INTERVAL_MS = 15e3;
8076
8250
  /**
8077
8251
  * A session is offline once 45 s pass without a heartbeat, or as soon as its host process is gone.
@@ -8181,53 +8355,6 @@ function clearOrchestrator(holder, sessions) {
8181
8355
  function holderAfterDeparture(holder, departed) {
8182
8356
  return holder === departed ? null : holder;
8183
8357
  }
8184
- const pathApi$2 = (platform) => platform === "win32" ? win32 : posix;
8185
- /**
8186
- * Conveno data directory. Pure: platform, environment and home directory are arguments.
8187
- *
8188
- * - linux and other posix: `$XDG_DATA_HOME/conveno` (absolute only), else `~/.local/share/conveno`
8189
- * - darwin: `~/Library/Application Support/conveno`
8190
- * - win32: `%LOCALAPPDATA%\conveno`, else `<home>\AppData\Local\conveno`
8191
- */
8192
- function dataDir(platform, env, homedir) {
8193
- const p = pathApi$2(platform);
8194
- const home = platform === "win32" ? env.USERPROFILE ?? homedir : env.HOME || homedir;
8195
- if (platform === "win32") {
8196
- const local = env.LOCALAPPDATA;
8197
- if (local) return p.join(local, "conveno");
8198
- if (!home) throw new Error("cannot determine LOCALAPPDATA or home directory for the data dir");
8199
- return p.join(home, "AppData", "Local", "conveno");
8200
- }
8201
- if (platform === "darwin") {
8202
- if (!home) throw new Error("cannot determine home directory for the data dir");
8203
- return p.join(home, "Library", "Application Support", "conveno");
8204
- }
8205
- const xdg = env.XDG_DATA_HOME;
8206
- if (xdg?.startsWith("/")) return p.join(xdg, "conveno");
8207
- if (!home) throw new Error("cannot determine home directory for the data dir");
8208
- return p.join(home, ".local", "share", "conveno");
8209
- }
8210
- /** Files and folders inside the data dir, joined with the platform's separator. */
8211
- function dataPaths(platform, dir) {
8212
- const p = pathApi$2(platform);
8213
- return {
8214
- dir,
8215
- token: p.join(dir, "daemon.token"),
8216
- database: p.join(dir, "conveno.db"),
8217
- lock: p.join(dir, "daemon.lock"),
8218
- backups: p.join(dir, "backups"),
8219
- /** The CLI writes its error logs here, and the daemon writes `daemon.log`. */
8220
- logs: p.join(dir, "logs"),
8221
- daemonLog: p.join(dir, "logs", "daemon.log"),
8222
- /** What the daemon printed to stdout and stderr, from the last time a client started it. */
8223
- daemonStartLog: p.join(dir, "logs", "daemon-start.log"),
8224
- manifest: p.join(dir, "install-manifest.json"),
8225
- /** Conveno account tokens from `conveno login`, mode 0600. See account.ts. */
8226
- account: p.join(dir, "account.json"),
8227
- /** Choices the user made, such as whether ACP adapters may be fetched with npx. See settings.ts. */
8228
- settings: p.join(dir, "settings.json")
8229
- };
8230
- }
8231
8358
  const defaultIsFile = (path) => {
8232
8359
  try {
8233
8360
  return statSync(path).isFile();
@@ -8764,7 +8891,10 @@ function readSettings(path) {
8764
8891
  const v = JSON.parse(readFileSync(path, "utf8"));
8765
8892
  if (typeof v !== "object" || v === null) return {};
8766
8893
  const o = v;
8767
- return { ...typeof o.acpAdapterNpx === "boolean" ? { acpAdapterNpx: o.acpAdapterNpx } : {} };
8894
+ return {
8895
+ ...typeof o.acpAdapterNpx === "boolean" ? { acpAdapterNpx: o.acpAdapterNpx } : {},
8896
+ ...typeof o.leadCli === "string" && CLI_KINDS.includes(o.leadCli) ? { leadCli: o.leadCli } : {}
8897
+ };
8768
8898
  } catch {
8769
8899
  return {};
8770
8900
  }
@@ -9417,7 +9547,7 @@ const SPAWN_TABLE = {
9417
9547
  args: [],
9418
9548
  adapterPackage: "@agentclientprotocol/claude-agent-acp",
9419
9549
  fullAccessMode: "bypassPermissions",
9420
- note: "Claude Code has no ACP server of its own. The third-party npm package @agentclientprotocol/claude-agent-acp provides one and uses the Claude Code sign-in. Run conveno init to let Conveno fetch it with npx, or install it yourself.",
9550
+ note: "Claude Code has no ACP server of its own. The ACP project's npm package @agentclientprotocol/claude-agent-acp provides one and uses the Claude Code sign-in. Run conveno init to let Conveno fetch it with npx, or install it yourself.",
9421
9551
  docs: ["https://github.com/agentclientprotocol/claude-agent-acp (Apache-2.0, maintained by the ACP project)", "https://www.npmjs.com/package/@agentclientprotocol/claude-agent-acp (bin claude-agent-acp)"]
9422
9552
  }
9423
9553
  },
@@ -9431,7 +9561,7 @@ const SPAWN_TABLE = {
9431
9561
  args: [],
9432
9562
  adapterPackage: "@agentclientprotocol/codex-acp",
9433
9563
  fullAccessMode: "agent-full-access",
9434
- note: "Codex has no ACP server of its own. The third-party npm package @agentclientprotocol/codex-acp provides one and uses the Codex sign-in. Run conveno init to let Conveno fetch it with npx, or install it yourself.",
9564
+ note: "Codex has no ACP server of its own. The ACP project's npm package @agentclientprotocol/codex-acp provides one and uses the Codex sign-in. Run conveno init to let Conveno fetch it with npx, or install it yourself.",
9435
9565
  docs: [
9436
9566
  "https://github.com/agentclientprotocol/codex-acp (Apache-2.0, built on the Codex app server)",
9437
9567
  "https://www.npmjs.com/package/@agentclientprotocol/codex-acp (bin codex-acp)",
@@ -9951,4 +10081,4 @@ async function waitForRegistration(deps, w) {
9951
10081
  await deps.sleep(250);
9952
10082
  }
9953
10083
  }
9954
- export { jwtClaim as $, EVENT_NAMES as $t, daemonProof as A, literal as An, resolveRecipient as At, evaluateLiveness as B, takeAcpLaunchFile as Bt, claimSpawnRecord as C, safeParse as Cn, realSpawnDeps as Ct, completeLogin as D, array as Dn, requeueMessages as Dt, compatStatus as E, _enum as En, requeueEntries as Et, detectRepo as F, senderOf as Ft, formatHookContext as G, updateSpawnRecord as Gt, fetchAccountStatus as H, takeWithinChars as Ht, dropFromList as I, spawnRecordPath as It, holderAfterDeparture as J, waitForWorkBatch as Jt, formatInbox as K, validateRename as Kt, editJson as L, spawnSession as Lt, dataPaths as M, object as Mn, runLaunchFile as Mt, decideAutoContinue as N, string as Nn, runWaker as Nt, createWmiWalker as O, boolean as On, requeueOwnMessages as Ot, defaultProcessIo as P, sameJson as Pt, isOnline as Q, DeviceId as Qt, effectiveHolder as R, startTurnContext as Rt, claimOrchestrator as S, parseRelayFrame as Sn, readSpawnRecord as St, clientProof as T, socketPathTooLongMessage as Tn, requestDeviceCode as Tt, findOnPath as U, tooManyUnreadMessage as Ut, existedBefore as V, takeWithinBytes as Vt, formatContinuation as W, turnHops as Wt, isFromOwner as X, CLI_KINDS as Xt, isAllowed as Y, writeSettings as Yt, isObject as Z, CliKind as Zt, attachAcpSession as _, makeResult as _n, readAccountTokens as _t, FROM_USER_NOTICE as a, PROTOCOL_VERSION as an, parseAllowPatterns as at, baseName as b, newSessionId as bn, readInbox as bt, ORCHESTRATOR_TASK_NOTICE as c, RpcResponse as cn, parsePs1ShimTarget as ct, SPAWN_TABLE as d, defaultSocketPath as dn, pinnedAdapter as dt, EVENT_NOTIFICATION_METHOD as en, loadJson as et, SpawnError as f, encodeFrame as fn, planProgram as ft, adapterNpxCommand as g, makeEventNotification as gn, putInList as gt, adapterInstallCommand as h, makeError as hn, proofsMatch as ht, DEFAULT_ALLOW_RULES as i, OWNER_SESSION_ID as in, ownSession as it, dataDir as j, number as jn, resolveWindowsCommand as jt, currentAccessToken as k, discriminatedUnion as kn, resolveAcpProgram as kt, RESPONSE_BUDGET_BYTES as l, SessionId as ln, pendingForInjection as lt, acpOverrideVar as m, isSocketPathTooLong as mn, pollDeviceCode as mt, AccountError as n, Message as nn, markDelivered as nt, HEARTBEAT_INTERVAL_MS as o, RelayPayload as on, parseCliVersion as ot, ackEntries as p, ipcMethods as pn, planSpawn as pt, generateSessionName as q, waitForWork as qt, ConvenoError as r, MessageId as rn, newAuthNonce as rt, NOT_FROM_USER_NOTICE as s, RpcErrorCode as sn, parseCmdShimTarget as st, ACCOUNT_API as t, EventPayload as tn, logoutAccount as tt, SPAWN_CLIS as u, createLineDecoder as un, pendingHookContext as ut, autoCandidates as v, newDeviceId as vn, readAncestry as vt, clearOrchestrator as w, sanitizeLine as wn, renderBody as wt, bindAccountDevice as x, parseIpcRequest as xn, readSettings as xt, autoLimitsFromEnv as y, newMessageId as yn, readCommandLine as yt, endTurnContinuation as z, statusAfterLiveness as zt };
10084
+ export { isFromOwner as $, uninstallLauncher as $t, completeLogin as A, newSessionId as An, readSpawnRecord as At, editJson as B, literal as Bn, runLaunchFile as Bt, bindAccountDevice as C, ipcMethods as Cn, proofsMatch as Ct, clientProof as D, makeResult as Dn, readCommandLine as Dt, clearOrchestrator as E, makeEventNotification as En, readAncestry as Et, dataPaths as F, socketPathTooLongMessage as Fn, requeueMessages as Ft, fetchAccountStatus as G, spawnSession as Gt, endTurnContinuation as H, object as Hn, sameJson as Ht, decideAutoContinue as I, _enum as In, requeueOwnMessages as It, formatHookContext as J, takeAcpLaunchFile as Jt, findOnPath as K, startTurnContext as Kt, defaultProcessIo as L, array as Ln, resolveAcpProgram as Lt, currentAccessToken as M, parseRelayFrame as Mn, renderBody as Mt, daemonProof as N, safeParse as Nn, requestDeviceCode as Nt, compareVersions as O, newDeviceId as On, readInbox as Ot, dataDir as P, sanitizeLine as Pn, requeueEntries as Pt, isAllowed as Q, turnHops as Qt, detectRepo as R, boolean as Rn, resolveRecipient as Rt, baseName as S, encodeFrame as Sn, pollDeviceCode as St, claimSpawnRecord as T, makeError as Tn, readAccountTokens as Tt, evaluateLiveness as U, string as Un, senderOf as Ut, effectiveHolder as V, number as Vn, runWaker as Vt, existedBefore as W, spawnRecordPath as Wt, generateSessionName as X, takeWithinChars as Xt, formatInbox as Y, takeWithinBytes as Yt, holderAfterDeparture as Z, tooManyUnreadMessage as Zt, agentCommand as _, RpcResponse as _n, pendingHookContext as _t, FROM_USER_NOTICE as a, CLI_KINDS as an, launcherText as at, autoCandidates as b, createLineDecoder as bn, planProgram as bt, ORCHESTRATOR_TASK_NOTICE as c, EVENT_NAMES as cn, markDelivered as ct, SPAWN_TABLE as d, Message as dn, ownSession as dt, updateSpawnRecord as en, isObject as et, SpawnError as f, MessageId as fn, parseAllowPatterns as ft, adapterNpxCommand as g, RpcErrorCode as gn, pendingForInjection as gt, adapterInstallCommand as h, RelayPayload as hn, parsePs1ShimTarget as ht, DEFAULT_ALLOW_RULES as i, writeSettings as in, launcherPath as it, createWmiWalker as j, parseIpcRequest as jn, realSpawnDeps as jt, compatStatus as k, newMessageId as kn, readSettings as kt, RESPONSE_BUDGET_BYTES as l, EVENT_NOTIFICATION_METHOD as ln, needsQuoting as lt, acpOverrideVar as m, PROTOCOL_VERSION as mn, parseCmdShimTarget as mt, AccountError as n, waitForWork as nn, jwtClaim as nt, HEARTBEAT_INTERVAL_MS as o, CliKind as on, loadJson as ot, ackEntries as p, OWNER_SESSION_ID as pn, parseCliVersion as pt, formatContinuation as q, statusAfterLiveness as qt, ConvenoError as r, waitForWorkBatch as rn, late as rt, NOT_FROM_USER_NOTICE as s, DeviceId as sn, logoutAccount as st, ACCOUNT_API as t, validateRename as tn, isOnline as tt, SPAWN_CLIS as u, EventPayload as un, newAuthNonce as ut, askedMarker as v, SESSION_NAME_PATTERN as vn, pinnedAdapter as vt, claimOrchestrator as w, isSocketPathTooLong as wn, putInList as wt, autoLimitsFromEnv as x, defaultSocketPath as xn, planSpawn as xt, attachAcpSession as y, SessionId as yn, planLauncher as yt, dropFromList as z, discriminatedUnion as zn, resolveWindowsCommand as zt };
@@ -1,3 +1,4 @@
1
+ import { appendFileSync } from "node:fs";
1
2
  import { n as connectOpts } from "./ctx-tYftvhz_.js";
2
3
  // src/hook.ts
3
4
  /**
@@ -31,6 +32,18 @@ async function findHostPid(ctx, client, cli, local) {
31
32
  return (await local()).hostPid;
32
33
  }
33
34
  /**
35
+ * One line of the timing log: `<iso time> cli=<cli> event=<event> ms=<n> proc_ms=<n> timeout=<yes|no>`.
36
+ * `ms` is the time inside `runHook`; `proc_ms` also counts process start-up (what the CLI's own
37
+ * hook limit sees). `timeout=yes` means the hook ran past its limit and was cut off.
38
+ */
39
+ function timingLine(cli, event, ms, procMs, timedOut) {
40
+ return `${(/* @__PURE__ */ new Date()).toISOString()} cli=${cli} event=${event} ms=${ms}${procMs === void 0 ? "" : ` proc_ms=${procMs}`} timeout=${timedOut ? "yes" : "no"}\n`;
41
+ }
42
+ /** After a timeout, the hook gets this many more timeouts' worth of time to finish recording. */
43
+ const FINISH_GRACE_FACTOR = 2;
44
+ /** How long before the hook's timeout its messages count as too late to print. */
45
+ const DEADLINE_MARGIN_MS = 300;
46
+ /**
34
47
  * `conveno hook <cli> <event>`: reads the CLI's hook JSON on stdin and prints what the adapter
35
48
  * returns. Never starts a daemon. A hook that fails or stalls must not hold the CLI up, so an
36
49
  * ordinary hook gives up after the context's timeout (2 s), never writes to stderr and exits 0.
@@ -40,14 +53,14 @@ async function findHostPid(ctx, client, cli, local) {
40
53
  * the message on stderr (Claude Code's `asyncRewake`). They stop on their own when the host CLI
41
54
  * exits, the session goes offline, or a newer listener replaces them.
42
55
  */
43
- /** How long before the hook's timeout its messages count as too late to print. */
44
- const DEADLINE_MARGIN_MS = 300;
45
56
  async function runHook(ctx, argv) {
46
57
  const [cli, event] = argv;
47
58
  const adapter = ctx.adapters.find((a) => a.cli === cli);
48
59
  if (!adapter || !event) return 0;
49
60
  const listener = adapter.listenEvents?.includes(event) === true;
50
61
  const deadline = listener ? void 0 : Date.now() + ctx.hookTimeoutMs - DEADLINE_MARGIN_MS;
62
+ const t0 = ctx.timingLog && !listener ? Date.now() : void 0;
63
+ let timedOut = false;
51
64
  let client;
52
65
  let timer;
53
66
  const early = ctx.hostLookup ? void 0 : ctx.ancestry(HOOK_ANCESTRY_TIMEOUT_MS);
@@ -73,15 +86,25 @@ async function runHook(ctx, argv) {
73
86
  });
74
87
  })();
75
88
  const timeout = listener ? new Promise(() => void 0) : new Promise((resolve) => {
76
- timer = setTimeout(() => resolve(NOTHING), ctx.hookTimeoutMs);
89
+ timer = setTimeout(() => {
90
+ timedOut = true;
91
+ resolve(NOTHING);
92
+ }, ctx.hookTimeoutMs);
77
93
  });
78
94
  let code = 0;
79
95
  try {
80
96
  const out = await Promise.race([work, timeout]);
97
+ if (out === NOTHING && !listener) await Promise.race([work.catch(() => void 0), new Promise((r) => setTimeout(r, ctx.hookTimeoutMs * FINISH_GRACE_FACTOR))]);
81
98
  if (out.stdout) ctx.out(out.stdout.endsWith("\n") ? out.stdout : `${out.stdout}\n`);
82
99
  if (listener && out.stderr) ctx.err(out.stderr.endsWith("\n") ? out.stderr : `${out.stderr}\n`);
83
100
  if (listener) code = out.exitCode;
84
101
  } catch {} finally {
102
+ if (t0 !== void 0 && ctx.timingLog) {
103
+ const up = ctx.uptimeMs?.();
104
+ try {
105
+ appendFileSync(ctx.timingLog, timingLine(adapter.cli, event, Date.now() - t0, up === void 0 ? void 0 : Math.round(up), timedOut));
106
+ } catch {}
107
+ }
85
108
  if (timer) clearTimeout(timer);
86
109
  work.catch(() => void 0);
87
110
  await Promise.race([client?.close().catch(() => void 0), new Promise((r) => setTimeout(r, 100))]);
@@ -1,13 +1,13 @@
1
1
  import { homedir } from "node:os";
2
- import { n as antigravityAdapter } from "./dist-D9Gu-mQm.js";
2
+ import { n as antigravityAdapter } from "./dist-BjdBeCHy.js";
3
3
  import { isAbsolute, join } from "node:path";
4
- import { Dt as requeueMessages, I as dropFromList, Jt as waitForWorkBatch, L as editJson$1, Ot as requeueOwnMessages, Pt as sameJson$1, Rt as startTurnContext, V as existedBefore, Z as isObject$1, et as loadJson$1, gt as putInList, it as ownSession, j as dataDir, ot as parseCliVersion, qt as waitForWork, ut as pendingHookContext, vt as readAncestry, z as endTurnContinuation } from "./dist-D2hMvcZu.js";
4
+ import { B as editJson$1, Et as readAncestry, Ft as requeueMessages, H as endTurnContinuation, Ht as sameJson$1, It as requeueOwnMessages, Kt as startTurnContext, P as dataDir, W as existedBefore, _t as pendingHookContext, dt as ownSession, et as isObject$1, nn as waitForWork, ot as loadJson$1, pt as parseCliVersion, rn as waitForWorkBatch, wt as putInList, z as dropFromList } from "./dist-STNJjbNH.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-DOGlDbRb.js";
8
- import { t as grokAdapter } from "./dist-Dd31Fg0h.js";
9
- import { n as connect } from "./dist-ftx5RNCp.js";
10
- import { t as runHook } from "./hook-CQeSn-w4.js";
7
+ import { t as codexAdapter } from "./dist-MK-cK1JY.js";
8
+ import { t as grokAdapter } from "./dist-DaIpdMke.js";
9
+ import { n as connect } from "./dist-D_O_JLLq.js";
10
+ import { t as runHook } from "./hook-CDF1A8AY.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. */
@@ -933,6 +933,7 @@ async function planExtension(env) {
933
933
  path: p.extension,
934
934
  before,
935
935
  after: want,
936
+ pruneEmptyDir: true,
936
937
  description: `${before === null ? "Add" : "Update"} the Conveno extension for Copilot CLI. It wakes an idle session when a message arrives.`
937
938
  });
938
939
  }
@@ -963,6 +964,7 @@ async function planExtension(env) {
963
964
  path: p.marker,
964
965
  before: null,
965
966
  after: MARKER_TEXT,
967
+ pruneEmptyDir: true,
966
968
  description: "Note that Conveno turned on experimental mode, so uninstall turns it off again."
967
969
  });
968
970
  }
@@ -2412,9 +2414,13 @@ async function sessionName(ctx) {
2412
2414
  return null;
2413
2415
  }
2414
2416
  }
2415
- /** Only the plugin delivers, on 1.x and 2.x alike; it adds nothing to a prompt the user types. */
2417
+ /**
2418
+ * Only the plugin delivers, on 1.x and 2.4+ alike; it adds nothing to a prompt the user types.
2419
+ * 2.0 to 2.3 are not supported (`opencodeDoctorNotes`), so doctor claims no waking for them.
2420
+ */
2416
2421
  function delivery(detection) {
2417
- const supported = detection.version !== void 0 && parseVersion(detection.version) !== void 0;
2422
+ const v = detection.version === void 0 ? void 0 : parseVersion(detection.version);
2423
+ const supported = v !== void 0 && (!isV2OrLater(v) || atLeast(v, V2_SUPPORTED));
2418
2424
  return {
2419
2425
  nextTurn: false,
2420
2426
  endOfTurn: supported,
@@ -2481,7 +2487,11 @@ function createHookCtx() {
2481
2487
  launcherPaths
2482
2488
  },
2483
2489
  isAlive: isProcessAlive,
2484
- hookTimeoutMs: 2e3
2490
+ hookTimeoutMs: 2e3,
2491
+ ...process.env.CONVENO_HOOK_TIMING_LOG ? {
2492
+ timingLog: process.env.CONVENO_HOOK_TIMING_LOG,
2493
+ uptimeMs: () => process.uptime() * 1e3
2494
+ } : {}
2485
2495
  };
2486
2496
  }
2487
2497
  function runHookEntry(argv) {
@@ -0,0 +1 @@
1
+ export { i as runHookEntry } from "./hook-entry-BTJK7aO0.js";