@conveno/cli 0.2.0-rc.8 → 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. */
@@ -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();
@@ -9954,4 +10081,4 @@ async function waitForRegistration(deps, w) {
9954
10081
  await deps.sleep(250);
9955
10082
  }
9956
10083
  }
9957
- export { jwtClaim as $, EVENT_NAMES as $t, daemonProof as A, discriminatedUnion as An, resolveRecipient as At, evaluateLiveness as B, takeAcpLaunchFile as Bt, claimSpawnRecord as C, parseRelayFrame as Cn, realSpawnDeps as Ct, completeLogin as D, _enum as Dn, requeueMessages as Dt, compatStatus as E, socketPathTooLongMessage 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, number as Mn, runLaunchFile as Mt, decideAutoContinue as N, object as Nn, runWaker as Nt, createWmiWalker as O, array as On, requeueOwnMessages as Ot, defaultProcessIo as P, string as Pn, sameJson as Pt, isOnline as Q, DeviceId as Qt, effectiveHolder as R, startTurnContext as Rt, claimOrchestrator as S, parseIpcRequest as Sn, readSpawnRecord as St, clientProof as T, sanitizeLine 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 _, makeEventNotification as _n, readAccountTokens as _t, FROM_USER_NOTICE as a, PROTOCOL_VERSION as an, parseAllowPatterns as at, baseName as b, newMessageId as bn, readInbox as bt, ORCHESTRATOR_TASK_NOTICE as c, RpcResponse as cn, parsePs1ShimTarget as ct, SPAWN_TABLE as d, createLineDecoder as dn, pinnedAdapter as dt, EVENT_NOTIFICATION_METHOD as en, loadJson as et, SpawnError as f, defaultSocketPath as fn, planProgram as ft, adapterNpxCommand as g, makeError as gn, putInList as gt, adapterInstallCommand as h, isSocketPathTooLong as hn, proofsMatch as ht, DEFAULT_ALLOW_RULES as i, OWNER_SESSION_ID as in, ownSession as it, dataDir as j, literal as jn, resolveWindowsCommand as jt, currentAccessToken as k, boolean as kn, resolveAcpProgram as kt, RESPONSE_BUDGET_BYTES as l, SESSION_NAME_PATTERN as ln, pendingForInjection as lt, acpOverrideVar as m, ipcMethods 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, encodeFrame 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, SessionId as un, pendingHookContext as ut, autoCandidates as v, makeResult as vn, readAncestry as vt, clearOrchestrator as w, safeParse as wn, renderBody as wt, bindAccountDevice as x, newSessionId as xn, readSettings as xt, autoLimitsFromEnv as y, newDeviceId 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,16 +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
- /** After a timeout, the hook gets this many more timeouts' worth of time to finish recording. */
44
- const FINISH_GRACE_FACTOR = 2;
45
- /** How long before the hook's timeout its messages count as too late to print. */
46
- const DEADLINE_MARGIN_MS = 300;
47
56
  async function runHook(ctx, argv) {
48
57
  const [cli, event] = argv;
49
58
  const adapter = ctx.adapters.find((a) => a.cli === cli);
50
59
  if (!adapter || !event) return 0;
51
60
  const listener = adapter.listenEvents?.includes(event) === true;
52
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;
53
64
  let client;
54
65
  let timer;
55
66
  const early = ctx.hostLookup ? void 0 : ctx.ancestry(HOOK_ANCESTRY_TIMEOUT_MS);
@@ -75,7 +86,10 @@ async function runHook(ctx, argv) {
75
86
  });
76
87
  })();
77
88
  const timeout = listener ? new Promise(() => void 0) : new Promise((resolve) => {
78
- timer = setTimeout(() => resolve(NOTHING), ctx.hookTimeoutMs);
89
+ timer = setTimeout(() => {
90
+ timedOut = true;
91
+ resolve(NOTHING);
92
+ }, ctx.hookTimeoutMs);
79
93
  });
80
94
  let code = 0;
