@agentguard-run/burn 0.6.2 → 0.7.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.
@@ -0,0 +1,877 @@
1
+ "use strict";
2
+ /**
3
+ * `agentguard-burn install`: AgentGuard on every agent host on this machine.
4
+ *
5
+ * It finds Claude Code, Codex, Cursor and Hermes by their command on PATH and
6
+ * their config folder, and decides what to do by reading files: nothing is
7
+ * started to look. Without --yes it prints the plan (each host, the exact
8
+ * commands, the files they change) and changes nothing, so an agent can show
9
+ * the plan to its person first. With --yes it runs each host's own plugin
10
+ * commands, reads the same files again, and reports one line per host.
11
+ *
12
+ * It never pipes a downloaded script to a shell, never uses sudo, never
13
+ * installs a host itself and never asks for or stores a key. It also never
14
+ * writes Burn's policy file: the plugin seeds enforce mode into a fresh one,
15
+ * and a file written first would keep a new install in shadow.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.INSTALL_USAGE = exports.PLUGIN_FLOOR_VERSION = exports.OLD_PLUGIN_REPO = exports.HERMES_PLUGIN = exports.HERMES_PACKAGE = exports.PLUGIN_ID = exports.PLUGIN_REPO = exports.HOST_NAMES = exports.AGENT_HOSTS = void 0;
19
+ exports.compareVersions = compareVersions;
20
+ exports.parseInstallArgs = parseInstallArgs;
21
+ exports.which = which;
22
+ exports.pluginDependenciesPresent = pluginDependenciesPresent;
23
+ exports.pluginDataDir = pluginDataDir;
24
+ exports.dataDirForRoot = dataDirForRoot;
25
+ exports.probeHost = probeHost;
26
+ exports.detectHosts = detectHosts;
27
+ exports.planInstall = planInstall;
28
+ exports.modeText = modeText;
29
+ exports.renderPlan = renderPlan;
30
+ exports.defaultRunner = defaultRunner;
31
+ exports.runInstall = runInstall;
32
+ exports.renderReport = renderReport;
33
+ exports.installJson = installJson;
34
+ const node_child_process_1 = require("node:child_process");
35
+ const node_crypto_1 = require("node:crypto");
36
+ const node_fs_1 = require("node:fs");
37
+ const node_path_1 = require("node:path");
38
+ const install_1 = require("./install");
39
+ const hook_edit_1 = require("./hook-edit");
40
+ const policy_1 = require("./policy");
41
+ exports.AGENT_HOSTS = ['claude', 'codex', 'cursor', 'hermes'];
42
+ exports.HOST_NAMES = { claude: 'Claude Code', codex: 'Codex', cursor: 'Cursor', hermes: 'Hermes' };
43
+ exports.PLUGIN_REPO = 'agentguard-run/agentguard-codex-plugin';
44
+ exports.PLUGIN_ID = 'agentguard@agentguard';
45
+ exports.HERMES_PACKAGE = 'agentguard-spend-hermes';
46
+ exports.HERMES_PLUGIN = 'agentguard-spend';
47
+ /** Where the plugin lived before it moved; GitHub forwards it to PLUGIN_REPO. */
48
+ exports.OLD_PLUGIN_REPO = 'MerchantGuard/agentguard-codex-plugin';
49
+ /**
50
+ * The oldest plugin release this Burn treats as current. A host's local
51
+ * marketplace copy can be weeks stale (it refreshes only when asked), so an
52
+ * install older than this is updated even when that copy offers nothing newer.
53
+ */
54
+ exports.PLUGIN_FLOOR_VERSION = '0.5.0';
55
+ const versionParts = (v) => {
56
+ const m = typeof v === 'string' ? v.match(/^(\d+)\.(\d+)\.(\d+)/) : null;
57
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
58
+ };
59
+ /** Negative when a is older than b. Versions that are not x.y.z compare equal. */
60
+ function compareVersions(a, b) {
61
+ const x = versionParts(a);
62
+ const y = versionParts(b);
63
+ if (!x || !y)
64
+ return 0;
65
+ return x[0] - y[0] || x[1] - y[1] || x[2] - y[2];
66
+ }
67
+ // ---------------------------------------------------------------------------
68
+ // Arguments
69
+ // ---------------------------------------------------------------------------
70
+ exports.INSTALL_USAGE = 'Usage: agentguard-burn install [--yes] [--only claude,codex,cursor,hermes] [--skip <hosts>] [--json]';
71
+ const ALIASES = { claude: 'claude', 'claude-code': 'claude', codex: 'codex', cursor: 'cursor', hermes: 'hermes' };
72
+ function hostList(value) {
73
+ if (!value || value.startsWith('-'))
74
+ return 'expects a comma-separated list of hosts';
75
+ const out = [];
76
+ for (const raw of value.split(',').map((v) => v.trim().toLowerCase()).filter(Boolean)) {
77
+ const host = ALIASES[raw];
78
+ if (!host)
79
+ return `does not know "${raw}"; hosts are claude, codex, cursor and hermes`;
80
+ if (!out.includes(host))
81
+ out.push(host);
82
+ }
83
+ return out.length ? out : 'expects a comma-separated list of hosts';
84
+ }
85
+ function parseInstallArgs(args) {
86
+ const options = { yes: false, json: false, only: null, skip: [] };
87
+ for (let i = 0; i < args.length; i++) {
88
+ const arg = args[i];
89
+ const [name, inline] = arg.startsWith('--') && arg.includes('=') ? [arg.slice(0, arg.indexOf('=')), arg.slice(arg.indexOf('=') + 1)] : [arg, undefined];
90
+ if (name === '--yes' || name === '-y')
91
+ options.yes = true;
92
+ else if (name === '--json' || name === 'json')
93
+ options.json = true;
94
+ else if (name === '--only' || name === '--skip') {
95
+ const value = inline ?? args[++i];
96
+ const list = hostList(value);
97
+ if (typeof list === 'string')
98
+ return { error: `install: ${name} ${list}\n${exports.INSTALL_USAGE}` };
99
+ if (name === '--only')
100
+ options.only = [...(options.only ?? []), ...list.filter((h) => !(options.only ?? []).includes(h))];
101
+ else
102
+ options.skip = [...options.skip, ...list.filter((h) => !options.skip.includes(h))];
103
+ }
104
+ else
105
+ return { error: `install: unknown argument "${arg}"\n${exports.INSTALL_USAGE}` };
106
+ }
107
+ return options;
108
+ }
109
+ // ---------------------------------------------------------------------------
110
+ // Reading the machine (files only)
111
+ // ---------------------------------------------------------------------------
112
+ function which(name, ctx) {
113
+ const windows = ctx.platform === 'win32';
114
+ const dirs = (ctx.env.PATH ?? ctx.env.Path ?? '').split(windows ? ';' : ':').filter(Boolean);
115
+ const extensions = windows ? (ctx.env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean) : [''];
116
+ for (const dir of dirs) {
117
+ for (const extension of extensions) {
118
+ const file = (0, node_path_1.join)(dir, name + extension);
119
+ try {
120
+ if (!(0, node_fs_1.statSync)(file).isFile())
121
+ continue;
122
+ if (!windows)
123
+ (0, node_fs_1.accessSync)(file, node_fs_1.constants.X_OK);
124
+ return file;
125
+ }
126
+ catch {
127
+ /* not here */
128
+ }
129
+ }
130
+ }
131
+ return null;
132
+ }
133
+ const nonEmpty = (value) => (value && value.trim() ? value : null);
134
+ function readText(file) {
135
+ try {
136
+ return (0, node_fs_1.readFileSync)(file, 'utf8');
137
+ }
138
+ catch {
139
+ return null;
140
+ }
141
+ }
142
+ function readJsonObject(file) {
143
+ const text = readText(file);
144
+ if (text === null)
145
+ return null;
146
+ try {
147
+ const value = JSON.parse(text);
148
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
149
+ }
150
+ catch {
151
+ return null;
152
+ }
153
+ }
154
+ const isDir = (path) => {
155
+ try {
156
+ return (0, node_fs_1.statSync)(path).isDirectory();
157
+ }
158
+ catch {
159
+ return false;
160
+ }
161
+ };
162
+ /**
163
+ * The plugin's two locked runtime packages are on disk: in its folder, or in
164
+ * the durable copy its postinstall keeps in the plugin data folder, keyed by
165
+ * the lockfile digest (Codex can replace its install cache at session start).
166
+ */
167
+ function pluginDependenciesPresent(root, data = null) {
168
+ const has = (modules) => ['burn', 'spend'].every((name) => (0, node_fs_1.existsSync)((0, node_path_1.join)(modules, '@agentguard-run', name, 'package.json')));
169
+ if (has((0, node_path_1.join)(root, 'node_modules')))
170
+ return true;
171
+ if (!data)
172
+ return false;
173
+ try {
174
+ const digest = (0, node_crypto_1.createHash)('sha256').update((0, node_fs_1.readFileSync)((0, node_path_1.join)(root, 'package-lock.json'))).digest('hex');
175
+ return has((0, node_path_1.join)(data, 'dependencies', digest, 'node_modules'));
176
+ }
177
+ catch {
178
+ return false;
179
+ }
180
+ }
181
+ /** Where the host keeps the plugin's data: `<plugins>/data/agentguard-<marketplace>`, the same for Claude Code and Codex. */
182
+ function pluginDataDir(configDir) {
183
+ return (0, node_path_1.join)(configDir, 'plugins', 'data', 'agentguard-agentguard');
184
+ }
185
+ /**
186
+ * The plugin's mode: the local policy (or the shared team file it names),
187
+ * else the plugin's default, which is enforce. Without a key that is the
188
+ * effective mode; with one, the license check can still select shadow, and
189
+ * only agentguard-status inside a session can see that. A key set through
190
+ * Claude Code's plugin settings lives in the system credential store and is
191
+ * not visible here, so the check line always names agentguard-status.
192
+ */
193
+ function pluginMode(host, configDir, root, ctx) {
194
+ const data = pluginDataDir(configDir);
195
+ const personal = readJsonObject((0, node_path_1.join)(data, 'policy.json'));
196
+ const base = personal ?? (root ? readJsonObject((0, node_path_1.join)(root, 'config', 'default-policy.json')) : null);
197
+ const teamFile = nonEmpty(ctx.env.AGENTGUARD_PLUGIN_POLICY) ?? (typeof base?.teamPolicyFile === 'string' ? base.teamPolicyFile : null);
198
+ const shared = teamFile ? readJsonObject((0, node_path_1.resolve)(data, teamFile)) : null;
199
+ const mode = ({ ...(base ?? {}), ...(shared ?? {}) }).mode === 'shadow' ? 'shadow' : 'enforce';
200
+ const source = shared ? 'team policy file' : personal ? 'local policy' : 'plugin default';
201
+ const keySet = nonEmpty(ctx.env.AGENTGUARD_LICENSE_KEY) !== null || (typeof base?.licenseKey === 'string' && base.licenseKey.trim() !== '');
202
+ const reason = mode === 'shadow' ? `the ${source} sets shadow, so decisions are recorded and nothing is blocked`
203
+ : keySet ? 'a license key is set; if its check fails, the plugin falls back to shadow' : null;
204
+ const check = host === 'claude' ? 'agentguard-status in a new Claude Code session' : 'agentguard-status in a new Codex session, after you trust the hooks in /hooks';
205
+ return { mode, reason, source, check };
206
+ }
207
+ /** Burn's own mode, which the Cursor hook follows: burn-policy.json, else Burn's shadow default. */
208
+ function burnMode(ctx) {
209
+ const home = nonEmpty(ctx.env.AGENTGUARD_HOME) ?? (0, node_path_1.join)(ctx.home, '.agentguard');
210
+ const file = (0, policy_1.checkPolicyFile)(home);
211
+ const check = 'agentguard-burn status';
212
+ if (file.status === 'ignored')
213
+ return { mode: 'shadow', reason: file.line, source: 'burn-policy.json', check };
214
+ const mode = (0, policy_1.loadPolicy)(home, { notice: false }).mode === 'enforce' ? 'enforce' : 'shadow';
215
+ const reason = mode === 'enforce' ? null
216
+ : file.status === 'missing' ? 'no burn-policy.json yet, so Burn only records; agentguard-burn enforce turns it on once eligible'
217
+ : 'burn-policy.json sets shadow, so Burn only records';
218
+ return { mode, reason, source: file.status === 'missing' ? 'Burn default' : 'burn-policy.json', check };
219
+ }
220
+ /** The Hermes plugin's mode, from the policy.yaml it writes under HERMES_HOME on first load (enforce until then). */
221
+ function hermesMode(configDir) {
222
+ const text = readText((0, node_path_1.join)(configDir, 'agentguard', 'policy.yaml'));
223
+ const mode = text?.match(/^mode:\s*["']?([A-Za-z_]+)/m)?.[1] === 'shadow' ? 'shadow' : 'enforce';
224
+ return {
225
+ mode, reason: mode === 'shadow' ? 'policy.yaml sets shadow, so decisions are recorded and nothing is blocked' : null,
226
+ source: text === null ? 'plugin default' : 'policy.yaml', check: '/agentguard status in Hermes, after a restart',
227
+ };
228
+ }
229
+ /** The body of a TOML table, up to the next table header, or null. */
230
+ function tomlTable(text, name) {
231
+ if (!text)
232
+ return null;
233
+ const lines = text.split(/\r?\n/);
234
+ const header = new RegExp(`^\\s*\\[${name.replace(/[.*+?^${}()|[\]\\"]/g, (c) => `\\${c}`)}\\]\\s*(#.*)?$`);
235
+ const start = lines.findIndex((line) => header.test(line));
236
+ if (start < 0)
237
+ return null;
238
+ const body = [];
239
+ for (const line of lines.slice(start + 1)) {
240
+ if (/^\s*\[/.test(line))
241
+ break;
242
+ body.push(line);
243
+ }
244
+ return body.join('\n');
245
+ }
246
+ /** Whether a top-level YAML mapping holds `key:` with `item` in its list (block or inline). Enough for Hermes's config.yaml. */
247
+ function yamlListHas(text, section, key, item) {
248
+ if (!text)
249
+ return false;
250
+ const lines = text.split(/\r?\n/);
251
+ const top = lines.findIndex((line) => new RegExp(`^${section}:\\s*(#.*)?$`).test(line));
252
+ if (top < 0)
253
+ return false;
254
+ const clean = (v) => v.replace(/\s+#.*$/, '').trim().replace(/^(["'])(.*)\1$/, '$2');
255
+ for (let i = top + 1; i < lines.length; i++) {
256
+ const line = lines[i];
257
+ if (/^\S/.test(line))
258
+ return false; // the next top-level key: the section ended
259
+ const match = line.match(new RegExp(`^(\\s+)${key}:\\s*(.*)$`));
260
+ if (!match)
261
+ continue;
262
+ const rest = clean(match[2] ?? '');
263
+ if (rest.startsWith('['))
264
+ return rest.replace(/^\[|\]$/g, '').split(',').map(clean).includes(item);
265
+ const indent = match[1].length;
266
+ for (const next of lines.slice(i + 1)) {
267
+ if (!next.trim() || /^\s*#/.test(next))
268
+ continue;
269
+ const depth = next.length - next.trimStart().length;
270
+ const entry = next.trim().match(/^-\s+(.*)$/);
271
+ if (!entry || depth < indent)
272
+ return false;
273
+ if (clean(entry[1] ?? '') === item)
274
+ return true;
275
+ }
276
+ return false;
277
+ }
278
+ return false;
279
+ }
280
+ function base(host, binary, configDir) {
281
+ const configDirExists = isDir(configDir);
282
+ return {
283
+ host, binary, configDir, configDirExists, present: binary !== null || configDirExists,
284
+ installed: false, registered: false, version: null, root: null, dependencies: null, marketplace: null,
285
+ enabled: null, standaloneHook: null, problem: null, python: null, broken: false, mode: null,
286
+ offered: null, updateTo: null, oldMarketplace: false, complete: false,
287
+ };
288
+ }
289
+ /** The version a package.json or plugin.json declares, if it is x.y.z. */
290
+ function versionIn(file) {
291
+ const version = readJsonObject(file)?.version;
292
+ return typeof version === 'string' && versionParts(version) ? version : null;
293
+ }
294
+ /** The data folder the plugin derives from its install folder: `<plugins>/data/agentguard-<marketplace>`. */
295
+ function dataDirForRoot(root) {
296
+ const marketplaceRoot = (0, node_path_1.dirname)((0, node_path_1.dirname)(root));
297
+ return (0, node_path_1.join)((0, node_path_1.dirname)((0, node_path_1.dirname)(marketplaceRoot)), 'data', `agentguard-${(0, node_path_1.basename)(marketplaceRoot)}`);
298
+ }
299
+ const isOldSource = (source) => source !== null && /merchantguard\/agentguard-codex-plugin/i.test(source);
300
+ /** Sets what follows from the plugin facts already read: installed, update, complete. */
301
+ function finishPlugin(state) {
302
+ state.installed = state.registered && state.dependencies === true;
303
+ state.oldMarketplace = isOldSource(state.marketplace);
304
+ const latest = state.offered && compareVersions(state.offered, exports.PLUGIN_FLOOR_VERSION) > 0 ? state.offered : exports.PLUGIN_FLOOR_VERSION;
305
+ state.updateTo = state.registered && versionParts(state.version) && compareVersions(state.version, latest) < 0 ? latest : null;
306
+ state.complete = state.installed && !state.updateTo && !(state.standaloneHook && state.enabled !== false);
307
+ return state;
308
+ }
309
+ function probeClaude(ctx) {
310
+ const dir = nonEmpty(ctx.env.CLAUDE_CONFIG_DIR) ?? (0, node_path_1.join)(ctx.home, '.claude');
311
+ const state = base('claude', which('claude', ctx), dir);
312
+ const registry = readJsonObject((0, node_path_1.join)(dir, 'plugins', 'installed_plugins.json'));
313
+ const entries = registry?.plugins?.[exports.PLUGIN_ID];
314
+ // A project-scoped install covers one project only, so it does not count as installed here.
315
+ const entry = Array.isArray(entries)
316
+ ? entries.find((e) => e && typeof e.installPath === 'string' && (e.scope === undefined || e.scope === 'user'))
317
+ : undefined;
318
+ if (entry && isDir(entry.installPath)) {
319
+ state.registered = true;
320
+ state.root = entry.installPath;
321
+ state.version = typeof entry.version === 'string' && versionParts(entry.version) ? entry.version : versionIn((0, node_path_1.join)(state.root, 'package.json')) ?? (typeof entry.version === 'string' ? entry.version : null);
322
+ state.dependencies = pluginDependenciesPresent(state.root, dataDirForRoot(state.root));
323
+ state.mode = pluginMode('claude', dir, state.root, ctx);
324
+ }
325
+ const market = readJsonObject((0, node_path_1.join)(dir, 'plugins', 'known_marketplaces.json'))?.agentguard;
326
+ if (market) {
327
+ const source = market.source;
328
+ state.marketplace = typeof source?.repo === 'string' ? source.repo : typeof source?.url === 'string' ? source.url : 'configured';
329
+ }
330
+ // What the marketplace offers, from Claude Code's own local copy of it.
331
+ const snapshot = typeof market?.installLocation === 'string' ? market.installLocation : (0, node_path_1.join)(dir, 'plugins', 'marketplaces', 'agentguard');
332
+ const listed = readJsonObject((0, node_path_1.join)(snapshot, '.claude-plugin', 'marketplace.json'))?.plugins?.find((p) => p?.name === 'agentguard');
333
+ state.offered = typeof listed?.version === 'string' && versionParts(listed.version) ? listed.version
334
+ : versionIn((0, node_path_1.join)((0, node_path_1.resolve)(snapshot, typeof listed?.source === 'string' ? listed.source : '.'), '.claude-plugin', 'plugin.json'));
335
+ const settings = (0, node_path_1.join)(dir, 'settings.json');
336
+ const enabledPlugins = readJsonObject(settings)?.enabledPlugins;
337
+ state.enabled = enabledPlugins?.[exports.PLUGIN_ID] === false ? false : state.registered ? true : null;
338
+ state.standaloneHook = (0, hook_edit_1.countStandaloneBurnHooks)(settings) ? settings : null;
339
+ return finishPlugin(state);
340
+ }
341
+ /** The newest version folder Codex keeps for the plugin. */
342
+ function newestPluginRoot(dir) {
343
+ let best = null;
344
+ let names = [];
345
+ try {
346
+ names = (0, node_fs_1.readdirSync)(dir);
347
+ }
348
+ catch {
349
+ return null;
350
+ }
351
+ for (const name of names) {
352
+ const path = (0, node_path_1.join)(dir, name);
353
+ if (!(0, node_fs_1.existsSync)((0, node_path_1.join)(path, 'package.json')))
354
+ continue;
355
+ const at = (0, node_fs_1.statSync)(path).mtimeMs;
356
+ if (!best || at > best.at || (at === best.at && path > best.path))
357
+ best = { path, at };
358
+ }
359
+ return best?.path ?? null;
360
+ }
361
+ function probeCodex(ctx) {
362
+ const dir = nonEmpty(ctx.env.CODEX_HOME) ?? (0, node_path_1.join)(ctx.home, '.codex');
363
+ const state = base('codex', which('codex', ctx), dir);
364
+ const config = readText((0, node_path_1.join)(dir, 'config.toml'));
365
+ const table = tomlTable(config, `plugins."${exports.PLUGIN_ID}"`);
366
+ const market = tomlTable(config, 'marketplaces.agentguard') ?? tomlTable(config, 'marketplaces."agentguard"');
367
+ if (market !== null)
368
+ state.marketplace = market.match(/^\s*source\s*=\s*"([^"]*)"/m)?.[1] ?? 'configured';
369
+ const root = newestPluginRoot((0, node_path_1.join)(dir, 'plugins', 'cache', 'agentguard', 'agentguard'));
370
+ if (table !== null && root) {
371
+ state.registered = true;
372
+ state.root = root;
373
+ state.version = versionIn((0, node_path_1.join)(root, 'package.json')) ?? versionIn((0, node_path_1.join)(root, '.codex-plugin', 'plugin.json')) ?? (0, node_path_1.basename)(root);
374
+ state.dependencies = pluginDependenciesPresent(root, dataDirForRoot(root));
375
+ state.enabled = !/^\s*enabled\s*=\s*false\b/m.test(table);
376
+ state.mode = pluginMode('codex', dir, root, ctx);
377
+ }
378
+ // What the marketplace offers, from Codex's own local copy of it.
379
+ const snapshot = (0, node_path_1.join)(dir, '.tmp', 'marketplaces', 'agentguard');
380
+ const listed = readJsonObject((0, node_path_1.join)(snapshot, '.agents', 'plugins', 'marketplace.json'))?.plugins?.find((p) => p?.name === 'agentguard');
381
+ const sourcePath = listed?.source?.path;
382
+ const offeredRoot = (0, node_path_1.resolve)(snapshot, typeof sourcePath === 'string' ? sourcePath : '.');
383
+ state.offered = versionIn((0, node_path_1.join)(offeredRoot, '.codex-plugin', 'plugin.json')) ?? versionIn((0, node_path_1.join)(offeredRoot, 'package.json'));
384
+ const hooks = (0, node_path_1.join)(dir, 'hooks.json');
385
+ state.standaloneHook = (0, hook_edit_1.countStandaloneBurnHooks)(hooks) ? hooks : null;
386
+ return finishPlugin(state);
387
+ }
388
+ function probeCursor(ctx) {
389
+ const state = base('cursor', which('cursor', ctx) ?? which('cursor-agent', ctx), (0, node_path_1.join)(ctx.home, '.cursor'));
390
+ const file = (0, install_1.configPath)('cursor', ctx.home);
391
+ state.root = file;
392
+ const text = readText(file);
393
+ if (text !== null && text.trim()) {
394
+ try {
395
+ const value = JSON.parse(text);
396
+ if (!value || typeof value !== 'object' || Array.isArray(value))
397
+ state.problem = `${file} is not a JSON object; fix or move it, then run this again`;
398
+ }
399
+ catch {
400
+ state.problem = `${file} is not valid JSON; fix or move it, then run this again`;
401
+ }
402
+ }
403
+ const h = (0, install_1.health)('cursor', ctx.home);
404
+ state.registered = h.installed;
405
+ state.broken = h.installed && !h.commandExists;
406
+ state.installed = h.installed && h.commandExists;
407
+ state.complete = state.installed;
408
+ if (state.registered)
409
+ state.mode = burnMode(ctx);
410
+ return state;
411
+ }
412
+ const venvPython = (venv, platform) => (0, node_path_1.join)(venv, ...(platform === 'win32' ? ['Scripts', 'python.exe'] : ['bin', 'python']));
413
+ const isVenvPython = (python) => (0, node_fs_1.existsSync)(python) && (0, node_fs_1.existsSync)((0, node_path_1.join)((0, node_path_1.dirname)((0, node_path_1.dirname)(python)), 'pyvenv.cfg'));
414
+ /**
415
+ * The Python environment Hermes runs from: the interpreter named in the
416
+ * `hermes` launcher's first line, else the newest managed environment, else
417
+ * the classic install's venv. Only a virtual environment counts, so nothing
418
+ * is ever installed into a system Python.
419
+ */
420
+ function hermesPython(binary, dir, platform) {
421
+ if (binary) {
422
+ try {
423
+ const head = (0, node_fs_1.readFileSync)((0, node_fs_1.realpathSync)(binary), 'utf8').slice(0, 512);
424
+ const interpreter = head.startsWith('#!') ? head.slice(2).split(/\r?\n/)[0].trim().split(/\s+/)[0] : undefined;
425
+ if (interpreter && /python[\d.]*(\.exe)?$/i.test(interpreter) && isVenvPython(interpreter))
426
+ return interpreter;
427
+ }
428
+ catch {
429
+ /* a binary launcher: fall through to the known locations */
430
+ }
431
+ }
432
+ const managed = [];
433
+ const installs = (0, node_path_1.join)(dir, 'installs');
434
+ for (const id of safeList(installs)) {
435
+ for (const environment of safeList((0, node_path_1.join)(installs, id, 'environments'))) {
436
+ const python = venvPython((0, node_path_1.join)(installs, id, 'environments', environment, 'venv'), platform);
437
+ if (isVenvPython(python))
438
+ managed.push({ python, at: (0, node_fs_1.statSync)(python).mtimeMs });
439
+ }
440
+ }
441
+ managed.sort((a, b) => b.at - a.at);
442
+ if (managed[0])
443
+ return managed[0].python;
444
+ const classic = venvPython((0, node_path_1.join)(dir, 'hermes-agent', 'venv'), platform);
445
+ return isVenvPython(classic) ? classic : null;
446
+ }
447
+ function safeList(dir) {
448
+ try {
449
+ return (0, node_fs_1.readdirSync)(dir);
450
+ }
451
+ catch {
452
+ return [];
453
+ }
454
+ }
455
+ /** The installed version of a Python distribution in a venv, from its dist-info folder name. */
456
+ function distVersion(python, distribution, platform) {
457
+ const venv = (0, node_path_1.dirname)((0, node_path_1.dirname)(python));
458
+ const sites = platform === 'win32'
459
+ ? [(0, node_path_1.join)(venv, 'Lib', 'site-packages')]
460
+ : safeList((0, node_path_1.join)(venv, 'lib')).filter((name) => name.startsWith('python')).map((name) => (0, node_path_1.join)(venv, 'lib', name, 'site-packages'));
461
+ const pattern = new RegExp(`^${distribution.replace(/-/g, '_')}-([^-]+)\\.dist-info$`, 'i');
462
+ for (const site of sites) {
463
+ for (const name of safeList(site)) {
464
+ const match = name.match(pattern);
465
+ if (match)
466
+ return match[1];
467
+ }
468
+ }
469
+ return null;
470
+ }
471
+ function probeHermes(ctx) {
472
+ const dir = nonEmpty(ctx.env.HERMES_HOME) ?? (0, node_path_1.join)(ctx.home, '.hermes');
473
+ const state = base('hermes', which('hermes', ctx), dir);
474
+ state.python = state.present ? hermesPython(state.binary, dir, ctx.platform) : null;
475
+ const packaged = state.python ? distVersion(state.python, exports.HERMES_PACKAGE, ctx.platform) : null;
476
+ const copy = (0, node_path_1.join)(dir, 'plugins', exports.HERMES_PLUGIN, 'plugin.yaml');
477
+ const copied = (0, node_fs_1.existsSync)(copy) ? (readText(copy)?.match(/^version:\s*["']?([^"'\s]+)/m)?.[1] ?? 'unknown') : null;
478
+ state.registered = packaged !== null || copied !== null;
479
+ state.version = packaged ?? copied;
480
+ state.root = packaged !== null ? (0, node_path_1.dirname)((0, node_path_1.dirname)(state.python)) : copied !== null ? (0, node_path_1.dirname)(copy) : null;
481
+ state.enabled = yamlListHas(readText((0, node_path_1.join)(dir, 'config.yaml')), 'plugins', 'enabled', exports.HERMES_PLUGIN);
482
+ state.installed = state.registered && state.enabled;
483
+ state.complete = state.installed;
484
+ if (state.registered)
485
+ state.mode = hermesMode(dir);
486
+ return state;
487
+ }
488
+ function probeHost(host, ctx) {
489
+ return host === 'claude' ? probeClaude(ctx) : host === 'codex' ? probeCodex(ctx) : host === 'cursor' ? probeCursor(ctx) : probeHermes(ctx);
490
+ }
491
+ function detectHosts(ctx) {
492
+ return exports.AGENT_HOSTS.map((host) => probeHost(host, ctx));
493
+ }
494
+ const tilde = (path, home) => (home && (path === home || path.startsWith(home + node_path_1.sep)) ? `~${path.slice(home.length)}` : path);
495
+ function absentDetail(state, ctx) {
496
+ const command = state.host === 'cursor' ? 'no cursor or cursor-agent command' : `no ${state.host} command`;
497
+ return `not found on this machine (${command} on PATH, no ${tilde(state.configDir, ctx.home)})`;
498
+ }
499
+ const runningFromNpxCache = (cliPath) => cliPath.split(/[\\/]/).includes('_npx');
500
+ const CLAUDE_AFTER_INSTALL = 'After install: start a new Claude Code session so the plugin loads, and answer Claude Code\'s own trust prompts yourself.';
501
+ const CODEX_AFTER_INSTALL = 'After install: start a new Codex session, open /hooks, review the AgentGuard hooks and trust them yourself (an agent must never approve its own hooks). Until then Codex can stall the first time a launch is held.';
502
+ const CLAUDE_AFTER_UPDATE = 'After the update: start a new Claude Code session; Claude Code applies plugin updates when it restarts.';
503
+ const CODEX_AFTER_UPDATE = 'After the update: start a new Codex session, open /hooks, review the updated AgentGuard hooks and trust them yourself (an agent must never approve its own hooks). Changed hook definitions need review again.';
504
+ /**
505
+ * Claude Code and Codex: install the plugin, update an older one, install
506
+ * missing dependencies, and take out a standalone Burn hook the plugin
507
+ * replaces. Every plugin change goes through the host's own plugin commands.
508
+ */
509
+ function planPlugin(state, ctx) {
510
+ const host = state.host === 'claude' ? 'claude' : 'codex';
511
+ const name = exports.HOST_NAMES[host];
512
+ const t = (p) => tilde(p, ctx.home);
513
+ const notes = [];
514
+ const disabled = state.enabled === false;
515
+ if (disabled)
516
+ notes.push(`The plugin is turned off in ${t((0, node_path_1.join)(state.configDir, host === 'claude' ? 'settings.json' : 'config.toml'))}. Left as you set it.`);
517
+ if (state.oldMarketplace)
518
+ notes.push(`The agentguard marketplace points at ${exports.OLD_PLUGIN_REPO}, which GitHub forwards to ${exports.PLUGIN_REPO}. ${name} will not add the new source under the same name while that entry exists, so it stays in place and updates come through it.`);
519
+ if (state.standaloneHook && disabled)
520
+ notes.push(`A standalone Burn hook is in ${t(state.standaloneHook)}. With the plugin turned off, it is left in place.`);
521
+ const version = state.version ?? 'unknown version';
522
+ if (state.complete)
523
+ return { state: 'installed', detail: `${exports.PLUGIN_ID} ${version} is installed, with its dependencies`, commands: [], files: [], notes };
524
+ const needsHost = !state.registered || state.updateTo !== null;
525
+ if (needsHost && !state.binary)
526
+ return { state: 'blocked', detail: `found ${t(state.configDir)}, but the ${host} command is not on PATH`, commands: [], files: [], notes };
527
+ const npm = which('npm', ctx);
528
+ const bin = state.binary ?? host;
529
+ const plugins = (0, node_path_1.join)(state.configDir, 'plugins');
530
+ const hostFiles = host === 'claude'
531
+ ? [(0, node_path_1.join)(state.configDir, 'settings.json'), (0, node_path_1.join)(plugins, 'known_marketplaces.json'), (0, node_path_1.join)(plugins, 'installed_plugins.json'), (0, node_path_1.join)(plugins, 'marketplaces', 'agentguard'), (0, node_path_1.join)(plugins, 'cache', 'agentguard')]
532
+ : [(0, node_path_1.join)(state.configDir, 'config.toml'), (0, node_path_1.join)(state.configDir, '.tmp', 'marketplaces', 'agentguard'), (0, node_path_1.join)(plugins, 'cache', 'agentguard'), pluginDataDir(state.configDir)];
533
+ const run = (command, ...args) => ({ command: `${host} ${command}`, argv: [bin, ...args], cwd: null });
534
+ const addMarketplace = run(`plugin marketplace add ${exports.PLUGIN_REPO}`, 'plugin', 'marketplace', 'add', exports.PLUGIN_REPO);
535
+ const npmCi = (cwd) => ({ command: 'npm ci', argv: [npm ?? 'npm', 'ci'], cwd, ...(cwd ? {} : { cwdFromPluginRoot: true }), onlyIfDependenciesMissing: true });
536
+ const commands = [];
537
+ const files = [];
538
+ let detail;
539
+ let update = null;
540
+ if (!state.registered) {
541
+ if (!state.marketplace)
542
+ commands.push(addMarketplace);
543
+ else if (!state.oldMarketplace)
544
+ notes.push(`Uses the agentguard marketplace already added (${state.marketplace}).`);
545
+ commands.push(host === 'claude' ? run(`plugin install ${exports.PLUGIN_ID}`, 'plugin', 'install', exports.PLUGIN_ID) : run(`plugin add ${exports.PLUGIN_ID} --json`, 'plugin', 'add', exports.PLUGIN_ID, '--json'), npmCi(null));
546
+ files.push(...hostFiles);
547
+ detail = `the AgentGuard plugin (${exports.PLUGIN_ID}) from ${exports.PLUGIN_REPO}`;
548
+ notes.unshift(host === 'claude' ? CLAUDE_AFTER_INSTALL : CODEX_AFTER_INSTALL);
549
+ }
550
+ else if (state.updateTo) {
551
+ update = { from: version, to: state.updateTo };
552
+ commands.push(!state.marketplace ? addMarketplace
553
+ : host === 'claude' ? run('plugin marketplace update agentguard', 'plugin', 'marketplace', 'update', 'agentguard')
554
+ : run('plugin marketplace upgrade agentguard', 'plugin', 'marketplace', 'upgrade', 'agentguard'), host === 'claude' ? run(`plugin update ${exports.PLUGIN_ID}`, 'plugin', 'update', exports.PLUGIN_ID) : run(`plugin add ${exports.PLUGIN_ID} --json`, 'plugin', 'add', exports.PLUGIN_ID, '--json'), npmCi(null));
555
+ files.push(...hostFiles);
556
+ detail = `${exports.PLUGIN_ID} ${version} is installed and ${state.updateTo} is available; it updates through ${name}'s own plugin commands`;
557
+ notes.unshift(host === 'claude' ? CLAUDE_AFTER_UPDATE : CODEX_AFTER_UPDATE);
558
+ }
559
+ else if (state.dependencies === false) {
560
+ commands.push(npmCi(state.root));
561
+ files.push((0, node_path_1.join)(state.root, 'node_modules'), dataDirForRoot(state.root));
562
+ detail = `${exports.PLUGIN_ID} ${version} is installed but its dependencies are missing`;
563
+ }
564
+ else
565
+ detail = `${exports.PLUGIN_ID} ${version} is installed, with its dependencies`;
566
+ // Codex never installs the plugin's dependencies, so it always needs npm; Claude Code needs it only to repair them.
567
+ if (!npm && commands.some((c) => c.command === 'npm ci' && (host === 'codex' || c.cwd !== null))) {
568
+ return { state: 'blocked', detail: `npm is not on PATH; the ${name} plugin needs it to install its locked dependencies`, commands: [], files: [], notes };
569
+ }
570
+ if (state.standaloneHook && !disabled) {
571
+ const file = state.standaloneHook;
572
+ commands.push({ command: `remove the standalone Burn hook from ${t(file)} (the plugin includes it): a timestamped backup first, every other hook kept as written`, argv: null, cwd: null, builtin: 'remove-burn-hook', file });
573
+ files.push(file);
574
+ if (state.installed && !state.updateTo)
575
+ detail = `${exports.PLUGIN_ID} ${version} is installed, and a standalone Burn hook is also in ${t(file)}`;
576
+ notes.push(host === 'claude'
577
+ ? 'With the standalone hook gone, the plugin counts launches itself instead of leaving that to the hook.'
578
+ : 'In Codex the plugin does not hand launch checks to a standalone hook, so with both, every launch is checked twice.');
579
+ }
580
+ return { state: 'install', detail, commands, files, notes, update };
581
+ }
582
+ function planCursor(state, ctx) {
583
+ const file = (0, install_1.configPath)('cursor', ctx.home);
584
+ if (state.problem)
585
+ return { state: 'blocked', detail: state.problem, commands: [], files: [], notes: [] };
586
+ if (state.installed)
587
+ return { state: 'installed', detail: `the AgentGuard hook is in ${tilde(file, ctx.home)}`, commands: [], files: [], notes: [] };
588
+ const notes = ['Cursor support is beta: checked against Cursor\'s documented hook format, not yet against every installed build. A crashed hook denies the sub-agent (failClosed).'];
589
+ if (runningFromNpxCache(ctx.cliPath)) {
590
+ notes.push('Burn is running from the npx cache, so the hook points there and stops working if npm clears that cache (status then says INSTALLED BUT BROKEN). For a lasting hook, install Burn globally (npm i -g @agentguard-run/burn) and run agentguard-burn install from it.');
591
+ }
592
+ return {
593
+ state: 'install',
594
+ detail: state.broken ? `the AgentGuard hook in ${tilde(file, ctx.home)} points at a file that is gone; it will be rewritten` : 'the AgentGuard hook (Burn)',
595
+ commands: [{ command: `merge the AgentGuard hook into ${tilde(file, ctx.home)} (a timestamped backup first; the same entry agentguard-burn init cursor --write adds)`, argv: null, cwd: null, builtin: 'cursor-hook' }],
596
+ files: [file],
597
+ notes,
598
+ };
599
+ }
600
+ function planHermes(state, ctx) {
601
+ const restart = 'Restart Hermes (the CLI or the gateway) so it loads AgentGuard.';
602
+ if (state.installed)
603
+ return { state: 'installed', detail: `${exports.HERMES_PACKAGE} ${state.version} is installed and enabled`, commands: [], files: [], notes: [] };
604
+ const config = (0, node_path_1.join)(state.configDir, 'config.yaml');
605
+ const enable = state.enabled ? null : state.binary ? { command: `hermes plugins enable ${exports.HERMES_PLUGIN}`, argv: [state.binary, 'plugins', 'enable', exports.HERMES_PLUGIN], cwd: null } : null;
606
+ if (!state.enabled && !state.binary)
607
+ return { state: 'blocked', detail: `found ${tilde(state.configDir, ctx.home)}, but the hermes command is not on PATH`, commands: [], files: [], notes: [] };
608
+ if (state.registered) {
609
+ return { state: 'install', detail: `${exports.HERMES_PACKAGE} ${state.version} is installed but not enabled`, commands: [enable], files: [config], notes: [restart] };
610
+ }
611
+ if (!state.python)
612
+ return { state: 'blocked', detail: `could not find the Python environment Hermes runs from (looked at the hermes launcher, ${tilde((0, node_path_1.join)(state.configDir, 'installs'), ctx.home)} and ${tilde((0, node_path_1.join)(state.configDir, 'hermes-agent', 'venv'), ctx.home)})`, commands: [], files: [], notes: [] };
613
+ const uv = which('uv', ctx);
614
+ if (!uv)
615
+ return { state: 'blocked', detail: 'uv is not on PATH. Install uv, then run this again, or follow https://agentguard.run/hermes', commands: [], files: [], notes: [] };
616
+ const commands = [{ command: `uv pip install --python ${tilde(state.python, ctx.home)} ${exports.HERMES_PACKAGE}`, argv: [uv, 'pip', 'install', '--python', state.python, exports.HERMES_PACKAGE], cwd: null }];
617
+ if (enable)
618
+ commands.push(enable);
619
+ return {
620
+ state: 'install', detail: `${exports.HERMES_PACKAGE} into the Python environment Hermes runs from${enable ? ', then enable it' : ''}`, commands,
621
+ files: [(0, node_path_1.dirname)((0, node_path_1.dirname)(state.python)), ...(enable ? [config] : [])], notes: [restart],
622
+ };
623
+ }
624
+ function hostPlan(state, ctx, options) {
625
+ const requested = options.only?.includes(state.host) ?? false;
626
+ const head = {
627
+ host: state.host, name: exports.HOST_NAMES[state.host], requested,
628
+ found: { binary: state.binary, configDir: state.configDirExists ? state.configDir : null },
629
+ mode: state.present ? state.mode : null,
630
+ update: null,
631
+ };
632
+ if (options.skip.includes(state.host))
633
+ return { ...head, state: 'excluded', detail: 'left out with --skip', commands: [], files: [], notes: [] };
634
+ if (options.only && !requested)
635
+ return { ...head, state: 'excluded', detail: 'not named in --only', commands: [], files: [], notes: [] };
636
+ if (!state.present)
637
+ return { ...head, state: 'absent', detail: absentDetail(state, ctx), commands: [], files: [], notes: [] };
638
+ const body = state.host === 'claude' || state.host === 'codex' ? planPlugin(state, ctx) : state.host === 'cursor' ? planCursor(state, ctx) : planHermes(state, ctx);
639
+ return { ...head, ...body };
640
+ }
641
+ /** The command that runs this plan, with the same host selection. */
642
+ function nextCommand(options, ctx) {
643
+ const parts = [runningFromNpxCache(ctx.cliPath) ? 'npx agentguard-burn install --yes' : 'agentguard-burn install --yes'];
644
+ if (options.only)
645
+ parts.push(`--only ${options.only.join(',')}`);
646
+ if (options.skip.length)
647
+ parts.push(`--skip ${options.skip.join(',')}`);
648
+ return parts.join(' ');
649
+ }
650
+ function planInstall(ctx, options) {
651
+ const hosts = detectHosts(ctx).map((state) => hostPlan(state, ctx, options));
652
+ const work = hosts.some((h) => h.state === 'install');
653
+ return { hosts, options, next: work ? nextCommand(options, ctx) : null };
654
+ }
655
+ /** "enforce (local policy)" or "shadow: <why> (<where read>)". */
656
+ function modeText(mode) {
657
+ return `${mode.mode}${mode.reason ? `: ${mode.reason}` : ''} (${mode.source})`;
658
+ }
659
+ function renderPlan(plan, ctx) {
660
+ const t = (p) => tilde(p, ctx.home);
661
+ const lines = ['AgentGuard install plan. Nothing has changed yet.', ''];
662
+ const label = { absent: 'not found', excluded: 'left out', installed: 'already installed', install: 'will install', blocked: 'cannot install yet' };
663
+ for (const h of plan.hosts) {
664
+ lines.push(`${h.name}: ${h.update ? `update available (${h.update.from} to ${h.update.to})` : label[h.state]}`);
665
+ const found = [h.found.binary, h.found.configDir].filter((v) => v !== null).map(t);
666
+ if (found.length)
667
+ lines.push(` found: ${found.join(', ')}`);
668
+ lines.push(` ${h.detail}`);
669
+ if (h.mode && h.state !== 'excluded')
670
+ lines.push(` mode: ${modeText(h.mode)}. Effective mode: ${h.mode.check}`);
671
+ if (h.commands.length) {
672
+ const runs = h.commands.filter((c) => c.argv !== null);
673
+ const writes = h.commands.filter((c) => c.argv === null);
674
+ if (runs.length) {
675
+ lines.push(' runs:');
676
+ for (const c of runs) {
677
+ const where = c.cwd ? `in ${t(c.cwd)}` : c.cwdFromPluginRoot ? 'in the plugin folder the step before installs' : '';
678
+ const when = c.onlyIfDependenciesMissing ? 'only if the plugin dependencies are missing' : '';
679
+ const extra = [where, when].filter(Boolean).join(', ');
680
+ lines.push(` ${c.command}${extra ? ` (${extra})` : ''}`);
681
+ }
682
+ }
683
+ for (const c of writes)
684
+ lines.push(` writes: ${c.command}`);
685
+ lines.push(` changes: ${h.files.map(t).join(', ')}`);
686
+ }
687
+ for (const note of h.notes)
688
+ lines.push(` note: ${note}`);
689
+ lines.push('');
690
+ }
691
+ const considered = plan.hosts.filter((h) => h.state !== 'excluded');
692
+ const blocked = considered.some((h) => h.state === 'blocked');
693
+ if (plan.next) {
694
+ if (blocked)
695
+ lines.push('Hosts that cannot install yet are reported as failed when it runs.');
696
+ lines.push('It never runs a downloaded script, never uses sudo and never asks for a key.');
697
+ lines.push(`Run it: ${plan.next}`);
698
+ }
699
+ else if (considered.every((h) => h.state === 'absent')) {
700
+ lines.push(plan.options.only ? 'None of the hosts named in --only was found on this machine.' : 'No supported agent host was found on this machine (Claude Code, Codex, Cursor, Hermes).');
701
+ }
702
+ else if (blocked) {
703
+ lines.push('Nothing to run until the hosts above that cannot install yet are fixed.');
704
+ }
705
+ else {
706
+ lines.push('Nothing to install: every host found already has AgentGuard.');
707
+ }
708
+ return lines.join('\n') + '\n';
709
+ }
710
+ /** Runs a host command without a shell and without stdin, so nothing can wait on a prompt. */
711
+ function defaultRunner(ctx) {
712
+ return (argv, { cwd }) => {
713
+ // Windows starts npm, claude and codex through .cmd shims, which need the shell.
714
+ const windows = ctx.platform === 'win32';
715
+ const args = windows ? argv.map((a) => (/\s/.test(a) ? `"${a}"` : a)) : argv;
716
+ const result = (0, node_child_process_1.spawnSync)(args[0], args.slice(1), {
717
+ cwd: cwd ?? undefined, env: ctx.env, encoding: 'utf8',
718
+ stdio: ['ignore', 'pipe', 'pipe'], timeout: 15 * 60_000, maxBuffer: 64 * 1024 * 1024, shell: windows, windowsHide: true,
719
+ });
720
+ return { status: result.status, stdout: result.stdout ?? '', stderr: result.stderr ?? '', error: result.error?.message };
721
+ };
722
+ }
723
+ const lastLine = (text) => text.split(/\r?\n/).map((l) => l.trim()).filter(Boolean).pop()?.slice(0, 300) ?? '';
724
+ /** The plugin folder a host reports after installing, else the one on disk. */
725
+ function pluginRootAfter(host, output, ctx) {
726
+ if (host === 'codex') {
727
+ try {
728
+ const parsed = JSON.parse(output);
729
+ if (typeof parsed.installedPath === 'string' && isDir(parsed.installedPath))
730
+ return parsed.installedPath;
731
+ }
732
+ catch {
733
+ /* text output */
734
+ }
735
+ const line = output.match(/^Installed plugin root:\s*(.+)$/m)?.[1]?.trim();
736
+ if (line && isDir(line))
737
+ return line;
738
+ const dir = nonEmpty(ctx.env.CODEX_HOME) ?? (0, node_path_1.join)(ctx.home, '.codex');
739
+ return newestPluginRoot((0, node_path_1.join)(dir, 'plugins', 'cache', 'agentguard', 'agentguard'));
740
+ }
741
+ return probeClaude(ctx).root;
742
+ }
743
+ function missingAfter(state) {
744
+ if (state.host === 'hermes')
745
+ return state.registered ? `${exports.HERMES_PLUGIN} is not in plugins.enabled in config.yaml` : `${exports.HERMES_PACKAGE} is not in the Hermes Python environment`;
746
+ if (state.host === 'cursor')
747
+ return state.broken ? 'the hook command is not on disk' : 'the hook is not in hooks.json';
748
+ if (!state.registered)
749
+ return `${exports.PLUGIN_ID} is not registered with ${exports.HOST_NAMES[state.host]}`;
750
+ if (state.dependencies !== true)
751
+ return 'the plugin dependencies are missing';
752
+ if (state.updateTo)
753
+ return `${exports.PLUGIN_ID} is still ${state.version}; ${state.updateTo} is available`;
754
+ return `the standalone Burn hook is still in ${state.standaloneHook}`;
755
+ }
756
+ function describeAfter(state, ctx) {
757
+ const what = state.host === 'cursor' ? `hook in ${tilde(state.root ?? '', ctx.home)}`
758
+ : state.host === 'hermes' ? `${exports.HERMES_PACKAGE} ${state.version ?? ''}, enabled`.replace(' ,', ',')
759
+ : `${exports.PLUGIN_ID} ${state.version ?? ''}`.trim();
760
+ return state.mode ? `${what}; mode ${modeText(state.mode)}` : what;
761
+ }
762
+ function runHost(plan, ctx, runner, log) {
763
+ const ran = [];
764
+ if (plan.state === 'excluded')
765
+ return { outcome: 'skipped', reason: plan.detail, ran };
766
+ if (plan.state === 'absent')
767
+ return plan.requested ? { outcome: 'failed', reason: `${plan.detail}; it was named in --only`, ran } : { outcome: 'skipped', reason: 'not found on this machine', ran };
768
+ if (plan.state === 'installed')
769
+ return { outcome: 'already-installed', reason: plan.detail, ran };
770
+ if (plan.state === 'blocked')
771
+ return { outcome: 'failed', reason: plan.detail, ran };
772
+ let previous = '';
773
+ for (const step of plan.commands) {
774
+ if (step.builtin === 'remove-burn-hook' && step.file) {
775
+ // Only the Burn gate entries go; the rest of the file keeps its bytes. A backup is taken first.
776
+ try {
777
+ const result = (0, hook_edit_1.removeStandaloneBurnHooksFromFile)(step.file);
778
+ log(`${plan.name}: ${result.removed ? `removed the standalone Burn hook from ${tilde(step.file, ctx.home)} (backup ${tilde(result.backup, ctx.home)})` : `${tilde(step.file, ctx.home)} no longer had a standalone Burn hook`}`);
779
+ }
780
+ catch (error) {
781
+ return { outcome: 'failed', reason: `refused to change ${tilde(step.file, ctx.home)}: ${error instanceof Error ? error.message : String(error)}`, ran };
782
+ }
783
+ continue;
784
+ }
785
+ if (step.argv === null) {
786
+ // Cursor: Burn merges its own hook entry, with the same backup and atomic write as init --write.
787
+ try {
788
+ const result = (0, install_1.install)('cursor', ctx.cliPath, ctx.home);
789
+ log(`${plan.name}: ${result.changed ? `merged the hook into ${tilde(result.file, ctx.home)}${result.backup ? ` (backup ${tilde(result.backup, ctx.home)})` : ''}` : `${tilde(result.file, ctx.home)} already had the hook`}`);
790
+ }
791
+ catch (error) {
792
+ return { outcome: 'failed', reason: `refused to change ${tilde((0, install_1.configPath)('cursor', ctx.home), ctx.home)}: ${error instanceof Error ? error.message : String(error)}`, ran };
793
+ }
794
+ continue;
795
+ }
796
+ let cwd = step.cwd;
797
+ if (step.cwdFromPluginRoot) {
798
+ cwd = pluginRootAfter(plan.host, previous, ctx);
799
+ if (!cwd)
800
+ return { outcome: 'failed', reason: `${exports.HOST_NAMES[plan.host]} did not report where it installed the plugin, so its dependencies were not installed`, ran };
801
+ }
802
+ if (step.onlyIfDependenciesMissing && cwd && pluginDependenciesPresent(cwd, dataDirForRoot(cwd)))
803
+ continue;
804
+ if (step.argv[0] === 'npm')
805
+ return { outcome: 'failed', reason: 'npm is not on PATH, so the plugin dependencies were not installed', ran };
806
+ log(`${plan.name}: ${step.command}${cwd ? ` (in ${tilde(cwd, ctx.home)})` : ''}`);
807
+ const result = runner(step.argv, { cwd });
808
+ ran.push({ command: step.command, cwd, exitCode: result.status });
809
+ if (result.error || result.status !== 0) {
810
+ const why = result.error ? `could not run: ${result.error}` : `exited with code ${result.status}`;
811
+ const tail = lastLine(result.stderr) || lastLine(result.stdout);
812
+ return { outcome: 'failed', reason: `${step.command} ${why}${tail ? `: ${tail}` : ''}`, ran };
813
+ }
814
+ previous = result.stdout;
815
+ }
816
+ return { outcome: 'installed', reason: '', ran };
817
+ }
818
+ /**
819
+ * Carries out a plan: each host in turn, continuing past a host that fails,
820
+ * then reads every host again (the same checks the plan used) for its line.
821
+ */
822
+ function runInstall(plan, ctx, runner, log = () => undefined) {
823
+ const hosts = [];
824
+ for (const h of plan.hosts) {
825
+ const result = runHost(h, ctx, runner, log);
826
+ const after = probeHost(h.host, ctx);
827
+ let { outcome, reason } = result;
828
+ if (outcome === 'installed') {
829
+ if (after.complete)
830
+ reason = describeAfter(after, ctx);
831
+ else {
832
+ outcome = 'failed';
833
+ reason = `the commands finished, but ${missingAfter(after)}`;
834
+ }
835
+ }
836
+ else if (outcome === 'already-installed')
837
+ reason = describeAfter(after, ctx);
838
+ hosts.push({
839
+ host: h.host, name: h.name, outcome, reason, ran: result.ran,
840
+ after: { installed: after.installed, version: after.version, root: after.root, mode: after.mode },
841
+ notes: outcome === 'installed' ? h.notes : h.state === 'installed' ? h.notes.filter((n) => !n.startsWith('After install')) : [],
842
+ });
843
+ }
844
+ return { ok: hosts.every((h) => h.outcome !== 'failed'), hosts };
845
+ }
846
+ function renderReport(report) {
847
+ const words = { installed: 'installed', 'already-installed': 'already installed', skipped: 'skipped', failed: 'failed' };
848
+ const width = Math.max(...report.hosts.map((h) => h.name.length)) + 2;
849
+ const lines = report.hosts.map((h) => `${h.name.padEnd(width)}${words[h.outcome]}${h.reason ? (h.outcome === 'failed' ? `: ${h.reason}` : ` (${h.reason})`) : ''}`);
850
+ const notes = report.hosts.flatMap((h) => h.notes.map((n) => ` ${h.name}: ${n}`));
851
+ if (notes.length)
852
+ lines.push('', 'Notes:', ...notes);
853
+ const checks = report.hosts.filter((h) => (h.outcome === 'installed' || h.outcome === 'already-installed') && h.after.mode).map((h) => ` ${h.name}: ${h.after.mode.check}`);
854
+ if (checks.length)
855
+ lines.push('', 'Check the effective mode:', ...checks);
856
+ if (!report.ok)
857
+ lines.push('', 'At least one host failed. The others are done; fix the reason shown and run the same command again.');
858
+ return lines.join('\n') + '\n';
859
+ }
860
+ /** What --json prints: the plan, and after --yes the result for each host. `mode` is plan or install; each host's `agentguardMode` is the enforce or shadow mode AgentGuard runs in there. */
861
+ function installJson(version, plan, report) {
862
+ return {
863
+ version,
864
+ mode: report ? 'install' : 'plan',
865
+ ok: report ? report.ok : true,
866
+ next: report ? null : plan.next,
867
+ hosts: plan.hosts.map((h) => {
868
+ const result = report?.hosts.find((r) => r.host === h.host);
869
+ return {
870
+ host: h.host, name: h.name, state: h.state, detail: h.detail, found: h.found, agentguardMode: h.mode, update: h.update ?? null,
871
+ commands: h.commands.map((c) => ({ command: c.command, argv: c.argv, cwd: c.cwd, ...(c.cwdFromPluginRoot ? { cwdFromPluginRoot: true } : {}), ...(c.onlyIfDependenciesMissing ? { onlyIfDependenciesMissing: true } : {}) })),
872
+ files: h.files, notes: h.notes,
873
+ ...(result ? { result: { outcome: result.outcome, reason: result.reason, ran: result.ran, after: { installed: result.after.installed, version: result.after.version, root: result.after.root, agentguardMode: result.after.mode } } } : {}),
874
+ };
875
+ }),
876
+ };
877
+ }