@conveno/cli 0.2.0-rc.16 → 0.2.0-rc.17

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 { homedir, tmpdir } from "node:os";
1
+ import { homedir, tmpdir, userInfo } from "node:os";
2
2
  import { dirname, join, posix, win32 } from "node:path";
3
- import { execFile, spawn, spawnSync } from "node:child_process";
3
+ import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
4
4
  import { accessSync, appendFileSync, chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
5
- import { chmod, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
5
+ import { 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
@@ -5937,7 +5937,8 @@ const RelayState = _enum([
5937
5937
  "connecting",
5938
5938
  "connected",
5939
5939
  "disconnected",
5940
- "revoked"
5940
+ "revoked",
5941
+ "upgrade_required"
5941
5942
  ]);
5942
5943
  const DeviceName = string().min(1).max(64);
5943
5944
  const Fingerprint = string().min(1).max(64);
@@ -6218,6 +6219,8 @@ const Session = object({
6218
6219
  });
6219
6220
  /** Wire protocol identifier. Bumped only on breaking changes. */
6220
6221
  const PROTOCOL_VERSION = "conveno/1";
6222
+ /** What a device's daemon calls itself in a relay `hello` (`client.name`). */
6223
+ const RELAY_CLIENT_NAME = "conveno-cli";
6221
6224
  const ClientKind = _enum([
6222
6225
  "mcp",
6223
6226
  "cli",
@@ -6267,7 +6270,7 @@ const RegisterParams = object({
6267
6270
  spawned: boolean().default(false),
6268
6271
  /**
6269
6272
  * A `conveno acp-host` registers the session it drives over the Agent Client Protocol: the
6270
- * session's delivery tier is `acp`, and its host prompts it with waiting messages (section 6.8).
6273
+ * session's delivery tier is `acp`, and its host prompts it with waiting messages (section 5.8).
6271
6274
  */
6272
6275
  acp: boolean().default(false)
6273
6276
  });
@@ -6718,20 +6721,30 @@ const b64Bytes = (n) => {
6718
6721
  const RelayKey32 = b64Bytes(32);
6719
6722
  /** A 64-byte Ed25519 signature, base64. */
6720
6723
  const RelaySig = b64Bytes(64);
6724
+ /** Relay to device, first frame: a fresh nonce the device signs in `hello`. */
6725
+ const RelayChallenge = object({
6726
+ t: literal("challenge"),
6727
+ v,
6728
+ nonce: b64Bytes(32)
6729
+ });
6730
+ /** What sent a `hello`: the program and its version. Not signed; the relay only reads it. */
6731
+ const RelayClientInfo = object({
6732
+ name: string().min(1).max(64),
6733
+ version: string().min(1).max(64)
6734
+ });
6721
6735
  const RelayFrame = discriminatedUnion("t", [
6722
- object({
6723
- t: literal("challenge"),
6724
- v,
6725
- nonce: b64Bytes(32)
6726
- }),
6736
+ RelayChallenge,
6727
6737
  object({
6728
6738
  t: literal("hello"),
6729
6739
  v,
6730
6740
  deviceId: DeviceId,
6731
6741
  /** Ed25519 public key, base64. */
6732
6742
  signingKey: RelayKey32,
6733
- /** Ed25519 signature over the canonical hello bytes (PROTOCOL.md section 7.2). */
6734
- sig: RelaySig
6743
+ /** Ed25519 signature over the canonical hello bytes (PROTOCOL.md section 6.2). */
6744
+ sig: RelaySig,
6745
+ client: RelayClientInfo.optional(),
6746
+ /** Optional protocol features the device supports, for the relay to branch on later. */
6747
+ features: array(string().min(1).max(64)).max(32).optional()
6735
6748
  }),
6736
6749
  object({
6737
6750
  t: literal("ready"),
@@ -6780,7 +6793,9 @@ const RelayFrame = discriminatedUnion("t", [
6780
6793
  object({
6781
6794
  t: literal("error"),
6782
6795
  code: string().min(1).max(64),
6783
- message: string().max(1e3)
6796
+ message: string().max(1e3),
6797
+ /** With `upgrade_required`: the oldest client version the relay accepts. */
6798
+ minVersion: string().min(1).max(64).optional()
6784
6799
  })
6785
6800
  ]);
6786
6801
  /** A session as published to the owner's other devices. Process ids stay on their machine. */
@@ -6864,15 +6879,245 @@ function socketPathTooLongMessage(path, platform) {
6864
6879
  return `The Conveno socket path is too long for this system (${utf8ByteLength(path)} bytes, the limit is ${max}): ${path}. Set XDG_RUNTIME_DIR to a shorter directory and try again.`;
6865
6880
  }
6866
6881
  // ../core/dist/index.js
6882
+ const defaultIsFile = (path) => {
6883
+ try {
6884
+ return statSync(path).isFile();
6885
+ } catch {
6886
+ return false;
6887
+ }
6888
+ };
6889
+ /** Environment variable lookup that ignores case, as Windows does (`Path`, `PATH`, `PathExt`). */
6890
+ function envGet(env, name) {
6891
+ const want = name.toLowerCase();
6892
+ for (const [k, v] of Object.entries(env)) if (k.toLowerCase() === want && v !== void 0) return v;
6893
+ }
6894
+ const DEFAULT_PATHEXT = ".COM;.EXE;.BAT;.CMD";
6895
+ /** Only these can be started safely: other PATHEXT entries (.JS, .VBS) open Windows Script Host. */
6896
+ const LAUNCHABLE = /* @__PURE__ */ new Set([
6897
+ ".com",
6898
+ ".exe",
6899
+ ".bat",
6900
+ ".cmd"
6901
+ ]);
6867
6902
  /**
6868
- * Conveno account tokens on this machine, and how to get and renew them.
6869
- *
6870
- * The account server (packages/account-web, api.conveno.dev) signs a short-lived access token, a
6871
- * JWT, and the CLI keeps it with a long-lived refresh token in `<data dir>/account.json`
6872
- * (mode 0600). The relay's client reads the access token with {@link currentAccessToken}.
6873
- * The contract is in packages/account-web/README.md and packages/protocol/PROTOCOL.md.
6903
+ * Find `command` the way cmd.exe does: each PATH directory in order, each PATHEXT extension in
6904
+ * order. A name that already ends in a launchable extension is tried as written first. Returns
6905
+ * undefined when nothing matches.
6874
6906
  */
6875
- const ACCOUNT_API = "https://api.conveno.dev";
6907
+ function resolveWindowsCommand(command, env, isFile = defaultIsFile) {
6908
+ const exts = (envGet(env, "PATHEXT") ?? DEFAULT_PATHEXT).split(";").map((e) => e.trim()).filter((e) => LAUNCHABLE.has(e.toLowerCase()));
6909
+ const own = win32.extname(command).toLowerCase();
6910
+ const candidatesIn = (base) => [...LAUNCHABLE.has(own) ? [base] : [], ...exts.map((e) => base + e)];
6911
+ const dirs = /[\\/]/.test(command) || win32.isAbsolute(command) ? [""] : (envGet(env, "PATH") ?? "").split(";").map((d) => d.trim().replace(/^"(.*)"$/, "$1")).filter(Boolean);
6912
+ for (const dir of dirs) for (const candidate of candidatesIn(dir === "" ? command : win32.join(dir, command))) if (isFile(candidate)) return candidate;
6913
+ }
6914
+ /** Characters cmd.exe treats specially, plus the ones cross-spawn escapes defensively. */
6915
+ const CMD_META = /([()\][%!^"`<>&|;, *?])/g;
6916
+ /** The program name part of a cmd.exe command line: escape only, never wrap in quotes. */
6917
+ function escapeCmdCommand(command) {
6918
+ return command.replace(CMD_META, "^$1");
6919
+ }
6920
+ /**
6921
+ * Quote one argument for a `cmd.exe /d /s /c "..."` command line, the way cross-spawn does:
6922
+ * make it safe for the program's own parser (backslashes before a quote are doubled, the quote
6923
+ * is backslash-escaped, the whole thing is wrapped in quotes), then caret-escape every
6924
+ * character cmd.exe would act on, including the quotes themselves.
6925
+ */
6926
+ function escapeCmdArg(arg) {
6927
+ let a = `${arg}`;
6928
+ a = a.replace(/(\\*)"/g, "$1$1\\\"");
6929
+ a = a.replace(/(\\*)$/, "$1$1");
6930
+ a = `"${a}"`;
6931
+ return a.replace(CMD_META, "^$1");
6932
+ }
6933
+ /** `cmd.exe /d /s /c "<command line>"` for a .cmd or .bat file. */
6934
+ function cmdShimPlan(file, args, env) {
6935
+ const line = [escapeCmdCommand(file), ...args.map(escapeCmdArg)].join(" ");
6936
+ return {
6937
+ file: envGet(env, "ComSpec") || "cmd.exe",
6938
+ args: [
6939
+ "/d",
6940
+ "/s",
6941
+ "/c",
6942
+ `"${line}"`
6943
+ ],
6944
+ windowsVerbatimArguments: true
6945
+ };
6946
+ }
6947
+ /**
6948
+ * What to spawn for `command args...`. On Windows the command is resolved on PATH: .exe and .com
6949
+ * run directly, .cmd and .bat (npm shims) go through cmd.exe with one quoted command line. Never
6950
+ * uses a shell option with an args array. Elsewhere, and when nothing is found, the command is
6951
+ * returned unchanged so the caller sees the normal ENOENT.
6952
+ */
6953
+ function planSpawn(command, args, opts = {}) {
6954
+ if ((opts.platform ?? process.platform) !== "win32") return {
6955
+ file: command,
6956
+ args
6957
+ };
6958
+ const env = opts.env ?? process.env;
6959
+ const found = resolveWindowsCommand(command, env, opts.isFile);
6960
+ if (!found) return {
6961
+ file: command,
6962
+ args
6963
+ };
6964
+ const ext = win32.extname(found).toLowerCase();
6965
+ if (ext === ".cmd" || ext === ".bat") return cmdShimPlan(found, args, env);
6966
+ return {
6967
+ file: found,
6968
+ args
6969
+ };
6970
+ }
6971
+ /**
6972
+ * Files only the current user may read: account tokens, device keys, the daemon token. POSIX
6973
+ * gets mode 0600; Windows ignores the mode, so there the file gets a user-only ACL from icacls.
6974
+ */
6975
+ /**
6976
+ * The icacls command that leaves only the current user with access to `path`: inherited entries
6977
+ * removed (`/inheritance:r`), full control granted to the user, replacing any earlier grant
6978
+ * (`/grant:r`). For a directory, `inherit` makes the grant apply to files and folders created in
6979
+ * it (`(OI)(CI)`), so they are user-only from the moment they exist.
6980
+ * See https://learn.microsoft.com/windows-server/administration/windows-commands/icacls.
6981
+ * icacls is run from System32 by absolute path, never looked up on PATH.
6982
+ */
6983
+ function userOnlyAclPlan(path, env, user, isFile, inherit = false) {
6984
+ const systemRoot = env.SystemRoot ?? env.SYSTEMROOT ?? "C:\\Windows";
6985
+ const icacls = win32.join(systemRoot, "System32", "icacls.exe");
6986
+ const domain = env.USERDOMAIN;
6987
+ return planSpawn(icacls, [
6988
+ path,
6989
+ "/inheritance:r",
6990
+ "/grant:r",
6991
+ `${domain ? `${domain}\\${user}` : user}:${inherit ? "(OI)(CI)" : ""}F`
6992
+ ], {
6993
+ platform: "win32",
6994
+ env,
6995
+ ...isFile ? { isFile } : {}
6996
+ });
6997
+ }
6998
+ const runPlan = (plan) => {
6999
+ execFileSync(plan.file, plan.args, {
7000
+ stdio: "ignore",
7001
+ windowsHide: true,
7002
+ ...plan.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
7003
+ });
7004
+ };
7005
+ /**
7006
+ * Make a file readable by the current user only: mode 0600 on POSIX, a user-only ACL on Windows
7007
+ * (where the mode is ignored). A directory gets 0700, or an ACL its new entries inherit.
7008
+ */
7009
+ function restrictToUser(path, platform = process.platform, directory = false, run = runPlan, sid = currentUserSid) {
7010
+ if (platform !== "win32") {
7011
+ chmodSync(path, directory ? 448 : 384);
7012
+ return;
7013
+ }
7014
+ const id = sid();
7015
+ const env = {
7016
+ ...process.env,
7017
+ USERDOMAIN: void 0
7018
+ };
7019
+ const principals = id ? [`*${id}`, userInfo().username] : [userInfo().username];
7020
+ for (const principal of principals) try {
7021
+ run(userOnlyAclPlan(path, env, principal, void 0, directory));
7022
+ return;
7023
+ } catch {}
7024
+ }
7025
+ let sidCache = null;
7026
+ /** The current user's SID from `whoami /user`, or undefined. Read once per process. */
7027
+ function currentUserSid() {
7028
+ if (sidCache !== null) return sidCache;
7029
+ sidCache = void 0;
7030
+ try {
7031
+ const systemRoot = process.env.SystemRoot ?? process.env.SYSTEMROOT ?? "C:\\Windows";
7032
+ const out = execFileSync(win32.join(systemRoot, "System32", "whoami.exe"), [
7033
+ "/user",
7034
+ "/fo",
7035
+ "csv",
7036
+ "/nh"
7037
+ ], {
7038
+ encoding: "utf8",
7039
+ windowsHide: true,
7040
+ stdio: [
7041
+ "ignore",
7042
+ "pipe",
7043
+ "ignore"
7044
+ ]
7045
+ });
7046
+ sidCache = /"(S-1-[0-9-]+)"/.exec(out)?.[1];
7047
+ } catch {}
7048
+ return sidCache;
7049
+ }
7050
+ const tmpName = (path) => `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
7051
+ const busy = (e) => {
7052
+ const code = e.code;
7053
+ return code === "EPERM" || code === "EACCES" || code === "EBUSY";
7054
+ };
7055
+ /**
7056
+ * Write `body` to `path`, readable by this user only. The file is written next to its final
7057
+ * place, restricted, then renamed over it, so a reader never sees a half-written file or one with
7058
+ * looser permissions (a rename on one volume keeps the ACL). On Windows the temporary file is
7059
+ * restricted while still empty, before the secret is written into it.
7060
+ */
7061
+ async function writePrivateFile(path, body, o = {}) {
7062
+ const platform = o.platform ?? process.platform;
7063
+ const restrict = o.restrict ?? ((f) => restrictToUser(f, platform));
7064
+ await mkdir(dirname(path), { recursive: true });
7065
+ const tmp = tmpName(path);
7066
+ try {
7067
+ if (platform === "win32") {
7068
+ await writeFile(tmp, "", { flag: "wx" });
7069
+ restrict(tmp);
7070
+ await writeFile(tmp, body);
7071
+ } else {
7072
+ await writeFile(tmp, body, {
7073
+ mode: 384,
7074
+ flag: "wx"
7075
+ });
7076
+ restrict(tmp);
7077
+ }
7078
+ for (let attempt = 0;; attempt++) try {
7079
+ await rename(tmp, path);
7080
+ break;
7081
+ } catch (e) {
7082
+ if (platform !== "win32" || attempt >= 20 || !busy(e)) throw e;
7083
+ await new Promise((r) => setTimeout(r, Math.min(25 * (attempt + 1), 200)));
7084
+ }
7085
+ } catch (e) {
7086
+ await rm(tmp, { force: true });
7087
+ throw e;
7088
+ }
7089
+ }
7090
+ /** {@link writePrivateFile}, synchronously. */
7091
+ function writePrivateFileSync(path, body, o = {}) {
7092
+ const platform = o.platform ?? process.platform;
7093
+ const restrict = o.restrict ?? ((f) => restrictToUser(f, platform));
7094
+ mkdirSync(dirname(path), { recursive: true });
7095
+ const tmp = tmpName(path);
7096
+ try {
7097
+ if (platform === "win32") {
7098
+ writeFileSync(tmp, "", { flag: "wx" });
7099
+ restrict(tmp);
7100
+ writeFileSync(tmp, body);
7101
+ } else {
7102
+ writeFileSync(tmp, body, {
7103
+ mode: 384,
7104
+ flag: "wx"
7105
+ });
7106
+ restrict(tmp);
7107
+ }
7108
+ const wait = new Int32Array(new SharedArrayBuffer(4));
7109
+ for (let attempt = 0;; attempt++) try {
7110
+ renameSync(tmp, path);
7111
+ break;
7112
+ } catch (e) {
7113
+ if (platform !== "win32" || attempt >= 20 || !busy(e)) throw e;
7114
+ Atomics.wait(wait, 0, 0, Math.min(25 * (attempt + 1), 200));
7115
+ }
7116
+ } catch (e) {
7117
+ rmSync(tmp, { force: true });
7118
+ throw e;
7119
+ }
7120
+ }
6876
7121
  /** The `client_id` of the device authorization grant. The server accepts only this one. */
6877
7122
  const DEVICE_CLIENT_ID = "conveno-cli";
6878
7123
  /** Renew an access token this long before it expires, so a request never carries a dead one. */
@@ -6885,14 +7130,36 @@ var AccountError = class extends Error {
6885
7130
  this.name = "AccountError";
6886
7131
  }
6887
7132
  };
6888
- const base = (io) => (io.apiBase ?? "https://api.conveno.dev").replace(/\/+$/, "");
7133
+ const trimBase = (url) => url.replace(/\/+$/, "");
7134
+ const base = (io) => trimBase(io.apiBase ?? "https://api.conveno.dev");
7135
+ /** Where requests carrying these tokens go: the server that issued them, never another one. */
7136
+ const baseFor = (t, io) => t.apiBase ? trimBase(t.apiBase) : base(io);
6889
7137
  const doFetch = (io) => io.fetch ?? fetch;
6890
7138
  const clock = (io) => (io.now ?? Date.now)();
6891
7139
  function isTokens(v) {
6892
7140
  if (!v || typeof v !== "object") return false;
6893
7141
  const t = v;
6894
- return typeof t.accessToken === "string" && typeof t.refreshToken === "string" && t.refreshToken.length > 0 && typeof t.expiresAt === "number" && Number.isFinite(t.expiresAt);
7142
+ return typeof t.accessToken === "string" && typeof t.refreshToken === "string" && t.refreshToken.length > 0 && typeof t.expiresAt === "number" && Number.isFinite(t.expiresAt) && (t.apiBase === void 0 || typeof t.apiBase === "string" && t.apiBase.length > 0);
7143
+ }
7144
+ /**
7145
+ * The account server for a new login: `CONVENO_API_URL`, else {@link ACCOUNT_API}. Every other
7146
+ * request uses {@link signedInAccountApi}.
7147
+ */
7148
+ const loginAccountApi = (env = process.env) => trimBase(env.CONVENO_API_URL || "https://api.conveno.dev");
7149
+ /**
7150
+ * The account server of the saved login: the one saved in `account.json`, else
7151
+ * `CONVENO_API_URL`, else {@link ACCOUNT_API}. Also the server whose `/account` page the user
7152
+ * should visit.
7153
+ */
7154
+ function signedInAccountApi(path, env = process.env) {
7155
+ try {
7156
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
7157
+ if (isTokens(parsed) && parsed.apiBase) return trimBase(parsed.apiBase);
7158
+ } catch {}
7159
+ return loginAccountApi(env);
6895
7160
  }
7161
+ /** The relay the daemon connects to: `CONVENO_RELAY_URL`, else {@link RELAY_URL}. */
7162
+ const relayUrl = (env = process.env) => env.CONVENO_RELAY_URL || "wss://relay.conveno.dev/v1/connect";
6896
7163
  /** The saved tokens, or null when the user is not logged in or the file is unreadable. */
6897
7164
  async function readAccountTokens(path) {
6898
7165
  let text;
@@ -6908,27 +7175,14 @@ async function readAccountTokens(path) {
6908
7175
  return null;
6909
7176
  }
6910
7177
  }
6911
- /**
6912
- * Save the tokens, readable by this user only. The file is written next to its final place with
6913
- * the mode set at creation, then renamed over it, so a reader never sees a half-written file or
6914
- * one with looser permissions.
6915
- */
7178
+ /** Save the tokens, readable by this user only. See {@link writePrivateFile}. */
6916
7179
  async function writeAccountTokens(path, tokens) {
6917
- await mkdir(dirname(path), { recursive: true });
6918
- const tmp = `${path}.${process.pid}.tmp`;
6919
- const body = `${JSON.stringify({
7180
+ await writePrivateFile(path, `${JSON.stringify({
6920
7181
  accessToken: tokens.accessToken,
6921
7182
  refreshToken: tokens.refreshToken,
6922
- expiresAt: tokens.expiresAt
6923
- }, null, 2)}\n`;
6924
- try {
6925
- await writeFile(tmp, body, { mode: 384 });
6926
- await chmod(tmp, 384);
6927
- await rename(tmp, path);
6928
- } catch (e) {
6929
- await rm(tmp, { force: true });
6930
- throw e;
6931
- }
7183
+ expiresAt: tokens.expiresAt,
7184
+ ...tokens.apiBase ? { apiBase: tokens.apiBase } : {}
7185
+ }, null, 2)}\n`);
6932
7186
  }
6933
7187
  /** Delete the saved tokens. Returns whether there was a file. */
6934
7188
  async function clearAccountTokens(path) {
@@ -6982,8 +7236,12 @@ async function refreshAccountTokens(path, io = {}) {
6982
7236
  const current = await readAccountTokens(path);
6983
7237
  if (!current) throw new AccountError("not_logged_in", "Not logged in. Run conveno login.");
6984
7238
  const next = {
6985
- ...await requestAccessToken(current.refreshToken, io),
6986
- refreshToken: current.refreshToken
7239
+ ...await requestAccessToken(current.refreshToken, {
7240
+ ...io,
7241
+ apiBase: baseFor(current, io)
7242
+ }),
7243
+ refreshToken: current.refreshToken,
7244
+ ...current.apiBase ? { apiBase: current.apiBase } : {}
6987
7245
  };
6988
7246
  await writeAccountTokens(path, next);
6989
7247
  return next;
@@ -7014,7 +7272,7 @@ async function devicePost(path, route, deviceId, io) {
7014
7272
  const tokens = await readAccountTokens(path);
7015
7273
  if (!tokens) throw new AccountError("not_logged_in", "Not logged in. Run conveno login.");
7016
7274
  try {
7017
- return await doFetch(io)(`${base(io)}/api/device/${route}`, {
7275
+ return await doFetch(io)(`${baseFor(tokens, io)}/api/device/${route}`, {
7018
7276
  method: "POST",
7019
7277
  headers: {
7020
7278
  authorization: `Bearer ${tokens.refreshToken}`,
@@ -7121,11 +7379,15 @@ async function pollDeviceCode(code, o = {}) {
7121
7379
  }
7122
7380
  }
7123
7381
  }
7124
- /** After approval: keep the session token as the refresh token and get a first access token. */
7382
+ /**
7383
+ * After approval: keep the session token as the refresh token and get a first access token. The
7384
+ * account server is saved with them, so later requests go back to it.
7385
+ */
7125
7386
  async function completeLogin(path, sessionToken, io = {}) {
7126
7387
  const tokens = {
7127
7388
  ...await requestAccessToken(sessionToken, io),
7128
- refreshToken: sessionToken
7389
+ refreshToken: sessionToken,
7390
+ apiBase: base(io)
7129
7391
  };
7130
7392
  await writeAccountTokens(path, tokens);
7131
7393
  return tokens;
@@ -7137,18 +7399,21 @@ async function completeLogin(path, sessionToken, io = {}) {
7137
7399
  async function logoutAccount(path, io = {}) {
7138
7400
  const tokens = await readAccountTokens(path);
7139
7401
  let revoked = false;
7140
- if (tokens) try {
7141
- const res = await doFetch(io)(`${base(io)}/api/auth/sign-out`, {
7142
- ...json({}),
7143
- headers: {
7144
- "content-type": "application/json",
7145
- authorization: `Bearer ${tokens.refreshToken}`,
7146
- origin: base(io)
7147
- }
7148
- });
7149
- revoked = res.ok || res.status === 401;
7150
- } catch {
7151
- revoked = false;
7402
+ if (tokens) {
7403
+ const server = baseFor(tokens, io);
7404
+ try {
7405
+ const res = await doFetch(io)(`${server}/api/auth/sign-out`, {
7406
+ ...json({}),
7407
+ headers: {
7408
+ "content-type": "application/json",
7409
+ authorization: `Bearer ${tokens.refreshToken}`,
7410
+ origin: server
7411
+ }
7412
+ });
7413
+ revoked = res.ok || res.status === 401;
7414
+ } catch {
7415
+ revoked = false;
7416
+ }
7152
7417
  }
7153
7418
  const removed = await clearAccountTokens(path);
7154
7419
  return {
@@ -8618,95 +8883,6 @@ function pendingTurn(dir, folder) {
8618
8883
  }
8619
8884
  };
8620
8885
  }
8621
- const defaultIsFile = (path) => {
8622
- try {
8623
- return statSync(path).isFile();
8624
- } catch {
8625
- return false;
8626
- }
8627
- };
8628
- /** Environment variable lookup that ignores case, as Windows does (`Path`, `PATH`, `PathExt`). */
8629
- function envGet(env, name) {
8630
- const want = name.toLowerCase();
8631
- for (const [k, v] of Object.entries(env)) if (k.toLowerCase() === want && v !== void 0) return v;
8632
- }
8633
- const DEFAULT_PATHEXT = ".COM;.EXE;.BAT;.CMD";
8634
- /** Only these can be started safely: other PATHEXT entries (.JS, .VBS) open Windows Script Host. */
8635
- const LAUNCHABLE = /* @__PURE__ */ new Set([
8636
- ".com",
8637
- ".exe",
8638
- ".bat",
8639
- ".cmd"
8640
- ]);
8641
- /**
8642
- * Find `command` the way cmd.exe does: each PATH directory in order, each PATHEXT extension in
8643
- * order. A name that already ends in a launchable extension is tried as written first. Returns
8644
- * undefined when nothing matches.
8645
- */
8646
- function resolveWindowsCommand(command, env, isFile = defaultIsFile) {
8647
- const exts = (envGet(env, "PATHEXT") ?? DEFAULT_PATHEXT).split(";").map((e) => e.trim()).filter((e) => LAUNCHABLE.has(e.toLowerCase()));
8648
- const own = win32.extname(command).toLowerCase();
8649
- const candidatesIn = (base) => [...LAUNCHABLE.has(own) ? [base] : [], ...exts.map((e) => base + e)];
8650
- const dirs = /[\\/]/.test(command) || win32.isAbsolute(command) ? [""] : (envGet(env, "PATH") ?? "").split(";").map((d) => d.trim().replace(/^"(.*)"$/, "$1")).filter(Boolean);
8651
- for (const dir of dirs) for (const candidate of candidatesIn(dir === "" ? command : win32.join(dir, command))) if (isFile(candidate)) return candidate;
8652
- }
8653
- /** Characters cmd.exe treats specially, plus the ones cross-spawn escapes defensively. */
8654
- const CMD_META = /([()\][%!^"`<>&|;, *?])/g;
8655
- /** The program name part of a cmd.exe command line: escape only, never wrap in quotes. */
8656
- function escapeCmdCommand(command) {
8657
- return command.replace(CMD_META, "^$1");
8658
- }
8659
- /**
8660
- * Quote one argument for a `cmd.exe /d /s /c "..."` command line, the way cross-spawn does:
8661
- * make it safe for the program's own parser (backslashes before a quote are doubled, the quote
8662
- * is backslash-escaped, the whole thing is wrapped in quotes), then caret-escape every
8663
- * character cmd.exe would act on, including the quotes themselves.
8664
- */
8665
- function escapeCmdArg(arg) {
8666
- let a = `${arg}`;
8667
- a = a.replace(/(\\*)"/g, "$1$1\\\"");
8668
- a = a.replace(/(\\*)$/, "$1$1");
8669
- a = `"${a}"`;
8670
- return a.replace(CMD_META, "^$1");
8671
- }
8672
- /** `cmd.exe /d /s /c "<command line>"` for a .cmd or .bat file. */
8673
- function cmdShimPlan(file, args, env) {
8674
- const line = [escapeCmdCommand(file), ...args.map(escapeCmdArg)].join(" ");
8675
- return {
8676
- file: envGet(env, "ComSpec") || "cmd.exe",
8677
- args: [
8678
- "/d",
8679
- "/s",
8680
- "/c",
8681
- `"${line}"`
8682
- ],
8683
- windowsVerbatimArguments: true
8684
- };
8685
- }
8686
- /**
8687
- * What to spawn for `command args...`. On Windows the command is resolved on PATH: .exe and .com
8688
- * run directly, .cmd and .bat (npm shims) go through cmd.exe with one quoted command line. Never
8689
- * uses a shell option with an args array. Elsewhere, and when nothing is found, the command is
8690
- * returned unchanged so the caller sees the normal ENOENT.
8691
- */
8692
- function planSpawn(command, args, opts = {}) {
8693
- if ((opts.platform ?? process.platform) !== "win32") return {
8694
- file: command,
8695
- args
8696
- };
8697
- const env = opts.env ?? process.env;
8698
- const found = resolveWindowsCommand(command, env, opts.isFile);
8699
- if (!found) return {
8700
- file: command,
8701
- args
8702
- };
8703
- const ext = win32.extname(found).toLowerCase();
8704
- if (ext === ".cmd" || ext === ".bat") return cmdShimPlan(found, args, env);
8705
- return {
8706
- file: found,
8707
- args
8708
- };
8709
- }
8710
8886
  function exec(file, args, timeoutMs) {
8711
8887
  const plan = planSpawn(file, args);
8712
8888
  return new Promise((resolve) => {
@@ -10582,4 +10758,4 @@ async function waitForRegistration(deps, w) {
10582
10758
  await deps.sleep(250);
10583
10759
  }
10584
10760
  }
10585
- export { fetchAccountStatus as $, makeEventNotification as $n, realSpawnDeps as $t, bindAccountDevice as A, writeSettings as An, parseCliVersion as At, currentAccessToken as B, PROTOCOL_VERSION as Bn, planProgram as Bt, appendHookLog as C, validateRename as Cn, markDelivered as Ct, autoCandidates as D, workerAskTimeoutOf as Dn, newAuthNonce as Dt, attachAcpSession as E, workerAccessOf as En, needsQuoting as Et, clientProof as F, EVENT_NOTIFICATION_METHOD as Fn, pendingHookContext as Ft, defaultProcessIo as G, SESSION_NAME_PATTERN as Gn, readAccountTokens as Gt, dataDir as H, RpcErrorCode as Hn, pollDeviceCode as Ht, compareVersions as I, EventPayload as In, pendingTurn as It, editJson as J, defaultSocketPath as Jn, readInbox as Jt, detectRepo as K, SessionId as Kn, readAncestry as Kt, compatStatus as L, Message as Ln, pidAlive as Lt, claimSpawnRecord as M, CliKind as Mn, parsePs1ShimTarget as Mt, cleanModelName as N, DeviceId as Nn, parseWorkerAccess as Nt, autoLimitsFromEnv as O, workerUnansweredOf as On, oneWindowPerHost as Ot, clearOrchestrator as P, EVENT_NAMES as Pn, pendingForInjection as Pt, existedBefore as Q, makeError as Qn, readSpawnRecord as Qt, completeLogin as R, MessageId as Rn, pinnedAdapter as Rt, agentCommand as S, updateSpawnRecord as Sn, logoutAccount as St, askedMarker as T, waitForWorkBatch as Tn, modelLabel as Tt, dataPaths as U, RpcResponse as Un, proofsMatch as Ut, daemonProof as V, RelayPayload as Vn, planSpawn as Vt, decideAutoContinue as W, SESSION_ENDED_TEXT as Wn, putInList as Wt, endTurnContinuation as X, ipcMethods as Xn, readProcessList as Xt, effectiveHolder as Y, encodeFrame as Yn, readModelMenus as Yt, evaluateLiveness as Z, isSocketPathTooLong as Zn, readSettings as Zt, accessAllows as _, takeWithinBytes as _n, launcherPath as _t, FROM_USER_NOTICE as a, resolveRecipient as an, parseRelayFrame as ar, generateSessionName as at, adapterInstallCommand as b, turnHops as bn, leadLogPath as bt, NPX_SETUP_TIMEOUT_MS as c, runWaker as cn, socketPathTooLongMessage as cr, hookLogPath as ct, SPAWN_CLIS as d, spawnRecordOfSession as dn, boolean as dr, isAntigravityApp as dt, renderBody as en, makeResult as er, findModelOption as et, SPAWN_TABLE as f, spawnRecordPath as fn, discriminatedUnion as fr, isFromOwner as ft, WORKER_UNANSWERED as g, takeAcpLaunchFile as gn, string as gr, late as gt, WORKER_ASK_TIMEOUT_CHOICES as h, statusAfterLiveness as hn, object as hr, jwtClaim as ht, ConvenoError as i, resolveAcpProgram as in, parseIpcRequest as ir, formatInbox as it, claimOrchestrator as j, CLI_KINDS as jn, parseCmdShimTarget as jt, baseName as k, writeModelMenu as kn, ownSession as kt, ORCHESTRATOR_TASK_NOTICE as l, sameJson as ln, _enum as lr, hostAlive as lt, WORKER_ACCESS as m, startTurnContext as mn, number as mr, isOnline as mt, AccountError as n, requeueEntries as nn, newMessageId as nr, formatContinuation as nt, HEARTBEAT_INTERVAL_MS as o, resolveWindowsCommand as on, safeParse as or, holderAfterDeparture as ot, SpawnError as p, spawnSession as pn, literal as pr, isObject as pt, dropFromList as q, createLineDecoder as qn, readCommandLine as qt, CLAUDE_PENDING_TURN_FOLDER as r, requeueMessages as rn, newSessionId as rr, formatHookContext as rt, NOT_FROM_USER_NOTICE as s, runLaunchFile as sn, sanitizeLine as sr, hookLogLine as st, ACCOUNT_API as t, requestDeviceCode as tn, newDeviceId as tr, findOnPath as tt, RESPONSE_BUDGET_BYTES as u, senderOf as un, array as ur, hostPidOf as ut, ackEntries as v, takeWithinChars as vn, launcherText as vt, askedKey as w, waitForWork as wn, menuFromConfigOptions as wt, adapterNpxCommand as x, uninstallLauncher as xn, loadJson as xt, acpOverrideVar as y, tooManyUnreadMessage as yn, leadLogLine as yt, createWmiWalker as z, OWNER_SESSION_ID as zn, planLauncher as zt };
10761
+ export { findModelOption as $, defaultSocketPath as $n, realSpawnDeps as $t, claimOrchestrator as A, workerAskTimeoutOf as An, parseCliVersion as At, daemonProof as B, EventPayload as Bn, planProgram as Bt, askedKey as C, turnHops as Cn, markDelivered as Ct, autoLimitsFromEnv as D, waitForWork as Dn, newAuthNonce as Dt, autoCandidates as E, validateRename as En, needsQuoting as Et, compareVersions as F, CLI_KINDS as Fn, pendingHookContext as Ft, detectRepo as G, RELAY_CLIENT_NAME as Gn, readAccountTokens as Gt, dataPaths as H, MessageId as Hn, pollDeviceCode as Ht, compatStatus as I, CliKind as In, pendingTurn as It, effectiveHolder as J, RpcResponse as Jn, readInbox as Jt, dropFromList as K, RelayPayload as Kn, readAncestry as Kt, completeLogin as L, DeviceId as Ln, pidAlive as Lt, cleanModelName as M, writeModelMenu as Mn, parsePs1ShimTarget as Mt, clearOrchestrator as N, writePrivateFileSync as Nn, parseWorkerAccess as Nt, baseName as O, waitForWorkBatch as On, oneWindowPerHost as Ot, clientProof as P, writeSettings as Pn, pendingForInjection as Pt, fetchAccountStatus as Q, createLineDecoder as Qn, readSpawnRecord as Qt, createWmiWalker as R, EVENT_NAMES as Rn, pinnedAdapter as Rt, appendHookLog as S, tooManyUnreadMessage as Sn, logoutAccount as St, attachAcpSession as T, updateSpawnRecord as Tn, modelLabel as Tt, decideAutoContinue as U, OWNER_SESSION_ID as Un, proofsMatch as Ut, dataDir as V, Message as Vn, planSpawn as Vt, defaultProcessIo as W, PROTOCOL_VERSION as Wn, putInList as Wt, evaluateLiveness as X, SESSION_NAME_PATTERN as Xn, readProcessList as Xt, endTurnContinuation as Y, SESSION_ENDED_TEXT as Yn, readModelMenus as Yt, existedBefore as Z, SessionId as Zn, readSettings as Zt, ackEntries as _, startTurnContext as _n, discriminatedUnion as _r, launcherText as _t, HEARTBEAT_INTERVAL_MS as a, resolveAcpProgram as an, makeResult as ar, holderAfterDeparture as at, adapterNpxCommand as b, takeWithinBytes as bn, object as br, loadJson as bt, ORCHESTRATOR_TASK_NOTICE as c, restrictToUser as cn, newSessionId as cr, hostAlive as ct, SPAWN_TABLE as d, sameJson as dn, safeParse as dr, isFromOwner as dt, relayUrl as en, encodeFrame as er, findOnPath as et, SpawnError as f, senderOf as fn, sanitizeLine as fr, isObject as ft, accessAllows as g, spawnSession as gn, boolean as gr, launcherPath as gt, WORKER_UNANSWERED as h, spawnRecordPath as hn, array as hr, late as ht, FROM_USER_NOTICE as i, requeueMessages as in, makeEventNotification as ir, generateSessionName as it, claimSpawnRecord as j, workerUnansweredOf as jn, parseCmdShimTarget as jt, bindAccountDevice as k, workerAccessOf as kn, ownSession as kt, RESPONSE_BUDGET_BYTES as l, runLaunchFile as ln, parseIpcRequest as lr, hostPidOf as lt, WORKER_ASK_TIMEOUT_CHOICES as m, spawnRecordOfSession as mn, _enum as mr, jwtClaim as mt, CLAUDE_PENDING_TURN_FOLDER as n, requestDeviceCode as nn, isSocketPathTooLong as nr, formatHookContext as nt, NOT_FROM_USER_NOTICE as o, resolveRecipient as on, newDeviceId as or, hookLogLine as ot, WORKER_ACCESS as p, signedInAccountApi as pn, socketPathTooLongMessage as pr, isOnline as pt, editJson as q, RpcErrorCode as qn, readCommandLine as qt, ConvenoError as r, requeueEntries as rn, makeError as rr, formatInbox as rt, NPX_SETUP_TIMEOUT_MS as s, resolveWindowsCommand as sn, newMessageId as sr, hookLogPath as st, AccountError as t, renderBody as tn, ipcMethods as tr, formatContinuation as tt, SPAWN_CLIS as u, runWaker as un, parseRelayFrame as ur, isAntigravityApp as ut, acpOverrideVar as v, statusAfterLiveness as vn, literal as vr, leadLogLine as vt, askedMarker as w, uninstallLauncher as wn, menuFromConfigOptions as wt, agentCommand as x, takeWithinChars as xn, string as xr, loginAccountApi as xt, adapterInstallCommand as y, takeAcpLaunchFile as yn, number as yr, leadLogPath as yt, currentAccessToken as z, EVENT_NOTIFICATION_METHOD as zn, planLauncher as zt };
@@ -1,11 +1,12 @@
1
- import { n as connect } from "./dist-Ch3ohbIk.js";
2
- import { Bt as planProgram, Hn as RpcErrorCode, Kn as SessionId, Mn as CliKind, Sn as updateSpawnRecord, Tt as modelLabel, _ as accessAllows, c as NPX_SETUP_TIMEOUT_MS, et as findModelOption, f as SPAWN_TABLE, gn as takeAcpLaunchFile, i as ConvenoError, in as resolveAcpProgram, kn as writeModelMenu, nt as formatContinuation, tt as findOnPath, wt as menuFromConfigOptions } from "./dist-DnWOZkAu.js";
1
+ import { n as connect } from "./dist-BgAfkqeX.js";
2
+ import { $ as findModelOption, Bt as planProgram, In as CliKind, Mn as writeModelMenu, Tn as updateSpawnRecord, Tt as modelLabel, Zn as SessionId, an as resolveAcpProgram, d as SPAWN_TABLE, et as findOnPath, g as accessAllows, qn as RpcErrorCode, r as ConvenoError, s as NPX_SETUP_TIMEOUT_MS, tt as formatContinuation, wt as menuFromConfigOptions, yn as takeAcpLaunchFile } from "./dist-Dc50_P_f.js";
3
3
  import { randomBytes } from "node:crypto";
4
4
  import { existsSync, rmSync } from "node:fs";
5
5
  import { Readable, Writable } from "node:stream";
6
6
  import { PROTOCOL_VERSION, client, methods, ndJsonStream } from "@agentclientprotocol/sdk";
7
7
  import { spawn, spawnSync } from "node:child_process";
8
8
  // ../acp/dist/index.js
9
+ var version = "0.2.0-rc.17";
9
10
  /**
10
11
  * Pick the option to answer with. Allowing uses `allow_once` only: `allow_always` would change the
11
12
  * CLI's own saved permissions, which is the user's call. Denying uses `reject_once`, and when the
@@ -205,7 +206,11 @@ var ToolTracker = class {
205
206
  return u.sessionUpdate === "tool_call" ? next.title ?? next.kind ?? "tool" : void 0;
206
207
  }
207
208
  };
208
- const HOST_VERSION = "0.2.0-rc.16";
209
+ const HOST_VERSION = version;
210
+ /** How long the agent gets to answer `initialize` and `session/new`. */
211
+ const SETUP_TIMEOUT_MS = 12e4;
212
+ /** How often the host looks for a stop request from `conveno stop`. */
213
+ const STOP_POLL_MS = 500;
209
214
  /** A stop request file: `conveno stop` writes it next to the spawn record. */
210
215
  const stopRequestPath = (recordPath) => recordPath.replace(/\.json$/, ".stop");
211
216
  function withTimeout$1(p, ms, what) {
@@ -328,7 +333,7 @@ var AcpHost = class {
328
333
  }
329
334
  async setup() {
330
335
  const { spec } = this;
331
- const timeout = spec.setupTimeoutMs ?? this.deps.setupTimeoutMs ?? 12e4;
336
+ const timeout = spec.setupTimeoutMs ?? this.deps.setupTimeoutMs ?? SETUP_TIMEOUT_MS;
332
337
  this.agent = await this.deps.startAgent(spec);
333
338
  const agent = this.agent;
334
339
  this.log(`started ${spec.file} (pid ${agent.pid}) for ${spec.name}`);
@@ -343,7 +348,7 @@ var AcpHost = class {
343
348
  pid: process.pid,
344
349
  agentPid: agent.pid
345
350
  });
346
- this.every(this.deps.stopPollMs ?? 500, () => {
351
+ this.every(this.deps.stopPollMs ?? STOP_POLL_MS, () => {
347
352
  const path = stopRequestPath(spec.record);
348
353
  if (existsSync(path)) {
349
354
  rmSync(path, { force: true });
@@ -1,5 +1,5 @@
1
1
  import { appendFileSync } from "node:fs";
2
- import { C as appendHookLog, st as hookLogLine } from "./dist-DnWOZkAu.js";
2
+ import { S as appendHookLog, ot as hookLogLine } from "./dist-Dc50_P_f.js";
3
3
  import { n as connectOpts } from "./ctx-tYftvhz_.js";
4
4
  // src/hook.ts
5
5
  /**
@@ -140,7 +140,7 @@ async function runHook(ctx, argv) {
140
140
  hostPid ??= (async () => {
141
141
  const t = Date.now();
142
142
  try {
143
- const pid = await findHostPid(ctx, connected, adapter.cli, () => early ?? ctx.ancestry(1200));
143
+ const pid = await findHostPid(ctx, connected, adapter.cli, () => early ?? ctx.ancestry(HOOK_ANCESTRY_TIMEOUT_MS));
144
144
  if (pid === void 0) hostMissing = true;
145
145
  return pid;
146
146
  } finally {
@@ -0,0 +1 @@
1
+ export { i as runHookEntry } from "./hook-entry-DYXjVztc.js";