@xtrom-ai/sdk 0.0.0-stage → 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.
Files changed (53) hide show
  1. package/LICENSE +190 -0
  2. package/README.md +185 -2
  3. package/dist/allowances.js +74 -0
  4. package/dist/cli.js +268 -0
  5. package/dist/credentials.js +37 -0
  6. package/dist/directive.js +57 -0
  7. package/dist/enforce.js +972 -0
  8. package/dist/index.js +31 -0
  9. package/dist/inspect.js +135 -0
  10. package/dist/local/agents.js +378 -0
  11. package/dist/local/appliers.js +61 -0
  12. package/dist/local/browser.js +135 -0
  13. package/dist/local/discover.js +154 -0
  14. package/dist/local/hook.js +778 -0
  15. package/dist/local/install.js +238 -0
  16. package/dist/local/inventory.js +219 -0
  17. package/dist/local/reasonText.js +29 -0
  18. package/dist/local/shipper.js +251 -0
  19. package/dist/local/spool.js +178 -0
  20. package/dist/local/updateKeys.js +3 -0
  21. package/dist/local/updater.js +224 -0
  22. package/dist/local/view.js +110 -0
  23. package/dist/memory.js +172 -0
  24. package/dist/reporter.js +336 -0
  25. package/dist/session.js +439 -0
  26. package/dist/version.js +2 -0
  27. package/dist/workspace.js +72 -0
  28. package/package.json +23 -4
  29. package/src/allowances.ts +74 -0
  30. package/src/cli.ts +268 -0
  31. package/src/credentials.ts +37 -0
  32. package/src/directive.ts +57 -0
  33. package/src/enforce.ts +972 -0
  34. package/src/index.ts +31 -0
  35. package/src/inspect.ts +135 -0
  36. package/src/local/agents.ts +378 -0
  37. package/src/local/appliers.ts +61 -0
  38. package/src/local/browser.ts +135 -0
  39. package/src/local/discover.ts +154 -0
  40. package/src/local/hook.ts +778 -0
  41. package/src/local/install.ts +238 -0
  42. package/src/local/inventory.ts +219 -0
  43. package/src/local/reasonText.ts +29 -0
  44. package/src/local/shipper.ts +251 -0
  45. package/src/local/spool.ts +178 -0
  46. package/src/local/updateKeys.ts +3 -0
  47. package/src/local/updater.ts +224 -0
  48. package/src/local/view.ts +110 -0
  49. package/src/memory.ts +172 -0
  50. package/src/reporter.ts +336 -0
  51. package/src/session.ts +439 -0
  52. package/src/version.ts +2 -0
  53. package/src/workspace.ts +72 -0