81
95
  try {
@@ -85,6 +99,12 @@ async function runHook(ctx, argv) {
85
99
  if (listener && out.stderr) ctx.err(out.stderr.endsWith("\n") ? out.stderr : `${out.stderr}\n`);
86
100
  if (listener) code = out.exitCode;
87
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
+ }
88
108
  if (timer) clearTimeout(timer);
89
109
  work.catch(() => void 0);
90
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-B6Sm0MRT.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-BBdba94T.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-B1EVHdIM.js";
8
- import { t as grokAdapter } from "./dist-CcoTmwrf.js";
9
- import { n as connect } from "./dist-WTkKRM39.js";
10
- import { t as runHook } from "./hook-DxjJDCjz.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
  }
@@ -2485,7 +2487,11 @@ function createHookCtx() {
2485
2487
  launcherPaths
2486
2488
  },
2487
2489
  isAlive: isProcessAlive,
2488
- 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
+ } : {}
2489
2495
  };
2490
2496
  }
2491
2497
  function runHookEntry(argv) {
@@ -0,0 +1 @@
1
+ export { i as runHookEntry } from "./hook-entry-BTJK7aO0.js";
@@ -1,16 +1,16 @@
1
- import { Ct as realSpawnDeps, Lt as spawnSession, M as dataPaths, Mt as runLaunchFile, Xt as CLI_KINDS, d as SPAWN_TABLE, f as SpawnError, u as SPAWN_CLIS } from "./dist-BBdba94T.js";
2
- import { b as runLogin, c as runInit, g as runDaemon, h as runRelay, i as runDoctor, l as runSetup, m as runDevices, t as runUninstall, x as runLogout, y as runAccount } from "./uninstall-D9rW_j7H.js";
3
- import { a as parseFlags, i as commandHelp, n as COMMANDS, r as COMMAND_NAMES, t as ALL_COMMAND_NAMES } from "./args-CGL-AmNd.js";
4
- import { t as daemonProblem } from "./daemonError-DJ-P55nH.js";
1
+ import { Bt as runLaunchFile, F as dataPaths, Gt as spawnSession, an as CLI_KINDS, d as SPAWN_TABLE, f as SpawnError, jt as realSpawnDeps, u as SPAWN_CLIS } from "./dist-STNJjbNH.js";
2
+ import { E as runLogout, T as runLogin, b as runRelay, i as runDoctor, m as runSetup, p as runInit, t as runUninstall, w as runAccount, x as runDaemon, y as runDevices } from "./uninstall-8AHErPRN.js";
3
+ import { a as parseFlags, i as commandHelp, n as COMMANDS, r as COMMAND_NAMES, t as ALL_COMMAND_NAMES } from "./args-B3Cj2Ie4.js";
4
+ import { t as daemonProblem } from "./daemonError-C05GqdhQ.js";
5
5
  import { chmod, mkdir, writeFile } from "node:fs/promises";
6
6
  import { join, resolve } from "node:path";
7
7
  import { a as fail, c as plural, d as warnBlock, n as cmd, r as columns, s as plainError, t as closest, u as tilde } from "./fmt-C2SsP5Y0.js";
8
- import { t as runHook } from "./hook-DxjJDCjz.js";
8
+ import { t as runHook } from "./hook-CDF1A8AY.js";
9
9
  import { n as connectOpts, t as adapterEnv } from "./ctx-tYftvhz_.js";
10
- import { t as findSession } from "./pick-Bi1yJDh6.js";
10
+ import { t as findSession } from "./pick-DLp6w_-z.js";
11
11
  import { readFileSync } from "node:fs";
12
12
  // src/version.ts
13
- const VERSION = "0.2.0-rc.8";
13
+ const VERSION = "0.2.0-rc.9";
14
14
  // src/errorLog.ts
15
15
  /** The message of an unexpected error, as it is. Not the softened text `plainError` gives. */
16
16
  function rawMessage(e) {
@@ -572,11 +572,11 @@ async function dispatch(name, rest, ctx) {
572
572
  case "rename": return runRename(ctx, rest);
573
573
  case "lead": return runLead(ctx, rest);
574
574
  case "spawn": return runSpawn(ctx, rest);
575
- case "acp-host": return (await import("./acp-YHhVx0Ya.js")).runAcpHostCmd(ctx, rest);
576
- case "stop": return (await import("./acp-YHhVx0Ya.js")).runStop(ctx, rest);
575
+ case "acp-host": return (await import("./acp-BVk6rmXR.js")).runAcpHostCmd(ctx, rest);
576
+ case "stop": return (await import("./acp-BVk6rmXR.js")).runStop(ctx, rest);
577
577
  case "spawn-run": return runSpawnRun(ctx, rest);
578
- case "agy-relay": return (await import("./agy-relay-BS2NeFlh.js")).runAgyRelay(ctx, rest);
579
- case "watch": return (await import("./watch-BrTWYf3Y.js")).runWatch(ctx, rest);
578
+ case "agy-relay": return (await import("./agy-relay-D8eZcLuc.js")).runAgyRelay(ctx, rest);
579
+ case "watch": return (await import("./watch-D0KIPowJ.js")).runWatch(ctx, rest);
580
580
  case "devices": return runDevices(ctx, rest);
581
581
  case "relay": return runRelay(ctx, rest);
582
582
  case "doctor": return runDoctor(ctx, rest);
@@ -615,7 +615,7 @@ function opensApp(env, tty = {
615
615
  async function main(argv, ctx) {
616
616
  const [command, ...rest] = argv;
617
617
  if (command === void 0 && opensApp(ctx.env)) try {
618
- return await (await import("./run-C32oP2c_.js")).runTui(ctx);
618
+ return await (await import("./run-BPtFUGtu.js")).runTui(ctx);
619
619
  } catch (e) {
620
620
  ctx.err(`The app could not start (${rawMessage(e)}). Showing the help instead.\n`);
621
621
  ctx.out(helpText(ctx));
@@ -1,4 +1,4 @@
1
- import { un as SessionId } from "./dist-BBdba94T.js";
1
+ import { yn as SessionId } from "./dist-STNJjbNH.js";
2
2
  // src/pick.ts
3
3
  /** The online session a name or id means, or undefined when nothing matches. */
4
4
  async function findSession(client, text) {
@@ -1,10 +1,10 @@
1
1
  import { Box, Text, render, useApp, useInput, useStdin, useStdout } from "ink";
2
2
  import { n as connectOpts, t as adapterEnv } from "./ctx-tYftvhz_.js";
3
- import { t as daemonProblem } from "./daemonError-DJ-P55nH.js";
3
+ import { t as daemonProblem } from "./daemonError-C05GqdhQ.js";
4
4
  import { a as fail, n as cmd, s as plainError, u as tilde } from "./fmt-C2SsP5Y0.js";
5
5
  import { createContext, useContext, useEffect, useImperativeHandle, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
6
- import { Ct as realSpawnDeps, D as completeLogin, E as compatStatus, H as fetchAccountStatus, It as spawnRecordPath, Lt as spawnSession, M as dataPaths, St as readSpawnRecord, Tt as requestDeviceCode, U as findOnPath, Yt as writeSettings, _t as readAccountTokens, ln as SESSION_NAME_PATTERN, mt as pollDeviceCode, n as AccountError, pt as planSpawn, tt as logoutAccount, xt as readSettings } from "./dist-BBdba94T.js";
7
- import { S as showCode$1, _ as stopDaemonIfRunning, a as collectPlans, d as applyChanges, f as unifiedDiff, n as inspect, o as detectAll, p as PAIR_TIMEOUT_MS, r as partState, s as pendingOptions, t as runUninstall, u as StaleError, v as openInBrowser } from "./uninstall-D9rW_j7H.js";
6
+ import { A as completeLogin, At as readSpawnRecord, F as dataPaths, G as fetchAccountStatus, Gt as spawnSession, K as findOnPath, Nt as requestDeviceCode, St as pollDeviceCode, Tt as readAccountTokens, Wt as spawnRecordPath, in as writeSettings, jt as realSpawnDeps, k as compatStatus, kt as readSettings, n as AccountError, st as logoutAccount, vn as SESSION_NAME_PATTERN, xt as planSpawn } from "./dist-STNJjbNH.js";
7
+ import { C as openInBrowser, D as showCode$1, S as stopDaemonIfRunning, _ as unifiedDiff, a as applyOptions, c as collectPlans, d as refreshManifest, f as renewedApprovals, g as applyChanges, h as StaleError, l as detectAll, n as inspect, o as approvalWrites, r as partState, s as approvedBySetup, t as runUninstall, u as pendingOptions, v as PAIR_TIMEOUT_MS } from "./uninstall-8AHErPRN.js";
8
8
  import { i as tokens, n as detectColorLevel, r as detectUnicode } from "./dist-BRjg9CLd.js";
9
9
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
10
10
  import { readFileSync, statSync, writeFileSync } from "node:fs";
@@ -12,7 +12,7 @@ import { Readable } from "node:stream";
12
12
  import { basename, posix, win32 } from "node:path";
13
13
  import { spawn } from "node:child_process";
14
14
  import { homedir } from "node:os";
15
- import { r as stopRequestPath, t as killProcessTree } from "./dist-BlWWt5gx.js";
15
+ import { r as stopRequestPath, t as killProcessTree } from "./dist-DzpERiRx.js";
16
16
  // src/tui/home/deps.ts
17
17
  /**
18
18
  * What home does outside the store: sign in and out, and take Conveno away. Real in the app, fake
@@ -3703,7 +3703,11 @@ async function planFix(ctx, fixId) {
3703
3703
  const { items, error } = await planFor(ctx, fixId);
3704
3704
  const parsed = parseFixId(fixId);
3705
3705
  const adapter = parsed && ctx.adapters.find((x) => x.cli === parsed.cli);
3706
- const options = parsed?.kind === "init" && adapter ? await pendingOptions(ctx, [adapter]) : [];
3706
+ const options = parsed?.kind === "init" && adapter ? (await pendingOptions(ctx, [adapter])).map(({ cli, id, question }) => ({
3707
+ cli,
3708
+ id,
3709
+ question
3710
+ })) : [];
3707
3711
  return {
3708
3712
  files: items.map(({ change }) => {
3709
3713
  const lines = unifiedDiff(change.before, change.after);
@@ -3726,13 +3730,31 @@ async function planFix(ctx, fixId) {
3726
3730
  async function applyFix(ctx, fixId) {
3727
3731
  const { items, error } = await planFor(ctx, fixId);
3728
3732
  if (error) throw new Error(error);
3729
- if (items.length === 0) return;
3730
- try {
3731
- await applyChanges(ctx, items, parseFixId(fixId)?.kind === "uninstall" ? { markRestored: true } : {});
3733
+ const parsed = parseFixId(fixId);
3734
+ const adapter = parsed && ctx.adapters.find((x) => x.cli === parsed.cli);
3735
+ const init = parsed?.kind === "init" && adapter ? adapter : void 0;
3736
+ const ids = new Set(init ? parsed?.accept ?? [] : []);
3737
+ if (init) for (const id of await renewedApprovals(ctx, [init], items)) ids.add(id);
3738
+ let backupDir;
3739
+ if (items.length > 0) try {
3740
+ const writes = init ? await approvalWrites(ctx, [init], ids, items) : { backups: [] };
3741
+ backupDir = (await applyChanges(ctx, [...items, ...writes.backups], parsed?.kind === "uninstall" ? { markRestored: true } : {})).backupDir;
3732
3742
  } catch (e) {
3733
3743
  if (e instanceof StaleError) throw new Error("A settings file changed while we waited. Press g, then try again.");
3734
3744
  throw new Error(plainError(e));
3735
3745
  }
3746
+ if (!init) return { problems: [] };
3747
+ const { done, problems } = await applyOptions(ctx, [init], ids);
3748
+ if (backupDir && done.length > 0) {
3749
+ const env = adapterEnv(ctx);
3750
+ const paths = (init.optional ?? []).flatMap((o) => done.some((d) => d.id === o.id) && o.applyWrites ? o.applyWrites(env).paths : []);
3751
+ await refreshManifest(backupDir, paths);
3752
+ }
3753
+ const approved = await approvedBySetup(ctx, init);
3754
+ return {
3755
+ ...approved === void 0 ? {} : { approved },
3756
+ problems
3757
+ };
3736
3758
  }
3737
3759
  async function getExtras(ctx) {
3738
3760
  return { helpers: readSettings(dataPaths(ctx.platform, ctx.dataDir).settings).acpAdapterNpx === true };
@@ -3773,13 +3795,20 @@ const SHORT_NAMES = {
3773
3795
  cursor: "cursor"
3774
3796
  };
3775
3797
  const toolName = (cli, fallback) => TOOL_NAMES[cli] ?? fallback ?? cli;
3776
- /** Friendly wording for optional setups, by the adapter's option id. Unknown ids use the adapter's text. */
3777
- const FRIENDLY_OPTIONS = { "copilot-idle-wake": "Let Conveno wake Copilot when it's idle? This turns on Copilot's experimental features." };
3778
- const friendlyQuestion = (id, adapterText) => FRIENDLY_OPTIONS[id] ?? adapterText;
3779
3798
  const WELCOME_LINES = ["Your AI coding tools, working as one team.", "One leads, the others pick up the work, even when idle."];
3780
3799
  const installQuestion = (name) => `${name} isn't installed. Install it now? It takes about a minute.`;
3781
3800
  const updateQuestion = (name, major) => major ? `${name} needs version 2 to work with Conveno. This replaces your current version. Update?` : `${name} needs an update to work with Conveno. Update now?`;
3782
3801
  const SAMPLE_TASK = "write tests for the login page";
3802
+ /**
3803
+ * What each tool asks the first time it runs with Conveno, with the exact label to pick. The
3804
+ * labels are the tools' own: Codex's startup hook review (codex-rs tui startup_hooks_review.rs),
3805
+ * Copilot's extension prompt (asked once per folder) and Antigravity's command approval.
3806
+ */
3807
+ const FIRST_RUN_APPROVALS = {
3808
+ codex: "Codex: when it says \"Hooks need review\", choose \"Review hooks\" and trust only the ones that run `conveno hook codex`.",
3809
+ copilot: "Copilot: when it asks to launch \"user:conveno\", choose \"Yes, and always allow\". It asks once per folder.",
3810
+ antigravity: "Antigravity: when it asks to run Conveno's helper, choose the \"always allow\" option that saves to settings."
3811
+ };
3783
3812
  // src/tui/onboarding/deps.ts
3784
3813
  const KNOWN = new Set(TOOL_ORDER);
3785
3814
  /** True when no adapter reports Conveno's setup in place: `conveno` then opens the onboarding. */
@@ -3802,10 +3831,12 @@ async function detectTools(ctx) {
3802
3831
  const up = known ? updatePlan(cli, detection.version) : { available: false };
3803
3832
  const options = [];
3804
3833
  for (const o of adapter.optional ?? []) {
3834
+ if (o.available && !await o.available(env).catch(() => false)) continue;
3805
3835
  if (await o.enabled(env).catch(() => true)) continue;
3806
3836
  options.push({
3807
3837
  id: o.id,
3808
- question: o.question
3838
+ question: o.question,
3839
+ ...o.defaultYes ? { defaultYes: true } : {}
3809
3840
  });
3810
3841
  }
3811
3842
  let connected = false;
@@ -3874,10 +3905,12 @@ async function changeTool(ctx, cli, fixId, failed, io) {
3874
3905
  for (const f of files) io.line(f);
3875
3906
  if (files.length > 0) io.line(`Backups go to ${tilde(dataPaths(ctx.platform, ctx.dataDir).backups, ctx.home)}/<timestamp>/`);
3876
3907
  try {
3877
- await applyFix(ctx, fixId);
3908
+ const done = await applyFix(ctx, fixId);
3909
+ for (const p of done.problems) io.line(p);
3878
3910
  return {
3879
3911
  ok: true,
3880
- ...files.length === 0 ? { note: "already connected" } : {}
3912
+ ...files.length === 0 ? { note: "already connected" } : {},
3913
+ ...done.approved === void 0 ? {} : { approved: done.approved }
3881
3914
  };
3882
3915
  } catch (e) {
3883
3916
  const msg = plainError(e);
@@ -4029,8 +4062,8 @@ function buildQuestions(s) {
4029
4062
  kind: "option",
4030
4063
  optionId: o.id,
4031
4064
  title: `One more thing about ${t.name}`,
4032
- text: friendlyQuestion(o.id, o.question),
4033
- defaultYes: false
4065
+ text: o.question,
4066
+ defaultYes: o.defaultYes === true
4034
4067
  });
4035
4068
  return out;
4036
4069
  }
@@ -4274,6 +4307,7 @@ function reduce(s, a) {
4274
4307
  const { reason: _r, ...rest } = withLog;
4275
4308
  return {
4276
4309
  ...rest,
4310
+ ...a.result.approved === void 0 ? {} : { approved: a.result.approved },
4277
4311
  state: "done",
4278
4312
  note: a.result.note ?? (r.kind === "remove" ? "removed" : r.installedNow ? "installed and connected" : "connected")
4279
4313
  };
@@ -4736,9 +4770,26 @@ function tryLine(s) {
4736
4770
  if (other) return `Open ${name} as usual and try: "ask ${SHORT_NAMES[other.cli]} to ${SAMPLE_TASK}"`;
4737
4771
  return s.signedIn ? `Open ${name} as usual. It can now reach your other computers.` : `Open ${name} as usual. Add more tools any time with conveno setup.`;
4738
4772
  }
4773
+ /**
4774
+ * The one-time approvals the connected tools will ask for. Copilot's extension prompt only comes
4775
+ * when its idle wake is on: accepted now, or already on (then it is not among the open options).
4776
+ */
4777
+ function firstRunApprovals(s) {
4778
+ return connectedRows(s).flatMap((r) => {
4779
+ const note = FIRST_RUN_APPROVALS[r.cli];
4780
+ if (!note || r.approved === true) return [];
4781
+ if (r.cli === "copilot") {
4782
+ const pending = (s.tools?.find((t) => t.cli === "copilot"))?.options.some((o) => o.id === "copilot-idle-wake") ?? false;
4783
+ const accepted = s.answers["option:copilot:copilot-idle-wake"] === true;
4784
+ if (pending && !accepted) return [];
4785
+ }
4786
+ return [note];
4787
+ });
4788
+ }
4739
4789
  function FinishStep({ s }) {
4740
4790
  const open = connectedRows(s).filter((r) => s.runningTools.includes(r.cli));
4741
4791
  const any = connectedRows(s).length > 0;
4792
+ const approvals = firstRunApprovals(s);
4742
4793
  return /* @__PURE__ */ jsxs(Frame, {
4743
4794
  keys: [{
4744
4795
  k: "enter",
@@ -4761,6 +4812,14 @@ function FinishStep({ s }) {
4761
4812
  tone: "warn",
4762
4813
  children: `${r.name} is open. Restart it to pick up Conveno.`
4763
4814
  }, r.cli)),
4815
+ approvals.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
4816
+ /* @__PURE__ */ jsx(Gap, {}),
4817
+ /* @__PURE__ */ jsx(Text, {
4818
+ bold: true,
4819
+ children: "The first time you open them:"
4820
+ }),
4821
+ approvals.map((a) => /* @__PURE__ */ jsx(Body, { children: a }, a))
4822
+ ] }) : null,
4764
4823
  /* @__PURE__ */ jsx(Gap, {}),
4765
4824
  /* @__PURE__ */ jsx(Quiet, { children: "Run conveno any time to see your team." })
4766
4825
  ]