agentapprove 0.2.0 → 0.2.1

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.
Files changed (2) hide show
  1. package/dist/cli.js +1208 -566
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1842,6 +1842,484 @@ function upsertCursorHook(existing, entry) {
1842
1842
  return entries;
1843
1843
  }
1844
1844
 
1845
+ // src/json-config.ts
1846
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
1847
+ import { dirname } from "path";
1848
+ var UTF8_BOM = "\uFEFF";
1849
+ var UTF8_BOM_BYTES = [239, 187, 191];
1850
+
1851
+ class ConfigParseError extends Error {
1852
+ configPath;
1853
+ detail;
1854
+ constructor(configPath, detail) {
1855
+ super(`Could not read ${configPath}: ${detail}. ` + "The file was left unchanged. Fix it (or move it aside), then run the installer again.");
1856
+ this.name = "ConfigParseError";
1857
+ this.configPath = configPath;
1858
+ this.detail = detail;
1859
+ }
1860
+ }
1861
+ function errorDetail(error) {
1862
+ return error instanceof Error ? error.message : String(error);
1863
+ }
1864
+ function configErrorMessage(error) {
1865
+ return errorDetail(error);
1866
+ }
1867
+ function stripBom(content) {
1868
+ return content.startsWith(UTF8_BOM) ? { content: content.slice(1), hadBom: true } : { content, hadBom: false };
1869
+ }
1870
+ function stripJsonComments(content) {
1871
+ let withoutComments = "";
1872
+ let inString = false;
1873
+ let i = 0;
1874
+ while (i < content.length) {
1875
+ const ch = content[i];
1876
+ if (inString) {
1877
+ withoutComments += ch;
1878
+ if (ch === "\\" && i + 1 < content.length) {
1879
+ withoutComments += content[i + 1];
1880
+ i += 2;
1881
+ continue;
1882
+ }
1883
+ if (ch === '"')
1884
+ inString = false;
1885
+ i++;
1886
+ continue;
1887
+ }
1888
+ if (ch === '"') {
1889
+ inString = true;
1890
+ withoutComments += ch;
1891
+ i++;
1892
+ continue;
1893
+ }
1894
+ if (ch === "/" && content[i + 1] === "/") {
1895
+ while (i < content.length && content[i] !== `
1896
+ ` && content[i] !== "\r")
1897
+ i++;
1898
+ withoutComments += " ";
1899
+ continue;
1900
+ }
1901
+ if (ch === "/" && content[i + 1] === "*") {
1902
+ i += 2;
1903
+ while (i < content.length && !(content[i] === "*" && content[i + 1] === "/")) {
1904
+ if (content[i] === `
1905
+ `)
1906
+ withoutComments += `
1907
+ `;
1908
+ i++;
1909
+ }
1910
+ i += 2;
1911
+ withoutComments += " ";
1912
+ continue;
1913
+ }
1914
+ withoutComments += ch;
1915
+ i++;
1916
+ }
1917
+ let result = "";
1918
+ inString = false;
1919
+ i = 0;
1920
+ while (i < withoutComments.length) {
1921
+ const ch = withoutComments[i];
1922
+ if (inString) {
1923
+ result += ch;
1924
+ if (ch === "\\" && i + 1 < withoutComments.length) {
1925
+ result += withoutComments[i + 1];
1926
+ i += 2;
1927
+ continue;
1928
+ }
1929
+ if (ch === '"')
1930
+ inString = false;
1931
+ i++;
1932
+ continue;
1933
+ }
1934
+ if (ch === '"') {
1935
+ inString = true;
1936
+ result += ch;
1937
+ i++;
1938
+ continue;
1939
+ }
1940
+ if (ch === ",") {
1941
+ let j = i + 1;
1942
+ while (j < withoutComments.length && /\s/.test(withoutComments[j]))
1943
+ j++;
1944
+ if (withoutComments[j] === "}" || withoutComments[j] === "]") {
1945
+ i++;
1946
+ continue;
1947
+ }
1948
+ }
1949
+ result += ch;
1950
+ i++;
1951
+ }
1952
+ return result;
1953
+ }
1954
+ function parseConfigText(text, configPath, options = {}) {
1955
+ const { content } = stripBom(text);
1956
+ const source = options.jsonc ? stripJsonComments(content) : content;
1957
+ if (source.trim() === "") {
1958
+ return {};
1959
+ }
1960
+ let parsed;
1961
+ try {
1962
+ parsed = JSON.parse(source);
1963
+ } catch (error) {
1964
+ throw new ConfigParseError(configPath, `it is not valid ${options.jsonc ? "JSON (comments and trailing commas are allowed)" : "JSON"} (${errorDetail(error)})`);
1965
+ }
1966
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
1967
+ throw new ConfigParseError(configPath, "its top level is not a JSON object");
1968
+ }
1969
+ return parsed;
1970
+ }
1971
+ function readConfigFile(configPath, jsonc) {
1972
+ if (!existsSync(configPath)) {
1973
+ return {};
1974
+ }
1975
+ let text;
1976
+ try {
1977
+ text = readFileSync(configPath, "utf-8");
1978
+ } catch (error) {
1979
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
1980
+ return {};
1981
+ }
1982
+ throw new ConfigParseError(configPath, `it could not be opened (${errorDetail(error)})`);
1983
+ }
1984
+ return parseConfigText(text, configPath, { jsonc });
1985
+ }
1986
+ function readJsonConfig(configPath) {
1987
+ return readConfigFile(configPath, false);
1988
+ }
1989
+ function readJsoncConfig(configPath) {
1990
+ return readConfigFile(configPath, true);
1991
+ }
1992
+ function configUsesJsoncSyntax(configPath) {
1993
+ let text;
1994
+ try {
1995
+ text = readFileSync(configPath, "utf-8");
1996
+ } catch {
1997
+ return false;
1998
+ }
1999
+ const { content } = stripBom(text);
2000
+ if (content.trim() === "")
2001
+ return false;
2002
+ try {
2003
+ JSON.parse(content);
2004
+ return false;
2005
+ } catch {}
2006
+ try {
2007
+ parseConfigText(text, configPath, { jsonc: true });
2008
+ return true;
2009
+ } catch {
2010
+ return false;
2011
+ }
2012
+ }
2013
+ function fileHasBom(configPath) {
2014
+ try {
2015
+ const bytes = readFileSync(configPath);
2016
+ return UTF8_BOM_BYTES.every((byte, index) => bytes[index] === byte);
2017
+ } catch {
2018
+ return false;
2019
+ }
2020
+ }
2021
+ function writeJsonConfig(configPath, config) {
2022
+ const dir = dirname(configPath);
2023
+ if (!existsSync(dir)) {
2024
+ mkdirSync(dir, { recursive: true, mode: 448 });
2025
+ }
2026
+ const bom = fileHasBom(configPath) ? UTF8_BOM : "";
2027
+ writeFileSync(configPath, bom + JSON.stringify(config, null, 2) + `
2028
+ `);
2029
+ }
2030
+ function backupConfig(configPath) {
2031
+ if (!existsSync(configPath)) {
2032
+ return null;
2033
+ }
2034
+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
2035
+ const backupPath = `${configPath}.backup.${timestamp}`;
2036
+ copyFileSync(configPath, backupPath);
2037
+ return backupPath;
2038
+ }
2039
+
2040
+ // src/private-file.ts
2041
+ import { chmodSync, closeSync, fsyncSync, lstatSync, mkdirSync as mkdirSync2, openSync, renameSync, rmSync, statSync, writeSync } from "fs";
2042
+ import { randomBytes } from "crypto";
2043
+ import { basename, dirname as dirname2, join } from "path";
2044
+ var PRIVATE_FILE_MODE = 384;
2045
+ var PRIVATE_DIR_MODE = 448;
2046
+ function modesApply(platform) {
2047
+ return platform !== "win32";
2048
+ }
2049
+ function currentUid(options) {
2050
+ if (options.uid !== undefined)
2051
+ return options.uid;
2052
+ return typeof process.getuid === "function" ? process.getuid() : undefined;
2053
+ }
2054
+ function lstatOrNull(path) {
2055
+ try {
2056
+ return lstatSync(path);
2057
+ } catch (error) {
2058
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT")
2059
+ return null;
2060
+ throw error;
2061
+ }
2062
+ }
2063
+ function assertWritableDestination(path) {
2064
+ const stat = lstatOrNull(path);
2065
+ if (!stat)
2066
+ return;
2067
+ if (stat.isSymbolicLink()) {
2068
+ throw new Error(`Refusing to write ${path}: it is a symbolic link. Agent Approve stores a secret in this file and will not write it ` + "through a link. Replace the link with a regular file (or remove it), then run the installer again.");
2069
+ }
2070
+ if (!stat.isFile()) {
2071
+ throw new Error(`Refusing to write ${path}: it is not a regular file. Remove or rename it, then run the installer again.`);
2072
+ }
2073
+ }
2074
+ function restrictToOwner(path, options = {}) {
2075
+ const platform = (typeof options === "string" ? options : options.platform) ?? process.platform;
2076
+ if (!modesApply(platform))
2077
+ return;
2078
+ const stat = lstatOrNull(path);
2079
+ if (!stat || stat.isSymbolicLink() || !stat.isFile())
2080
+ return;
2081
+ chmodSync(path, PRIVATE_FILE_MODE);
2082
+ }
2083
+ function writePrivateFile(path, content, options = {}) {
2084
+ const platform = (typeof options === "string" ? options : options.platform) ?? process.platform;
2085
+ assertWritableDestination(path);
2086
+ const tempPath = join(dirname2(path), `.${basename(path)}.${randomBytes(8).toString("hex")}.tmp`);
2087
+ let fd = null;
2088
+ try {
2089
+ fd = openSync(tempPath, "wx", PRIVATE_FILE_MODE);
2090
+ writeSync(fd, content);
2091
+ fsyncSync(fd);
2092
+ closeSync(fd);
2093
+ fd = null;
2094
+ if (modesApply(platform))
2095
+ chmodSync(tempPath, PRIVATE_FILE_MODE);
2096
+ assertWritableDestination(path);
2097
+ renameSync(tempPath, path);
2098
+ } catch (error) {
2099
+ if (fd !== null) {
2100
+ try {
2101
+ closeSync(fd);
2102
+ } catch {}
2103
+ }
2104
+ rmSync(tempPath, { force: true });
2105
+ throw error;
2106
+ }
2107
+ }
2108
+ function ensurePrivateDir(dir, options = {}) {
2109
+ const resolved = typeof options === "string" ? { platform: options } : options;
2110
+ const platform = resolved.platform ?? process.platform;
2111
+ let stat;
2112
+ try {
2113
+ stat = statSync(dir);
2114
+ } catch (error) {
2115
+ if (!(error && typeof error === "object" && ("code" in error) && error.code === "ENOENT"))
2116
+ throw error;
2117
+ mkdirSync2(dir, { recursive: true, mode: PRIVATE_DIR_MODE });
2118
+ if (modesApply(platform))
2119
+ chmodSync(dir, PRIVATE_DIR_MODE);
2120
+ return true;
2121
+ }
2122
+ if (!stat.isDirectory()) {
2123
+ throw new Error(`${dir} exists and is not a directory. Remove or rename it, then run the installer again.`);
2124
+ }
2125
+ if (!modesApply(platform))
2126
+ return false;
2127
+ if ((stat.mode & 63) === 0)
2128
+ return false;
2129
+ const uid = currentUid(resolved);
2130
+ if (uid !== undefined && stat.uid !== uid) {
2131
+ throw new Error(`${dir} is accessible to other users and is owned by a different account, so Agent Approve will not store its token or keys there. ` + `Fix the ownership and run: chmod 700 ${dir}`);
2132
+ }
2133
+ chmodSync(dir, PRIVATE_DIR_MODE);
2134
+ return false;
2135
+ }
2136
+
2137
+ // src/post-pair-hooks.ts
2138
+ import { existsSync as existsSync2 } from "fs";
2139
+ async function refreshHooksAfterPairing(hooksDir, token, apiUrl, deps) {
2140
+ if (!existsSync2(hooksDir)) {
2141
+ throw new Error("Hooks directory not found");
2142
+ }
2143
+ const filters = await deps.copyHookScripts(hooksDir, token, deps.filterFiles, { apiUrl });
2144
+ return { filtersRefreshed: !(filters.failed.length || filters.terminalFailure) };
2145
+ }
2146
+
2147
+ // src/pairing-effective-config.ts
2148
+ var PRIVACY_RANK = { minimal: 0, summary: 1, full: 2 };
2149
+ var FAIL_RANK = { allow: 0, ask: 1, deny: 2 };
2150
+ var SETTING_LABEL = {
2151
+ privacyTier: "Privacy level",
2152
+ retentionDays: "Data retention",
2153
+ failBehavior: "If Agent Approve cannot be reached",
2154
+ e2eEnabled: "End-to-end encryption"
2155
+ };
2156
+ function isPrivacyTier(value) {
2157
+ return value === "minimal" || value === "summary" || value === "full";
2158
+ }
2159
+ function isFailBehavior(value) {
2160
+ return value === "allow" || value === "ask" || value === "deny";
2161
+ }
2162
+ function describeRetention(days) {
2163
+ if (days === null)
2164
+ return "keep forever";
2165
+ return days === 1 ? "1 day" : `${days} days`;
2166
+ }
2167
+ var DEFAULT_FAIL_BEHAVIOR = "ask";
2168
+ var DEFAULT_PRIVACY_TIER = "full";
2169
+ function parseEffectivePairingConfig(value) {
2170
+ if (!value || typeof value !== "object" || Array.isArray(value))
2171
+ return null;
2172
+ const candidate = value;
2173
+ const parsed = {};
2174
+ if (isPrivacyTier(candidate.privacyTier))
2175
+ parsed.privacyTier = candidate.privacyTier;
2176
+ const retention = candidate.retentionDays;
2177
+ if (retention === null || typeof retention === "number" && Number.isFinite(retention) && retention >= 0) {
2178
+ parsed.retentionDays = retention;
2179
+ }
2180
+ if (isFailBehavior(candidate.failBehavior))
2181
+ parsed.failBehavior = candidate.failBehavior;
2182
+ if (typeof candidate.e2eEnabled === "boolean")
2183
+ parsed.e2eEnabled = candidate.e2eEnabled;
2184
+ return parsed;
2185
+ }
2186
+ function reconcilePairingConfig(picks, effective, options = {}) {
2187
+ const local = {
2188
+ privacyTier: picks.privacyTier,
2189
+ retentionDays: picks.retentionDays,
2190
+ failBehavior: picks.failBehavior,
2191
+ e2eEnabled: picks.e2eEnabled
2192
+ };
2193
+ const accountKept = [];
2194
+ const unknown = [];
2195
+ const account = effective ?? {};
2196
+ const accountPrivacy = account.privacyTier ?? (isPrivacyTier(options.reportedPrivacy) ? options.reportedPrivacy : undefined);
2197
+ if (accountPrivacy === undefined) {
2198
+ unknown.push("privacyTier");
2199
+ if (PRIVACY_RANK[DEFAULT_PRIVACY_TIER] < PRIVACY_RANK[local.privacyTier])
2200
+ local.privacyTier = DEFAULT_PRIVACY_TIER;
2201
+ } else if (PRIVACY_RANK[accountPrivacy] < PRIVACY_RANK[picks.privacyTier]) {
2202
+ local.privacyTier = accountPrivacy;
2203
+ accountKept.push({ setting: "privacyTier", picked: picks.privacyTier, kept: accountPrivacy });
2204
+ }
2205
+ if (account.retentionDays === undefined) {
2206
+ unknown.push("retentionDays");
2207
+ } else if (account.retentionDays !== null && account.retentionDays < picks.retentionDays) {
2208
+ local.retentionDays = account.retentionDays;
2209
+ accountKept.push({
2210
+ setting: "retentionDays",
2211
+ picked: describeRetention(picks.retentionDays),
2212
+ kept: describeRetention(account.retentionDays)
2213
+ });
2214
+ }
2215
+ if (account.failBehavior === undefined) {
2216
+ unknown.push("failBehavior");
2217
+ if (FAIL_RANK[DEFAULT_FAIL_BEHAVIOR] > FAIL_RANK[local.failBehavior])
2218
+ local.failBehavior = DEFAULT_FAIL_BEHAVIOR;
2219
+ } else if (FAIL_RANK[account.failBehavior] > FAIL_RANK[picks.failBehavior]) {
2220
+ local.failBehavior = account.failBehavior;
2221
+ accountKept.push({ setting: "failBehavior", picked: picks.failBehavior, kept: account.failBehavior });
2222
+ }
2223
+ let encryptionRequired = false;
2224
+ if (account.e2eEnabled === undefined) {
2225
+ unknown.push("e2eEnabled");
2226
+ if (!picks.e2eEnabled && options.localE2eOn === true)
2227
+ local.e2eEnabled = true;
2228
+ } else if (account.e2eEnabled && !picks.e2eEnabled) {
2229
+ encryptionRequired = true;
2230
+ accountKept.push({ setting: "e2eEnabled", picked: "off", kept: "on" });
2231
+ }
2232
+ return { local, accountKept, unknown, encryptionRequired, letAccountWin: unknown.length > 0 };
2233
+ }
2234
+ function formatAccountKeptWarning(reconciliation) {
2235
+ const kept = reconciliation.accountKept.filter((entry) => entry.setting !== "e2eEnabled");
2236
+ if (kept.length === 0)
2237
+ return null;
2238
+ return [
2239
+ "Your Agent Approve account kept its stricter settings. This computer now uses them:",
2240
+ ...kept.map((entry) => ` ${SETTING_LABEL[entry.setting]}: ${entry.kept} (you chose ${entry.picked})`),
2241
+ "You can change account settings in the Agent Approve app."
2242
+ ].join(`
2243
+ `);
2244
+ }
2245
+ function formatAccountUnknownNote(reconciliation) {
2246
+ if (reconciliation.unknown.length === 0)
2247
+ return null;
2248
+ const names = reconciliation.unknown.map((setting) => SETTING_LABEL[setting]).join(", ");
2249
+ return `This pairing could not confirm your account's value for: ${names}. ` + "This computer uses the safer value for now and picks up your account settings on the next agent event.";
2250
+ }
2251
+ function formatEncryptionRequiredMessage(rerun) {
2252
+ const again = rerun === "pair" ? 'Run "npx agentapprove pair" again and choose an encryption key instead of disabling encryption.' : 'Run "npx agentapprove" again and keep end-to-end encryption on (choose Customize if you are not asked, and do not pass --no-e2e).';
2253
+ return [
2254
+ "This computer is not set up yet.",
2255
+ "Your Agent Approve account has end-to-end encryption turned on, and this setup chose to leave it off.",
2256
+ "Pairing a computer cannot turn encryption off for the account, and the encryption key can only be created during setup, so this computer has no key to use.",
2257
+ "Nothing from this pairing was saved on this computer. If it was set up before, its earlier pairing has been replaced and will not work until you set it up again.",
2258
+ again
2259
+ ].join(`
2260
+ `);
2261
+ }
2262
+
2263
+ // src/pair-key-plan.ts
2264
+ import { createHash } from "crypto";
2265
+ import { existsSync as existsSync3, readFileSync as readFileSync2, renameSync as renameSync2 } from "fs";
2266
+ import { join as join2 } from "path";
2267
+ var PAIR_KEY_GENERATE = "__generate__";
2268
+ var PAIR_KEY_DISABLE = "__disable__";
2269
+ function e2eKeyId(keyHex) {
2270
+ return createHash("sha256").update(Buffer.from(keyHex, "hex")).digest("hex").slice(0, 8);
2271
+ }
2272
+ function planPairKey(selection, keys, agentApproveDir, generateKeyHex) {
2273
+ if (selection === PAIR_KEY_DISABLE) {
2274
+ return { kind: "disable", e2eUserKey: null };
2275
+ }
2276
+ if (selection === PAIR_KEY_GENERATE) {
2277
+ const keyHex = generateKeyHex();
2278
+ const current = keys.find((key) => key.isCurrent);
2279
+ return {
2280
+ kind: "generate",
2281
+ e2eUserKey: keyHex,
2282
+ e2eKeyId: e2eKeyId(keyHex),
2283
+ ...current ? { backup: { from: current.path, to: join2(agentApproveDir, `e2e-key.${current.keyId}.bak`), keyId: current.keyId } } : {}
2284
+ };
2285
+ }
2286
+ const selected = keys.find((key) => key.keyId === selection);
2287
+ if (!selected)
2288
+ return { kind: "not_found" };
2289
+ return { kind: "existing", e2eUserKey: selected.keyHex, e2eKeyId: selected.keyId };
2290
+ }
2291
+ function applyPairKeyPlan(plan, agentApproveDir, deps) {
2292
+ if (plan.kind === "disable") {
2293
+ return { backedUp: null };
2294
+ }
2295
+ const rootKeyPath = join2(agentApproveDir, "e2e-root-key");
2296
+ const userKeyPath = join2(agentApproveDir, "e2e-key");
2297
+ let backedUp = null;
2298
+ if (plan.kind === "generate") {
2299
+ if (plan.backup && existsSync3(plan.backup.from)) {
2300
+ renameSync2(plan.backup.from, plan.backup.to);
2301
+ backedUp = plan.backup.keyId;
2302
+ }
2303
+ writePrivateFile(rootKeyPath, plan.e2eUserKey);
2304
+ writePrivateFile(userKeyPath, plan.e2eUserKey);
2305
+ deps.rotation.write({ rootKeyId: plan.e2eKeyId, epoch: 0, periodSeconds: 0, startedAt: deps.now() });
2306
+ } else {
2307
+ if (!existsSync3(rootKeyPath) || readFileSync2(rootKeyPath, "utf-8").trim() !== plan.e2eUserKey) {
2308
+ writePrivateFile(rootKeyPath, plan.e2eUserKey);
2309
+ } else {
2310
+ restrictToOwner(rootKeyPath);
2311
+ }
2312
+ restrictToOwner(userKeyPath);
2313
+ if (!deps.rotation.read()) {
2314
+ deps.rotation.write({ rootKeyId: plan.e2eKeyId, epoch: 0, periodSeconds: 0, startedAt: deps.now() });
2315
+ }
2316
+ }
2317
+ if (deps.serverKey) {
2318
+ writePrivateFile(join2(agentApproveDir, "e2e-server-key"), deps.serverKey);
2319
+ }
2320
+ return { backedUp };
2321
+ }
2322
+
1845
2323
  // src/openclaw-install.ts
1846
2324
  import { spawnSync } from "node:child_process";
1847
2325
  import { isDeepStrictEqual } from "node:util";
@@ -2491,15 +2969,15 @@ var source_default = chalk;
2491
2969
 
2492
2970
  // src/cli.ts
2493
2971
  var import_qrcode_terminal = __toESM(require_main(), 1);