@@ -0,0 +1,238 @@
1
+ // Idempotent install/uninstall of the Xtrom hook into each supported coding agent's hook config
2
+ // (see agents.ts for the per-agent protocol). Entries are recognised by a `--managed-by=` marker ARGUMENT (schema-clean, no custom keys), so
3
+ // uninstall removes only ours. Because `npx` caches are ephemeral, install copies the zero-dependency
4
+ // runtime into ~/.xtrom/local/runtime/ and points the hook there with an absolute node path.
5
+ import { chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
6
+ import { spawnSync } from "node:child_process";
7
+ import { homedir } from "node:os";
8
+ import { dirname, extname, join, relative, sep } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import { requireSecureUrl } from "../reporter.ts";
11
+ import { paths, readConfig } from "./hook.ts";
12
+ import {
13
+ AGENTS, DEFAULT_AGENT, HookCommand, MARKER_PY, MARKER_TS, PRE, applyEntries, isInstalled, isOurs as isOursFor,
14
+ onlyXtrom, ourScripts, removeEntries,
15
+ } from "./agents.ts";
16
+
17
+ export const MARKER = MARKER_TS;
18
+
19
+ export type Scope = "user" | "project";
20
+ export interface InstallOpts {
21
+ monitor?: boolean;
22
+ home?: string;
23
+ projectDir?: string;
24
+ settingsPath?: string;
25
+ /** Override the runtime copy location (tests). */
26
+ runtimeDir?: string;
27
+ /** Reporting credentials, stored 0600 in ~/.xtrom/local/config.json (kept on reinstall if omitted). */
28
+ controlPlaneUrl?: string;
29
+ token?: string;
30
+ /** Coding agent to wire (agents.ts id). Defaults to Claude Code. */
31
+ agent?: string;
32
+ }
33
+ type Json = Record<string, any>;
34
+
35
+ function adapterFor(agent: string = DEFAULT_AGENT) {
36
+ if (!Object.hasOwn(AGENTS, agent)) throw new Error(`unknown agent ${JSON.stringify(agent)}`);
37
+ return AGENTS[agent];
38
+ }
39
+
40
+ export function settingsPath(scope: Scope = "user", home?: string, projectDir?: string, agent: string = DEFAULT_AGENT): string {
41
+ return adapterFor(agent).configPath(scope, home ?? homedir(), projectDir ?? process.cwd(),
42
+ home === undefined ? process.env : undefined);
43
+ }
44
+
45
+ /** Root of the running package build (dist/ when published, src/ in a checkout). */
46
+ function packageRoot(): string {
47
+ return dirname(dirname(fileURLToPath(import.meta.url)));
48
+ }
49
+
50
+ function runtimeTarget(o: InstallOpts): string {
51
+ return o.runtimeDir ?? join(paths(o.home).base, "runtime", "sdk-ts");
52
+ }
53
+
54
+ // Running from a .ts checkout needs type stripping on Node < 23.6; a published dist/ is plain JS.
55
+ const nodeFlags = (cli: string) => (extname(cli) === ".ts" ? ["--experimental-strip-types", "--no-warnings"] : []);
56
+ const cliIn = (dir: string) => join(dir, `cli${extname(fileURLToPath(import.meta.url))}`);
57
+
58
+ export const LAUNCHER_NAME = "xtrom-hook.sh";
59
+ const shq = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;
60
+
61
+ /**
62
+ * Every supported agent treats exit 2 from a hook as "block"; most treat any other failure as a
63
+ * non-blocking error and run the tool anyway, so a missing node (nvm upgrade) or a crash would fail
64
+ * OPEN, silently. The launcher turns "can't start" or "crashed" into exit 2 and tells the developer how
65
+ * to fix it. A deliberate exit 2 (Windsurf's only way to deny) passes through with the hook's reason.
66
+ */
67
+ function writeLauncher(runtime: string, cli: string): string {
68
+ const path = join(runtime, LAUNCHER_NAME);
69
+ writeFileSync(path, [
70
+ "#!/bin/sh",
71
+ "# Xtrom hook launcher (generated by `xtrom install`).",
72
+ `${shq(process.execPath)} ${nodeFlags(cli).map(shq).join(" ")} ${shq(cli)} hook "$@"`.replace(/\s+/g, " "),
73
+ "rc=$?",
74
+ '[ "$rc" -eq 0 ] && exit 0',
75
+ '[ "$rc" -eq 2 ] && exit 2',
76
+ `echo "Xtrom hook could not run (exit $rc), so this tool call is blocked. Fix: re-run the Xtrom install in a terminal, or uninstall it." >&2`,
77
+ "exit 2",
78
+ "",
79
+ ].join("\n"), { mode: 0o700 });
80
+ chmodSync(path, 0o700);
81
+ return path;
82
+ }
83
+
84
+ function hookCommand(cli: string, launcher: string | null, agent: string, event: string): HookCommand {
85
+ const tail = ["--agent", agent, "--event", event === PRE ? "pre" : "post", MARKER];
86
+ return new HookCommand(launcher ? ["/bin/sh", launcher, ...tail] : [process.execPath, ...nodeFlags(cli), cli, "hook", ...tail]);
87
+ }
88
+
89
+ /**
90
+ * Copy the runtime to a staging dir, prove it loads, then swap it in. A hook that can't start exits
91
+ * non-zero, which most agents treat as a non-blocking error — i.e. fail-open — so a broken copy
92
+ * must never replace a working one or reach an agent's hook config.
93
+ */
94
+ export function deployRuntime(src: string, target: string) {
95
+ const staging = `${target}.new-${process.pid}`;
96
+ rmSync(staging, { recursive: true, force: true });
97
+ mkdirSync(dirname(target), { recursive: true });
98
+ // Filter relative to the package root: under npx the package itself lives in node_modules/.
99
+ cpSync(src, staging, {
100
+ recursive: true,
101
+ filter: (f) => !relative(src, f).split(sep).includes("node_modules"),
102
+ });
103
+ // The copy is dist/ alone. Without its own package.json, Node resolves the module type from a
104
+ // parent dir, so a ~/package.json with "type": "commonjs" would crash every hook call.
105
+ writeFileSync(join(staging, "package.json"), JSON.stringify({ private: true, type: "module" }) + "\n");
106
+ const cli = cliIn(staging);
107
+ const r = spawnSync(process.execPath, [...nodeFlags(cli), cli, "version"], { encoding: "utf8", timeout: 10_000 });
108
+ if (r.status !== 0) {
109
+ rmSync(staging, { recursive: true, force: true });
110
+ throw new Error(`Xtrom runtime self-test failed; hook config left unchanged.\n${r.stderr || r.error || ""}`.trim());
111
+ }
112
+ rmSync(target, { recursive: true, force: true });
113
+ renameSync(staging, target);
114
+ }
115
+
116
+ export const isOurs = (e: unknown) => isOursFor(e, MARKER);
117
+ const isPython = (e: unknown) => isOursFor(e, MARKER_PY);
118
+
119
+ function load(path: string): Json {
120
+ if (!existsSync(path)) return {};
121
+ const data = JSON.parse(readFileSync(path, "utf8"));
122
+ return data && typeof data === "object" && !Array.isArray(data) ? data : {};
123
+ }
124
+
125
+ function backup(path: string): string | null {
126
+ if (!existsSync(path)) return null;
127
+ const stamp = new Date().toISOString().replace(/[-:T]/g, "").slice(0, 14);
128
+ let dest = `${path}.xtrom-backup-${stamp}`;
129
+ for (let i = 1; existsSync(dest); i++) dest = `${path}.xtrom-backup-${stamp}-${i}`;
130
+ copyFileSync(path, dest);
131
+ return dest;
132
+ }
133
+
134
+ function write(path: string, data: Json) {
135
+ mkdirSync(dirname(path), { recursive: true });
136
+ writeFileSync(path, JSON.stringify(data, null, 2) + "\n");
137
+ }
138
+
139
+ export interface InstallResult { agent: string; settingsPath: string; runtime: string; backup: string | null; pythonHookPresent: boolean }
140
+
141
+ const anyEntry = (data: Json, pred: (e: unknown) => boolean, agent: string) =>
142
+ AGENTS[agent].events.some(([n]) => Array.isArray(data?.hooks?.[n]) && data.hooks[n].some(pred));
143
+
144
+ export function install(scope: Scope = "user", o: InstallOpts = {}): InstallResult {
145
+ if (o.controlPlaneUrl) requireSecureUrl(o.controlPlaneUrl);
146
+ const agent = o.agent ?? DEFAULT_AGENT;
147
+ const adapter = adapterFor(agent);
148
+ const path = o.settingsPath ?? settingsPath(scope, o.home, o.projectDir, agent);
149
+ const data = load(path); // throws on malformed JSON — never overwrite a file we can't parse
150
+ const target = runtimeTarget(o);
151
+ deployRuntime(packageRoot(), target);
152
+ const cli = cliIn(target);
153
+ const launcher = process.platform === "win32" ? null : writeLauncher(target, cli);
154
+
155
+ const bak = adapter.ownsFile ? null : backup(path);
156
+ const pythonHookPresent = anyEntry(data, isPython, agent);
157
+ applyEntries(adapter, data, (event) => hookCommand(cli, launcher, agent, event), MARKER);
158
+ write(path, data);
159
+
160
+ const p = paths(o.home);
161
+ mkdirSync(p.base, { recursive: true, mode: 0o700 });
162
+ const prev = readConfig(p);
163
+ const cfg: Json = { mode: o.monitor ? "monitor" : "enforce" };
164
+ const url = o.controlPlaneUrl || prev.control_plane_url, token = o.token || prev.token;
165
+ if (url) cfg.control_plane_url = url;
166
+ if (token) cfg.token = token;
167
+ if (existsSync(p.config)) chmodSync(p.config, 0o600); // an existing file keeps its old mode: tighten it before the token
168
+ writeFileSync(p.config, JSON.stringify(cfg, null, 2) + "\n", { mode: 0o600 });
169
+ chmodSync(p.config, 0o600);
170
+ return { agent, settingsPath: path, runtime: target, backup: bak, pythonHookPresent };
171
+ }
172
+
173
+ /** Turn reporting on (both given) or off (both undefined), keeping every other setting (parity: set_reporting).
174
+ * The same hooks keep deciding locally either way (docs/design/PUBLIC-INSTALL.md). */
175
+ export function setReporting(controlPlaneUrl: string | undefined, token: string | undefined, home?: string): boolean {
176
+ if ((controlPlaneUrl === undefined) !== (token === undefined)) throw new Error("reporting needs both a console URL and a token");
177
+ if (controlPlaneUrl) requireSecureUrl(controlPlaneUrl);
178
+ const p = paths(home);
179
+ mkdirSync(p.base, { recursive: true, mode: 0o700 });
180
+ const cfg: Json = { ...readConfig(p) };
181
+ delete cfg.control_plane_url; delete cfg.token;
182
+ if (!cfg.mode) cfg.mode = "enforce";
183
+ if (controlPlaneUrl) { cfg.control_plane_url = controlPlaneUrl; cfg.token = token; }
184
+ if (existsSync(p.config)) chmodSync(p.config, 0o600); // an existing file keeps its old mode: tighten it before the token
185
+ writeFileSync(p.config, JSON.stringify(cfg, null, 2) + "\n", { mode: 0o600 });
186
+ chmodSync(p.config, 0o600);
187
+ return !!controlPlaneUrl;
188
+ }
189
+
190
+ export function uninstall(scope: Scope = "user", o: InstallOpts = {}): string {
191
+ const agent = o.agent ?? DEFAULT_AGENT;
192
+ const adapter = adapterFor(agent);
193
+ const path = o.settingsPath ?? settingsPath(scope, o.home, o.projectDir, agent);
194
+ if (existsSync(path)) {
195
+ const data = load(path);
196
+ if (!adapter.ownsFile) backup(path);
197
+ removeEntries(adapter, data, MARKER);
198
+ if (onlyXtrom(adapter, data)) rmSync(path, { force: true });
199
+ else write(path, data);
200
+ }
201
+ // The runtime copy is kept: another scope's or agent's hook may still point at it, and a dangling
202
+ // hook path would make most agents treat every call as a non-blocking hook error (fail-open).
203
+ return path;
204
+ }
205
+
206
+ /** An Xtrom hook from either SDK is installed for this agent at user scope (local inventory). */
207
+ export function hooked(agent: string, home?: string): boolean {
208
+ try {
209
+ const data = load(settingsPath("user", home, undefined, agent));
210
+ return isInstalled(adapterFor(agent), data, MARKER_PY) || isInstalled(adapterFor(agent), data, MARKER_TS);
211
+ } catch { return false; }
212
+ }
213
+
214
+ export function status(scope: Scope = "user", o: InstallOpts = {}) {
215
+ const agent = o.agent ?? DEFAULT_AGENT;
216
+ const adapter = adapterFor(agent);
217
+ const path = o.settingsPath ?? settingsPath(scope, o.home, o.projectDir, agent);
218
+ let data: Json = {};
219
+ try { data = load(path); } catch { /* malformed: report not installed */ }
220
+ const p = paths(o.home);
221
+ let mode = "enforce";
222
+ try { mode = JSON.parse(readFileSync(p.config, "utf8")).mode ?? mode; } catch { /* default */ }
223
+ const installed = isInstalled(adapter, data, MARKER);
224
+ return {
225
+ agent,
226
+ label: adapter.label,
227
+ settings_path: path,
228
+ installed,
229
+ python_hook_present: anyEntry(data, isPython, agent),
230
+ runtime: runtimeTarget(o),
231
+ // The hook script each of our entries actually points at must exist, or the agent fails open.
232
+ runtime_ok: installed && ourScripts(adapter, data, MARKER).every((s) => !!s && existsSync(s)),
233
+ mode: process.env.XTROM_MODE || mode,
234
+ reporting: !!((process.env.XTROM_CONTROL_PLANE_URL && process.env.XTROM_TOKEN)
235
+ || (readConfig(p).control_plane_url && readConfig(p).token)),
236
+ audit_log: p.audit,
237
+ };
238
+ }
@@ -0,0 +1,219 @@
1
+ // What this machine has set up for AI agents, reported to the console (docs/design/LOCAL-INVENTORY.md):
2
+ // the coding agents installed and whether an Xtrom hook covers each, and the MCP servers their configs
3
+ // name. Mirror of xtrom_sdk/local/inventory.py; both reproduce test/fixtures/inventory_golden.json.
4
+ //
5
+ // Minimum by design: a remote server is its scheme and host (hosted MCP URLs often carry the credential
6
+ // in the path), a local one its launcher and, for package launchers, the package name. Never arguments,
7
+ // env values or key names, headers, query strings or file paths. Risk is sent as fixed codes.
8
+ import { createHash } from "node:crypto";
9
+ import { readFileSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { detected, getAdapter } from "./agents.ts";
12
+ import { parseTomlLite } from "./discover.ts";
13
+ import { sortedJson } from "./hook.ts";
14
+
15
+ type Json = Record<string, any>;
16
+
17
+ export const NOTES = ["plain_http", "remote", "secret_env", "static_auth", "unpinned_package"] as const;
18
+ export interface InvServer {
19
+ name: string; agent: string; scope: "user" | "project"; transport: string; where: "remote" | "local";
20
+ host?: string; launcher?: string; package?: string; notes: string[];
21
+ }
22
+ export interface InvAgent { agent: string; hooked: boolean }
23
+ export interface Inventory { agents: InvAgent[]; servers: InvServer[]; truncated?: true }
24
+
25
+ const MAX_SERVERS = 300;
26
+ // Ingest refuses a record over 32,000 bytes (RECORD_MAX_BYTES); leave room for the envelope fields.
27
+ export const INVENTORY_MAX_BYTES = 30_000;
28
+ const SECRET_KEY_PARTS = ["token", "secret", "password", "passwd", "api_key", "apikey", "key", "credential", "auth"];
29
+ const NAME_RX = /[^A-Za-z0-9._@:/-]/g;
30
+ const LAUNCHER_RX = /^[A-Za-z0-9._+-]{1,64}$/;
31
+ const NPM_RX = /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(@[A-Za-z0-9._^~<>=*-]+)?$/i;
32
+ const PYPI_RX = /^[A-Za-z0-9][A-Za-z0-9._-]*(\[[A-Za-z0-9,._-]+\])?((==|>=|<=|~=|@)[A-Za-z0-9._*+-]+)?$/;
33
+ const IMAGE_RX = /^[a-z0-9][a-z0-9._\/-]*(:[A-Za-z0-9._-]+)?(@sha256:[a-f0-9]{64})?$/;
34
+ const HOST_RX = /^[A-Za-z0-9.-]{1,253}(:\d{1,5})?$|^\[[0-9A-Fa-f:.]+\](:\d{1,5})?$/;
35
+ const LOOPBACK = /^(localhost|127\.\d+\.\d+\.\d+|\[::1\])(:\d+)?$/i;
36
+ const DOCKER_VALUE_FLAGS = new Set(["-e", "--env", "--env-file", "-v", "--volume", "-p", "--publish", "--name", "--network",
37
+ "-w", "--workdir", "--entrypoint", "-u", "--user", "--mount", "-l", "--label", "--platform", "--add-host", "-h", "--hostname"]);
38
+
39
+ function readJson(path: string): unknown {
40
+ try { return JSON.parse(readFileSync(path, "utf8")); } catch { return null; }
41
+ }
42
+ function readToml(path: string): unknown {
43
+ try { return parseTomlLite(readFileSync(path, "utf8")); } catch { return null; }
44
+ }
45
+ const isObj = (v: unknown): v is Json => !!v && typeof v === "object" && !Array.isArray(v);
46
+
47
+ function basename(cmd: string): string {
48
+ const b = cmd.trim().split(/[\\/]/).pop() ?? "";
49
+ return b.replace(/\.(exe|cmd|bat)$/i, "");
50
+ }
51
+
52
+ /** The package a launcher pulls, when it names one we can recognise; anything else is not sent. */
53
+ function packageOf(launcher: string, args: string[]): [string | undefined, boolean] {
54
+ const plain = args.filter((a) => typeof a === "string");
55
+ const firstFree = (from: number, skipValues: Set<string> = new Set()): string | undefined => {
56
+ for (let i = from; i < plain.length; i++) {
57
+ const a = plain[i];
58
+ if (a === "--from" && i + 1 < plain.length) return plain[i + 1];
59
+ if (skipValues.has(a)) { i++; continue; }
60
+ if (a.startsWith("-")) continue;
61
+ return a;
62
+ }
63
+ return undefined;
64
+ };
65
+ if (["npx", "bunx", "pnpx"].includes(launcher)) {
66
+ const p = firstFree(0, new Set(["-p", "--package"]));
67
+ if (!p || !NPM_RX.test(p)) return [undefined, false];
68
+ const versioned = p.startsWith("@") ? p.indexOf("@", 1) > 0 : p.includes("@");
69
+ return [p, !versioned || /@latest$/i.test(p)];
70
+ }
71
+ if (launcher === "uvx" || launcher === "pipx") {
72
+ const from = launcher === "pipx" ? plain.indexOf("run") + 1 : 0;
73
+ if (launcher === "pipx" && from === 0) return [undefined, false];
74
+ const p = firstFree(from);
75
+ if (!p || !PYPI_RX.test(p)) return [undefined, false];
76
+ return [p, !/(==|@)/.test(p)];
77
+ }
78
+ if (launcher === "docker" || launcher === "podman") {
79
+ const from = plain.indexOf("run") + 1;
80
+ if (from === 0) return [undefined, false];
81
+ const p = firstFree(from, DOCKER_VALUE_FLAGS);
82
+ if (!p || !IMAGE_RX.test(p)) return [undefined, false];
83
+ const tag = /:([A-Za-z0-9._-]+)(@|$)/.exec(p.slice(p.lastIndexOf("/") + 1));
84
+ return [p, !p.includes("@sha256:") && (!tag || tag[1] === "latest")];
85
+ }
86
+ return [undefined, false];
87
+ }
88
+
89
+ function transportOf(c: Json, remote: boolean): string {
90
+ const t = String(c.transport ?? c.type ?? "").toLowerCase().replace(/[^a-z]/g, "");
91
+ if (t === "stdio") return "stdio";
92
+ if (t === "sse") return "sse";
93
+ if (t === "ws" || t === "websocket") return "ws";
94
+ if (t === "http" || t === "streamablehttp") return "http";
95
+ return remote ? "http" : c.command ? "stdio" : "unknown";
96
+ }
97
+
98
+ export function serverOf(name: string, cfg: unknown, agent: string, scope: "user" | "project"): InvServer | null {
99
+ if (!isObj(cfg)) return null;
100
+ const notes = new Set<string>();
101
+ const url = cfg.url ?? cfg.serverUrl ?? cfg.httpUrl ?? cfg.endpoint;
102
+ const out: InvServer = {
103
+ name: String(name).replace(NAME_RX, "-").slice(0, 64) || "unnamed", agent, scope,
104
+ transport: "unknown", where: "local", notes: [],
105
+ };
106
+ if (typeof url === "string" && /^[a-z][a-z0-9+.-]*:\/\//i.test(url)) {
107
+ const m = /^([a-z][a-z0-9+.-]*):\/\/(?:[^/?#@]*@)?([^/?#]*)/i.exec(url);
108
+ const scheme = (m?.[1] ?? "").toLowerCase();
109
+ const host = (m?.[2] ?? "").toLowerCase();
110
+ out.where = "remote";
111
+ if (HOST_RX.test(host)) out.host = `${scheme}://${host}`;
112
+ if (!LOOPBACK.test(host)) notes.add("remote");
113
+ if ((scheme === "http" || scheme === "ws") && !LOOPBACK.test(host)) notes.add("plain_http");
114
+ out.transport = transportOf(cfg, true);
115
+ } else if (typeof cfg.command === "string" && cfg.command.trim()) {
116
+ const launcher = basename(cfg.command);
117
+ out.launcher = LAUNCHER_RX.test(launcher) ? launcher : "local";
118
+ const [pkg, unpinned] = packageOf(out.launcher, Array.isArray(cfg.args) ? cfg.args : []);
119
+ if (pkg) out.package = pkg;
120
+ if (unpinned) notes.add("unpinned_package");
121
+ out.transport = transportOf(cfg, false);
122
+ } else {
123
+ out.transport = transportOf(cfg, false);
124
+ }
125
+ const env = isObj(cfg.env) ? cfg.env : isObj(cfg.environment) ? cfg.environment : null;
126
+ if (env && Object.keys(env).some((k) => SECRET_KEY_PARTS.some((p) => k.toLowerCase().includes(p)))) notes.add("secret_env");
127
+ if (isObj(cfg.headers) && Object.keys(cfg.headers).length) notes.add("static_auth");
128
+ if (isObj(cfg.http_headers) && Object.keys(cfg.http_headers).length) notes.add("static_auth");
129
+ if (typeof cfg.bearer_token_env_var === "string") notes.add("secret_env");
130
+ out.notes = NOTES.filter((n) => notes.has(n));
131
+ return out;
132
+ }
133
+
134
+ function serversIn(map: unknown, agent: string, scope: "user" | "project", into: InvServer[]): void {
135
+ if (!isObj(map)) return;
136
+ for (const [name, cfg] of Object.entries(map)) {
137
+ const s = serverOf(name, cfg, agent, scope);
138
+ if (s) into.push(s);
139
+ }
140
+ }
141
+
142
+ export interface InventoryOpts { home: string; env?: Record<string, string | undefined>; platform?: string;
143
+ hooked?: (agent: string) => boolean }
144
+
145
+ function vscodeUserDir(home: string, env: Record<string, string | undefined> | undefined, platform: string): string {
146
+ if (platform === "darwin") return join(home, "Library", "Application Support", "Code", "User");
147
+ if (platform === "win32") return join(env?.APPDATA ?? join(home, "AppData", "Roaming"), "Code", "User");
148
+ return join(home, ".config", "Code", "User");
149
+ }
150
+
151
+ /** The machine's inventory. Reads a handful of small config files; never throws. */
152
+ export function buildInventory(o: InventoryOpts): Inventory {
153
+ const { home, env } = o;
154
+ const platform = o.platform ?? process.platform;
155
+ const dir = (id: string) => getAdapter(id).userDir(home, env);
156
+ const servers: InvServer[] = [];
157
+ const safe = (f: () => void) => { try { f(); } catch { /* one bad config never hides the rest */ } };
158
+
159
+ safe(() => {
160
+ const claude = readJson(join(home, ".claude.json"));
161
+ if (isObj(claude)) {
162
+ serversIn(claude.mcpServers, "claude", "user", servers);
163
+ if (isObj(claude.projects)) for (const p of Object.values(claude.projects)) if (isObj(p)) serversIn(p.mcpServers, "claude", "project", servers);
164
+ }
165
+ });
166
+ safe(() => { const c = readJson(join(dir("cursor"), "mcp.json")); if (isObj(c)) serversIn(c.mcpServers, "cursor", "user", servers); });
167
+ safe(() => { const c = readToml(join(dir("codex"), "config.toml")); if (isObj(c)) serversIn(c.mcp_servers, "codex", "user", servers); });
168
+ safe(() => { const c = readJson(join(dir("gemini"), "settings.json")); if (isObj(c)) serversIn(c.mcpServers, "gemini", "user", servers); });
169
+ safe(() => { const c = readJson(join(dir("windsurf"), "mcp_config.json")); if (isObj(c)) serversIn(c.mcpServers, "windsurf", "user", servers); });
170
+ safe(() => { const c = readJson(join(dir("copilot"), "mcp-config.json")); if (isObj(c)) serversIn(c.mcpServers, "copilot", "user", servers); });
171
+ safe(() => {
172
+ const vs = vscodeUserDir(home, env, platform);
173
+ const settings = readJson(join(vs, "settings.json"));
174
+ if (isObj(settings) && isObj(settings.mcp)) serversIn(settings.mcp.servers, "vscode", "user", servers);
175
+ const mcp = readJson(join(vs, "mcp.json"));
176
+ if (isObj(mcp)) serversIn(mcp.servers, "vscode", "user", servers);
177
+ });
178
+
179
+ const seen = new Set<string>();
180
+ const unique = servers.filter((s) => {
181
+ const k = [s.agent, s.scope, s.name, s.host ?? "", s.launcher ?? "", s.package ?? ""].join("\u0000");
182
+ if (seen.has(k)) return false;
183
+ seen.add(k);
184
+ return true;
185
+ });
186
+ unique.sort((a, b) => cmp(a.agent, b.agent) || cmp(a.name, b.name) || cmp(a.scope, b.scope)
187
+ || cmp(a.host ?? "", b.host ?? "") || cmp(a.launcher ?? "", b.launcher ?? "") || cmp(a.package ?? "", b.package ?? ""));
188
+
189
+ const agents = detected(home, env)
190
+ .map((id) => ({ agent: id, hooked: !!(o.hooked && safeBool(() => o.hooked!(id))) }))
191
+ .sort((a, b) => cmp(a.agent, b.agent));
192
+ return fitBudget(agents, unique);
193
+ }
194
+
195
+ /** Keep the report within MAX_SERVERS and the ingest record limit. When it must cut, the servers with the most
196
+ * setup risks are kept first (then canonical order), and the report says it was truncated. Same rule as the
197
+ * Python SDK. */
198
+ export function fitBudget(agents: InvAgent[], servers: InvServer[], budget = INVENTORY_MAX_BYTES): Inventory {
199
+ if (servers.length <= MAX_SERVERS && JSON.stringify({ agents, servers }).length <= budget) return { agents, servers };
200
+ let size = JSON.stringify({ agents, servers: [], truncated: true }).length;
201
+ const order = servers.map((s, i) => [s, i] as const).sort((a, b) => b[0].notes.length - a[0].notes.length || a[1] - b[1]);
202
+ const kept: number[] = [];
203
+ for (const [s, i] of order) {
204
+ const add = JSON.stringify(s).length + (kept.length ? 1 : 0);
205
+ if (kept.length < MAX_SERVERS && size + add <= budget) { kept.push(i); size += add; }
206
+ }
207
+ kept.sort((a, b) => a - b);
208
+ return { agents, servers: kept.map((i) => servers[i]), truncated: true };
209
+ }
210
+
211
+ const cmp = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
212
+ function safeBool(f: () => boolean): boolean { try { return f(); } catch { return false; } }
213
+
214
+ /** Stable fingerprint: the shipper resends only when this changes (or a day passed). Identical to the Python
215
+ * SDK's (sorted keys, json.dumps separators; the inventory is ASCII by construction): both runtimes share
216
+ * one state file, so a machine with both must not see a change that isn't there. */
217
+ export function inventoryFingerprint(inv: Inventory): string {
218
+ return createHash("sha256").update(sortedJson(inv)).digest("hex");
219
+ }
@@ -0,0 +1,29 @@
1
+ // Plain-English sentence per decision reason code. A copy of xtrom-engine/xtrom/reason_text.json (the one source,
2
+ // shared with the Python CLI and the console); test/local-view.test.ts keeps it equal.
3
+ export const REASON_TEXT: Readonly<Record<string, string>> = Object.freeze({
4
+ "policy.allow": "Within policy",
5
+ "scope.deny": "Action is outside the agent's policy scope",
6
+ "ifc.untrusted_to_sink": "Untrusted data reached a sensitive argument",
7
+ "ifc.untrusted_content_stepup": "Untrusted content reached this action — needs approval",
8
+ "ifc.context_tainted_stepup": "Sensitive action after untrusted input in this session",
9
+ "egress.secret_non_allowlisted": "A secret was headed to a host not on the allowlist",
10
+ "egress.secret_to_durable_sink": "A secret was headed into durable storage — needs approval",
11
+ "policy.destructive_prod_stepup": "Destructive action in production — needs approval",
12
+ "policy.transfer_threshold_stepup": "Transfer above the approval threshold",
13
+ "risk.high_block": "Behavioural risk score over the block threshold",
14
+ "risk.elevated_stepup": "Elevated behavioural risk — needs approval",
15
+ "fail_closed": "Enforcement error — failed closed",
16
+ "plan.planned_call": "Planned from the user's request; untrusted data only filled planned fields",
17
+ "ifc.allowlisted_read": "Read of an allowlisted site; untrusted content only chose which page",
18
+ "approval.allowance": "Covered by an earlier approval",
19
+ "local.tamper_protected": "Tried to change Xtrom's own files or settings",
20
+ "local.env_override": "Tried to set an Xtrom environment override",
21
+ "local.shell_startup": "Tried to edit a shell startup file",
22
+ "local.self_manage": "Tried to reinstall, remove or reconnect Xtrom",
23
+ "local.settings_change": "Tried to change the coding agent's hook settings",
24
+ "local.fail_safe_state": "Session state unreadable — asked to be safe",
25
+ "local.browser_credentials": "Touched a site's cookies or storage",
26
+ "local.browser_secret_entry": "Typed a secret into a web page",
27
+ "local.browser_secret_upload": "Uploaded a credential file to a web page",
28
+ "context.tainted": "Sensitive action after untrusted input in this session",
29
+ });