2494
- import { existsSync as existsSync2, readFileSync, writeFileSync, mkdirSync, mkdtempSync, copyFileSync, renameSync as renameSync2, readdirSync as readdirSync2, statSync, lstatSync, realpathSync as realpathSync2, rmSync as rmSync2 } from "fs";
2972
+ import { existsSync as existsSync5, readFileSync as readFileSync3, writeFileSync as writeFileSync2, mkdirSync as mkdirSync3, mkdtempSync, copyFileSync as copyFileSync2, renameSync as renameSync4, readdirSync as readdirSync2, statSync as statSync2, lstatSync as lstatSync2, realpathSync as realpathSync2, rmSync as rmSync3 } from "fs";
2495
2973
  import { homedir, hostname, platform, tmpdir } from "os";
2496
- import { join, dirname as dirname2, sep as sep2 } from "path";
2974
+ import { join as join3, dirname as dirname4, sep as sep2 } from "path";
2497
2975
  import { execSync, spawnSync as spawnSync2 } from "child_process";
2498
- import { randomBytes, createHash } from "crypto";
2976
+ import { randomBytes as randomBytes2, createHash as createHash3 } from "crypto";
2499
2977
 
2500
2978
  // src/uninstall-utils.ts
2501
- import { existsSync, readdirSync, realpathSync, rmSync } from "fs";
2502
- import { basename, dirname, sep } from "path";
2979
+ import { existsSync as existsSync4, readdirSync, realpathSync, rmSync as rmSync2 } from "fs";
2980
+ import { basename as basename2, dirname as dirname3, sep } from "path";
2503
2981
  var INSTALLER_COMMAND_DESCRIPTIONS = {
2504
2982
  uninstall: "Remove hooks/plugins from agent configs and keep local Agent Approve state",
2505
2983
  purge: "Remove hooks/plugins and delete local Agent Approve state"
@@ -2572,7 +3050,7 @@ function appendPathSegments(basePath, childSegments) {
2572
3050
  return basePath.endsWith(sep) ? `${basePath}${childSegments.join(sep)}` : `${basePath}${sep}${childSegments.join(sep)}`;
2573
3051
  }
2574
3052
  function createRemovalTarget(path, kind, recursive = false) {
2575
- if (!existsSync(path)) {
3053
+ if (!existsSync4(path)) {
2576
3054
  return null;
2577
3055
  }
2578
3056
  let actualPath = path;
@@ -2586,13 +3064,13 @@ function createRemovalTarget(path, kind, recursive = false) {
2586
3064
  return { path, actualPath, displayPath, kind, recursive };
2587
3065
  }
2588
3066
  function removeRemovalTarget(target) {
2589
- if (!existsSync(target.path) && !existsSync(target.actualPath)) {
3067
+ if (!existsSync4(target.path) && !existsSync4(target.actualPath)) {
2590
3068
  return false;
2591
3069
  }
2592
3070
  try {
2593
- rmSync(target.actualPath, { recursive: target.recursive, force: true });
3071
+ rmSync2(target.actualPath, { recursive: target.recursive, force: true });
2594
3072
  if (target.path !== target.actualPath) {
2595
- rmSync(target.path, { recursive: false, force: true });
3073
+ rmSync2(target.path, { recursive: false, force: true });
2596
3074
  }
2597
3075
  return true;
2598
3076
  } catch {
@@ -2600,7 +3078,7 @@ function removeRemovalTarget(target) {
2600
3078
  }
2601
3079
  }
2602
3080
  function getOpenClawPluginTargets(openclawConfigPath) {
2603
- const configDir = dirname(openclawConfigPath);
3081
+ const configDir = dirname3(openclawConfigPath);
2604
3082
  const npmPath = safeJoinWithinBase(configDir, "npm", "node_modules", "@agentapprove", "openclaw");
2605
3083
  const openclawPath = safeJoinWithinBase(configDir, "extensions", "openclaw");
2606
3084
  const legacyPath = safeJoinWithinBase(configDir, "extensions", "agentapprove");
@@ -2616,7 +3094,7 @@ function getOpenCodePluginTargets(opencodeConfigDir, opencodeCacheDir) {
2616
3094
  const packageCacheTargets = [];
2617
3095
  if (opencodeCacheDir) {
2618
3096
  const scopedPackageCacheDir = safeJoinWithinBase(opencodeCacheDir, "packages", "@agentapprove");
2619
- if (scopedPackageCacheDir && existsSync(scopedPackageCacheDir)) {
3097
+ if (scopedPackageCacheDir && existsSync4(scopedPackageCacheDir)) {
2620
3098
  for (const entry of readdirSync(scopedPackageCacheDir)) {
2621
3099
  if (!entry.startsWith("opencode@")) {
2622
3100
  continue;
@@ -2645,11 +3123,11 @@ function getAntigravityPluginTargets(geminiDir) {
2645
3123
  function collectBackupTargets(configPaths) {
2646
3124
  const targets = [];
2647
3125
  for (const configPath of configPaths) {
2648
- const configDir = dirname(configPath);
2649
- if (!existsSync(configDir)) {
3126
+ const configDir = dirname3(configPath);
3127
+ if (!existsSync4(configDir)) {
2650
3128
  continue;
2651
3129
  }
2652
- const configBase = basename(configPath);
3130
+ const configBase = basename2(configPath);
2653
3131
  for (const entry of readdirSync(configDir)) {
2654
3132
  if (!entry.startsWith(`${configBase}.backup.`)) {
2655
3133
  continue;
@@ -2679,7 +3157,7 @@ function getManagedStateTargets(agentApproveDir) {
2679
3157
  safeJoinWithinBase(agentApproveDir, "e2e-server-key"),
2680
3158
  safeJoinWithinBase(agentApproveDir, "e2e-rotation.json")
2681
3159
  ].map((path) => path ? createRemovalTarget(path, "crypto_material") : null).filter((target) => target !== null);
2682
- if (existsSync(agentApproveDir)) {
3160
+ if (existsSync4(agentApproveDir)) {
2683
3161
  for (const entry of readdirSync(agentApproveDir)) {
2684
3162
  if (!/^e2e-key\.[^.]+\.bak$/.test(entry)) {
2685
3163
  continue;
@@ -3177,8 +3655,8 @@ function classifyHookDownloadFailure(status, body) {
3177
3655
 
3178
3656
  // src/copy-hook-scripts.ts
3179
3657
  import { writeFileSync as fsWriteFileSync } from "fs";
3180
- import { renameSync } from "fs";
3181
- import { randomUUID } from "crypto";
3658
+ import { renameSync as renameSync3 } from "fs";
3659
+ import { createHash as createHash2, randomUUID } from "crypto";
3182
3660
 
3183
3661
  // src/background-filters.ts
3184
3662
  var BACKGROUND_FILTER_FILES = ["background-filter.js", "background-filters.json"];
@@ -3195,6 +3673,7 @@ function validBackgroundFilters(content) {
3195
3673
 
3196
3674
  // src/copy-hook-scripts.ts
3197
3675
  import { join as pathJoin } from "path";
3676
+ var HOOK_INTEGRITY_FAILURE = "integrity check failed; run the latest installer: npx agentapprove@latest";
3198
3677
  function retryDelay(response) {
3199
3678
  const value = response.headers.get("Retry-After")?.trim();
3200
3679
  if (!value)
@@ -3240,7 +3719,8 @@ async function copyHookScripts(hooksDir, token, files, options) {
3240
3719
  response = await download();
3241
3720
  }
3242
3721
  if (response.ok) {
3243
- const content = await response.text();
3722
+ const bytes = new Uint8Array(await response.arrayBuffer());
3723
+ const content = new TextDecoder("utf-8").decode(bytes);
3244
3724
  if (file === "background-filters.json") {
3245
3725
  if (!validBackgroundFilters(content)) {
3246
3726
  recordFailure(file, "invalid catalog; previous copy retained");
@@ -3252,6 +3732,14 @@ async function copyHookScripts(hooksDir, token, files, options) {
3252
3732
  }
3253
3733
  const isShellScript = content.startsWith("#!/") || content.startsWith("# ");
3254
3734
  const isJsBundle = file.endsWith(".js") && (content.startsWith("//") || content.startsWith("import ") || content.startsWith("var ") || content.startsWith("const ") || content.startsWith("export "));
3735
+ if (options.expectedHashes) {
3736
+ const pinned = Object.prototype.hasOwnProperty.call(options.expectedHashes, file) ? options.expectedHashes[file] : undefined;
3737
+ const actual = createHash2("sha256").update(Buffer.from(bytes)).digest("hex");
3738
+ if (!pinned || !pinned.includes(actual)) {
3739
+ recordFailure(file, HOOK_INTEGRITY_FAILURE);
3740
+ continue;
3741
+ }
3742
+ }
3255
3743
  if (isShellScript || isJsBundle) {
3256
3744
  staged.push({ file, content, mode: isShellScript ? 493 : 420 });
3257
3745
  downloaded++;
@@ -3305,7 +3793,7 @@ async function copyHookScripts(hooksDir, token, files, options) {
3305
3793
  if (failed.length === 0) {
3306
3794
  for (const { temporary, filePath, file } of replacements) {
3307
3795
  try {
3308
- renameSync(temporary, filePath);
3796
+ renameSync3(temporary, filePath);
3309
3797
  } catch {
3310
3798
  failed.push(`${file} (could not replace hook file)`);
3311
3799
  break;
@@ -3316,6 +3804,207 @@ async function copyHookScripts(hooksDir, token, files, options) {
3316
3804
  return { downloaded, failed, optionalFailed };
3317
3805
  }
3318
3806
 
3807
+ // src/hook-manifest.generated.ts
3808
+ var HOOK_SCRIPT_SHA256 = {
3809
+ "antigravity-hook.sh": [
3810
+ "1ed82442099b7216b9dd3fd6b1e9f2648b5230b528778a374ba7f1d570603d8a",
3811
+ "0cfac7fdab920af8b243dc8f0cffcc5355d06cec13a71060f1e77a22487379cf"
3812
+ ],
3813
+ "background-filter.js": [
3814
+ "5850ec58a56474891627e54b4e34255a878b7d21037382296c5512ee6d250d54"
3815
+ ],
3816
+ "claude-notification.sh": [
3817
+ "f699c4ac0d47ad66ab7c5dca549d8413b344dd20c6317f0ed278aed933306583"
3818
+ ],
3819
+ "claude-post-tool-failure.sh": [
3820
+ "a14693c771609d63d42c2a84fcb6c6a09edfd5e7977ef37d193af7379db85907"
3821
+ ],
3822
+ "claude-post-tool.sh": [
3823
+ "8a61253504c99ecdf101b4fa8681a09489f128ef4ba6dcfb47450c881011654e"
3824
+ ],
3825
+ "claude-pre-tool.sh": [
3826
+ "a4bae2a689b075762a11df659b10ca783c1c780af93277efe37a398243fbc8ed",
3827
+ "5a317ed1eb620bf5751fbe50ac266295f9a9436a5b5368ff4d5f3ae1e0202f33"
3828
+ ],
3829
+ "claude-prompt.sh": [
3830
+ "449cffbd8efb1f04f51d67aedb817883cffd20ab99ddff4eb32acfb4d3692080"
3831
+ ],
3832
+ "claude-session-end.sh": [
3833
+ "f27ff70502327886d28f234631bbe01cf1b02369f0491b956c8cdb1aaf07c4b6"
3834
+ ],
3835
+ "claude-session-start.sh": [
3836
+ "dc2d906e448d277be0f9b5e1cd1b0bddadd9d5d86f6a0012ffa6e63cb38fb906"
3837
+ ],
3838
+ "claude-stop.sh": [
3839
+ "158629503c11d44d3864c6a4ea5448e5743b4cacc11f0246ef604ce5a4c27830",
3840
+ "5dd2f71fb534dda5599af3bdaf44092134460ab46195254a830715d3cdf0936a"
3841
+ ],
3842
+ "claude-subagent-start.sh": [
3843
+ "93738cd3c3667feae235fd08a44be6381f7e7d6291c102257ae1913917a58d17"
3844
+ ],
3845
+ "claude-subagent-stop.sh": [
3846
+ "3cacc15624672dc10109fc01456540027293c30b3e581d9376311c35cd937dd2"
3847
+ ],
3848
+ "claude-user-prompt.sh": [
3849
+ "62dc6f72c856ed70e2bd2812471d9a825c5004948db309eff996ff9c78be9be4"
3850
+ ],
3851
+ "codex-post-tool.sh": [
3852
+ "b2d6a3352198a79780ace8303b476b37250d020d066d3be0b32719be34cb1198"
3853
+ ],
3854
+ "codex-pre-tool.sh": [
3855
+ "3d1c6b7f8717f7b043d54f79af6225bebffb2baa4f0badde759182c415bcc343",
3856
+ "6c44eb3f3774024d26a2d9162b9a91f1ac8c15559a164823f122aa0f423b454f"
3857
+ ],
3858
+ "codex-session-start.sh": [
3859
+ "b14351394abeab95d047d6843e34d52e33758eef1f4f129a31efe6334858db53"
3860
+ ],
3861
+ "codex-stop.sh": [
3862
+ "6c46b605b482a474205d850cec28f35ced74796beedf1f2647a1268fcfa7d45e",
3863
+ "e0c3c95605c6f04004c4cb350ee7d997f471a7d07546e2e0b0fec9b9de845cd5"
3864
+ ],
3865
+ "codex-subagent-start.sh": [
3866
+ "053caf81244b7510057c307d7dbc35f2190b0c5665dfdae252ae29e98744de4e"
3867
+ ],
3868
+ "codex-subagent-stop.sh": [
3869
+ "0876893314ccf0ebbb8e07dd879c0e751ab24a6b195008d8d1ccf29ee86f581d"
3870
+ ],
3871
+ "codex-user-prompt.sh": [
3872
+ "0e8886fa08e6c5529721f6e94907c9bad6c32e97c1f4827e2ef5270f349cce4f"
3873
+ ],
3874
+ "common.sh": [
3875
+ "626da6d015a3686cc4ba9b578ec19e378f18156c5fa0b11fdd10250908ba47da",
3876
+ "dba7e22eb923e22054a776eb2a5cbf958acf5b55f83d49b685eef3cac1ce30e6"
3877
+ ],
3878
+ "completion-hook.sh": [
3879
+ "ec94b799c35cd650b79d50f223bd57e817fed5d7e379aac5948e06f14ad7b31a"
3880
+ ],
3881
+ "cursor-approval.sh": [
3882
+ "547e056485093ff9071a5c45326dfaf1320918495c54908f7413d7f6c7a9422f",
3883
+ "cd831b97a0631202275d98925be1401b0b8915d4cf90783e158d05fea813cdfd"
3884
+ ],
3885
+ "cursor-mcp-approval.sh": [
3886
+ "e5638dde8b7767ff4e3c0a361dec27fe49fa63048ea06952bb602b98e8abb80d",
3887
+ "801cff771a4640a77d5c07e1d0c45038333650ceb3e169cf0b8c0d1eda22add9"
3888
+ ],
3889
+ "cursor-mcp-complete.sh": [
3890
+ "0c7131db3e9007dc1e614cd5a132f08f4ee60030d48c0ee3fcb48074ae37c37b"
3891
+ ],
3892
+ "cursor-post-tool.sh": [
3893
+ "44971e10d711667a659a493f062cadb4d44545c42aec0bbd24ad3821cfb27594"
3894
+ ],
3895
+ "cursor-pre-tool.sh": [
3896
+ "87ed62e2d5976b1c04337b2407f73f86d039751a12a3803ca2f8db1ca3a10446",
3897
+ "d5e397a1a33d300c61ef1afea4208927b3d1cfc292a67bd2b8084dbf718acc52"
3898
+ ],
3899
+ "cursor-precompact.sh": [
3900
+ "33faedfd07999296911aa9080a2799938493114ad29878db025d6c42db418f83"
3901
+ ],
3902
+ "cursor-response.sh": [
3903
+ "913e2ef96526b092589ac3e744872e8ede47c3a3d280590e356fa406749c5c0c"
3904
+ ],
3905
+ "cursor-session-end.sh": [
3906
+ "ce2e29ccab8396b4537ac1217f1152cf4b20f0f8261394742c77ff83572112b0"
3907
+ ],
3908
+ "cursor-session-start.sh": [
3909
+ "512047dab51b1ef69338bc8ef6d205d7605f128523bd47a3e296992b720faed5"
3910
+ ],
3911
+ "cursor-shell-complete.sh": [
3912
+ "3e1976d565f82b0768f6a76f2aed3636123cf69195854a5b3d574de2035f4879"
3913
+ ],
3914
+ "cursor-start.sh": [
3915
+ "23895ab6d2ecaa9fe278b3fb9d53b21418edd7cfac5116d53bd659d4ecbabae3"
3916
+ ],
3917
+ "cursor-stop.sh": [
3918
+ "052c9de32572aeb8b5c9d27313cd20a27790a2250ce3c9aeb8e7356a755c5de3",
3919
+ "9fdb148a495a80173a5c8a627cd5f22e02d824ee5cc5e955e13bb5f0dce53d82"
3920
+ ],
3921
+ "cursor-subagent-start.sh": [
3922
+ "b614d1619331b2a900046efdf65eb5d759fb301d2aa7a115f0b107b1b41b3eb9"
3923
+ ],
3924
+ "cursor-subagent-stop.sh": [
3925
+ "96d68c3ce020ad8ded49088e5665c3813c89539a0f15e6fda37a50beba08e7ca"
3926
+ ],
3927
+ "cursor-thought.sh": [
3928
+ "79b5e73597df5eeec14c3327371f177eabc825edd593aea3c1012e7ae1ea4139"
3929
+ ],
3930
+ "gemini-after-agent.sh": [
3931
+ "3c974a52bad64246a40a9cb58f1efa0ec3530be49b1e4a6e980f8469127ce70f"
3932
+ ],
3933
+ "gemini-after-model.sh": [
3934
+ "ee5421957f1a9c31bd333df1b012a3ba56ac1e2b2bd7cad9c8fb300bb2c0faf2"
3935
+ ],
3936
+ "gemini-after-tool.sh": [
3937
+ "46a3b655e295562301ebf54fce0fb271fbfa61679a8deb3fbab6affc7433d57e"
3938
+ ],
3939
+ "gemini-before-agent.sh": [
3940
+ "4e3f6e8b04e1027562e55d13faa4c9521b665ef0299155a6da320a2c96d38f78"
3941
+ ],
3942
+ "gemini-before-model.sh": [
3943
+ "b074d767fe5e211a7f6434db1d2b02c6761df73b01f8defa703691cd1d986485"
3944
+ ],
3945
+ "gemini-before-tool.sh": [
3946
+ "65c12342fd73cd200c6b6934b3742390e2f2d16524f9d643889c6b1107762ca9",
3947
+ "222623ee4dd6ddd592d8aa0bcf3553d1acda3a2543cf6528bb3cabb50d2cb593"
3948
+ ],
3949
+ "gemini-notification.sh": [
3950
+ "5978c5d4b689f2e87131d9950b50588a4aa74390b548a43c3ea6e607fe407e16"
3951
+ ],
3952
+ "gemini-session-end.sh": [
3953
+ "326b0db81850cbc63008815c27f8b0b6ab5af0e6d7692a7e9a9bc5b7cca79f9e"
3954
+ ],
3955
+ "gemini-session-start.sh": [
3956
+ "5d1113f25accd644c82e21bbc7efc56739f549b6b8227bd8874afc6500112b46"
3957
+ ],
3958
+ "gemini-stop.sh": [
3959
+ "da82707cd945b2307efa0a137e54f3dc9a630b2d02a5056d676ad49712f8534f",
3960
+ "dbf663489b778e8be2665f48ad601b99d43ae2462c43936276cb354505870ad8"
3961
+ ],
3962
+ "github-error.sh": [
3963
+ "e4dd8874cb837727c795a095ea5829eaa9d350ef65ab4c9fb802334558c44859"
3964
+ ],
3965
+ "github-post-tool.sh": [
3966
+ "e057c5f624d7d4998ea59ef524b97b2364f860477a6aadd2512d562cdecfc6c2"
3967
+ ],
3968
+ "github-pre-tool.sh": [
3969
+ "1066e08beb1ff864a8075cf9cd77ab1b64e5913f30675edd97cbb58e5fa05a7b",
3970
+ "a331d5980824db7ca38a586f5f6398627b6653397eb4d5bcd19b18a293479c38"
3971
+ ],
3972
+ "github-precompact.sh": [
3973
+ "f34011aa926611fe8691ef24250ab22561ff6c0387d3e3527e52d44c7aac6f44"
3974
+ ],
3975
+ "github-session-end.sh": [
3976
+ "370fa14d68739b398233d60982cefd6dc946e3be6f4c3560b0a6e8652928f2d9"
3977
+ ],
3978
+ "github-session-start.sh": [
3979
+ "505f44ed4ca6345b8e9ff8a328198ed6141d4774a630821b984ab5cf4c3954ff"
3980
+ ],
3981
+ "github-stop.sh": [
3982
+ "07f2d802700cf7ace009207aaa3f9c96e4e5943c022faa9601d9b85277e50fa4",
3983
+ "3f4d12832b22be48d708eb70f1bcb00d4c437a19c898e17a0989ab29d3efe4b4"
3984
+ ],
3985
+ "github-subagent-start.sh": [
3986
+ "506e39c02806ca20e8a3605a0de3eb089d9ef98d3556ceb675a70433ea313889"
3987
+ ],
3988
+ "github-subagent-stop.sh": [
3989
+ "27cab61bdad7c7efddb8be43bcc8cedb03d0789d1288db933386c185b02c0027"
3990
+ ],
3991
+ "github-user-prompt.sh": [
3992
+ "67ac8e7c33991402cc2dfcaf6b3380ba50b92cf224fcb447c2bb39cbd7c7a1a8"
3993
+ ],
3994
+ "notify-hook.sh": [
3995
+ "0892b3f3b71b8f7df08917ad4f38baac1655093a38f5d43238aca49b9f0554a1",
3996
+ "04013b4988d2d663279f6e75838244aad16247ccec7c37df1c4b5c4413505a05"
3997
+ ],
3998
+ "openhands-hook.sh": [
3999
+ "ebdb17e34918e6e58e9ab70e2db9521f25b1907f9cd96d78d217074db64fc566",
4000
+ "f1c09c383891d2dd0048f74ab5c71a3d1a027d2a50a75ac1dc0cdee72c9772f2"
4001
+ ],
4002
+ "windsurf-hook.sh": [
4003
+ "16a73925f6a2b2fb3a9e29166316519bb5f5afd05bbed0df80513b004434ebd8",
4004
+ "94753235d4de704a9a0399f734912000e23f9cd15ee1e494f584a0b49ebfda24"
4005
+ ]
4006
+ };
4007
+
3319
4008
  // src/host-command.ts
3320
4009
  import { execFileSync } from "node:child_process";
3321
4010
  var HOST_COMMAND_TIMEOUT_MS = 30000;
@@ -3434,63 +4123,30 @@ Configured on this computer: ${ready.join(", ")}. Nothing was changed.`);
3434
4123
  }
3435
4124
 
3436
4125
  // src/cli.ts
3437
- var VERSION = "0.2.0";
4126
+ var VERSION = "0.2.1";
3438
4127
  function getApiUrl() {
3439
4128
  return process.env.AGENTAPPROVE_API || "https://api.agentapprove.com";
3440
4129
  }
3441
4130
  function getXdgConfigHome() {
3442
- return process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
4131
+ return process.env.XDG_CONFIG_HOME || join3(homedir(), ".config");
3443
4132
  }
3444
4133
  function getOpenCodeConfigDir() {
3445
- return join(getXdgConfigHome(), "opencode");
4134
+ return join3(getXdgConfigHome(), "opencode");
3446
4135
  }
3447
4136
  function getOpenCodeConfigPath() {
3448
- return join(getOpenCodeConfigDir(), "opencode.json");
4137
+ return join3(getOpenCodeConfigDir(), "opencode.json");
3449
4138
  }
3450
4139
  function getXdgCacheHome() {
3451
- return process.env.XDG_CACHE_HOME || join(homedir(), ".cache");
4140
+ return process.env.XDG_CACHE_HOME || join3(homedir(), ".cache");
3452
4141
  }
3453
4142
  function getOpenCodeCacheDir() {
3454
- return join(getXdgCacheHome(), "opencode");
4143
+ return join3(getXdgCacheHome(), "opencode");
3455
4144
  }
3456
4145
  var API_URL = getApiUrl();
3457
4146
  var API_VERSION = process.env.AGENTAPPROVE_API_VERSION || "v001";
3458
4147
  function hasFlag2(flag) {
3459
4148
  return process.argv.slice(2).includes(flag);
3460
4149
  }
3461
- function updateEnvValue(key, value) {
3462
- const envPath = join(getAgentApproveDir(), "env");
3463
- let content;
3464
- try {
3465
- content = readFileSync(envPath, "utf-8");
3466
- } catch (err) {
3467
- if (err && typeof err === "object" && "code" in err && err.code === "ENOENT") {
3468
- return;
3469
- }
3470
- throw err;
3471
- }
3472
- const lines = content.endsWith(`
3473
- `) ? content.slice(0, -1).split(`
3474
- `) : content.split(`
3475
- `);
3476
- let seenKey = false;
3477
- const updatedLines = lines.flatMap((line) => {
3478
- const trimmed = line.replace(/^export\s+/, "").trim();
3479
- const eqIdx = trimmed.indexOf("=");
3480
- if (eqIdx <= 0 || trimmed.slice(0, eqIdx) !== key)
3481
- return [line];
3482
- if (seenKey)
3483
- return [];
3484
- seenKey = true;
3485
- return [`${key}=${value}`];
3486
- });
3487
- if (!seenKey) {
3488
- updatedLines.push(`${key}=${value}`);
3489
- }
3490
- writeFileSync(envPath, `${updatedLines.join(`
3491
- `)}
3492
- `, { mode: 384 });
3493
- }
3494
4150
  function getCommand() {
3495
4151
  const args = process.argv.slice(2);
3496
4152
  const filtered = [];
@@ -3506,19 +4162,19 @@ function getCommand() {
3506
4162
  }
3507
4163
  return filtered[0] || "install";
3508
4164
  }
3509
- var OPENCODE_PLUGIN_VERSION = "0.1.26";
4165
+ var OPENCODE_PLUGIN_VERSION = "0.1.27";
3510
4166
  var OPENCODE_PLUGIN_SPEC = `@agentapprove/opencode@${OPENCODE_PLUGIN_VERSION}`;
3511
- var OPENCLAW_PLUGIN_VERSION = "0.2.21";
4167
+ var OPENCLAW_PLUGIN_VERSION = "0.2.22";
3512
4168
  var OPENCLAW_PLUGIN_SPEC = `@agentapprove/openclaw@${OPENCLAW_PLUGIN_VERSION}`;
3513
- var PI_PLUGIN_VERSION = "0.1.14";
4169
+ var PI_PLUGIN_VERSION = "0.1.15";
3514
4170
  var PI_PLUGIN_SPEC = `npm:@agentapprove/pi@${PI_PLUGIN_VERSION}`;
3515
4171
  var PI_STATUS_TIMEOUT_MS = 5000;
3516
- var HERMES_PLUGIN_VERSION = "0.1.16";
4172
+ var HERMES_PLUGIN_VERSION = "0.1.17";
3517
4173
  var HERMES_PIP_DEPS = ["cryptography>=44.0,<46", "httpx>=0.27,<0.29"];
3518
4174
  var AGENTS = {
3519
4175
  "claude-code": {
3520
4176
  name: "Claude Code",
3521
- configPath: join(homedir(), ".claude", "settings.json"),
4177
+ configPath: join3(homedir(), ".claude", "settings.json"),
3522
4178
  hooksKey: "hooks",
3523
4179
  hooks: [
3524
4180
  { name: "PreToolUse", file: "claude-pre-tool.sh", description: "Before tool execution (approval)", hasMatcher: true, isApprovalHook: true, timeout: 300 },
@@ -3535,7 +4191,7 @@ var AGENTS = {
3535
4191
  },
3536
4192
  cursor: {
3537
4193
  name: "Cursor",
3538
- configPath: join(homedir(), ".cursor", "hooks.json"),
4194
+ configPath: join3(homedir(), ".cursor", "hooks.json"),
3539
4195
  hooksKey: "hooks",
3540
4196
  hooks: [
3541
4197
  { name: "sessionStart", file: "cursor-session-start.sh", description: "Session started" },
@@ -3557,7 +4213,7 @@ var AGENTS = {
3557
4213
  },
3558
4214
  windsurf: {
3559
4215
  name: "Windsurf",
3560
- configPath: join(homedir(), ".codeium", "windsurf", "hooks.json"),
4216
+ configPath: join3(homedir(), ".codeium", "windsurf", "hooks.json"),
3561
4217
  hooksKey: "hooks",
3562
4218
  hooks: [
3563
4219
  { name: "pre_user_prompt", file: "windsurf-hook.sh", description: "User prompt (logging only)" },
@@ -3574,7 +4230,7 @@ var AGENTS = {
3574
4230
  },
3575
4231
  antigravity: {
3576
4232
  name: "Antigravity",
3577
- configPath: join(homedir(), ".gemini", "config", "plugins", "agentapprove", "hooks.json"),
4233
+ configPath: join3(homedir(), ".gemini", "config", "plugins", "agentapprove", "hooks.json"),
3578
4234
  hooksKey: "antigravityPlugin",
3579
4235
  hooks: [
3580
4236
  { name: "PreToolUse", file: "antigravity-hook.sh", description: "Tool approval", isApprovalHook: true, timeout: 300 },
@@ -3586,7 +4242,7 @@ var AGENTS = {
3586
4242
  },
3587
4243
  "gemini-cli": {
3588
4244
  name: "Gemini CLI (legacy)",
3589
- configPath: join(homedir(), ".gemini", "settings.json"),
4245
+ configPath: join3(homedir(), ".gemini", "settings.json"),
3590
4246
  hooksKey: "hooks",
3591
4247
  hooks: [
3592
4248
  { name: "SessionStart", file: "gemini-session-start.sh", description: "Session started" },
@@ -3602,7 +4258,7 @@ var AGENTS = {
3602
4258
  },
3603
4259
  "antigravity-cli": {
3604
4260
  name: "Antigravity CLI",
3605
- configPath: join(homedir(), ".gemini", "antigravity-cli", "plugins", "agentapprove", "hooks.json"),
4261
+ configPath: join3(homedir(), ".gemini", "antigravity-cli", "plugins", "agentapprove", "hooks.json"),
3606
4262
  hooksKey: "antigravityPlugin",
3607
4263
  hooks: [
3608
4264
  { name: "PreToolUse", file: "antigravity-hook.sh", description: "Tool approval", isApprovalHook: true, timeout: 300 },
@@ -3614,7 +4270,7 @@ var AGENTS = {
3614
4270
  },
3615
4271
  "vscode-agent": {
3616
4272
  name: "VS Code GitHub Copilot",
3617
- configPath: join(homedir(), ".agentapprove", "hooks", "vscode-hooks.json"),
4273
+ configPath: join3(homedir(), ".agentapprove", "hooks", "vscode-hooks.json"),
3618
4274
  hooksKey: "hooks",
3619
4275
  hooks: [
3620
4276
  { name: "SessionStart", file: "github-session-start.sh", description: "Session started" },
@@ -3629,7 +4285,7 @@ var AGENTS = {
3629
4285
  },
3630
4286
  "copilot-cli": {
3631
4287
  name: "GitHub Copilot CLI",
3632
- configPath: join(homedir(), ".agentapprove", "copilot-cli-hooks.json"),
4288
+ configPath: join3(homedir(), ".agentapprove", "copilot-cli-hooks.json"),
3633
4289
  hooksKey: "hooks",
3634
4290
  hooks: [
3635
4291
  { name: "sessionStart", file: "github-session-start.sh", description: "Session started" },
@@ -3642,7 +4298,7 @@ var AGENTS = {
3642
4298
  },
3643
4299
  openclaw: {
3644
4300
  name: "OpenClaw",
3645
- configPath: join(homedir(), ".openclaw", "openclaw.json"),
4301
+ configPath: join3(homedir(), ".openclaw", "openclaw.json"),
3646
4302
  hooksKey: "plugins",
3647
4303
  hooks: [
3648
4304
  { name: "agentapprove", file: "@agentapprove/openclaw", description: "Tool approval + event monitoring", isApprovalHook: true, isPlugin: true }
@@ -3650,7 +4306,7 @@ var AGENTS = {
3650
4306
  },
3651
4307
  codex: {
3652
4308
  name: "OpenAI Codex",
3653
- configPath: join(homedir(), ".codex", "hooks.json"),
4309
+ configPath: join3(homedir(), ".codex", "hooks.json"),
3654
4310
  hooksKey: "hooks",
3655
4311
  hooks: [
3656
4312
  { name: "SubagentStart", file: "codex-subagent-start.sh", description: "Subagent started", hasMatcher: true },
@@ -3672,7 +4328,7 @@ var AGENTS = {
3672
4328
  },
3673
4329
  pi: {
3674
4330
  name: "Pi",
3675
- configPath: join(homedir(), ".pi", "agent", "settings.json"),
4331
+ configPath: join3(homedir(), ".pi", "agent", "settings.json"),
3676
4332
  hooksKey: "packages",
3677
4333
  hooks: [
3678
4334
  { name: "agentapprove", file: "@agentapprove/pi", description: "Tool approval + event monitoring", isApprovalHook: true, isPlugin: true }
@@ -3680,7 +4336,7 @@ var AGENTS = {
3680
4336
  },
3681
4337
  hermes: {
3682
4338
  name: "Hermes",
3683
- configPath: join(homedir(), ".hermes", "config.yaml"),
4339
+ configPath: join3(homedir(), ".hermes", "config.yaml"),
3684
4340
  hooksKey: "plugins",
3685
4341
  hooks: [
3686
4342
  { name: "agentapprove", file: "agentapprove", description: "Tool approval + event monitoring + follow-up input", isApprovalHook: true, isPlugin: true }
@@ -3688,7 +4344,7 @@ var AGENTS = {
3688
4344
  },
3689
4345
  openhands: {
3690
4346
  name: "OpenHands",
3691
- configPath: join(homedir(), ".openhands", "hooks.json"),
4347
+ configPath: join3(homedir(), ".openhands", "hooks.json"),
3692
4348
  hooksKey: "",
3693
4349
  hooks: [
3694
4350
  { name: "session_start", file: "openhands-hook.sh", description: "Session started" },
@@ -3806,11 +4462,11 @@ function findGitBash() {
3806
4462
  process.env.CLAUDE_CODE_GIT_BASH_PATH,
3807
4463
  "C:\\Program Files\\Git\\bin\\bash.exe",
3808
4464
  "C:\\Program Files (x86)\\Git\\bin\\bash.exe",
3809
- join(process.env.LOCALAPPDATA || "", "Programs", "Git", "bin", "bash.exe"),
3810
- join(process.env.ProgramW6432 || "", "Git", "bin", "bash.exe")
4465
+ join3(process.env.LOCALAPPDATA || "", "Programs", "Git", "bin", "bash.exe"),
4466
+ join3(process.env.ProgramW6432 || "", "Git", "bin", "bash.exe")
3811
4467
  ].filter(Boolean);
3812
4468
  for (const candidate of candidates) {
3813
- if (existsSync2(candidate)) {
4469
+ if (existsSync5(candidate)) {
3814
4470
  return candidate;
3815
4471
  }
3816
4472
  }
@@ -3818,7 +4474,7 @@ function findGitBash() {
3818
4474
  const result = execSync("where bash", { encoding: "utf-8", stdio: ["pipe", "pipe", "ignore"] });
3819
4475
  const firstLine = result.trim().split(`
3820
4476
  `)[0];
3821
- if (firstLine && existsSync2(firstLine)) {
4477
+ if (firstLine && existsSync5(firstLine)) {
3822
4478
  return firstLine;
3823
4479
  }
3824
4480
  } catch {}
@@ -3847,9 +4503,9 @@ function buildAntigravityHookCommand(hookScriptPath, agentId, hookName, mode) {
3847
4503
  }
3848
4504
  function getAntigravityPluginRoot(agentId) {
3849
4505
  if (agentId === "antigravity-cli") {
3850
- return join(homedir(), ".gemini", "antigravity-cli", "plugins", "agentapprove");
4506
+ return join3(homedir(), ".gemini", "antigravity-cli", "plugins", "agentapprove");
3851
4507
  }
3852
- return join(homedir(), ".gemini", "config", "plugins", "agentapprove");
4508
+ return join3(homedir(), ".gemini", "config", "plugins", "agentapprove");
3853
4509
  }
3854
4510
  function getAntigravityPluginManifest() {
3855
4511
  return {
@@ -3863,7 +4519,7 @@ function buildAntigravityHooksJson(agentId, hooksDir, mode) {
3863
4519
  const hooksToInstall = mode === "observe" ? agent.hooks.filter((h) => h.name !== "Stop") : agent.hooks;
3864
4520
  const bundle = { enabled: true };
3865
4521
  for (const hook of hooksToInstall) {
3866
- const hookPath = join(hooksDir, hook.file);
4522
+ const hookPath = join3(hooksDir, hook.file);
3867
4523
  const hookCommand = buildAntigravityHookCommand(hookPath, agentId, hook.name, mode);
3868
4524
  const hookTimeout = hook.timeout ?? 30;
3869
4525
  const commandHook = {
@@ -3887,11 +4543,11 @@ function buildAntigravityHooksJson(agentId, hooksDir, mode) {
3887
4543
  function installAntigravityPluginBundle(agentId, hooksDir, mode) {
3888
4544
  const agent = AGENTS[agentId];
3889
4545
  const pluginRoot = getAntigravityPluginRoot(agentId);
3890
- const hooksPath = join(pluginRoot, "hooks.json");
3891
- const manifestPath = join(pluginRoot, "plugin.json");
4546
+ const hooksPath = join3(pluginRoot, "hooks.json");
4547
+ const manifestPath = join3(pluginRoot, "plugin.json");
3892
4548
  const backupPath = backupConfig(hooksPath);
3893
4549
  try {
3894
- mkdirSync(pluginRoot, { recursive: true });
4550
+ mkdirSync3(pluginRoot, { recursive: true });
3895
4551
  writeJsonConfig(manifestPath, getAntigravityPluginManifest());
3896
4552
  writeJsonConfig(hooksPath, buildAntigravityHooksJson(agentId, hooksDir, mode));
3897
4553
  } catch (err) {
@@ -3908,77 +4564,20 @@ function installAntigravityPluginBundle(agentId, hooksDir, mode) {
3908
4564
  function getVSCodeSettingsPaths() {
3909
4565
  const paths = [];
3910
4566
  if (process.platform === "darwin") {
3911
- paths.push({ path: join(homedir(), "Library", "Application Support", "Code", "User", "settings.json"), variant: "VS Code" });
3912
- paths.push({ path: join(homedir(), "Library", "Application Support", "Code - Insiders", "User", "settings.json"), variant: "VS Code Insiders" });
4567
+ paths.push({ path: join3(homedir(), "Library", "Application Support", "Code", "User", "settings.json"), variant: "VS Code" });
4568
+ paths.push({ path: join3(homedir(), "Library", "Application Support", "Code - Insiders", "User", "settings.json"), variant: "VS Code Insiders" });
3913
4569
  } else if (process.platform === "win32") {
3914
- const appdata = process.env.APPDATA || join(homedir(), "AppData", "Roaming");
3915
- paths.push({ path: join(appdata, "Code", "User", "settings.json"), variant: "VS Code" });
3916
- paths.push({ path: join(appdata, "Code - Insiders", "User", "settings.json"), variant: "VS Code Insiders" });
4570
+ const appdata = process.env.APPDATA || join3(homedir(), "AppData", "Roaming");
4571
+ paths.push({ path: join3(appdata, "Code", "User", "settings.json"), variant: "VS Code" });
4572
+ paths.push({ path: join3(appdata, "Code - Insiders", "User", "settings.json"), variant: "VS Code Insiders" });
3917
4573
  } else {
3918
- paths.push({ path: join(homedir(), ".config", "Code", "User", "settings.json"), variant: "VS Code" });
3919
- paths.push({ path: join(homedir(), ".config", "Code - Insiders", "User", "settings.json"), variant: "VS Code Insiders" });
4574
+ paths.push({ path: join3(homedir(), ".config", "Code", "User", "settings.json"), variant: "VS Code" });
4575
+ paths.push({ path: join3(homedir(), ".config", "Code - Insiders", "User", "settings.json"), variant: "VS Code Insiders" });
3920
4576
  }
3921
4577
  return paths;
3922
4578
  }
3923
4579
  function findInstalledVSCodeVariants() {
3924
- return getVSCodeSettingsPaths().filter(({ path }) => existsSync2(dirname2(path)));
3925
- }
3926
- function stripJsonComments(content) {
3927
- let result = "";
3928
- let inString = false;
3929
- let escaped = false;
3930
- let i = 0;
3931
- while (i < content.length) {
3932
- const ch = content[i];
3933
- if (escaped) {
3934
- result += ch;
3935
- escaped = false;
3936
- i++;
3937
- continue;
3938
- }
3939
- if (ch === "\\" && inString) {
3940
- result += ch;
3941
- escaped = true;
3942
- i++;
3943
- continue;
3944
- }
3945
- if (ch === '"') {
3946
- inString = !inString;
3947
- result += ch;
3948
- i++;
3949
- continue;
3950
- }
3951
- if (!inString) {
3952
- if (ch === "/" && content[i + 1] === "/") {
3953
- while (i < content.length && content[i] !== `
3954
- `)
3955
- i++;
3956
- continue;
3957
- }
3958
- if (ch === "/" && content[i + 1] === "*") {
3959
- i += 2;
3960
- while (i < content.length && !(content[i] === "*" && content[i + 1] === "/"))
3961
- i++;
3962
- i += 2;
3963
- continue;
3964
- }
3965
- }
3966
- result += ch;
3967
- i++;
3968
- }
3969
- result = result.replace(/,(\s*[}\]])/g, "$1");
3970
- return result;
3971
- }
3972
- function readJsoncConfig(configPath) {
3973
- if (!existsSync2(configPath))
3974
- return {};
3975
- try {
3976
- const content = readFileSync(configPath, "utf-8");
3977
- const stripped = stripJsonComments(content);
3978
- return JSON.parse(stripped);
3979
- } catch {
3980
- return {};
3981
- }
4580
+ return getVSCodeSettingsPaths().filter(({ path }) => existsSync5(dirname4(path)));
3982
4581
  }
3983
4582
  function getGithubHookEnv(agentId) {
3984
4583
  if (agentId === "vscode-agent") {
@@ -3989,9 +4588,20 @@ function getGithubHookEnv(agentId) {
3989
4588
  }
3990
4589
  return;
3991
4590
  }
4591
+ var JSONC_CONFIG_AGENTS = new Set(["gemini-cli"]);
4592
+ function readAgentConfig(agentId, configPath) {
4593
+ return JSONC_CONFIG_AGENTS.has(agentId) ? readJsoncConfig(configPath) : readJsonConfig(configPath);
4594
+ }
4595
+ function keepCommentedConfig(agentId, configPath, existingBackup = null) {
4596
+ if (!JSONC_CONFIG_AGENTS.has(agentId) || !configUsesJsoncSyntax(configPath))
4597
+ return null;
4598
+ const backupPath = existingBackup ?? backupConfig(configPath);
4599
+ return `Comments in ${configPath} are not preserved. The original, with its comments, is in ${backupPath}`;
4600
+ }
3992
4601
  function addToVSCodeHookLocations() {
3993
4602
  const hookLocation = "~/.agentapprove/hooks";
3994
4603
  const modified = [];
4604
+ const failed = [];
3995
4605
  for (const { path: settingsPath, variant } of findInstalledVSCodeVariants()) {
3996
4606
  try {
3997
4607
  const config = readJsoncConfig(settingsPath);
@@ -4001,17 +4611,20 @@ function addToVSCodeHookLocations() {
4001
4611
  }
4002
4612
  locations[hookLocation] = true;
4003
4613
  config["chat.hookFilesLocations"] = locations;
4614
+ backupConfig(settingsPath);
4004
4615
  writeJsonConfig(settingsPath, config);
4005
4616
  modified.push(`${variant}: ${settingsPath}`);
4006
- } catch {}
4617
+ } catch (error) {
4618
+ failed.push({ variant, path: settingsPath, error: configErrorMessage(error) });
4619
+ }
4007
4620
  }
4008
- return modified;
4621
+ return { modified, failed };
4009
4622
  }
4010
- function removeFromVSCodeHookLocations() {
4623
+ function removeFromVSCodeHookLocations(onFailure) {
4011
4624
  const hookLocation = "~/.agentapprove/hooks";
4012
4625
  const modified = [];
4013
4626
  for (const { path: settingsPath, variant } of getVSCodeSettingsPaths()) {
4014
- if (!existsSync2(settingsPath))
4627
+ if (!existsSync5(settingsPath))
4015
4628
  continue;
4016
4629
  try {
4017
4630
  const config = readJsoncConfig(settingsPath);
@@ -4024,9 +4637,12 @@ function removeFromVSCodeHookLocations() {
4024
4637
  } else {
4025
4638
  config["chat.hookFilesLocations"] = locations;
4026
4639
  }
4640
+ backupConfig(settingsPath);
4027
4641
  writeJsonConfig(settingsPath, config);
4028
4642
  modified.push(`${variant}: ${settingsPath}`);
4029
- } catch {}
4643
+ } catch (error) {
4644
+ onFailure?.({ variant, path: settingsPath, error: configErrorMessage(error) });
4645
+ }
4030
4646
  }
4031
4647
  return modified;
4032
4648
  }
@@ -4038,23 +4654,23 @@ function detectInstalledAgents() {
4038
4654
  installed.push(id);
4039
4655
  }
4040
4656
  } else if (id === "copilot-cli") {
4041
- if (existsSync2(join(homedir(), ".copilot"))) {
4657
+ if (existsSync5(join3(homedir(), ".copilot"))) {
4042
4658
  installed.push(id);
4043
4659
  }
4044
4660
  } else if (id === "openclaw") {
4045
- if (existsSync2(join(homedir(), ".openclaw"))) {
4661
+ if (existsSync5(join3(homedir(), ".openclaw"))) {
4046
4662
  installed.push(id);
4047
4663
  }
4048
4664
  } else if (id === "codex") {
4049
- if (existsSync2(join(homedir(), ".codex"))) {
4665
+ if (existsSync5(join3(homedir(), ".codex"))) {
4050
4666
  installed.push(id);
4051
4667
  }
4052
4668
  } else if (id === "opencode") {
4053
- if (existsSync2(getOpenCodeConfigDir())) {
4669
+ if (existsSync5(getOpenCodeConfigDir())) {
4054
4670
  installed.push(id);
4055
4671
  }
4056
4672
  } else if (id === "pi") {
4057
- if (existsSync2(join(homedir(), ".pi", "agent"))) {
4673
+ if (existsSync5(join3(homedir(), ".pi", "agent"))) {
4058
4674
  installed.push(id);
4059
4675
  } else {
4060
4676
  try {
@@ -4063,7 +4679,7 @@ function detectInstalledAgents() {
4063
4679
  } catch {}
4064
4680
  }
4065
4681
  } else if (id === "hermes") {
4066
- if (existsSync2(join(homedir(), ".hermes"))) {
4682
+ if (existsSync5(join3(homedir(), ".hermes"))) {
4067
4683
  installed.push(id);
4068
4684
  } else {
4069
4685
  try {
@@ -4072,11 +4688,11 @@ function detectInstalledAgents() {
4072
4688
  } catch {}
4073
4689
  }
4074
4690
  } else if (id === "antigravity") {
4075
- if (existsSync2(getAntigravityPluginRoot(id)) || existsSync2(join(homedir(), ".gemini", "antigravity")) || existsSync2(join(homedir(), ".gemini", "antigravity-ide")) || existsSync2("/Applications/Antigravity.app")) {
4691
+ if (existsSync5(getAntigravityPluginRoot(id)) || existsSync5(join3(homedir(), ".gemini", "antigravity")) || existsSync5(join3(homedir(), ".gemini", "antigravity-ide")) || existsSync5("/Applications/Antigravity.app")) {
4076
4692
  installed.push(id);
4077
4693
  }
4078
4694
  } else if (id === "antigravity-cli") {
4079
- if (existsSync2(join(homedir(), ".gemini", "antigravity-cli"))) {
4695
+ if (existsSync5(join3(homedir(), ".gemini", "antigravity-cli"))) {
4080
4696
  installed.push(id);
4081
4697
  } else {
4082
4698
  try {
@@ -4085,8 +4701,8 @@ function detectInstalledAgents() {
4085
4701
  } catch {}
4086
4702
  }
4087
4703
  } else {
4088
- const configDir = dirname2(agent.configPath);
4089
- if (existsSync2(configDir)) {
4704
+ const configDir = dirname4(agent.configPath);
4705
+ if (existsSync5(configDir)) {
4090
4706
  installed.push(id);
4091
4707
  }
4092
4708
  }
@@ -4246,7 +4862,7 @@ function formatHookStatusLabel(name) {
4246
4862
  return name.replace(/\*/g, "events").replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[-_]/g, " ").replace(/\s+/g, " ").trim().replace(/^./, (letter) => letter.toUpperCase());
4247
4863
  }
4248
4864
  function getAgentApproveDir() {
4249
- return join(homedir(), ".agentapprove");
4865
+ return join3(homedir(), ".agentapprove");
4250
4866
  }
4251
4867
  function uniqueRemovalTargets(targets) {
4252
4868
  const seen = new Set;
@@ -4266,7 +4882,7 @@ function buildUninstallPlan() {
4266
4882
  const pluginArtifactTargets = uniqueRemovalTargets([
4267
4883
  ...getOpenClawPluginTargets(AGENTS.openclaw.configPath),
4268
4884
  ...getOpenCodePluginTargets(getOpenCodeConfigDir(), getOpenCodeCacheDir()),
4269
- ...getAntigravityPluginTargets(join(homedir(), ".gemini"))
4885
+ ...getAntigravityPluginTargets(join3(homedir(), ".gemini"))
4270
4886
  ]);
4271
4887
  return {
4272
4888
  configuredAgents,
@@ -4338,39 +4954,39 @@ async function confirmUninstallPlan(mode, plan) {
4338
4954
  return true;
4339
4955
  }
4340
4956
  function pruneEmptyDir(path) {
4341
- if (!existsSync2(path)) {
4957
+ if (!existsSync5(path)) {
4342
4958
  return;
4343
4959
  }
4344
4960
  try {
4345
4961
  if (readdirSync2(path).length === 0) {
4346
- rmSync2(path, { recursive: false, force: true });
4962
+ rmSync3(path, { recursive: false, force: true });
4347
4963
  }
4348
4964
  } catch {}
4349
4965
  }
4350
4966
  function finalizeAgentApproveDirPurge(agentApproveDir) {
4351
- if (!existsSync2(agentApproveDir)) {
4967
+ if (!existsSync5(agentApproveDir)) {
4352
4968
  return;
4353
4969
  }
4354
4970
  try {
4355
- const stat = lstatSync(agentApproveDir);
4971
+ const stat = lstatSync2(agentApproveDir);
4356
4972
  if (stat.isSymbolicLink()) {
4357
4973
  const actualDir = realpathSync2(agentApproveDir);
4358
- if (existsSync2(actualDir) && readdirSync2(actualDir).length === 0) {
4359
- rmSync2(actualDir, { recursive: false, force: true });
4974
+ if (existsSync5(actualDir) && readdirSync2(actualDir).length === 0) {
4975
+ rmSync3(actualDir, { recursive: false, force: true });
4360
4976
  }
4361
- rmSync2(agentApproveDir, { recursive: false, force: true });
4977
+ rmSync3(agentApproveDir, { recursive: false, force: true });
4362
4978
  return;
4363
4979
  }
4364
4980
  } catch {}
4365
4981
  pruneEmptyDir(agentApproveDir);
4366
4982
  }
4367
4983
  function readExistingConfig() {
4368
- const envPath = join(getAgentApproveDir(), "env");
4369
- if (!existsSync2(envPath)) {
4984
+ const envPath = join3(getAgentApproveDir(), "env");
4985
+ if (!existsSync5(envPath)) {
4370
4986
  return null;
4371
4987
  }
4372
4988
  try {
4373
- const content = readFileSync(envPath, "utf-8");
4989
+ const content = readFileSync3(envPath, "utf-8");
4374
4990
  const config = {};
4375
4991
  for (const line of content.split(`
4376
4992
  `)) {
@@ -4426,28 +5042,28 @@ function readExistingConfig() {
4426
5042
  }
4427
5043
  function discoverE2EKeys() {
4428
5044
  const dir = getAgentApproveDir();
4429
- if (!existsSync2(dir))
5045
+ if (!existsSync5(dir))
4430
5046
  return [];
4431
5047
  const keys = [];
4432
- const currentPath = join(dir, "e2e-key");
4433
- if (existsSync2(currentPath)) {
5048
+ const currentPath = join3(dir, "e2e-key");
5049
+ if (existsSync5(currentPath)) {
4434
5050
  try {
4435
- const hex = readFileSync(currentPath, "utf-8").trim();
5051
+ const hex = readFileSync3(currentPath, "utf-8").trim();
4436
5052
  if (hex.length === 64) {
4437
- const keyId = createHash("sha256").update(Buffer.from(hex, "hex")).digest("hex").slice(0, 8);
4438
- keys.push({ keyId, keyHex: hex, path: currentPath, isCurrent: true, modifiedAt: statSync(currentPath).mtime });
5053
+ const keyId = createHash3("sha256").update(Buffer.from(hex, "hex")).digest("hex").slice(0, 8);
5054
+ keys.push({ keyId, keyHex: hex, path: currentPath, isCurrent: true, modifiedAt: statSync2(currentPath).mtime });
4439
5055
  }
4440
5056
  } catch {}
4441
5057
  }
4442
5058
  try {
4443
5059
  const files = readdirSync2(dir).filter((f) => f.startsWith("e2e-key.") && f.endsWith(".bak"));
4444
5060
  for (const file of files) {
4445
- const fullPath = join(dir, file);
5061
+ const fullPath = join3(dir, file);
4446
5062
  try {
4447
- const hex = readFileSync(fullPath, "utf-8").trim();
5063
+ const hex = readFileSync3(fullPath, "utf-8").trim();
4448
5064
  if (hex.length === 64) {
4449
- const keyId = createHash("sha256").update(Buffer.from(hex, "hex")).digest("hex").slice(0, 8);
4450
- keys.push({ keyId, keyHex: hex, path: fullPath, isCurrent: false, modifiedAt: statSync(fullPath).mtime });
5065
+ const keyId = createHash3("sha256").update(Buffer.from(hex, "hex")).digest("hex").slice(0, 8);
5066
+ keys.push({ keyId, keyHex: hex, path: fullPath, isCurrent: false, modifiedAt: statSync2(fullPath).mtime });
4451
5067
  }
4452
5068
  } catch {}
4453
5069
  }
@@ -4455,43 +5071,38 @@ function discoverE2EKeys() {
4455
5071
  return keys;
4456
5072
  }
4457
5073
  function readRotationConfig() {
4458
- const configPath = join(getAgentApproveDir(), "e2e-rotation.json");
4459
- if (!existsSync2(configPath))
5074
+ const configPath = join3(getAgentApproveDir(), "e2e-rotation.json");
5075
+ if (!existsSync5(configPath))
4460
5076
  return null;
4461
5077
  try {
4462
- return JSON.parse(readFileSync(configPath, "utf-8"));
5078
+ return JSON.parse(readFileSync3(configPath, "utf-8"));
4463
5079
  } catch {
4464
5080
  return null;
4465
5081
  }
4466
5082
  }
4467
5083
  function writeRotationConfig(config) {
4468
- const configPath = join(getAgentApproveDir(), "e2e-rotation.json");
4469
- writeFileSync(configPath, JSON.stringify(config, null, 2), { mode: 384 });
5084
+ const configPath = join3(getAgentApproveDir(), "e2e-rotation.json");
5085
+ writePrivateFile(configPath, JSON.stringify(config, null, 2));
4470
5086
  }
4471
5087
  function ensureAgentApproveDir() {
4472
5088
  const dir = getAgentApproveDir();
4473
- if (!existsSync2(dir)) {
4474
- mkdirSync(dir, { recursive: true, mode: 448 });
4475
- }
4476
- const hooksDir = join(dir, "hooks");
4477
- if (!existsSync2(hooksDir)) {
4478
- mkdirSync(hooksDir, { recursive: true, mode: 448 });
4479
- }
5089
+ ensurePrivateDir(dir);
5090
+ ensurePrivateDir(join3(dir, "hooks"));
4480
5091
  }
4481
5092
  function migrateE2ERootKey() {
4482
5093
  const dir = getAgentApproveDir();
4483
- const keyPath = join(dir, "e2e-key");
4484
- const rootKeyPath = join(dir, "e2e-root-key");
4485
- const rotationPath = join(dir, "e2e-rotation.json");
4486
- if (!existsSync2(keyPath) || existsSync2(rootKeyPath))
5094
+ const keyPath = join3(dir, "e2e-key");
5095
+ const rootKeyPath = join3(dir, "e2e-root-key");
5096
+ const rotationPath = join3(dir, "e2e-rotation.json");
5097
+ if (!existsSync5(keyPath) || existsSync5(rootKeyPath))
4487
5098
  return;
4488
5099
  try {
4489
- const keyHex = readFileSync(keyPath, "utf-8").trim();
5100
+ const keyHex = readFileSync3(keyPath, "utf-8").trim();
4490
5101
  if (keyHex.length !== 64)
4491
5102
  return;
4492
- writeFileSync(rootKeyPath, keyHex, { mode: 384 });
4493
- if (!existsSync2(rotationPath)) {
4494
- const keyId = createHash("sha256").update(Buffer.from(keyHex, "hex")).digest("hex").slice(0, 8);
5103
+ writePrivateFile(rootKeyPath, keyHex);
5104
+ if (!existsSync5(rotationPath)) {
5105
+ const keyId = createHash3("sha256").update(Buffer.from(keyHex, "hex")).digest("hex").slice(0, 8);
4495
5106
  writeRotationConfig({
4496
5107
  rootKeyId: keyId,
4497
5108
  epoch: 0,
@@ -4501,48 +5112,20 @@ function migrateE2ERootKey() {
4501
5112
  }
4502
5113
  } catch {}
4503
5114
  }
4504
- function backupConfig(configPath) {
4505
- if (!existsSync2(configPath)) {
4506
- return null;
4507
- }
4508
- const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
4509
- const backupPath = `${configPath}.backup.${timestamp}`;
4510
- copyFileSync(configPath, backupPath);
4511
- return backupPath;
4512
- }
4513
- function readJsonConfig(configPath) {
4514
- if (!existsSync2(configPath)) {
4515
- return {};
4516
- }
4517
- try {
4518
- const content = readFileSync(configPath, "utf-8");
4519
- return JSON.parse(content);
4520
- } catch {
4521
- return {};
4522
- }
4523
- }
4524
- function writeJsonConfig(configPath, config) {
4525
- const dir = dirname2(configPath);
4526
- if (!existsSync2(dir)) {
4527
- mkdirSync(dir, { recursive: true, mode: 448 });
4528
- }
4529
- writeFileSync(configPath, JSON.stringify(config, null, 2) + `
4530
- `);
4531
- }
4532
- function ensureCodexFeatureFlag(configPath = join(homedir(), ".codex", "config.toml")) {
4533
- const dir = dirname2(configPath);
4534
- if (!existsSync2(dir)) {
4535
- mkdirSync(dir, { recursive: true, mode: 448 });
5115
+ function ensureCodexFeatureFlag(configPath = join3(homedir(), ".codex", "config.toml")) {
5116
+ const dir = dirname4(configPath);
5117
+ if (!existsSync5(dir)) {
5118
+ mkdirSync3(dir, { recursive: true, mode: 448 });
4536
5119
  }
4537
5120
  const sectionHeader = "[features]";
4538
5121
  const desiredLine = "codex_hooks = true";
4539
- if (!existsSync2(configPath)) {
4540
- writeFileSync(configPath, `${sectionHeader}
5122
+ if (!existsSync5(configPath)) {
5123
+ writeFileSync2(configPath, `${sectionHeader}
4541
5124
  ${desiredLine}
4542
5125
  `, { mode: 384 });
4543
5126
  return { updated: true, backupPath: null };
4544
5127
  }
4545
- const original = readFileSync(configPath, "utf-8");
5128
+ const original = readFileSync3(configPath, "utf-8");
4546
5129
  const lines = original.split(/\r?\n/);
4547
5130
  const updatedLines = [];
4548
5131
  let inFeatures = false;
@@ -4590,16 +5173,16 @@ ${desiredLine}
4590
5173
  return { updated: false, backupPath: null };
4591
5174
  }
4592
5175
  const backupPath = backupConfig(configPath);
4593
- writeFileSync(configPath, `${updatedLines.join(`
5176
+ writeFileSync2(configPath, `${updatedLines.join(`
4594
5177
  `).replace(/\n*$/, `
4595
5178
  `)}`, { mode: 384 });
4596
5179
  return { updated: true, backupPath };
4597
5180
  }
4598
- function disableCodexFeatureFlag(configPath = join(homedir(), ".codex", "config.toml")) {
4599
- if (!existsSync2(configPath)) {
5181
+ function disableCodexFeatureFlag(configPath = join3(homedir(), ".codex", "config.toml")) {
5182
+ if (!existsSync5(configPath)) {
4600
5183
  return { updated: false, backupPath: null };
4601
5184
  }
4602
- const original = readFileSync(configPath, "utf-8");
5185
+ const original = readFileSync3(configPath, "utf-8");
4603
5186
  const updated = original.split(/\r?\n/).filter((line) => !/^\s*codex_hooks\s*=/.test(line)).join(`
4604
5187
  `).replace(/\n*$/, `
4605
5188
  `);
@@ -4607,7 +5190,7 @@ function disableCodexFeatureFlag(configPath = join(homedir(), ".codex", "config.
4607
5190
  return { updated: false, backupPath: null };
4608
5191
  }
4609
5192
  const backupPath = backupConfig(configPath);
4610
- writeFileSync(configPath, updated, { mode: 384 });
5193
+ writeFileSync2(configPath, updated, { mode: 384 });
4611
5194
  return { updated: true, backupPath };
4612
5195
  }
4613
5196
  async function createPairingSession(configuredAgents, e2eKeyId, apiBaseUrl = API_URL) {
@@ -4678,7 +5261,8 @@ async function waitForPairing(sessionCode, onProgress, onCancel, apiBaseUrl = AP
4678
5261
  privacy: result.privacy || "full",
4679
5262
  email: result.email || "",
4680
5263
  apiUrl: result.apiUrl || apiBaseUrl,
4681
- e2eServerKey: result.e2eServerKey
5264
+ e2eServerKey: result.e2eServerKey,
5265
+ effectiveConfig: parseEffectivePairingConfig(result.effectiveConfig)
4682
5266
  };
4683
5267
  }
4684
5268
  if (result.status === "expired") {
@@ -4789,7 +5373,7 @@ async function showPairingPresentation(params) {
4789
5373
  `);
4790
5374
  }
4791
5375
  function saveEnvConfig(config) {
4792
- const envPath = join(getAgentApproveDir(), "env");
5376
+ const envPath = join3(getAgentApproveDir(), "env");
4793
5377
  const configSetAt = config.configSetAt ?? Math.floor(Date.now() / 1000);
4794
5378
  const hasBackgroundPreference = config.preserved?.AGENTAPPROVE_FILTER_BACKGROUND_ACTIVITY !== undefined;
4795
5379
  const preserved = {
@@ -4831,7 +5415,7 @@ ${renderPreservedEnvSection(preserved)}
4831
5415
  # manual edits here are overwritten on the next config sync.
4832
5416
  # To change settings, run: npx agentapprove install
4833
5417
  `;
4834
- writeFileSync(envPath, content, { mode: 384 });
5418
+ writePrivateFile(envPath, content);
4835
5419
  }
4836
5420
  var KEYCHAIN_SERVICE = "com.agentapprove";
4837
5421
  var KEYCHAIN_ACCOUNT = "api-token";
@@ -4984,8 +5568,14 @@ async function installHooksForAgent(agentId, hooksDir, mode = "approval") {
4984
5568
  if (isAntigravityAgent(agentId)) {
4985
5569
  return installAntigravityPluginBundle(agentId, hooksDir, mode);
4986
5570
  }
5571
+ let config;
5572
+ try {
5573
+ config = readAgentConfig(agentId, agent.configPath);
5574
+ } catch (error) {
5575
+ return { success: false, backupPath: null, hooks: [], error: configErrorMessage(error) };
5576
+ }
4987
5577
  const backupPath = backupConfig(agent.configPath);
4988
- const config = readJsonConfig(agent.configPath);
5578
+ const commentsNote = keepCommentedConfig(agentId, agent.configPath, backupPath);
4989
5579
  const useTopLevelHooks = agent.hooksKey === "";
4990
5580
  if (!useTopLevelHooks && !config[agent.hooksKey]) {
4991
5581
  config[agent.hooksKey] = {};
@@ -4999,9 +5589,9 @@ async function installHooksForAgent(agentId, hooksDir, mode = "approval") {
4999
5589
  mode,
5000
5590
  readVersion: readOpenClawInstalledVersion,
5001
5591
  readConfig: () => {
5002
- if (!existsSync2(agent.configPath))
5592
+ if (!existsSync5(agent.configPath))
5003
5593
  return {};
5004
- const current = JSON.parse(readFileSync(agent.configPath, "utf8"));
5594
+ const current = JSON.parse(readFileSync3(agent.configPath, "utf8"));
5005
5595
  if (!current || typeof current !== "object" || Array.isArray(current)) {
5006
5596
  throw new Error("OpenClaw configuration must be a JSON object; no settings were overwritten.");
5007
5597
  }
@@ -5020,7 +5610,12 @@ async function installHooksForAgent(agentId, hooksDir, mode = "approval") {
5020
5610
  if (!installResult.success) {
5021
5611
  return { success: false, backupPath, hooks: [], error: installResult.error };
5022
5612
  }
5023
- const opencodeConfig = readJsonConfig(agent.configPath);
5613
+ let opencodeConfig;
5614
+ try {
5615
+ opencodeConfig = readJsonConfig(agent.configPath);
5616
+ } catch (error) {
5617
+ return { success: false, backupPath, hooks: [], error: configErrorMessage(error) };
5618
+ }
5024
5619
  if (!Array.isArray(opencodeConfig.plugin)) {
5025
5620
  opencodeConfig.plugin = [];
5026
5621
  }
@@ -5030,16 +5625,16 @@ async function installHooksForAgent(agentId, hooksDir, mode = "approval") {
5030
5625
  }
5031
5626
  opencodeConfig.plugin = pluginArray;
5032
5627
  writeJsonConfig(agent.configPath, opencodeConfig);
5033
- const opencodePkgPath = join(getOpenCodeConfigDir(), "package.json");
5628
+ const opencodePkgPath = join3(getOpenCodeConfigDir(), "package.json");
5034
5629
  try {
5035
- const pkgJson = JSON.parse(readFileSync(opencodePkgPath, "utf-8"));
5630
+ const pkgJson = JSON.parse(readFileSync3(opencodePkgPath, "utf-8"));
5036
5631
  const deps = pkgJson.dependencies;
5037
5632
  if (deps?.["@agentapprove/opencode"]) {
5038
5633
  delete deps["@agentapprove/opencode"];
5039
5634
  if (Object.keys(deps).length === 0) {
5040
5635
  delete pkgJson.dependencies;
5041
5636
  }
5042
- writeFileSync(opencodePkgPath, JSON.stringify(pkgJson, null, 2) + `
5637
+ writeFileSync2(opencodePkgPath, JSON.stringify(pkgJson, null, 2) + `
5043
5638
  `);
5044
5639
  }
5045
5640
  } catch (err) {
@@ -5055,7 +5650,7 @@ async function installHooksForAgent(agentId, hooksDir, mode = "approval") {
5055
5650
  }
5056
5651
  const hooksToInstall = mode === "observe" ? agent.hooks.filter((h) => !h.isApprovalHook) : agent.hooks;
5057
5652
  for (const hook of hooksToInstall) {
5058
- const hookPath = join(hooksDir, hook.file);
5653
+ const hookPath = join3(hooksDir, hook.file);
5059
5654
  const hookCommand = buildHookCommand(hookPath, agentId);
5060
5655
  if (agentId === "claude-code") {
5061
5656
  if (!hooksConfig[hook.name]) {
@@ -5343,7 +5938,7 @@ async function installHooksForAgent(agentId, hooksDir, mode = "approval") {
5343
5938
  if (agentId === "codex") {
5344
5939
  ensureCodexFeatureFlag();
5345
5940
  }
5346
- return { success: true, backupPath, hooks: installedHooks };
5941
+ return { success: true, backupPath, hooks: installedHooks, ...commentsNote ? { note: commentsNote } : {} };
5347
5942
  }
5348
5943
  function getManualInstructions(agentId, hooksDir) {
5349
5944
  const agent = AGENTS[agentId];
@@ -5354,7 +5949,7 @@ function getManualInstructions(agentId, hooksDir) {
5354
5949
  for (const hook of agent.hooks) {
5355
5950
  const hasMatcher = hook.hasMatcher ?? true;
5356
5951
  const hookTimeout = hook.timeout;
5357
- const hookPath = join(hooksDir, hook.file);
5952
+ const hookPath = join3(hooksDir, hook.file);
5358
5953
  const hookCmd = buildHookCommand(hookPath, agentId);
5359
5954
  const hookObject = {
5360
5955
  type: "command",
@@ -5372,7 +5967,7 @@ function getManualInstructions(agentId, hooksDir) {
5372
5967
  for (const hook of agent.hooks) {
5373
5968
  const hasMatcher = hook.hasMatcher ?? true;
5374
5969
  const hookTimeout = hook.timeout;
5375
- const hookPath = join(hooksDir, hook.file);
5970
+ const hookPath = join3(hooksDir, hook.file);
5376
5971
  const hookCmd = buildHookCommand(hookPath, agentId);
5377
5972
  const hookObject = {
5378
5973
  type: "command",
@@ -5392,7 +5987,7 @@ codex_hooks = true`;
5392
5987
  } else if (agentId === "cursor") {
5393
5988
  const hooksObj = {};
5394
5989
  for (const hook of agent.hooks) {
5395
- const hookPath = join(hooksDir, hook.file);
5990
+ const hookPath = join3(hooksDir, hook.file);
5396
5991
  const hookCmd = buildHookCommand(hookPath, agentId);
5397
5992
  const entry = cursorHookEntry(hook.name, hookCmd, hook.isApprovalHook);
5398
5993
  hooksObj[hook.name] = [entry];
@@ -5401,7 +5996,7 @@ codex_hooks = true`;
5401
5996
  } else if (agentId === "windsurf") {
5402
5997
  const hooksObj = {};
5403
5998
  for (const hook of agent.hooks) {
5404
- const hookPath = join(hooksDir, hook.file);
5999
+ const hookPath = join3(hooksDir, hook.file);
5405
6000
  const hookCmd = buildHookCommand(hookPath, agentId);
5406
6001
  hooksObj[hook.name] = [{ command: hookCmd, show_output: false }];
5407
6002
  }
@@ -5410,7 +6005,7 @@ codex_hooks = true`;
5410
6005
  const hooksObj = {};
5411
6006
  for (const hook of agent.hooks) {
5412
6007
  const hookTimeout = hook.timeout;
5413
- const hookCmd = buildHookCommand(join(hooksDir, hook.file), agentId);
6008
+ const hookCmd = buildHookCommand(join3(hooksDir, hook.file), agentId);
5414
6009
  const hookObject = hookTimeout ? { type: "command", command: hookCmd, timeout: hookTimeout * 1000 } : { type: "command", command: hookCmd };
5415
6010
  hooksObj[hook.name] = [{ hooks: [hookObject] }];
5416
6011
  }
@@ -5430,7 +6025,7 @@ codex_hooks = true`;
5430
6025
  } else if (agentId === "vscode-agent") {
5431
6026
  const hooksObj = {};
5432
6027
  for (const hook of agent.hooks) {
5433
- const hookPath = join(hooksDir, hook.file);
6028
+ const hookPath = join3(hooksDir, hook.file);
5434
6029
  const hookCmd = buildHookCommand(hookPath, agentId);
5435
6030
  const isApproval = hook.isApprovalHook;
5436
6031
  const hookTimeout = hook.timeout;
@@ -5451,7 +6046,7 @@ codex_hooks = true`;
5451
6046
  } else if (agentId === "copilot-cli") {
5452
6047
  const hooksObj = {};
5453
6048
  for (const hook of agent.hooks) {
5454
- const hookPath = join(hooksDir, hook.file);
6049
+ const hookPath = join3(hooksDir, hook.file);
5455
6050
  const isApproval = hook.isApprovalHook;
5456
6051
  const entry = {
5457
6052
  type: "command",
@@ -5468,7 +6063,7 @@ codex_hooks = true`;
5468
6063
  } else if (agentId === "openhands") {
5469
6064
  const hooksObj = {};
5470
6065
  for (const hook of agent.hooks) {
5471
- const hookPath = join(hooksDir, hook.file);
6066
+ const hookPath = join3(hooksDir, hook.file);
5472
6067
  const hookCmd = buildHookCommand(hookPath, agentId);
5473
6068
  const hookTimeout = hook.timeout;
5474
6069
  const isApproval = hook.isApprovalHook;
@@ -5593,7 +6188,8 @@ async function copyHookScripts2(hooksDir, token, files, options = {}) {
5593
6188
  apiUrl: options.apiUrl || API_URL,
5594
6189
  apiVersion: API_VERSION,
5595
6190
  onRateLimit: options.onRateLimit,
5596
- optionalFiles: options.optionalFiles
6191
+ optionalFiles: options.optionalFiles,
6192
+ expectedHashes: HOOK_SCRIPT_SHA256
5597
6193
  });
5598
6194
  }
5599
6195
  function readOpenClawInstalledVersion() {
@@ -5607,14 +6203,14 @@ function readOpenClawInstalledVersion() {
5607
6203
  if (result.status === 0) {
5608
6204
  const metadata = JSON.parse(result.stdout);
5609
6205
  if (metadata.plugin?.packageName === "@agentapprove/openclaw" && typeof metadata.plugin.rootDir === "string") {
5610
- return readJsonPackageVersion(join(metadata.plugin.rootDir, "package.json"));
6206
+ return readJsonPackageVersion(join3(metadata.plugin.rootDir, "package.json"));
5611
6207
  }
5612
6208
  return null;
5613
6209
  }
5614
6210
  } catch {}
5615
6211
  for (const packagePath of [
5616
- join(homedir(), ".openclaw", "npm", "node_modules", "@agentapprove", "openclaw", "package.json"),
5617
- join(homedir(), ".openclaw", "extensions", "openclaw", "package.json")
6212
+ join3(homedir(), ".openclaw", "npm", "node_modules", "@agentapprove", "openclaw", "package.json"),
6213
+ join3(homedir(), ".openclaw", "extensions", "openclaw", "package.json")
5618
6214
  ]) {
5619
6215
  const version = readJsonPackageVersion(packagePath);
5620
6216
  if (version)
@@ -5623,11 +6219,11 @@ function readOpenClawInstalledVersion() {
5623
6219
  return null;
5624
6220
  }
5625
6221
  function readJsonPackageVersion(packagePath) {
5626
- if (!existsSync2(packagePath)) {
6222
+ if (!existsSync5(packagePath)) {
5627
6223
  return null;
5628
6224
  }
5629
6225
  try {
5630
- const pkg = JSON.parse(readFileSync(packagePath, "utf-8"));
6226
+ const pkg = JSON.parse(readFileSync3(packagePath, "utf-8"));
5631
6227
  return typeof pkg.version === "string" ? pkg.version : null;
5632
6228
  } catch {
5633
6229
  return null;
@@ -5636,10 +6232,10 @@ function readJsonPackageVersion(packagePath) {
5636
6232
  function readOpenCodeInstalledVersion() {
5637
6233
  const cacheDir = getOpenCodeCacheDir();
5638
6234
  const candidates = [
5639
- join(cacheDir, "packages", "@agentapprove", `opencode@${OPENCODE_PLUGIN_VERSION}`, "node_modules", "@agentapprove", "opencode", "package.json"),
5640
- join(cacheDir, "packages", "@agentapprove", "opencode@latest", "node_modules", "@agentapprove", "opencode", "package.json"),
5641
- join(cacheDir, "node_modules", "@agentapprove", "opencode", "package.json"),
5642
- join(getOpenCodeConfigDir(), "node_modules", "@agentapprove", "opencode", "package.json")
6235
+ join3(cacheDir, "packages", "@agentapprove", `opencode@${OPENCODE_PLUGIN_VERSION}`, "node_modules", "@agentapprove", "opencode", "package.json"),
6236
+ join3(cacheDir, "packages", "@agentapprove", "opencode@latest", "node_modules", "@agentapprove", "opencode", "package.json"),
6237
+ join3(cacheDir, "node_modules", "@agentapprove", "opencode", "package.json"),
6238
+ join3(getOpenCodeConfigDir(), "node_modules", "@agentapprove", "opencode", "package.json")
5643
6239
  ];
5644
6240
  for (const candidate of candidates) {
5645
6241
  const version = readJsonPackageVersion(candidate);
@@ -5707,10 +6303,10 @@ function installOpenCodePluginViaCli() {
5707
6303
  }
5708
6304
  function readPiPinnedSpec() {
5709
6305
  try {
5710
- const settingsPath = join(homedir(), ".pi", "agent", "settings.json");
5711
- if (!existsSync2(settingsPath))
6306
+ const settingsPath = join3(homedir(), ".pi", "agent", "settings.json");
6307
+ if (!existsSync5(settingsPath))
5712
6308
  return null;
5713
- const settings = JSON.parse(readFileSync(settingsPath, "utf8"));
6309
+ const settings = JSON.parse(readFileSync3(settingsPath, "utf8"));
5714
6310
  if (!Array.isArray(settings.packages))
5715
6311
  return null;
5716
6312
  const spec = settings.packages.find((entry) => typeof entry === "string" && entry.startsWith("npm:@agentapprove/pi"));
@@ -5764,9 +6360,9 @@ function removePiPluginViaCli() {
5764
6360
  };
5765
6361
  }
5766
6362
  }
5767
- var HERMES_BUNDLE_SHA256 = "7a4b063c78bbbb9e5b60f34c7ac6eddf4715df47ef474e98367706947b3bd1db";
6363
+ var HERMES_BUNDLE_SHA256 = "e17bf4464d2f1d20c9153596a62409a88c9e5ce79312c5313d6b9e8ea721054a";
5768
6364
  var HERMES_BUNDLE_FILENAME = `agentapprove-hermes-${HERMES_PLUGIN_VERSION}.tar.gz`;
5769
- var HERMES_PLUGIN_DIR = join(homedir(), ".hermes", "plugins", "agentapprove");
6365
+ var HERMES_PLUGIN_DIR = join3(homedir(), ".hermes", "plugins", "agentapprove");
5770
6366
  function findPython() {
5771
6367
  for (const candidate of ["python3.12", "python3.11", "python3.10", "python3"]) {
5772
6368
  try {
@@ -5797,13 +6393,13 @@ function isSafeApiVersion(candidate) {
5797
6393
  return /^[a-z0-9-]+$/i.test(candidate);
5798
6394
  }
5799
6395
  function readInstallerConfig() {
5800
- const envPath = join(getAgentApproveDir(), "env");
6396
+ const envPath = join3(getAgentApproveDir(), "env");
5801
6397
  let apiUrl = API_URL;
5802
6398
  let apiVersion = "v001";
5803
6399
  let token = "";
5804
- if (existsSync2(envPath)) {
6400
+ if (existsSync5(envPath)) {
5805
6401
  try {
5806
- const content = readFileSync(envPath, "utf-8");
6402
+ const content = readFileSync3(envPath, "utf-8");
5807
6403
  for (const line of content.split(`
5808
6404
  `)) {
5809
6405
  if (line.startsWith("#"))
@@ -5870,7 +6466,7 @@ async function downloadHermesBundle(apiUrl, apiVersion, token) {
5870
6466
  }
5871
6467
  }
5872
6468
  function verifyBundleHash(bytes) {
5873
- return createHash("sha256").update(bytes).digest("hex");
6469
+ return createHash3("sha256").update(bytes).digest("hex");
5874
6470
  }
5875
6471
  function validateExtractedTree(root) {
5876
6472
  const realRoot = realpathSync2(root);
@@ -5884,7 +6480,7 @@ function validateExtractedTree(root) {
5884
6480
  return { ok: false, error: `Cannot read staged dir ${dir}: ${err instanceof Error ? err.message : String(err)}` };
5885
6481
  }
5886
6482
  for (const entry of entries) {
5887
- const fullPath = join(dir, String(entry.name));
6483
+ const fullPath = join3(dir, String(entry.name));
5888
6484
  let resolved;
5889
6485
  try {
5890
6486
  resolved = realpathSync2(fullPath);
@@ -5968,7 +6564,7 @@ function isValidHermesProfileName(name) {
5968
6564
  return name === HERMES_DEFAULT_PROFILE || HERMES_PROFILE_ID_RE.test(name);
5969
6565
  }
5970
6566
  function hermesProfilePluginDir(profile) {
5971
- return profile === HERMES_DEFAULT_PROFILE ? HERMES_PLUGIN_DIR : join(homedir(), ".hermes", "profiles", profile, "plugins", "agentapprove");
6567
+ return profile === HERMES_DEFAULT_PROFILE ? HERMES_PLUGIN_DIR : join3(homedir(), ".hermes", "profiles", profile, "plugins", "agentapprove");
5972
6568
  }
5973
6569
  function hermesEnableCmd(profile) {
5974
6570
  return profile === HERMES_DEFAULT_PROFILE ? "hermes plugins enable agentapprove" : `hermes -p ${profile} plugins enable agentapprove`;
@@ -5979,54 +6575,54 @@ function hermesDisableCmd(profile) {
5979
6575
  function stageHermesBundle(bytes, targetDir) {
5980
6576
  let tmpDir;
5981
6577
  try {
5982
- tmpDir = mkdtempSync(join(tmpdir(), "aa-hermes-"));
6578
+ tmpDir = mkdtempSync(join3(tmpdir(), "aa-hermes-"));
5983
6579
  } catch (err) {
5984
6580
  return { success: false, error: `Could not create temp directory for bundle staging: ${err instanceof Error ? err.message : String(err)}` };
5985
6581
  }
5986
- const tarballPath = join(tmpDir, HERMES_BUNDLE_FILENAME);
6582
+ const tarballPath = join3(tmpDir, HERMES_BUNDLE_FILENAME);
5987
6583
  let backupPath = null;
5988
6584
  try {
5989
- writeFileSync(tarballPath, bytes);
6585
+ writeFileSync2(tarballPath, bytes);
5990
6586
  try {
5991
6587
  runHostCommand("tar", ["-xzf", tarballPath, "-C", tmpDir, "--no-same-owner", "--no-same-permissions"]);
5992
6588
  } catch (err) {
5993
6589
  return { success: false, error: `tar extract failed: ${err instanceof Error ? err.message : String(err)}` };
5994
6590
  }
5995
- const stagedDir = join(tmpDir, "agentapprove");
5996
- if (!existsSync2(stagedDir)) {
6591
+ const stagedDir = join3(tmpDir, "agentapprove");
6592
+ if (!existsSync5(stagedDir)) {
5997
6593
  return { success: false, error: "Bundle did not contain expected `agentapprove/` directory." };
5998
6594
  }
5999
6595
  const validation = validateExtractedTree(stagedDir);
6000
6596
  if (!validation.ok) {
6001
6597
  return { success: false, error: `Bundle integrity violation: ${validation.error}` };
6002
6598
  }
6003
- mkdirSync(dirname2(targetDir), { recursive: true });
6004
- if (existsSync2(targetDir)) {
6599
+ mkdirSync3(dirname4(targetDir), { recursive: true });
6600
+ if (existsSync5(targetDir)) {
6005
6601
  backupPath = `${targetDir}.bak-${Date.now()}`;
6006
- renameSync2(targetDir, backupPath);
6602
+ renameSync4(targetDir, backupPath);
6007
6603
  }
6008
6604
  try {
6009
- renameSync2(stagedDir, targetDir);
6605
+ renameSync4(stagedDir, targetDir);
6010
6606
  } catch (err) {
6011
6607
  if (backupPath) {
6012
6608
  try {
6013
- renameSync2(backupPath, targetDir);
6609
+ renameSync4(backupPath, targetDir);
6014
6610
  backupPath = null;
6015
6611
  } catch {}
6016
6612
  }
6017
6613
  const restoreNote = backupPath ? ` Your previous install was preserved at ${backupPath} — recover with: mv "${backupPath}" "${targetDir}"` : "";
6018
6614
  return { success: false, error: `Could not install bundle to ${targetDir}: ${err instanceof Error ? err.message : String(err)}.${restoreNote}` };
6019
6615
  }
6020
- writeFileSync(join(targetDir, ".bundle-hash"), HERMES_BUNDLE_SHA256, { mode: 420 });
6616
+ writeFileSync2(join3(targetDir, ".bundle-hash"), HERMES_BUNDLE_SHA256, { mode: 420 });
6021
6617
  if (backupPath) {
6022
- rmSync2(backupPath, { recursive: true, force: true });
6618
+ rmSync3(backupPath, { recursive: true, force: true });
6023
6619
  backupPath = null;
6024
6620
  }
6025
6621
  } catch (err) {
6026
6622
  if (backupPath) {
6027
6623
  try {
6028
- rmSync2(targetDir, { recursive: true, force: true });
6029
- renameSync2(backupPath, targetDir);
6624
+ rmSync3(targetDir, { recursive: true, force: true });
6625
+ renameSync4(backupPath, targetDir);
6030
6626
  backupPath = null;
6031
6627
  } catch {}
6032
6628
  }
@@ -6034,7 +6630,7 @@ function stageHermesBundle(bytes, targetDir) {
6034
6630
  return { success: false, error: `Bundle install failed: ${err instanceof Error ? err.message : String(err)}.${restoreNote}` };
6035
6631
  } finally {
6036
6632
  try {
6037
- rmSync2(tmpDir, { recursive: true, force: true });
6633
+ rmSync3(tmpDir, { recursive: true, force: true });
6038
6634
  } catch {}
6039
6635
  }
6040
6636
  return { success: true };
@@ -6146,7 +6742,7 @@ function disableHermesPluginViaCli() {
6146
6742
  function removeHermesPluginFromProfile(profile) {
6147
6743
  const disabled = disableHermesPluginForProfile(profile);
6148
6744
  try {
6149
- rmSync2(hermesProfilePluginDir(profile), { recursive: true, force: true });
6745
+ rmSync3(hermesProfilePluginDir(profile), { recursive: true, force: true });
6150
6746
  return disabled.success ? { success: true } : { success: false, error: `disable failed: ${disabled.error || "unknown"}` };
6151
6747
  } catch (err) {
6152
6748
  return {
@@ -6157,11 +6753,11 @@ function removeHermesPluginFromProfile(profile) {
6157
6753
  }
6158
6754
  function hermesProfilePluginStatus(profile) {
6159
6755
  const dir = hermesProfilePluginDir(profile);
6160
- const installed = existsSync2(join(dir, ".bundle-hash"));
6756
+ const installed = existsSync5(join3(dir, ".bundle-hash"));
6161
6757
  let version = null;
6162
6758
  if (installed) {
6163
6759
  try {
6164
- const configPy = readFileSync(join(dir, "config.py"), "utf-8");
6760
+ const configPy = readFileSync3(join3(dir, "config.py"), "utf-8");
6165
6761
  const m = configPy.match(/^PLUGIN_VERSION\s*=\s*["']([^"']+)["']/m);
6166
6762
  version = m ? m[1] : null;
6167
6763
  } catch {}
@@ -6171,8 +6767,8 @@ function hermesProfilePluginStatus(profile) {
6171
6767
  function listHermesProfiles() {
6172
6768
  const names = new Set([HERMES_DEFAULT_PROFILE]);
6173
6769
  try {
6174
- const profilesRoot = join(homedir(), ".hermes", "profiles");
6175
- if (existsSync2(profilesRoot)) {
6770
+ const profilesRoot = join3(homedir(), ".hermes", "profiles");
6771
+ if (existsSync5(profilesRoot)) {
6176
6772
  for (const entry of readdirSync2(profilesRoot, { withFileTypes: true })) {
6177
6773
  if (entry.isDirectory() && isValidHermesProfileName(entry.name)) {
6178
6774
  names.add(entry.name);
@@ -6298,8 +6894,8 @@ function checkCommand(name) {
6298
6894
  if (isWindows()) {
6299
6895
  const gitBashPath = findGitBash();
6300
6896
  if (gitBashPath) {
6301
- execSync(`"${gitBashPath}" -c "command -v ${name}"`, { stdio: "ignore" });
6302
- return true;
6897
+ const result = spawnSync2(gitBashPath, ["-c", 'command -v "$1"', "agentapprove", name], { stdio: "ignore" });
6898
+ return result.status === 0;
6303
6899
  }
6304
6900
  execSync(`where ${name}`, { stdio: "ignore" });
6305
6901
  return true;
@@ -6544,10 +7140,10 @@ async function installCommand() {
6544
7140
  let existingKeyId = null;
6545
7141
  if (existingConfig) {
6546
7142
  existingTokenPreview = hasExistingToken ? existingConfig.token.slice(0, 15) + "..." : "Not set";
6547
- const e2eKeyPath = join(getAgentApproveDir(), "e2e-key");
6548
- if (existsSync2(e2eKeyPath)) {
6549
- const keyHex = readFileSync(e2eKeyPath, "utf-8").trim();
6550
- existingKeyId = createHash("sha256").update(Buffer.from(keyHex, "hex")).digest("hex").slice(0, 8);
7143
+ const e2eKeyPath = join3(getAgentApproveDir(), "e2e-key");
7144
+ if (existsSync5(e2eKeyPath)) {
7145
+ const keyHex = readFileSync3(e2eKeyPath, "utf-8").trim();
7146
+ existingKeyId = createHash3("sha256").update(Buffer.from(keyHex, "hex")).digest("hex").slice(0, 8);
6551
7147
  }
6552
7148
  }
6553
7149
  const existingTokenPreflight = hasExistingToken ? await runExistingTokenPreflight(existingConfig.token, pairingApiBase) : null;
@@ -6601,9 +7197,10 @@ Monitor activity, enforce policy, and approve with a tap.`, "About");
6601
7197
  const requiresFreshPair = pendingRecoveryAction !== null;
6602
7198
  const forceKeyReuseForRecovery = pendingRecoveryAction === "refresh";
6603
7199
  ensureAgentApproveDir();
6604
- const hooksDir = join(getAgentApproveDir(), "hooks");
7200
+ const hooksDir = join3(getAgentApproveDir(), "hooks");
6605
7201
  const selectedInstallConfig = getInitialInstallConfig(setupProfile, existingConfig);
6606
7202
  let token = null;
7203
+ let pairingOutcome = null;
6607
7204
  let finalPrivacy = selectedInstallConfig.privacy;
6608
7205
  let email = "";
6609
7206
  let apiUrl = pairingApiBase;
@@ -6683,7 +7280,7 @@ Monitor activity, enforce policy, and approve with a tap.`, "About");
6683
7280
  }
6684
7281
  ensureAgentApproveDir();
6685
7282
  const agentApproveDir = getAgentApproveDir();
6686
- const existingKeyPath = join(agentApproveDir, "e2e-key");
7283
+ const existingKeyPath = join3(agentApproveDir, "e2e-key");
6687
7284
  let e2eUserKey = null;
6688
7285
  let backupOldKeyTo = null;
6689
7286
  if (setupProfile === "customize" && !e2eRequired && !skipE2E) {
@@ -6698,9 +7295,9 @@ Monitor activity, enforce policy, and approve with a tap.`, "About");
6698
7295
  useE2E = e2eChoice;
6699
7296
  }
6700
7297
  if (useE2E) {
6701
- if (existsSync2(existingKeyPath)) {
6702
- const oldKeyHex = readFileSync(existingKeyPath, "utf-8").trim();
6703
- const oldKeyId = createHash("sha256").update(Buffer.from(oldKeyHex, "hex")).digest("hex").slice(0, 8);
7298
+ if (existsSync5(existingKeyPath)) {
7299
+ const oldKeyHex = readFileSync3(existingKeyPath, "utf-8").trim();
7300
+ const oldKeyId = createHash3("sha256").update(Buffer.from(oldKeyHex, "hex")).digest("hex").slice(0, 8);
6704
7301
  const autoReuseKey = forceKeyReuseForRecovery || setupProfile === "existing-config" && !requiresFreshPair;
6705
7302
  if (autoReuseKey) {
6706
7303
  e2eUserKey = oldKeyHex;
@@ -6720,19 +7317,19 @@ Monitor activity, enforce policy, and approve with a tap.`, "About");
6720
7317
  e2eUserKey = oldKeyHex;
6721
7318
  } else {
6722
7319
  if (keyAction === "backup") {
6723
- backupOldKeyTo = join(agentApproveDir, `e2e-key.${oldKeyId}.bak`);
7320
+ backupOldKeyTo = join3(agentApproveDir, `e2e-key.${oldKeyId}.bak`);
6724
7321
  }
6725
- e2eUserKey = randomBytes(32).toString("hex");
7322
+ e2eUserKey = randomBytes2(32).toString("hex");
6726
7323
  }
6727
7324
  }
6728
7325
  } else {
6729
- e2eUserKey = randomBytes(32).toString("hex");
7326
+ e2eUserKey = randomBytes2(32).toString("hex");
6730
7327
  }
6731
7328
  }
6732
7329
  if (!useE2E) {
6733
7330
  v2.info("E2E encryption disabled — event content will be visible on the web dashboard");
6734
7331
  }
6735
- const e2eKeyId = e2eUserKey ? createHash("sha256").update(Buffer.from(e2eUserKey, "hex")).digest("hex").slice(0, 8) : undefined;
7332
+ const e2eKeyId = e2eUserKey ? createHash3("sha256").update(Buffer.from(e2eUserKey, "hex")).digest("hex").slice(0, 8) : undefined;
6736
7333
  if (setupProfile === "customize") {
6737
7334
  const retentionChoice = await le({
6738
7335
  message: "Data retention - how long to keep event history",
@@ -6802,7 +7399,7 @@ Monitor activity, enforce policy, and approve with a tap.`, "About");
6802
7399
  if (setupProfile === "existing-config" && existingConfig?.configSetAt) {
6803
7400
  configSetAt = existingConfig.configSetAt;
6804
7401
  }
6805
- const e2eKeyExists = existsSync2(existingKeyPath);
7402
+ const e2eKeyExists = existsSync5(existingKeyPath);
6806
7403
  useE2E = e2eKeyExists;
6807
7404
  e2eUserKey = null;
6808
7405
  backupOldKeyTo = null;
@@ -6811,11 +7408,6 @@ Monitor activity, enforce policy, and approve with a tap.`, "About");
6811
7408
  }
6812
7409
  } else if (shouldCreateFreshPairing(connectionMethod)) {
6813
7410
  const pairingMethod = connectionMethod;
6814
- if (backupOldKeyTo) {
6815
- renameSync2(existingKeyPath, backupOldKeyTo);
6816
- v2.success(`Old key backed up to ${backupOldKeyTo}`);
6817
- backupOldKeyTo = null;
6818
- }
6819
7411
  configSetAt = Math.floor(Date.now() / 1000);
6820
7412
  const pairingConfig = {
6821
7413
  privacyTier: finalPrivacy,
@@ -6856,17 +7448,32 @@ Monitor activity, enforce policy, and approve with a tap.`, "About");
6856
7448
  he("Installation cancelled");
6857
7449
  process.exit(0);
6858
7450
  } else if (result) {
6859
- token = result.token;
6860
- if (["minimal", "summary", "full"].includes(result.privacy)) {
6861
- finalPrivacy = result.privacy;
7451
+ pairingOutcome = reconcilePairingConfig(pairingConfig, result.effectiveConfig, {
7452
+ reportedPrivacy: result.privacy,
7453
+ localE2eOn: existingConfig?.e2eEnabled !== false && existsSync5(existingKeyPath)
7454
+ });
7455
+ if (pairingOutcome.encryptionRequired) {
7456
+ pairingSpinner.stop("Paired, but this computer is not set up");
7457
+ v2.error(formatEncryptionRequiredMessage("install"));
7458
+ he("Setup is not finished.");
7459
+ process.exit(1);
6862
7460
  }
7461
+ token = result.token;
7462
+ finalPrivacy = pairingOutcome.local.privacyTier;
7463
+ retentionDays = pairingOutcome.local.retentionDays;
7464
+ failBehavior = pairingOutcome.local.failBehavior;
6863
7465
  email = result.email;
6864
7466
  apiUrl = result.apiUrl || pairingApiBase;
7467
+ if (backupOldKeyTo) {
7468
+ renameSync4(existingKeyPath, backupOldKeyTo);
7469
+ v2.success(`Old key backed up to ${backupOldKeyTo}`);
7470
+ backupOldKeyTo = null;
7471
+ }
6865
7472
  if (e2eUserKey && e2eKeyId) {
6866
- const rootKeyPath = join(agentApproveDir, "e2e-root-key");
6867
- writeFileSync(rootKeyPath, e2eUserKey, { mode: 384 });
6868
- const userKeyPath = join(agentApproveDir, "e2e-key");
6869
- writeFileSync(userKeyPath, e2eUserKey, { mode: 384 });
7473
+ const rootKeyPath = join3(agentApproveDir, "e2e-root-key");
7474
+ writePrivateFile(rootKeyPath, e2eUserKey);
7475
+ const userKeyPath = join3(agentApproveDir, "e2e-key");
7476
+ writePrivateFile(userKeyPath, e2eUserKey);
6870
7477
  writeRotationConfig({
6871
7478
  rootKeyId: e2eKeyId,
6872
7479
  epoch: 0,
@@ -6874,8 +7481,8 @@ Monitor activity, enforce policy, and approve with a tap.`, "About");
6874
7481
  startedAt: new Date().toISOString()
6875
7482
  });
6876
7483
  if (result.e2eServerKey) {
6877
- const serverKeyPath = join(agentApproveDir, "e2e-server-key");
6878
- writeFileSync(serverKeyPath, result.e2eServerKey, { mode: 384 });
7484
+ const serverKeyPath = join3(agentApproveDir, "e2e-server-key");
7485
+ writePrivateFile(serverKeyPath, result.e2eServerKey);
6879
7486
  }
6880
7487
  }
6881
7488
  if (e2eKeyId) {
@@ -6883,6 +7490,12 @@ Monitor activity, enforce policy, and approve with a tap.`, "About");
6883
7490
  }
6884
7491
  const connectedMsg = email ? `Connected! Account: ${email}, Privacy: ${finalPrivacy}` : `Connected! Privacy: ${finalPrivacy}`;
6885
7492
  pairingSpinner.stop(connectedMsg);
7493
+ const keptWarning = formatAccountKeptWarning(pairingOutcome);
7494
+ if (keptWarning)
7495
+ v2.warn(keptWarning);
7496
+ const unknownNote = formatAccountUnknownNote(pairingOutcome);
7497
+ if (unknownNote)
7498
+ v2.info(unknownNote);
6886
7499
  } else {
6887
7500
  pairingSpinner.stop("Session expired");
6888
7501
  he("Session expired. Please try again.");
@@ -6906,8 +7519,8 @@ Monitor activity, enforce policy, and approve with a tap.`, "About");
6906
7519
  privacy: finalPrivacy,
6907
7520
  retentionDays,
6908
7521
  debugLog,
6909
- configSetAt: installPreservation.letAccountWin ? 0 : configSetAt,
6910
- e2eEnabled: useE2E,
7522
+ configSetAt: installPreservation.letAccountWin || pairingOutcome?.letAccountWin ? 0 : configSetAt,
7523
+ e2eEnabled: pairingOutcome ? pairingOutcome.local.e2eEnabled : useE2E,
6911
7524
  failBehavior,
6912
7525
  preserved: installPreservation.preserved
6913
7526
  });
@@ -6945,8 +7558,8 @@ Monitor activity, enforce policy, and approve with a tap.`, "About");
6945
7558
  } else {
6946
7559
  v2.success("No hook scripts needed for the selected agents");
6947
7560
  }
6948
- const e2eKeyPath = join(agentApproveDir, "e2e-key");
6949
- const hasE2EKey = existsSync2(e2eKeyPath);
7561
+ const e2eKeyPath = join3(agentApproveDir, "e2e-key");
7562
+ const hasE2EKey = existsSync5(e2eKeyPath);
6950
7563
  if (hasE2EKey) {
6951
7564
  if (!silentlyReuseExistingToken) {
6952
7565
  if (installMode === "observe") {
@@ -6955,9 +7568,9 @@ Monitor activity, enforce policy, and approve with a tap.`, "About");
6955
7568
  v2.info("Approval mode: Commands are sent via encrypted channel for policy evaluation.");
6956
7569
  }
6957
7570
  }
6958
- const envPath = join(agentApproveDir, "env");
6959
- if (existsSync2(envPath)) {
6960
- let envContent = readFileSync(envPath, "utf-8");
7571
+ const envPath = join3(agentApproveDir, "env");
7572
+ if (existsSync5(envPath)) {
7573
+ let envContent = readFileSync3(envPath, "utf-8");
6961
7574
  if (envContent.includes("AGENTAPPROVE_E2E_MODE=")) {
6962
7575
  envContent = envContent.replace(/AGENTAPPROVE_E2E_MODE=\w+/, `AGENTAPPROVE_E2E_MODE=${installMode}`);
6963
7576
  } else {
@@ -6966,7 +7579,7 @@ Monitor activity, enforce policy, and approve with a tap.`, "About");
6966
7579
  AGENTAPPROVE_E2E_MODE=${installMode}
6967
7580
  `;
6968
7581
  }
6969
- writeFileSync(envPath, envContent, { mode: 384 });
7582
+ writePrivateFile(envPath, envContent);
6970
7583
  }
6971
7584
  }
6972
7585
  const installMethod = await le({
@@ -6990,7 +7603,7 @@ AGENTAPPROVE_E2E_MODE=${installMode}
6990
7603
  filesToModify.push(agent.configPath);
6991
7604
  }
6992
7605
  if (agentId === "codex") {
6993
- filesToModify.push(join(homedir(), ".codex", "config.toml"));
7606
+ filesToModify.push(join3(homedir(), ".codex", "config.toml"));
6994
7607
  }
6995
7608
  if (agentId === "opencode") {
6996
7609
  filesToModify.push("OpenCode plugin cache");
@@ -7043,11 +7656,21 @@ Timestamped backups will be created.`);
7043
7656
  v2.success(`${agentName}: ${installedHookNames}${backupMsg}`);
7044
7657
  else
7045
7658
  spinner.stop(`${agentName}: ${installedHookNames}${backupMsg}`);
7659
+ if (result.note)
7660
+ v2.info(result.note);
7046
7661
  if (agentId === "vscode-agent") {
7047
7662
  const vsCodeSpinner = _2();
7048
7663
  vsCodeSpinner.start("Registering hook path in VS Code settings");
7049
- const modifiedPaths = addToVSCodeHookLocations();
7050
- if (modifiedPaths.length > 0) {
7664
+ const { modified: modifiedPaths, failed: failedSettings } = addToVSCodeHookLocations();
7665
+ if (failedSettings.length > 0) {
7666
+ failedSetupAgents.add(agentId);
7667
+ vsCodeSpinner.stop(modifiedPaths.length > 0 ? `Registered in: ${modifiedPaths.join(", ")}` : source_default.yellow("VS Code settings were not updated"));
7668
+ for (const failure of failedSettings) {
7669
+ v2.warn(`${failure.variant} settings were not changed.
7670
+ ` + ` ${failure.error}
7671
+ ` + ` Or add "~/.agentapprove/hooks": true under "chat.hookFilesLocations" yourself.`);
7672
+ }
7673
+ } else if (modifiedPaths.length > 0) {
7051
7674
  vsCodeSpinner.stop(`Registered in: ${modifiedPaths.join(", ")}`);
7052
7675
  } else {
7053
7676
  const variants = findInstalledVSCodeVariants();
@@ -7109,6 +7732,9 @@ Timestamped backups will be created.`);
7109
7732
  ` + ` 6. hermes config set plugins.entries.agentapprove.allow_gateway_injection true
7110
7733
  ` + ` 7. hermes plugins enable agentapprove
7111
7734
  ` + ` Then re-run: npx agentapprove`);
7735
+ } else if (result.error) {
7736
+ v2.warn(`${agent.name} was not set up.
7737
+ ` + ` ${result.error}`);
7112
7738
  }
7113
7739
  }
7114
7740
  }
@@ -7123,7 +7749,7 @@ Timestamped backups will be created.`);
7123
7749
  });
7124
7750
  }
7125
7751
  const integrationChecks = inspectSetup(selectedAgents).map((item) => failedSetupAgents.has(item.agent) ? { ...item, status: "failed", reason: "invalid_config" } : item);
7126
- writeFileSync(join(getAgentApproveDir(), "setup-agents.json"), JSON.stringify(selectedAgents), { mode: 384 });
7752
+ writePrivateFile(join3(getAgentApproveDir(), "setup-agents.json"), JSON.stringify(selectedAgents));
7127
7753
  const modeDesc = hasE2EKey ? installMode === "observe" ? source_default.cyan("E2E Observe Mode") + " - All events encrypted, no approval hooks" : source_default.green("E2E Approval Mode") + " - Commands sent via encrypted channel for policy evaluation" : "Standard mode (no E2E keys found)";
7128
7754
  me(`Mode: ${modeDesc}
7129
7755
 
@@ -7149,14 +7775,14 @@ function inspectSetup(agentIds) {
7149
7775
  return result("manual", "manual_step");
7150
7776
  if (!existing?.token)
7151
7777
  return result("failed", "not_configured");
7152
- if (existsSync2(join(getAgentApproveDir(), DISABLED_STATE_FILENAME)))
7778
+ if (existsSync5(join3(getAgentApproveDir(), DISABLED_STATE_FILENAME)))
7153
7779
  return result("failed", "disabled");
7154
7780
  try {
7155
7781
  if (existing.e2eEnabled !== false) {
7156
- const keyPath = join(getAgentApproveDir(), "e2e-key");
7157
- if (!existsSync2(keyPath))
7782
+ const keyPath = join3(getAgentApproveDir(), "e2e-key");
7783
+ if (!existsSync5(keyPath))
7158
7784
  return result("failed", "missing_files");
7159
- if (!/^[a-fA-F0-9]{64}$/.test(readFileSync(keyPath, "utf8").trim()))
7785
+ if (!/^[a-fA-F0-9]{64}$/.test(readFileSync3(keyPath, "utf8").trim()))
7160
7786
  return result("failed", "invalid_config");
7161
7787
  }
7162
7788
  if (agentId === "pi" || agentId === "hermes") {
@@ -7164,10 +7790,10 @@ function inspectSetup(agentIds) {
7164
7790
  const ready = agentId === "pi" ? output.includes("@agentapprove/pi") : /^.*agentapprove.*enabled/im.test(output);
7165
7791
  return result(ready ? "ready" : "failed", ready ? "verified" : "not_configured");
7166
7792
  }
7167
- const configPath = agentId === "copilot-cli" ? join(process.cwd(), ".github/hooks/agentapprove.json") : agent.configPath;
7168
- if (agentId === "copilot-cli" && !existsSync2(configPath))
7793
+ const configPath = agentId === "copilot-cli" ? join3(process.cwd(), ".github/hooks/agentapprove.json") : agent.configPath;
7794
+ if (agentId === "copilot-cli" && !existsSync5(configPath))
7169
7795
  return result("manual", "manual_step");
7170
- const config = readJsonConfig(configPath);
7796
+ const config = readAgentConfig(agentId, configPath);
7171
7797
  if (agentId === "opencode") {
7172
7798
  const ready = Array.isArray(config.plugin) && config.plugin.some((p) => typeof p === "string" && p.includes("@agentapprove/opencode"));
7173
7799
  return result(ready ? "ready" : "failed", ready ? "verified" : "not_configured");
@@ -7179,40 +7805,45 @@ function inspectSetup(agentIds) {
7179
7805
  }
7180
7806
  if (agentId === "vscode-agent") {
7181
7807
  const registered = findInstalledVSCodeVariants().some(({ path }) => {
7182
- const locations = readJsoncConfig(path)["chat.hookFilesLocations"];
7183
- return locations?.["~/.agentapprove/hooks"] === true || locations?.[join(getAgentApproveDir(), "hooks")] === true;
7808
+ let locations;
7809
+ try {
7810
+ locations = readJsoncConfig(path)["chat.hookFilesLocations"];
7811
+ } catch {
7812
+ return false;
7813
+ }
7814
+ return locations?.["~/.agentapprove/hooks"] === true || locations?.[join3(getAgentApproveDir(), "hooks")] === true;
7184
7815
  });
7185
7816
  if (!registered)
7186
7817
  return result("manual", "manual_step");
7187
7818
  }
7188
- if (agentId === "codex" && !/codex_hooks\s*=\s*true/.test(readFileSync(join(homedir(), ".codex/config.toml"), "utf8")))
7819
+ if (agentId === "codex" && !/codex_hooks\s*=\s*true/.test(readFileSync3(join3(homedir(), ".codex/config.toml"), "utf8")))
7189
7820
  return result("failed", "not_configured");
7190
7821
  const filesReady = (file) => {
7191
- const path = join(getAgentApproveDir(), "hooks", file);
7192
- return existsSync2(path) && statSync(path).size > 0 && (!file.endsWith(".sh") || (statSync(path).mode & 73) !== 0);
7822
+ const path = join3(getAgentApproveDir(), "hooks", file);
7823
+ return existsSync5(path) && statSync2(path).size > 0 && (!file.endsWith(".sh") || (statSync2(path).mode & 73) !== 0);
7193
7824
  };
7194
7825
  if (!SHARED_HOOK_FILES.filter((file) => !BACKGROUND_FILTER_FILES.includes(file)).every(filesReady))
7195
7826
  return result("failed", "missing_files");
7196
7827
  if (spawnSync2("bash", ["-c", "command -v curl >/dev/null && command -v jq >/dev/null && command -v openssl >/dev/null"], { timeout: 5000 }).status !== 0)
7197
7828
  return result("failed", "missing_dependency");
7198
7829
  if (isAntigravityAgent(agentId)) {
7199
- if (!existsSync2(join(getAntigravityPluginRoot(agentId), "plugin.json")))
7830
+ if (!existsSync5(join3(getAntigravityPluginRoot(agentId), "plugin.json")))
7200
7831
  return result("failed", "missing_files");
7201
7832
  const mode = existing.e2eMode ?? "approval";
7202
7833
  const hooks = mode === "observe" ? agent.hooks.filter((h) => h.name !== "Stop") : agent.hooks;
7203
- return checkHookConfiguration(agentId, config, "agentapprove", hooks, "approval", filesReady, (file, name) => buildAntigravityHookCommand(join(getAgentApproveDir(), "hooks", file), agentId, name, mode));
7834
+ return checkHookConfiguration(agentId, config, "agentapprove", hooks, "approval", filesReady, (file, name) => buildAntigravityHookCommand(join3(getAgentApproveDir(), "hooks", file), agentId, name, mode));
7204
7835
  }
7205
- return checkHookConfiguration(agentId, config, agent.hooksKey, agent.hooks, existing.e2eMode ?? "approval", filesReady, (file) => buildHookCommand(join(getAgentApproveDir(), "hooks", file), agentId));
7836
+ return checkHookConfiguration(agentId, config, agent.hooksKey, agent.hooks, existing.e2eMode ?? "approval", filesReady, (file) => buildHookCommand(join3(getAgentApproveDir(), "hooks", file), agentId));
7206
7837
  } catch {
7207
7838
  return result("failed", "invalid_config");
7208
7839
  }
7209
7840
  });
7210
7841
  }
7211
7842
  async function checkSetupCommand() {
7212
- const selectionFile = join(getAgentApproveDir(), "setup-agents.json");
7843
+ const selectionFile = join3(getAgentApproveDir(), "setup-agents.json");
7213
7844
  let agents;
7214
7845
  try {
7215
- agents = JSON.parse(readFileSync(selectionFile, "utf8")).filter((id) => typeof id === "string" && (id in AGENTS));
7846
+ agents = JSON.parse(readFileSync3(selectionFile, "utf8")).filter((id) => typeof id === "string" && (id in AGENTS));
7216
7847
  } catch {
7217
7848
  agents = detectInstalledAgents();
7218
7849
  }
@@ -7322,16 +7953,16 @@ async function statusCommand() {
7322
7953
  console.log(source_default.cyan(`
7323
7954
  Agent Approve Status
7324
7955
  `));
7325
- if (existsSync2(join(getAgentApproveDir(), DISABLED_STATE_FILENAME))) {
7956
+ if (existsSync5(join3(getAgentApproveDir(), DISABLED_STATE_FILENAME))) {
7326
7957
  console.log(source_default.yellow(" Disabled: hooks and plugins are deregistered from your agents."));
7327
7958
  console.log(source_default.dim(" Run `npx agentapprove enable` to restore them.\n"));
7328
7959
  }
7329
- const envPath = join(getAgentApproveDir(), "env");
7330
- if (!existsSync2(envPath)) {
7960
+ const envPath = join3(getAgentApproveDir(), "env");
7961
+ if (!existsSync5(envPath)) {
7331
7962
  console.log(source_default.yellow(" Not configured. Run `npx agentapprove` to set up.\n"));
7332
7963
  return;
7333
7964
  }
7334
- const envContent = readFileSync(envPath, "utf-8");
7965
+ const envContent = readFileSync3(envPath, "utf-8");
7335
7966
  const lines = envContent.split(`
7336
7967
  `);
7337
7968
  let envToken = "";
@@ -7351,15 +7982,15 @@ async function statusCommand() {
7351
7982
  }
7352
7983
  }
7353
7984
  await syncKeychainTokenWithEnv(envToken);
7354
- const e2eKeyFile = join(getAgentApproveDir(), "e2e-key");
7355
- const e2eServerKeyFile = join(getAgentApproveDir(), "e2e-server-key");
7356
- if (existsSync2(e2eKeyFile)) {
7985
+ const e2eKeyFile = join3(getAgentApproveDir(), "e2e-key");
7986
+ const e2eServerKeyFile = join3(getAgentApproveDir(), "e2e-server-key");
7987
+ if (existsSync5(e2eKeyFile)) {
7357
7988
  console.log(` ${source_default.green("✓")} E2E user key: installed`);
7358
7989
  }
7359
- if (existsSync2(e2eServerKeyFile)) {
7990
+ if (existsSync5(e2eServerKeyFile)) {
7360
7991
  console.log(` ${source_default.green("✓")} E2E server key: installed`);
7361
7992
  }
7362
- if (!existsSync2(e2eKeyFile) && !existsSync2(e2eServerKeyFile)) {
7993
+ if (!existsSync5(e2eKeyFile) && !existsSync5(e2eServerKeyFile)) {
7363
7994
  console.log(` ${source_default.dim(" E2E encryption: not configured")}`);
7364
7995
  }
7365
7996
  console.log();
@@ -7394,8 +8025,14 @@ async function statusCommand() {
7394
8025
  } catch {}
7395
8026
  continue;
7396
8027
  }
7397
- if (existsSync2(agent.configPath)) {
7398
- const config = readJsonConfig(agent.configPath);
8028
+ if (existsSync5(agent.configPath)) {
8029
+ let config;
8030
+ try {
8031
+ config = readAgentConfig(agentId, agent.configPath);
8032
+ } catch (error) {
8033
+ console.log(` ${source_default.yellow("⚠")} ${agent.name}: ${configErrorMessage(error)}`);
8034
+ continue;
8035
+ }
7399
8036
  if (agentId === "opencode") {
7400
8037
  const pluginConfig = config.plugin;
7401
8038
  if (Array.isArray(pluginConfig) && pluginConfig.some((entry) => typeof entry === "string" && entry.includes("@agentapprove/opencode"))) {
@@ -7446,12 +8083,12 @@ function sleepMsSync(ms) {
7446
8083
  function acquireDisabledStateMergeLock(lockPath) {
7447
8084
  for (let attempt = 0;attempt < 40; attempt++) {
7448
8085
  try {
7449
- mkdirSync(lockPath);
8086
+ mkdirSync3(lockPath);
7450
8087
  return true;
7451
8088
  } catch {
7452
8089
  try {
7453
- if (Date.now() - statSync(lockPath).mtimeMs > 1e4) {
7454
- rmSync2(lockPath, { recursive: true, force: true });
8090
+ if (Date.now() - statSync2(lockPath).mtimeMs > 1e4) {
8091
+ rmSync3(lockPath, { recursive: true, force: true });
7455
8092
  continue;
7456
8093
  }
7457
8094
  } catch {
@@ -7464,10 +8101,10 @@ function acquireDisabledStateMergeLock(lockPath) {
7464
8101
  }
7465
8102
  async function disableCommand() {
7466
8103
  const aaDir = getAgentApproveDir();
7467
- const statePath = join(aaDir, DISABLED_STATE_FILENAME);
8104
+ const statePath = join3(aaDir, DISABLED_STATE_FILENAME);
7468
8105
  let hasExistingRecord = false;
7469
8106
  try {
7470
- readFileSync(statePath);
8107
+ readFileSync3(statePath);
7471
8108
  hasExistingRecord = true;
7472
8109
  } catch {
7473
8110
  hasExistingRecord = false;
@@ -7479,7 +8116,7 @@ async function disableCommand() {
7479
8116
  return;
7480
8117
  }
7481
8118
  const existingConfig = readExistingConfig();
7482
- const legacyDisabledEnv = existsSync2(join(aaDir, "env.disabled"));
8119
+ const legacyDisabledEnv = existsSync5(join3(aaDir, "env.disabled"));
7483
8120
  console.log(source_default.cyan(`
7484
8121
  Disabling Agent Approve...
7485
8122
  `));
@@ -7514,7 +8151,7 @@ async function disableCommand() {
7514
8151
  agents: records
7515
8152
  };
7516
8153
  try {
7517
- writeFileSync(statePath, JSON.stringify(state, null, 2) + `
8154
+ writeFileSync2(statePath, JSON.stringify(state, null, 2) + `
7518
8155
  `, { mode: 384, flag: "wx" });
7519
8156
  } catch (err) {
7520
8157
  let failed = true;
@@ -7522,18 +8159,18 @@ async function disableCommand() {
7522
8159
  const lockPath = `${statePath}.lock`;
7523
8160
  if (acquireDisabledStateMergeLock(lockPath)) {
7524
8161
  try {
7525
- const existing = parseDisabledState(readFileSync(statePath, "utf-8"));
8162
+ const existing = parseDisabledState(readFileSync3(statePath, "utf-8"));
7526
8163
  const merged = existing ? mergeDisabledStates(existing, state) : state;
7527
8164
  const tmpPath = `${statePath}.tmp-${process.pid}`;
7528
- writeFileSync(tmpPath, JSON.stringify(merged, null, 2) + `
8165
+ writeFileSync2(tmpPath, JSON.stringify(merged, null, 2) + `
7529
8166
  `, { mode: 384 });
7530
- renameSync2(tmpPath, statePath);
8167
+ renameSync4(tmpPath, statePath);
7531
8168
  failed = false;
7532
8169
  } catch {
7533
8170
  failed = true;
7534
8171
  } finally {
7535
8172
  try {
7536
- rmSync2(lockPath, { recursive: true, force: true });
8173
+ rmSync3(lockPath, { recursive: true, force: true });
7537
8174
  } catch {}
7538
8175
  }
7539
8176
  }
@@ -7551,7 +8188,7 @@ async function disableCommand() {
7551
8188
  ✓ Agent Approve disabled.`));
7552
8189
  console.log(source_default.dim(" Hooks and plugins are deregistered from your agents, so Agent Approve no longer runs."));
7553
8190
  console.log(source_default.dim(" Local state (pairing, settings, E2E keys, hook scripts) is kept in ~/.agentapprove."));
7554
- if (existsSync2(join(aaDir, "copilot-cli-hooks.json"))) {
8191
+ if (existsSync5(join3(aaDir, "copilot-cli-hooks.json"))) {
7555
8192
  console.log(source_default.yellow(" Note: per-repo GitHub Copilot hooks (.github/hooks/agentapprove.json, added with `init-repo`)"));
7556
8193
  console.log(source_default.yellow(" cannot be reached from here and stay active until you remove them in each repo."));
7557
8194
  }
@@ -7562,9 +8199,15 @@ async function disableCommand() {
7562
8199
  }
7563
8200
  function disableAgent(agentId, agent, records, warnings) {
7564
8201
  if (agentId === "pi") {
7565
- if (!existsSync2(agent.configPath))
8202
+ if (!existsSync5(agent.configPath))
7566
8203
  return;
7567
- const settings = readJsonConfig(agent.configPath);
8204
+ let settings;
8205
+ try {
8206
+ settings = readJsonConfig(agent.configPath);
8207
+ } catch (error) {
8208
+ warnings.push(`${agent.name}: ${configErrorMessage(error)}`);
8209
+ return;
8210
+ }
7568
8211
  const removal = removePiPackageEntries(settings);
7569
8212
  if (removal.modified) {
7570
8213
  writeJsonConfig(agent.configPath, settings);
@@ -7593,10 +8236,10 @@ function disableAgent(agentId, agent, records, warnings) {
7593
8236
  }
7594
8237
  if (isAntigravityAgent(agentId)) {
7595
8238
  const pluginRoot = getAntigravityPluginRoot(agentId);
7596
- if (!existsSync2(pluginRoot))
8239
+ if (!existsSync5(pluginRoot))
7597
8240
  return;
7598
8241
  try {
7599
- rmSync2(pluginRoot, { recursive: true, force: true });
8242
+ rmSync3(pluginRoot, { recursive: true, force: true });
7600
8243
  records.push({ agentId, kind: "hooks" });
7601
8244
  console.log(` ${source_default.green("✓")} ${agent.name}: plugin deregistered`);
7602
8245
  } catch (err) {
@@ -7605,7 +8248,9 @@ function disableAgent(agentId, agent, records, warnings) {
7605
8248
  return;
7606
8249
  }
7607
8250
  if (agentId === "vscode-agent") {
7608
- const removedVSCode = removeFromVSCodeHookLocations();
8251
+ const removedVSCode = removeFromVSCodeHookLocations((failure) => {
8252
+ warnings.push(`${agent.name} (${failure.variant}): ${failure.error}`);
8253
+ });
7609
8254
  if (removedVSCode.length > 0) {
7610
8255
  records.push({ agentId, kind: "vscode_hook_location" });
7611
8256
  for (const path of removedVSCode) {
@@ -7617,9 +8262,15 @@ function disableAgent(agentId, agent, records, warnings) {
7617
8262
  if (agentId === "copilot-cli") {
7618
8263
  return;
7619
8264
  }
7620
- if (!existsSync2(agent.configPath))
8265
+ if (!existsSync5(agent.configPath))
7621
8266
  return;
7622
- const config = readJsonConfig(agent.configPath);
8267
+ let config;
8268
+ try {
8269
+ config = readAgentConfig(agentId, agent.configPath);
8270
+ } catch (error) {
8271
+ warnings.push(`${agent.name}: ${configErrorMessage(error)}`);
8272
+ return;
8273
+ }
7623
8274
  if (agentId === "openclaw") {
7624
8275
  const flip = disableOpenClawEntries(config);
7625
8276
  if (flip.modified) {
@@ -7650,9 +8301,12 @@ function disableAgent(agentId, agent, records, warnings) {
7650
8301
  const hooksConfig = useTopLevelHooks ? config : config[agent.hooksKey] ?? {};
7651
8302
  const modified = removeAgentApproveHookEntries(hooksConfig, agent.hooks.map((hook) => hook.name));
7652
8303
  if (modified) {
8304
+ const commentsNote = keepCommentedConfig(agentId, agent.configPath);
7653
8305
  writeJsonConfig(agent.configPath, config);
7654
8306
  records.push({ agentId, kind: "hooks" });
7655
8307
  console.log(` ${source_default.green("✓")} ${agent.name}: hooks deregistered`);
8308
+ if (commentsNote)
8309
+ console.log(source_default.dim(` ${commentsNote}`));
7656
8310
  if (agentId === "codex" && Object.keys(hooksConfig).length === 0) {
7657
8311
  const codexFlag = disableCodexFeatureFlag();
7658
8312
  if (codexFlag.updated) {
@@ -7661,24 +8315,33 @@ function disableAgent(agentId, agent, records, warnings) {
7661
8315
  }
7662
8316
  }
7663
8317
  }
8318
+ function readRestorableConfig(agent, record, failures) {
8319
+ try {
8320
+ return readJsonConfig(agent.configPath);
8321
+ } catch (error) {
8322
+ failures.push(record);
8323
+ console.log(` ${source_default.yellow("⚠")} ${agent.name}: could not restore the registration. ${configErrorMessage(error)}`);
8324
+ return null;
8325
+ }
8326
+ }
7664
8327
  async function enableCommand() {
7665
8328
  const aaDir = getAgentApproveDir();
7666
- const envPath = join(aaDir, "env");
7667
- const legacyDisabledPath = join(aaDir, "env.disabled");
7668
- const statePath = join(aaDir, DISABLED_STATE_FILENAME);
7669
- if (!existsSync2(envPath) && existsSync2(legacyDisabledPath)) {
7670
- renameSync2(legacyDisabledPath, envPath);
8329
+ const envPath = join3(aaDir, "env");
8330
+ const legacyDisabledPath = join3(aaDir, "env.disabled");
8331
+ const statePath = join3(aaDir, DISABLED_STATE_FILENAME);
8332
+ if (!existsSync5(envPath) && existsSync5(legacyDisabledPath)) {
8333
+ renameSync4(legacyDisabledPath, envPath);
7671
8334
  console.log(source_default.green(`
7672
8335
  ✓ Restored ~/.agentapprove/env (legacy disable).`));
7673
8336
  }
7674
8337
  let stateRaw = null;
7675
8338
  try {
7676
- stateRaw = readFileSync(statePath, "utf-8");
8339
+ stateRaw = readFileSync3(statePath, "utf-8");
7677
8340
  } catch {
7678
8341
  stateRaw = null;
7679
8342
  }
7680
8343
  if (stateRaw === null) {
7681
- if (existsSync2(envPath)) {
8344
+ if (existsSync5(envPath)) {
7682
8345
  console.log(source_default.yellow(`
7683
8346
  Already enabled.
7684
8347
  `));
@@ -7689,7 +8352,7 @@ async function enableCommand() {
7689
8352
  }
7690
8353
  const state = parseDisabledState(stateRaw);
7691
8354
  if (!state) {
7692
- rmSync2(statePath, { force: true });
8355
+ rmSync3(statePath, { force: true });
7693
8356
  console.log(source_default.yellow(`
7694
8357
  The disable record was unreadable, so registrations were not restored automatically.`));
7695
8358
  console.log(source_default.dim(" Run `npx agentapprove install` to re-register hooks and plugins (your pairing is kept).\n"));
@@ -7698,7 +8361,7 @@ async function enableCommand() {
7698
8361
  console.log(source_default.cyan(`
7699
8362
  Re-enabling Agent Approve...
7700
8363
  `));
7701
- const hooksDir = join(aaDir, "hooks");
8364
+ const hooksDir = join3(aaDir, "hooks");
7702
8365
  const failures = [];
7703
8366
  for (const record of state.agents) {
7704
8367
  const agent = AGENTS[record.agentId];
@@ -7709,7 +8372,7 @@ async function enableCommand() {
7709
8372
  }
7710
8373
  switch (record.kind) {
7711
8374
  case "hooks": {
7712
- if (!existsSync2(hooksDir)) {
8375
+ if (!existsSync5(hooksDir)) {
7713
8376
  failures.push(record);
7714
8377
  console.log(` ${source_default.yellow("⚠")} ${agent.name}: ~/.agentapprove/hooks is missing. Run \`npx agentapprove install\` to re-download hook scripts.`);
7715
8378
  break;
@@ -7717,6 +8380,8 @@ async function enableCommand() {
7717
8380
  const result = await installHooksForAgent(record.agentId, hooksDir, state.mode);
7718
8381
  if (result.success) {
7719
8382
  console.log(` ${source_default.green("✓")} ${agent.name}: hooks re-registered`);
8383
+ if (result.note)
8384
+ console.log(source_default.dim(` ${result.note}`));
7720
8385
  } else {
7721
8386
  failures.push(record);
7722
8387
  console.log(` ${source_default.yellow("⚠")} ${agent.name}: could not re-register hooks (${result.error || "unknown error"})`);
@@ -7724,20 +8389,28 @@ async function enableCommand() {
7724
8389
  break;
7725
8390
  }
7726
8391
  case "vscode_hook_location": {
7727
- const modifiedPaths = addToVSCodeHookLocations();
8392
+ const { modified: modifiedPaths, failed: failedSettings } = addToVSCodeHookLocations();
7728
8393
  if (modifiedPaths.length > 0) {
7729
8394
  console.log(` ${source_default.green("✓")} ${agent.name}: hook path re-registered in ${modifiedPaths.join(", ")}`);
7730
- } else {
8395
+ } else if (failedSettings.length === 0) {
7731
8396
  console.log(` ${source_default.green("✓")} ${agent.name}: hook path already registered`);
7732
8397
  }
8398
+ if (failedSettings.length > 0) {
8399
+ failures.push(record);
8400
+ for (const failure of failedSettings) {
8401
+ console.log(` ${source_default.yellow("⚠")} ${agent.name} (${failure.variant}): could not re-register the hook path. ${failure.error}`);
8402
+ }
8403
+ }
7733
8404
  break;
7734
8405
  }
7735
8406
  case "openclaw_entries": {
7736
- if (!existsSync2(agent.configPath)) {
8407
+ if (!existsSync5(agent.configPath)) {
7737
8408
  console.log(` ${source_default.yellow("⚠")} ${agent.name}: config not found; skipping`);
7738
8409
  break;
7739
8410
  }
7740
- const config = readJsonConfig(agent.configPath);
8411
+ const config = readRestorableConfig(agent, record, failures);
8412
+ if (!config)
8413
+ break;
7741
8414
  if (enableOpenClawEntries(config, record.entryKeys ?? [])) {
7742
8415
  writeJsonConfig(agent.configPath, config);
7743
8416
  }
@@ -7745,7 +8418,9 @@ async function enableCommand() {
7745
8418
  break;
7746
8419
  }
7747
8420
  case "opencode_plugin": {
7748
- const config = readJsonConfig(agent.configPath);
8421
+ const config = readRestorableConfig(agent, record, failures);
8422
+ if (!config)
8423
+ break;
7749
8424
  if (addOpenCodePluginEntries(config, record.specs ?? [])) {
7750
8425
  writeJsonConfig(agent.configPath, config);
7751
8426
  }
@@ -7756,7 +8431,9 @@ async function enableCommand() {
7756
8431
  break;
7757
8432
  }
7758
8433
  case "pi_packages": {
7759
- const settings = readJsonConfig(agent.configPath);
8434
+ const settings = readRestorableConfig(agent, record, failures);
8435
+ if (!settings)
8436
+ break;
7760
8437
  if (addPiPackageEntries(settings, record.specs ?? [])) {
7761
8438
  writeJsonConfig(agent.configPath, settings);
7762
8439
  }
@@ -7789,25 +8466,25 @@ async function enableCommand() {
7789
8466
  }
7790
8467
  if (failures.length > 0) {
7791
8468
  const remaining = { ...state, agents: failures };
7792
- writeFileSync(statePath, JSON.stringify(remaining, null, 2) + `
7793
- `, { mode: 384 });
8469
+ writePrivateFile(statePath, JSON.stringify(remaining, null, 2) + `
8470
+ `);
7794
8471
  console.log(source_default.yellow("\n Agent Approve is partially re-enabled. Fix the warnings above and re-run `npx agentapprove enable`.\n"));
7795
8472
  return;
7796
8473
  }
7797
- rmSync2(statePath, { force: true });
8474
+ rmSync3(statePath, { force: true });
7798
8475
  console.log(source_default.green(`
7799
8476
  ✓ Agent Approve enabled.
7800
8477
  `));
7801
8478
  }
7802
8479
  function removeOpenCodeLegacyDependency() {
7803
- const opencodePkgPath = join(getOpenCodeConfigDir(), "package.json");
8480
+ const opencodePkgPath = join3(getOpenCodeConfigDir(), "package.json");
7804
8481
  try {
7805
- const pkgJson = JSON.parse(readFileSync(opencodePkgPath, "utf-8"));
8482
+ const pkgJson = JSON.parse(readFileSync3(opencodePkgPath, "utf-8"));
7806
8483
  const deps = pkgJson.dependencies;
7807
8484
  const version = deps?.["@agentapprove/opencode"];
7808
8485
  if (deps && version) {
7809
8486
  delete deps["@agentapprove/opencode"];
7810
- writeFileSync(opencodePkgPath, JSON.stringify(pkgJson, null, 2) + `
8487
+ writeFileSync2(opencodePkgPath, JSON.stringify(pkgJson, null, 2) + `
7811
8488
  `);
7812
8489
  return version;
7813
8490
  }
@@ -7815,17 +8492,18 @@ function removeOpenCodeLegacyDependency() {
7815
8492
  return null;
7816
8493
  }
7817
8494
  function restoreOpenCodeLegacyDependency(version) {
7818
- const opencodePkgPath = join(getOpenCodeConfigDir(), "package.json");
7819
- let pkgJson = {};
8495
+ const opencodePkgPath = join3(getOpenCodeConfigDir(), "package.json");
8496
+ let pkgJson;
7820
8497
  try {
7821
- pkgJson = JSON.parse(readFileSync(opencodePkgPath, "utf-8"));
7822
- } catch {
7823
- pkgJson = {};
8498
+ pkgJson = readJsonConfig(opencodePkgPath);
8499
+ } catch (error) {
8500
+ console.log(` ${source_default.yellow("⚠")} OpenCode: the legacy plugin dependency was not restored. ${configErrorMessage(error)}`);
8501
+ return;
7824
8502
  }
7825
8503
  const deps = pkgJson.dependencies ?? {};
7826
8504
  deps["@agentapprove/opencode"] = version;
7827
8505
  pkgJson.dependencies = deps;
7828
- writeFileSync(opencodePkgPath, JSON.stringify(pkgJson, null, 2) + `
8506
+ writeFileSync2(opencodePkgPath, JSON.stringify(pkgJson, null, 2) + `
7829
8507
  `);
7830
8508
  }
7831
8509
  async function performUninstall(mode) {
@@ -7847,7 +8525,7 @@ async function performUninstall(mode) {
7847
8525
  const result = removePiPluginViaCli();
7848
8526
  if (result.success) {
7849
8527
  console.log(` ${source_default.green("✓")} Pi extension removed`);
7850
- } else if (existsSync2(agent.configPath)) {
8528
+ } else if (existsSync5(agent.configPath)) {
7851
8529
  console.log(` ${source_default.yellow("⚠")} Pi extension removal skipped or failed (${result.error || "Pi CLI unavailable"})`);
7852
8530
  }
7853
8531
  continue;
@@ -7864,9 +8542,15 @@ async function performUninstall(mode) {
7864
8542
  }
7865
8543
  continue;
7866
8544
  }
7867
- if (!existsSync2(agent.configPath))
8545
+ if (!existsSync5(agent.configPath))
8546
+ continue;
8547
+ let config;
8548
+ try {
8549
+ config = readAgentConfig(agentId, agent.configPath);
8550
+ } catch (error) {
8551
+ console.log(` ${source_default.yellow("⚠")} ${agent.name}: ${configErrorMessage(error)}`);
7868
8552
  continue;
7869
- const config = readJsonConfig(agent.configPath);
8553
+ }
7870
8554
  const hooksConfig = agent.hooksKey === "" ? config : config[agent.hooksKey] ?? {};
7871
8555
  let modified = false;
7872
8556
  if (agentId === "opencode") {
@@ -7879,8 +8563,11 @@ async function performUninstall(mode) {
7879
8563
  modified = removeAgentApproveHookEntries(hooksConfig, agent.hooks.map((hook) => hook.name));
7880
8564
  }
7881
8565
  if (modified) {
8566
+ const commentsNote = keepCommentedConfig(agentId, agent.configPath);
7882
8567
  writeJsonConfig(agent.configPath, config);
7883
8568
  console.log(` ${source_default.green("✓")} Removed hooks from ${agent.name}`);
8569
+ if (commentsNote)
8570
+ console.log(source_default.dim(` ${commentsNote}`));
7884
8571
  }
7885
8572
  if (agentId === "codex" && modified && Object.keys(hooksConfig).length === 0) {
7886
8573
  const codexFlag = disableCodexFeatureFlag();
@@ -7889,7 +8576,9 @@ async function performUninstall(mode) {
7889
8576
  }
7890
8577
  }
7891
8578
  }
7892
- const removedVSCode = removeFromVSCodeHookLocations();
8579
+ const removedVSCode = removeFromVSCodeHookLocations((failure) => {
8580
+ console.log(` ${source_default.yellow("⚠")} ${failure.variant}: ${failure.error}`);
8581
+ });
7893
8582
  if (removedVSCode.length > 0) {
7894
8583
  for (const path of removedVSCode) {
7895
8584
  console.log(` ${source_default.green("✓")} Removed hook path from ${path}`);
@@ -7901,16 +8590,16 @@ async function performUninstall(mode) {
7901
8590
  }
7902
8591
  console.log(` ${source_default.green("✓")} Removed plugin files at ${target.displayPath}`);
7903
8592
  if (target.actualPath.endsWith("/node_modules/@agentapprove/opencode")) {
7904
- pruneEmptyDir(dirname2(target.actualPath));
7905
- pruneEmptyDir(dirname2(dirname2(target.actualPath)));
8593
+ pruneEmptyDir(dirname4(target.actualPath));
8594
+ pruneEmptyDir(dirname4(dirname4(target.actualPath)));
7906
8595
  }
7907
8596
  if (target.actualPath.includes("/extensions/")) {
7908
- pruneEmptyDir(dirname2(target.actualPath));
8597
+ pruneEmptyDir(dirname4(target.actualPath));
7909
8598
  }
7910
8599
  }
7911
- const disabledStatePath = join(getAgentApproveDir(), DISABLED_STATE_FILENAME);
7912
- if (existsSync2(disabledStatePath)) {
7913
- rmSync2(disabledStatePath, { force: true });
8600
+ const disabledStatePath = join3(getAgentApproveDir(), DISABLED_STATE_FILENAME);
8601
+ if (existsSync5(disabledStatePath)) {
8602
+ rmSync3(disabledStatePath, { force: true });
7914
8603
  console.log(` ${source_default.green("✓")} Removed the disable restore record (superseded by ${mode})`);
7915
8604
  }
7916
8605
  if (mode === "purge") {
@@ -7956,13 +8645,13 @@ async function restoreCommand() {
7956
8645
  `));
7957
8646
  const { readdirSync, copyFileSync } = await import("fs");
7958
8647
  for (const [agentId, agent] of Object.entries(AGENTS)) {
7959
- const configDir = dirname2(agent.configPath);
7960
- if (!existsSync2(configDir))
8648
+ const configDir = dirname4(agent.configPath);
8649
+ if (!existsSync5(configDir))
7961
8650
  continue;
7962
8651
  const files = readdirSync(configDir);
7963
8652
  const backups = files.filter((f) => f.startsWith(agent.configPath.split("/").pop()) && f.includes(".backup.")).sort().reverse();
7964
8653
  if (backups.length > 0) {
7965
- const latestBackup = join(configDir, backups[0]);
8654
+ const latestBackup = join3(configDir, backups[0]);
7966
8655
  copyFileSync(latestBackup, agent.configPath);
7967
8656
  console.log(` ${source_default.green("✓")} ${agent.name} restored from ${backups[0]}`);
7968
8657
  }
@@ -7970,13 +8659,13 @@ async function restoreCommand() {
7970
8659
  console.log();
7971
8660
  }
7972
8661
  async function initRepoCommand() {
7973
- const cliHooksPath = join(getAgentApproveDir(), "copilot-cli-hooks.json");
7974
- if (existsSync2(join(getAgentApproveDir(), DISABLED_STATE_FILENAME))) {
8662
+ const cliHooksPath = join3(getAgentApproveDir(), "copilot-cli-hooks.json");
8663
+ if (existsSync5(join3(getAgentApproveDir(), DISABLED_STATE_FILENAME))) {
7975
8664
  console.log(source_default.yellow(`
7976
8665
  Agent Approve is currently disabled. Hooks copied into this repo will be active.`));
7977
8666
  console.log(source_default.dim(" Run `npx agentapprove enable` first if that is not what you want."));
7978
8667
  }
7979
- if (!existsSync2(cliHooksPath)) {
8668
+ if (!existsSync5(cliHooksPath)) {
7980
8669
  console.log(source_default.yellow(`
7981
8670
  GitHub Copilot CLI hooks not found. Run the installer first with GitHub Copilot CLI selected.`));
7982
8671
  console.log(source_default.dim(` npx agentapprove install
@@ -7985,12 +8674,12 @@ async function initRepoCommand() {
7985
8674
  }
7986
8675
  let repoRoot = process.cwd();
7987
8676
  let found = false;
7988
- while (repoRoot !== dirname2(repoRoot)) {
7989
- if (existsSync2(join(repoRoot, ".git"))) {
8677
+ while (repoRoot !== dirname4(repoRoot)) {
8678
+ if (existsSync5(join3(repoRoot, ".git"))) {
7990
8679
  found = true;
7991
8680
  break;
7992
8681
  }
7993
- repoRoot = dirname2(repoRoot);
8682
+ repoRoot = dirname4(repoRoot);
7994
8683
  }
7995
8684
  if (!found) {
7996
8685
  console.log(source_default.yellow(`
@@ -7998,12 +8687,12 @@ async function initRepoCommand() {
7998
8687
  `));
7999
8688
  process.exit(1);
8000
8689
  }
8001
- const targetDir = join(repoRoot, ".github", "hooks");
8002
- const targetFile = join(targetDir, "agentapprove.json");
8690
+ const targetDir = join3(repoRoot, ".github", "hooks");
8691
+ const targetFile = join3(targetDir, "agentapprove.json");
8003
8692
  console.log(source_default.cyan(`
8004
8693
  Installing GitHub Copilot CLI hooks to ${targetFile}
8005
8694
  `));
8006
- if (existsSync2(targetFile)) {
8695
+ if (existsSync5(targetFile)) {
8007
8696
  console.log(source_default.yellow(" agentapprove.json already exists in .github/hooks/"));
8008
8697
  const overwrite = await ce({
8009
8698
  message: "Overwrite existing file?"
@@ -8014,10 +8703,10 @@ async function initRepoCommand() {
8014
8703
  process.exit(0);
8015
8704
  }
8016
8705
  }
8017
- if (!existsSync2(targetDir)) {
8018
- mkdirSync(targetDir, { recursive: true });
8706
+ if (!existsSync5(targetDir)) {
8707
+ mkdirSync3(targetDir, { recursive: true });
8019
8708
  }
8020
- copyFileSync(cliHooksPath, targetFile);
8709
+ copyFileSync2(cliHooksPath, targetFile);
8021
8710
  console.log(source_default.green(` ✓ Copied GitHub Copilot CLI hooks to .github/hooks/agentapprove.json`));
8022
8711
  console.log(source_default.dim(` Commit this file so Copilot coding agent uses your hooks.
8023
8712
  `));
@@ -8079,14 +8768,14 @@ but if unused for 30 days they expire. Get a new one below.`, "Token Expired");
8079
8768
  let apiUrl = pairingApiBase;
8080
8769
  const installedAgents = detectInstalledAgents();
8081
8770
  const e2eEnabled = existingConfig.e2eEnabled !== false;
8082
- const e2eKeyPath = join(getAgentApproveDir(), "e2e-key");
8771
+ const e2eKeyPath = join3(getAgentApproveDir(), "e2e-key");
8083
8772
  let e2eUserKey = null;
8084
8773
  let e2eKeyId;
8085
- if (e2eEnabled && existsSync2(e2eKeyPath)) {
8086
- const existingKey = readFileSync(e2eKeyPath, "utf-8").trim();
8774
+ if (e2eEnabled && existsSync5(e2eKeyPath)) {
8775
+ const existingKey = readFileSync3(e2eKeyPath, "utf-8").trim();
8087
8776
  if (existingKey.length === 64) {
8088
8777
  e2eUserKey = existingKey;
8089
- e2eKeyId = createHash("sha256").update(Buffer.from(existingKey, "hex")).digest("hex").slice(0, 8);
8778
+ e2eKeyId = createHash3("sha256").update(Buffer.from(existingKey, "hex")).digest("hex").slice(0, 8);
8090
8779
  v2.info(`Refresh will reuse E2E key ${e2eKeyId}. Use "npx agentapprove pair" if you need to choose a different key or repair pairing on another device.`);
8091
8780
  }
8092
8781
  } else {
@@ -8162,16 +8851,16 @@ but if unused for 30 days they expire. Get a new one below.`, "Token Expired");
8162
8851
  });
8163
8852
  await storeTokenInKeychain(token);
8164
8853
  if (e2eEnabled && result.e2eServerKey) {
8165
- const serverKeyPath = join(getAgentApproveDir(), "e2e-server-key");
8166
- writeFileSync(serverKeyPath, result.e2eServerKey, { mode: 384 });
8854
+ const serverKeyPath = join3(getAgentApproveDir(), "e2e-server-key");
8855
+ writePrivateFile(serverKeyPath, result.e2eServerKey);
8167
8856
  }
8168
8857
  const updateSpinner = _2();
8169
- updateSpinner.start("Updating hook scripts with new token");
8858
+ updateSpinner.start("Refreshing background activity filters");
8170
8859
  try {
8171
- await updateHookScriptsWithToken(token, apiUrl);
8172
- updateSpinner.stop("Hook scripts updated");
8860
+ await refreshInstalledHooks(token, apiUrl);
8861
+ updateSpinner.stop("Hooks will use the new token on their next run");
8173
8862
  } catch (error) {
8174
- updateSpinner.stop("Warning: Could not update all hook scripts");
8863
+ updateSpinner.stop("Warning: Could not refresh the installed hooks");
8175
8864
  v2.warn('You may need to run "npx agentapprove install" to reconfigure hooks.');
8176
8865
  }
8177
8866
  ge(source_default.green("Token refreshed successfully!"));
@@ -8209,17 +8898,17 @@ async function pairCommand() {
8209
8898
  }
8210
8899
  }
8211
8900
  keyOptions.push({
8212
- value: "__generate__",
8901
+ value: PAIR_KEY_GENERATE,
8213
8902
  label: "Generate a new key",
8214
8903
  hint: "creates a fresh key for this pairing"
8215
8904
  });
8216
8905
  keyOptions.push({
8217
- value: "__disable__",
8906
+ value: PAIR_KEY_DISABLE,
8218
8907
  label: "Disable E2E encryption",
8219
8908
  hint: "events visible on web dashboard"
8220
8909
  });
8221
8910
  const skipE2E = hasFlag2("--no-e2e");
8222
- const selectedKeyId = skipE2E ? "__disable__" : await le({
8911
+ const selectedKeyId = skipE2E ? PAIR_KEY_DISABLE : await le({
8223
8912
  message: "Select an E2E key to pair with your iOS device",
8224
8913
  options: keyOptions
8225
8914
  });
@@ -8227,44 +8916,20 @@ async function pairCommand() {
8227
8916
  he("Pairing cancelled");
8228
8917
  process.exit(0);
8229
8918
  }
8230
- let e2eUserKey = null;
8231
- let e2eKeyId;
8232
- if (selectedKeyId === "__disable__") {
8233
- v2.info("E2E encryption disabled — event content will be visible on the web dashboard");
8234
- updateEnvValue("AGENTAPPROVE_E2E_ENABLED", "false");
8235
- } else if (selectedKeyId === "__generate__") {
8236
- const currentKey = keys.find((k) => k.isCurrent);
8237
- if (currentKey) {
8238
- const agentApproveDir = getAgentApproveDir();
8239
- const backupPath = join(agentApproveDir, `e2e-key.${currentKey.keyId}.bak`);
8240
- renameSync2(currentKey.path, backupPath);
8241
- v2.info(`Previous key backed up (${currentKey.keyId})`);
8242
- }
8243
- e2eUserKey = randomBytes(32).toString("hex");
8244
- e2eKeyId = createHash("sha256").update(Buffer.from(e2eUserKey, "hex")).digest("hex").slice(0, 8);
8245
- const agentApproveDir = getAgentApproveDir();
8246
- ensureAgentApproveDir();
8247
- writeFileSync(join(agentApproveDir, "e2e-root-key"), e2eUserKey, { mode: 384 });
8248
- writeFileSync(join(agentApproveDir, "e2e-key"), e2eUserKey, { mode: 384 });
8249
- writeRotationConfig({
8250
- rootKeyId: e2eKeyId,
8251
- epoch: 0,
8252
- periodSeconds: 0,
8253
- startedAt: new Date().toISOString()
8254
- });
8255
- v2.success(`New key generated (${e2eKeyId})`);
8256
- } else {
8257
- const selectedKey = keys.find((k) => k.keyId === selectedKeyId);
8258
- if (!selectedKey) {
8259
- v2.error("Selected key not found.");
8260
- process.exit(1);
8261
- }
8262
- e2eUserKey = selectedKey.keyHex;
8263
- e2eKeyId = selectedKey.keyId;
8264
- v2.info(`Using key ${e2eKeyId}${selectedKey.isCurrent ? " (current)" : " (backup)"}`);
8919
+ const keyPlan = planPairKey(selectedKeyId, keys, getAgentApproveDir(), () => randomBytes2(32).toString("hex"));
8920
+ if (keyPlan.kind === "not_found") {
8921
+ v2.error("Selected key not found.");
8922
+ process.exit(1);
8265
8923
  }
8266
- if (e2eUserKey) {
8267
- updateEnvValue("AGENTAPPROVE_E2E_ENABLED", "true");
8924
+ const e2eUserKey = keyPlan.e2eUserKey;
8925
+ const e2eKeyId = keyPlan.kind === "disable" ? undefined : keyPlan.e2eKeyId;
8926
+ if (keyPlan.kind === "disable") {
8927
+ v2.info("E2E encryption will be disabled when pairing completes. Event content will be visible on the web dashboard.");
8928
+ } else if (keyPlan.kind === "generate") {
8929
+ v2.info(`A new key (${e2eKeyId}) will be saved when pairing completes.`);
8930
+ } else {
8931
+ const selectedKey = keys.find((k) => k.keyId === keyPlan.e2eKeyId);
8932
+ v2.info(`Using key ${e2eKeyId}${selectedKey?.isCurrent ? " (current)" : " (backup)"}`);
8268
8933
  }
8269
8934
  const installedAgents = detectInstalledAgents();
8270
8935
  const pairingConfigSetAt = Math.floor(Date.now() / 1000);
@@ -8312,25 +8977,27 @@ async function pairCommand() {
8312
8977
  v2.error('Session expired. Run "npx agentapprove pair" to try again.');
8313
8978
  process.exit(1);
8314
8979
  }
8315
- pairingSpinner.stop(`Paired! ${result.email ? `Account: ${result.email}` : ""}`);
8316
- if (e2eUserKey && e2eKeyId) {
8317
- const rootKeyPath = join(getAgentApproveDir(), "e2e-root-key");
8318
- if (!existsSync2(rootKeyPath) || readFileSync(rootKeyPath, "utf-8").trim() !== e2eUserKey) {
8319
- writeFileSync(rootKeyPath, e2eUserKey, { mode: 384 });
8320
- }
8321
- if (!readRotationConfig()) {
8322
- writeRotationConfig({
8323
- rootKeyId: e2eKeyId,
8324
- epoch: 0,
8325
- periodSeconds: 0,
8326
- startedAt: new Date().toISOString()
8327
- });
8328
- }
8329
- if (result.e2eServerKey) {
8330
- const serverKeyPath = join(getAgentApproveDir(), "e2e-server-key");
8331
- writeFileSync(serverKeyPath, result.e2eServerKey, { mode: 384 });
8332
- }
8980
+ const pairOutcome = reconcilePairingConfig(pairingConfig, result.effectiveConfig, {
8981
+ reportedPrivacy: result.privacy,
8982
+ localE2eOn: existingConfig?.e2eEnabled !== false && keys.some((k) => k.isCurrent)
8983
+ });
8984
+ if (pairOutcome.encryptionRequired) {
8985
+ pairingSpinner.stop("Paired, but this computer is not set up");
8986
+ v2.error(formatEncryptionRequiredMessage("pair"));
8987
+ he("Pairing is not finished.");
8988
+ process.exit(1);
8333
8989
  }
8990
+ pairingSpinner.stop(`Paired! ${result.email ? `Account: ${result.email}` : ""}`);
8991
+ ensureAgentApproveDir();
8992
+ const keyResult = applyPairKeyPlan(keyPlan, getAgentApproveDir(), {
8993
+ serverKey: result.e2eServerKey,
8994
+ rotation: { read: readRotationConfig, write: writeRotationConfig },
8995
+ now: () => new Date().toISOString()
8996
+ });
8997
+ if (keyResult.backedUp)
8998
+ v2.info(`Previous key backed up (${keyResult.backedUp})`);
8999
+ if (keyPlan.kind === "generate")
9000
+ v2.success(`New key saved (${e2eKeyId})`);
8334
9001
  const apiUrl = result.apiUrl || pairingApiBase;
8335
9002
  const configSetAt = Math.floor(Date.now() / 1000);
8336
9003
  const pairPreservation = resolvePreservation({
@@ -8341,69 +9008,44 @@ async function pairCommand() {
8341
9008
  saveEnvConfig({
8342
9009
  apiUrl,
8343
9010
  token: result.token,
8344
- privacy: existingConfig?.privacy || result.privacy || "full",
8345
- retentionDays: existingConfig?.retentionDays ?? 30,
9011
+ privacy: pairOutcome.local.privacyTier,
9012
+ retentionDays: pairOutcome.local.retentionDays,
8346
9013
  debugLog: existingConfig?.debugLog,
8347
9014
  e2eMode: existingConfig?.e2eMode,
8348
- e2eEnabled: !!e2eUserKey,
8349
- failBehavior: existingConfig?.failBehavior || "ask",
8350
- configSetAt: pairPreservation.letAccountWin ? 0 : configSetAt,
9015
+ e2eEnabled: pairOutcome.local.e2eEnabled,
9016
+ failBehavior: pairOutcome.local.failBehavior,
9017
+ configSetAt: pairPreservation.letAccountWin || pairOutcome.letAccountWin ? 0 : configSetAt,
8351
9018
  preserved: pairPreservation.preserved
8352
9019
  });
8353
9020
  await storeTokenInKeychain(result.token);
8354
- const hooksDir = join(getAgentApproveDir(), "hooks");
8355
- if (existsSync2(hooksDir)) {
9021
+ const pairKeptWarning = formatAccountKeptWarning(pairOutcome);
9022
+ if (pairKeptWarning)
9023
+ v2.warn(pairKeptWarning);
9024
+ const pairUnknownNote = formatAccountUnknownNote(pairOutcome);
9025
+ if (pairUnknownNote)
9026
+ v2.info(pairUnknownNote);
9027
+ const hooksDir = join3(getAgentApproveDir(), "hooks");
9028
+ if (existsSync5(hooksDir)) {
8356
9029
  const updateSpinner = _2();
8357
- updateSpinner.start("Updating hook scripts with new token");
9030
+ updateSpinner.start("Refreshing background activity filters");
8358
9031
  try {
8359
- await updateHookScriptsWithToken(result.token, apiUrl);
8360
- updateSpinner.stop("Hook scripts updated");
9032
+ await refreshInstalledHooks(result.token, apiUrl);
9033
+ updateSpinner.stop("Hooks will use the new token on their next run");
8361
9034
  } catch {
8362
- updateSpinner.stop("Warning: Could not update all hook scripts");
9035
+ updateSpinner.stop("Warning: Could not refresh the installed hooks");
8363
9036
  v2.warn('You may need to run "npx agentapprove install" to reconfigure hooks.');
8364
9037
  }
8365
9038
  }
8366
9039
  ge(source_default.green(`Device paired with key ${e2eKeyId}`));
8367
9040
  }
8368
- async function updateHookScriptsWithToken(token, apiUrl) {
8369
- const hooksDir = join(getAgentApproveDir(), "hooks");
8370
- if (!existsSync2(hooksDir)) {
8371
- throw new Error("Hooks directory not found");
8372
- }
8373
- const filters = await copyHookScripts2(hooksDir, token, BACKGROUND_FILTER_FILES, { apiUrl });
8374
- if (filters.failed.length || filters.terminalFailure) {
9041
+ async function refreshInstalledHooks(token, apiUrl) {
9042
+ const result = await refreshHooksAfterPairing(join3(getAgentApproveDir(), "hooks"), token, apiUrl, {
9043
+ filterFiles: BACKGROUND_FILTER_FILES,
9044
+ copyHookScripts: copyHookScripts2
9045
+ });
9046
+ if (!result.filtersRefreshed) {
8375
9047
  v2.warn("Background activity filters could not be refreshed. The previous copy is retained.");
8376
9048
  }
8377
- const hookFiles = [
8378
- "claude-pre-tool.sh",
8379
- "claude-post-tool.sh",
8380
- "claude-prompt.sh",
8381
- "claude-session-start.sh",
8382
- "claude-session-end.sh",
8383
- "completion-hook.sh",
8384
- "notify-hook.sh",
8385
- "cursor-approval.sh",
8386
- "cursor-mcp-approval.sh",
8387
- "cursor-shell-complete.sh",
8388
- "cursor-start.sh",
8389
- "cursor-stop.sh",
8390
- "cursor-thought.sh",
8391
- "cursor-response.sh",
8392
- "gemini-approval.sh",
8393
- "gemini-complete.sh",
8394
- "windsurf-hook.sh",
8395
- "openhands-hook.sh",
8396
- "antigravity-hook.sh"
8397
- ];
8398
- for (const file of hookFiles) {
8399
- const filePath = join(hooksDir, file);
8400
- if (existsSync2(filePath)) {
8401
- let content = readFileSync(filePath, "utf-8");
8402
- content = content.replace(/export AGENTAPPROVE_TOKEN=".*"/, `export AGENTAPPROVE_TOKEN="${token}"`);
8403
- content = content.replace(/export AGENTAPPROVE_API=".*"/, `export AGENTAPPROVE_API="${apiUrl}"`);
8404
- writeFileSync(filePath, content, "utf-8");
8405
- }
8406
- }
8407
9049
  }
8408
9050
  async function main() {
8409
9051
  const command = getCommand();