@xtrom-ai/sdk 0.0.0-stage → 0.7.0
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.
- package/LICENSE +190 -0
- package/README.md +185 -2
- package/dist/allowances.js +74 -0
- package/dist/cli.js +268 -0
- package/dist/credentials.js +37 -0
- package/dist/directive.js +57 -0
- package/dist/enforce.js +972 -0
- package/dist/index.js +31 -0
- package/dist/inspect.js +135 -0
- package/dist/local/agents.js +378 -0
- package/dist/local/appliers.js +61 -0
- package/dist/local/browser.js +135 -0
- package/dist/local/discover.js +154 -0
- package/dist/local/hook.js +778 -0
- package/dist/local/install.js +238 -0
- package/dist/local/inventory.js +219 -0
- package/dist/local/reasonText.js +29 -0
- package/dist/local/shipper.js +251 -0
- package/dist/local/spool.js +178 -0
- package/dist/local/updateKeys.js +3 -0
- package/dist/local/updater.js +224 -0
- package/dist/local/view.js +110 -0
- package/dist/memory.js +172 -0
- package/dist/reporter.js +336 -0
- package/dist/session.js +439 -0
- package/dist/version.js +2 -0
- package/dist/workspace.js +72 -0
- package/package.json +23 -4
- package/src/allowances.ts +74 -0
- package/src/cli.ts +268 -0
- package/src/credentials.ts +37 -0
- package/src/directive.ts +57 -0
- package/src/enforce.ts +972 -0
- package/src/index.ts +31 -0
- package/src/inspect.ts +135 -0
- package/src/local/agents.ts +378 -0
- package/src/local/appliers.ts +61 -0
- package/src/local/browser.ts +135 -0
- package/src/local/discover.ts +154 -0
- package/src/local/hook.ts +778 -0
- package/src/local/install.ts +238 -0
- package/src/local/inventory.ts +219 -0
- package/src/local/reasonText.ts +29 -0
- package/src/local/shipper.ts +251 -0
- package/src/local/spool.ts +178 -0
- package/src/local/updateKeys.ts +3 -0
- package/src/local/updater.ts +224 -0
- package/src/local/view.ts +110 -0
- package/src/memory.ts +172 -0
- package/src/reporter.ts +336 -0
- package/src/session.ts +439 -0
- package/src/version.ts +2 -0
- package/src/workspace.ts +72 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Xtrom SDK (TypeScript) — public API.
|
|
2
|
+
export { Session, BlockedError, StepUpRequired } from "./session.js";
|
|
3
|
+
|
|
4
|
+
export {
|
|
5
|
+
decide, defaultPolicy, looksLikeSecret, matchesSecretPattern, sensitivity, sinkClass, originTag, isDestinationArg,
|
|
6
|
+
isKnownSecret, hostOf, trusted, untrusted, secret, Ingress, decisionSignals,
|
|
7
|
+
ReasonCode, Sensitivity, DEFAULT_SENSITIVITY, DEFAULT_DESTINATION_ARGS, EGRESS_ACTIONS,
|
|
8
|
+
DESTRUCTIVE_ACTIONS, SINK_ACTIONS, FINANCIAL_ACTIONS, CREDENTIAL_ACTIONS, SIGNALS_SCHEMA_VERSION,
|
|
9
|
+
planMatches, planSlotOk, planChoiceOk, extractChoices, PLAN_TEXT_MAX, PLAN_CHOICES_MAX,
|
|
10
|
+
|
|
11
|
+
} from "./enforce.js";
|
|
12
|
+
export { DecisionReporter, attribution, decisionEvent, INGEST_PATH } from "./reporter.js";
|
|
13
|
+
export { credentials, CredentialsError } from "./credentials.js";
|
|
14
|
+
|
|
15
|
+
export { inspectResult, RESULT_FLAGS, RESULT_SCAN_BUDGET } from "./inspect.js";
|
|
16
|
+
export { MemoryProvenance, FileMemoryProvenance, memoryChunks, memoryFingerprints, memoryReadTrust, DEFAULT_MEMORY_WRITE_ACTIONS, DEFAULT_MEMORY_READ_ACTIONS } from "./memory.js";
|
|
17
|
+
export { matchAllowance, dataCondition, COVERABLE, APPROVAL_LAYER, APPROVAL_REASON_CODE } from "./allowances.js";
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
import { API_VERSION, SDK_VERSION } from "./version.js";
|
|
22
|
+
export { API_VERSION, SDK_VERSION };
|
|
23
|
+
|
|
24
|
+
// Version headers for HTTP integrations — same handshake as the control plane's X-Xtrom-API-Version.
|
|
25
|
+
export function xtromHeaders() {
|
|
26
|
+
return {
|
|
27
|
+
"X-Xtrom-API-Version": API_VERSION,
|
|
28
|
+
"X-Xtrom-SDK-Version": SDK_VERSION,
|
|
29
|
+
"X-Xtrom-SDK-Lang": "typescript",
|
|
30
|
+
};
|
|
31
|
+
}
|
package/dist/inspect.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// Tool-RESULT inspection — what came back from a tool, reduced to closed-enum flags. Port of
|
|
2
|
+
// xtrom.core.inspect_result; gated on ../../xtrom-engine/result_golden.json (test/inspect.test.ts)
|
|
3
|
+
// together with the Python engine and the Go gateway. Observational: never changes a verdict and
|
|
4
|
+
// never ships content — only flags and a byte count leave the process.
|
|
5
|
+
import { decodedViews } from "./enforce.js";
|
|
6
|
+
|
|
7
|
+
export const RESULT_FLAGS = ["hidden_unicode", "instruction", "pii", "secret", "truncated"] ;
|
|
8
|
+
|
|
9
|
+
export const RESULT_SCAN_BUDGET = 256 * 1024;
|
|
10
|
+
const MAX_STRINGS = 10_000;
|
|
11
|
+
const MAX_DEPTH = 32;
|
|
12
|
+
|
|
13
|
+
// Bounded quantifiers everywhere: a result is attacker-controlled, so nothing may backtrack
|
|
14
|
+
// super-linearly over RESULT_SCAN_BUDGET bytes.
|
|
15
|
+
const SECRET_RX = [
|
|
16
|
+
/AKIA[0-9A-Z]{16}/,
|
|
17
|
+
/aws_secret_access_key/i,
|
|
18
|
+
/gh[pousr]_[A-Za-z0-9]{20}/,
|
|
19
|
+
/sk-[A-Za-z0-9]{20}/,
|
|
20
|
+
/-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/,
|
|
21
|
+
/(password|passwd|secret|api[_-]?key|token)[ \t]{0,8}[=:][ \t]{0,8}\S/i,
|
|
22
|
+
/postgres(?:ql)?:\/\/[^\s:@/]{1,256}:[^\s@/]{1,256}@[^\s@]/,
|
|
23
|
+
];
|
|
24
|
+
const INSTRUCTION_RX = [
|
|
25
|
+
/<\s{0,8}\/?\s{0,8}(important|system|instructions?|secret|admin)\b[^>]{0,200}>/i,
|
|
26
|
+
/\b(ignore|disregard|forget)\s+(all\s+|any\s+)?((your|my|the)\s+)?(previous|prior|above|earlier|other)\s+(instructions?|prompts?|rules?)/i,
|
|
27
|
+
/\bdo\s+not\s+(tell|inform|mention|reveal|show|alert|notify)\b[^.\n]{0,60}\b(user|human|operator)/i,
|
|
28
|
+
/\b(you|the\s+(assistant|model|ai|agent))\s+(must|should|need\s+to)\s+(first|also|always|secretly|silently|quietly)\s+(read|send|include|pass|forward|upload|exfiltrate|attach|call)\b/i,
|
|
29
|
+
/\bbefore\s+(using|calling|invoking)\s+(this|any)\s+tool\b[^.\n]{0,40}\b(read|send|include|pass|forward|upload|call|access|fetch|attach)\b/i,
|
|
30
|
+
/\b(secretly|silently|covertly|without\s+(telling|informing|notifying)\s+the\s+user)\b/i,
|
|
31
|
+
/\b(when|whenever|if)\s+(the\s+user|you)\s+(calls?|uses?|invokes?)\s+(the\s+)?[\w.-]+\s+tool\b/i,
|
|
32
|
+
/\binstead\s+of\s+(calling|using)\s+(the\s+)?[\w.-]+\s+tool\b/i,
|
|
33
|
+
// Addressed to the model, role spoofing, new-instruction declarations, override banners (injection_heldout.json).
|
|
34
|
+
/\b(dear|hey|hi|hello|attention|note\s+to(\s+the)?|message\s+(for|to)(\s+you,?)?(\s+the)?|to\s+the|for\s+the)\s+(ai|a\.i\.|assistant|language\s+model|llm|chatbot|agent|ai\s+(model|agent|assistant))\s{0,4}(,|:|!|\breading\b|\bprocessing\b)/i,
|
|
35
|
+
/\byou,?\s+the\s+(ai|a\.i\.|assistant|language\s+model|llm|chatbot|agent|ai\s+(model|agent|assistant))\b/i,
|
|
36
|
+
/\bif\s+you(\s+are|'re)\s+an?\s+(ai|a\.i\.|assistant|language\s+model|llm|chatbot|agent|ai\s+(model|agent|assistant))\b/i,
|
|
37
|
+
/\bas\s+an?\s+(ai|a\.i\.|assistant|language\s+model|llm|chatbot|agent|ai\s+(model|agent|assistant))\b[^.\n]{0,40}\b(must|required|need\s+to|have\s+to)\b/i,
|
|
38
|
+
/<\|\s{0,4}im_(start|end)\s{0,4}\|>|\[\/?INST\]|<<\s{0,4}\/?SYS\s{0,4}>>/,
|
|
39
|
+
/^\s{0,8}#{1,6}\s{0,8}(system|instructions?)\s{0,8}:/im,
|
|
40
|
+
/^\s{0,8}(system|assistant)\s{0,4}:\s/im,
|
|
41
|
+
/\"role\"\s{0,4}:\s{0,4}\"(system|developer)\"/i,
|
|
42
|
+
/\b(new|updated|additional|real|actual)\s+(instructions?|task|objective|directive|orders?)(\s+(for|to)\s+(you|the\s+(ai|a\.i\.|assistant|language\s+model|llm|chatbot|agent|ai\s+(model|agent|assistant))))?\s{0,4}:/i,
|
|
43
|
+
/\byour\s+(new|real|actual|true)\s+(instructions?|task|objective|directive|goal|purpose)\s+(is|are)\b/i,
|
|
44
|
+
/\b(begin|end|start)\s+(admin|administrator|developer|system)\s+(override|mode|instructions?)\b/i,
|
|
45
|
+
/\b(admin|administrator|developer|system)\s+(message|prompt\s+update|mode\s+(enabled|activated|on))\s{0,4}[:!.]/i,
|
|
46
|
+
/\b(ignore|disregard)\s+(what\s+the\s+user|the\s+user'?s?\s+(request|question|instructions?))\b/i,
|
|
47
|
+
/-{2,}\s{0,4}end\s+of\s+(document|context|email|page|file|input)\s{0,4}-{2,}/i,
|
|
48
|
+
];
|
|
49
|
+
const SSN_RX = /\b(\d{3})-(\d{2})-(\d{4})\b/g;
|
|
50
|
+
const CARD_RX = /\b(?:\d[ -]?){12,18}\d\b/g;
|
|
51
|
+
const EMAIL_RX = /[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9-]{1,63}(?:\.[A-Za-z0-9-]{1,63}){0,8}\.[A-Za-z]{2,24}/g;
|
|
52
|
+
const EMAIL_BULK = 5;
|
|
53
|
+
|
|
54
|
+
function hiddenRune(cp ) {
|
|
55
|
+
return (cp >= 0x200b && cp <= 0x200f) || (cp >= 0x202a && cp <= 0x202e) || (cp >= 0x2060 && cp <= 0x2064)
|
|
56
|
+
|| (cp >= 0x2066 && cp <= 0x2069) || cp === 0xfeff || (cp >= 0xe0000 && cp <= 0xe007f);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function luhn(digits ) {
|
|
60
|
+
let total = 0;
|
|
61
|
+
for (let i = 0; i < digits.length; i++) {
|
|
62
|
+
let n = digits.charCodeAt(digits.length - 1 - i) - 48;
|
|
63
|
+
if (i % 2) n = n > 4 ? n * 2 - 9 : n * 2;
|
|
64
|
+
total += n;
|
|
65
|
+
}
|
|
66
|
+
return total % 10 === 0;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function hasPii(text ) {
|
|
70
|
+
for (const m of text.matchAll(SSN_RX)) {
|
|
71
|
+
const [, area, group, serial] = m;
|
|
72
|
+
if (area !== "000" && area !== "666" && area[0] !== "9" && group !== "00" && serial !== "0000") return true;
|
|
73
|
+
}
|
|
74
|
+
for (const m of text.matchAll(CARD_RX)) {
|
|
75
|
+
const digits = m[0].replace(/[ -]/g, "");
|
|
76
|
+
if (digits.length >= 13 && digits.length <= 19 && new Set(digits).size > 1 && luhn(digits)) return true;
|
|
77
|
+
}
|
|
78
|
+
const emails = new Set ();
|
|
79
|
+
for (const m of text.matchAll(EMAIL_RX)) {
|
|
80
|
+
emails.add(m[0].toLowerCase());
|
|
81
|
+
if (emails.size >= EMAIL_BULK) return true;
|
|
82
|
+
}
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function collect(v , out , depth = 0) {
|
|
87
|
+
if (out.length >= MAX_STRINGS || depth > MAX_DEPTH) return;
|
|
88
|
+
if (typeof v === "string") { out.push(v); return; }
|
|
89
|
+
if (v === null || v === undefined || typeof v !== "object") return; // numbers, booleans, bigint…
|
|
90
|
+
if (ArrayBuffer.isView(v) || v instanceof ArrayBuffer) return; // raw bytes are not text
|
|
91
|
+
if (Array.isArray(v)) { for (const x of v) collect(x, out, depth + 1); return; }
|
|
92
|
+
const rec = v ;
|
|
93
|
+
for (const k of Object.keys(rec).sort()) {
|
|
94
|
+
out.push(k);
|
|
95
|
+
collect(rec[k], out, depth + 1);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
/** Deterministic, bounded inspection of a tool's output. Never throws. */
|
|
105
|
+
export function inspectResult(result , budget = RESULT_SCAN_BUDGET) {
|
|
106
|
+
try {
|
|
107
|
+
const strings = [];
|
|
108
|
+
collect(result, strings);
|
|
109
|
+
let total = 0, scanned = 0;
|
|
110
|
+
const parts = [];
|
|
111
|
+
for (const s of strings) {
|
|
112
|
+
const b = Buffer.from(s, "utf8");
|
|
113
|
+
total += b.length;
|
|
114
|
+
if (scanned < budget) {
|
|
115
|
+
const take = b.subarray(0, budget - scanned);
|
|
116
|
+
scanned += take.length;
|
|
117
|
+
parts.push(take.toString("utf8"));
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
const flags = new Set ();
|
|
121
|
+
if (total > budget) flags.add("truncated");
|
|
122
|
+
for (const text of parts) {
|
|
123
|
+
if (!text) continue;
|
|
124
|
+
if (!flags.has("secret") && decodedViews(text).some((view) => SECRET_RX.some((rx) => rx.test(view)))) flags.add("secret");
|
|
125
|
+
if (!flags.has("instruction") && INSTRUCTION_RX.some((rx) => rx.test(text))) flags.add("instruction");
|
|
126
|
+
if (!flags.has("hidden_unicode")) {
|
|
127
|
+
for (const ch of text) if (hiddenRune(ch.codePointAt(0) )) { flags.add("hidden_unicode"); break; }
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (hasPii(parts.join("\n"))) flags.add("pii");
|
|
131
|
+
return { flags: [...flags].sort() , bytes: total };
|
|
132
|
+
} catch {
|
|
133
|
+
return { flags: ["truncated"], bytes: 0 };
|
|
134
|
+
}
|
|
135
|
+
}
|
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
// Coding-agent adapters for the local hook — mirror of xtrom_sdk/local/agents.py (the differential
|
|
2
|
+
// test compares the two). An adapter is the only place that knows an agent's hook protocol: where its
|
|
3
|
+
// config lives and how our entry looks there, how its payload maps onto the canonical (Claude-style)
|
|
4
|
+
// payload the engine reads, and how a verdict is written back so the agent enforces it.
|
|
5
|
+
//
|
|
6
|
+
// Fail-closed rules shared by every adapter:
|
|
7
|
+
// - "ask" becomes "deny" where the agent can't pause for a human (Codex, Cursor, Gemini, Windsurf).
|
|
8
|
+
// - The launcher turns a crashed or missing runtime into exit 2, which every agent here treats as a block.
|
|
9
|
+
import { existsSync, statSync } from "node:fs";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
|
|
12
|
+
export const PRE = "PreToolUse";
|
|
13
|
+
export const POST = "PostToolUse";
|
|
14
|
+
// Entries are recognised by a marker argument on the hook command (schema-clean: no custom keys a
|
|
15
|
+
// strict config validator could reject). Each runtime owns only its own entries.
|
|
16
|
+
export const MARKER_PY = "--managed-by=xtrom-sdk-local";
|
|
17
|
+
export const MARKER_TS = "--managed-by=xtrom-sdk-ts";
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
const out = (stdout = null, exitCode = 0, stderr = "") => ({ stdout, exitCode, stderr });
|
|
23
|
+
|
|
24
|
+
const URL_IN_TEXT = /https?:\/\/[^\s'"<>)]+/i;
|
|
25
|
+
|
|
26
|
+
/** How the agent starts the hook: `argv` is the exec form, `line()` the shell-string form. */
|
|
27
|
+
export class HookCommand {
|
|
28
|
+
argv ;
|
|
29
|
+
constructor(argv ) { this.argv = argv; }
|
|
30
|
+
line() {
|
|
31
|
+
if (process.platform === "win32") return this.argv.map((a) => (/[\s"]/.test(a) ? `"${a.replace(/"/g, '\\"')}"` : a)).join(" ");
|
|
32
|
+
return this.argv.map((a) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(a) ? a : `'${a.replace(/'/g, `'"'"'`)}'`)).join(" ");
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function obj(value ) {
|
|
37
|
+
if (typeof value === "string") {
|
|
38
|
+
try { value = JSON.parse(value); } catch { return { input: value }; }
|
|
39
|
+
}
|
|
40
|
+
if (value && typeof value === "object" && !Array.isArray(value)) return value ;
|
|
41
|
+
return value === null || value === undefined ? {} : { input: value };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export const mcpName = (server , tool ) => `mcp__${server || "unknown"}__${tool || "tool"}`;
|
|
45
|
+
|
|
46
|
+
export class Adapter {
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
/** Attribution recorded on every decision. */
|
|
50
|
+
|
|
51
|
+
/** Dir under $HOME whose presence means the agent is installed. */
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
/** [native event, canonical event] */
|
|
56
|
+
|
|
57
|
+
canAsk = false;
|
|
58
|
+
toolMap = {};
|
|
59
|
+
/** The config file exists only for Xtrom (delete it when empty). */
|
|
60
|
+
ownsFile = false;
|
|
61
|
+
|
|
62
|
+
/** Env var that relocates the agent's user dir (`detect`). */
|
|
63
|
+
homeEnv = null;
|
|
64
|
+
|
|
65
|
+
/** `env` is consulted only for the real home (tests pass none), so a relocated agent
|
|
66
|
+
* (COPILOT_HOME, CODEX_HOME) gets hooks where it actually reads them. */
|
|
67
|
+
userDir(home , env ) {
|
|
68
|
+
const v = env && this.homeEnv ? env[this.homeEnv] : undefined;
|
|
69
|
+
return v ? v.replace(/^~(?=$|[/\\])/, home) : join(home, ...this.detect);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
configPath(scope , home , projectDir , env ) {
|
|
73
|
+
if (scope !== "user" && scope !== "project") throw new Error("scope must be 'user' or 'project'");
|
|
74
|
+
return scope === "project" ? join(projectDir, ...this.projectConfig)
|
|
75
|
+
: join(this.userDir(home, env), ...this.userConfig.slice(this.detect.length));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
toolName(name , _input , _raw ) {
|
|
79
|
+
return Object.hasOwn(this.toolMap, name) ? this.toolMap[name] : name;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
normalize(raw , eventHint ) {
|
|
83
|
+
let input = obj("tool_input" in raw ? raw.tool_input : raw.toolArgs);
|
|
84
|
+
const name = this.toolName(String(raw.tool_name ?? raw.toolName ?? ""), input, raw);
|
|
85
|
+
if (name === "WebFetch" && !("url" in input)) {
|
|
86
|
+
const m = URL_IN_TEXT.exec(JSON.stringify(input));
|
|
87
|
+
if (m) input = { ...input, url: m[0] };
|
|
88
|
+
}
|
|
89
|
+
const respKey = ["tool_response", "tool_output", "tool_result", "toolResult"].find((k) => k in raw);
|
|
90
|
+
return {
|
|
91
|
+
hook_event_name: this.canonicalEvent(String(raw.hook_event_name ?? ""), eventHint),
|
|
92
|
+
session_id: raw.session_id || raw.sessionId || raw.conversation_id,
|
|
93
|
+
tool_name: name,
|
|
94
|
+
tool_input: input,
|
|
95
|
+
tool_response: respKey ? raw[respKey] : null,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
canonicalEvent(native , hint ) {
|
|
100
|
+
for (const [n, c] of this.events) if (native && native === n) return c;
|
|
101
|
+
const h = (hint ?? "").toLowerCase();
|
|
102
|
+
return h === "pre" ? PRE : h === "post" ? POST : native;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
render(event , decision , reason = "") {
|
|
106
|
+
if (event !== PRE || decision === null) return out();
|
|
107
|
+
if (decision === "ask" && !this.canAsk) [decision, reason] = ["deny", this.noAsk(reason)];
|
|
108
|
+
return this.verdict(decision, reason);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
verdict(decision , reason ) {
|
|
112
|
+
return out({ hookSpecificOutput: { hookEventName: PRE, permissionDecision: decision, permissionDecisionReason: reason } });
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
noAsk(reason ) {
|
|
116
|
+
return `${reason.replace(/\.+$/, "")}. ${this.label} can't pause for your approval, so Xtrom blocked it. `
|
|
117
|
+
+ "If you intended this, run it yourself in a terminal.";
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Top-level keys the config needs besides `hooks`. */
|
|
121
|
+
prepare(_data ) {}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
class ClaudeCode extends Adapter {
|
|
127
|
+
id = "claude"; label = "Claude Code"; client = "claude-code";
|
|
128
|
+
detect = [".claude"]; userConfig = [".claude", "settings.json"]; projectConfig = [".claude", "settings.json"];
|
|
129
|
+
events = [[PRE, PRE], [POST, POST]] ;
|
|
130
|
+
canAsk = true;
|
|
131
|
+
entry(_e , cmd ) {
|
|
132
|
+
return { matcher: "*", hooks: [{ type: "command", command: cmd.argv[0], args: cmd.argv.slice(1), timeout: 10 }] };
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** GitHub Copilot CLI (also VS Code's Copilot agent host). Native camelCase events, so the payload is
|
|
137
|
+
* camelCase with runtime tool names; MCP tools surface as `<server>-<tool>`. */
|
|
138
|
+
class CopilotCLI extends Adapter {
|
|
139
|
+
id = "copilot"; label = "GitHub Copilot CLI"; client = "copilot-cli";
|
|
140
|
+
detect = [".copilot"]; userConfig = [".copilot", "hooks", "xtrom.json"]; projectConfig = [".github", "hooks", "xtrom.json"];
|
|
141
|
+
events = [["preToolUse", PRE], ["postToolUse", POST]] ;
|
|
142
|
+
canAsk = true;
|
|
143
|
+
ownsFile = true;
|
|
144
|
+
homeEnv = "COPILOT_HOME";
|
|
145
|
+
toolMap = {
|
|
146
|
+
bash: "Bash", powershell: "Bash", view: "Read", create: "Write", edit: "Edit", str_replace_editor: "Edit",
|
|
147
|
+
apply_patch: "Edit", grep: "Grep", rg: "Grep", glob: "Glob", web_fetch: "WebFetch", web_search: "WebSearch",
|
|
148
|
+
};
|
|
149
|
+
toolName(name ) {
|
|
150
|
+
if (Object.hasOwn(this.toolMap, name)) return this.toolMap[name];
|
|
151
|
+
// Built-ins are snake_case; MCP tools are "<server>-<tool>" (github-mcp-server-get_me).
|
|
152
|
+
if (name.includes("-") && !name.startsWith("mcp__")) {
|
|
153
|
+
const i = name.lastIndexOf("-");
|
|
154
|
+
return mcpName(name.slice(0, i), name.slice(i + 1));
|
|
155
|
+
}
|
|
156
|
+
return name;
|
|
157
|
+
}
|
|
158
|
+
prepare(data ) { data.version ??= 1; }
|
|
159
|
+
// Cloud agent treats "ask" as deny on its own; the CLI prompts.
|
|
160
|
+
verdict(decision , reason ) {
|
|
161
|
+
return out({ permissionDecision: decision, permissionDecisionReason: reason });
|
|
162
|
+
}
|
|
163
|
+
entry(_e , cmd ) { return { type: "command", command: cmd.line(), timeoutSec: 10 }; }
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
class Cursor extends Adapter {
|
|
167
|
+
id = "cursor"; label = "Cursor"; client = "cursor";
|
|
168
|
+
detect = [".cursor"]; userConfig = [".cursor", "hooks.json"]; projectConfig = [".cursor", "hooks.json"];
|
|
169
|
+
events = [["preToolUse", PRE], ["postToolUse", POST]] ;
|
|
170
|
+
toolMap = {
|
|
171
|
+
Shell: "Bash", Read: "Read", Write: "Write", Edit: "Edit", StrReplace: "Edit", MultiEdit: "Edit", Delete: "Edit",
|
|
172
|
+
Grep: "Grep", Glob: "Glob", LS: "Glob", WebFetch: "WebFetch", WebSearch: "WebSearch",
|
|
173
|
+
};
|
|
174
|
+
toolName(name , _input , raw ) {
|
|
175
|
+
if (name.startsWith("MCP:")) return mcpName(String(raw.server_name || "cursor"), name.slice(4));
|
|
176
|
+
return Object.hasOwn(this.toolMap, name) ? this.toolMap[name] : name;
|
|
177
|
+
}
|
|
178
|
+
// preToolUse is installed failClosed, where "no output" also blocks: always answer.
|
|
179
|
+
render(event , decision , reason = "") {
|
|
180
|
+
if (event === PRE && decision === null) return out({ permission: "allow" });
|
|
181
|
+
return super.render(event, decision, reason);
|
|
182
|
+
}
|
|
183
|
+
verdict(_d , reason ) {
|
|
184
|
+
return out({ permission: "deny", user_message: reason, agent_message: reason });
|
|
185
|
+
}
|
|
186
|
+
prepare(data ) { data.version ??= 1; }
|
|
187
|
+
entry(e , cmd ) {
|
|
188
|
+
const entry = { command: cmd.line(), timeout: 10 };
|
|
189
|
+
if (e === PRE) entry.failClosed = true;
|
|
190
|
+
return entry;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** OpenAI Codex CLI. Claude-shaped protocol, but "ask" is unsupported (Codex marks the hook failed and
|
|
195
|
+
* runs the tool), so it must never be emitted. New hooks need a one-time trust in /hooks. */
|
|
196
|
+
class CodexCLI extends Adapter {
|
|
197
|
+
id = "codex"; label = "OpenAI Codex CLI"; client = "codex";
|
|
198
|
+
detect = [".codex"]; userConfig = [".codex", "hooks.json"]; projectConfig = [".codex", "hooks.json"];
|
|
199
|
+
events = [[PRE, PRE], [POST, POST]] ;
|
|
200
|
+
toolMap = { apply_patch: "Edit" };
|
|
201
|
+
homeEnv = "CODEX_HOME";
|
|
202
|
+
entry(_e , cmd ) {
|
|
203
|
+
return { hooks: [{ type: "command", command: cmd.line(), timeout: 10, statusMessage: "Xtrom policy check" }] };
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
class GeminiCLI extends Adapter {
|
|
208
|
+
id = "gemini"; label = "Gemini CLI"; client = "gemini-cli";
|
|
209
|
+
detect = [".gemini"]; userConfig = [".gemini", "settings.json"]; projectConfig = [".gemini", "settings.json"];
|
|
210
|
+
events = [["BeforeTool", PRE], ["AfterTool", POST]] ;
|
|
211
|
+
toolMap = {
|
|
212
|
+
run_shell_command: "Bash", read_file: "Read", read_many_files: "Read", write_file: "Write", replace: "Edit",
|
|
213
|
+
edit: "Edit", list_directory: "Glob", glob: "Glob", search_file_content: "Grep", grep: "Grep",
|
|
214
|
+
web_fetch: "WebFetch", google_web_search: "WebSearch",
|
|
215
|
+
};
|
|
216
|
+
toolName(name ) {
|
|
217
|
+
if (Object.hasOwn(this.toolMap, name)) return this.toolMap[name];
|
|
218
|
+
if (name.startsWith("mcp_") && !name.startsWith("mcp__")) {
|
|
219
|
+
const rest = name.slice(4), i = rest.indexOf("_");
|
|
220
|
+
return i < 0 ? mcpName(rest, "") : mcpName(rest.slice(0, i), rest.slice(i + 1));
|
|
221
|
+
}
|
|
222
|
+
return name;
|
|
223
|
+
}
|
|
224
|
+
verdict(_d , reason ) { return out({ decision: "deny", reason }); }
|
|
225
|
+
entry(_e , cmd ) {
|
|
226
|
+
return { matcher: "*", hooks: [{ type: "command", command: cmd.line(), name: "xtrom", timeout: 10000,
|
|
227
|
+
description: "Xtrom runtime firewall" }] };
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Windsurf / Devin Desktop Cascade. One event per action kind; the only way to block is exit 2 with
|
|
232
|
+
* the reason on stderr. */
|
|
233
|
+
class Windsurf extends Adapter {
|
|
234
|
+
id = "windsurf"; label = "Windsurf"; client = "windsurf";
|
|
235
|
+
detect = [".codeium", "windsurf"]; userConfig = [".codeium", "windsurf", "hooks.json"]; projectConfig = [".devin", "hooks.json"];
|
|
236
|
+
events = [["pre_run_command", PRE], ["pre_read_code", PRE], ["pre_write_code", PRE], ["pre_mcp_tool_use", PRE],
|
|
237
|
+
["post_run_command", POST], ["post_mcp_tool_use", POST]] ;
|
|
238
|
+
tools = { run_command: "Bash", read_code: "Read", write_code: "Edit", mcp_tool_use: "mcp" };
|
|
239
|
+
normalize(raw , eventHint ) {
|
|
240
|
+
const action = String(raw.agent_action_name ?? "");
|
|
241
|
+
const info = raw.tool_info && typeof raw.tool_info === "object" && !Array.isArray(raw.tool_info) ? raw.tool_info : {};
|
|
242
|
+
const i = action.indexOf("_");
|
|
243
|
+
let tool = this.tools[i < 0 ? action : action.slice(i + 1)] ?? "";
|
|
244
|
+
let input ;
|
|
245
|
+
if (tool === "Bash") input = { command: String(info.command_line ?? ""), cwd: info.cwd ?? null };
|
|
246
|
+
else if (tool === "mcp") {
|
|
247
|
+
tool = mcpName(String(info.mcp_server_name ?? ""), String(info.mcp_tool_name ?? ""));
|
|
248
|
+
input = obj(info.mcp_tool_arguments);
|
|
249
|
+
} else input = Object.fromEntries(["file_path", "edits"].filter((k) => k in info).map((k) => [k, info[k]]));
|
|
250
|
+
return {
|
|
251
|
+
hook_event_name: this.canonicalEvent(action, eventHint), session_id: raw.trajectory_id || raw.execution_id,
|
|
252
|
+
tool_name: tool, tool_input: input, tool_response: info.mcp_result ?? null,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
verdict(_d , reason ) { return out(null, 2, reason); }
|
|
256
|
+
entry(_e , cmd ) { return { command: cmd.line(), show_output: false }; }
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const ADAPTERS = [new ClaudeCode(), new CopilotCLI(), new Cursor(), new CodexCLI(), new GeminiCLI(), new Windsurf()];
|
|
260
|
+
export const AGENTS = Object.fromEntries(ADAPTERS.map((a) => [a.id, a]));
|
|
261
|
+
export const AGENT_IDS = ADAPTERS.map((a) => a.id);
|
|
262
|
+
export const DEFAULT_AGENT = "claude";
|
|
263
|
+
|
|
264
|
+
/** Unknown ids fall back to Claude Code so a hook invoked with a stray flag still enforces. */
|
|
265
|
+
export function getAdapter(id ) {
|
|
266
|
+
const key = String(id || DEFAULT_AGENT).toLowerCase();
|
|
267
|
+
return Object.hasOwn(AGENTS, key) ? AGENTS[key] : AGENTS[DEFAULT_AGENT];
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const isDir = (p ) => { try { return existsSync(p) && statSync(p).isDirectory(); } catch { return false; } };
|
|
271
|
+
export const detected = (home , env ) =>
|
|
272
|
+
ADAPTERS.filter((a) => isDir(a.userDir(home, env))).map((a) => a.id);
|
|
273
|
+
|
|
274
|
+
/** `auto` → agents found on this machine (Claude Code if none); `all` → every adapter; otherwise a
|
|
275
|
+
* comma list. Unknown ids throw, so a typo never silently protects nothing. */
|
|
276
|
+
// Names people type for an agent (its product name or CLI), mapped to the id. Same in the Python SDK.
|
|
277
|
+
export const ALIASES = Object.freeze({
|
|
278
|
+
"claude-code": "claude", "copilot-cli": "copilot", "github-copilot": "copilot", "codex-cli": "codex",
|
|
279
|
+
"openai-codex": "codex", "gemini-cli": "gemini",
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
export function resolveAgents(spec , home , env ) {
|
|
283
|
+
const s = (spec ?? "auto").trim().toLowerCase().split(",")
|
|
284
|
+
.map((x) => (Object.hasOwn(ALIASES, x.trim()) ? ALIASES[x.trim()] : x)).join(",");
|
|
285
|
+
if (s === "auto") { const d = detected(home, env); return d.length ? d : [DEFAULT_AGENT]; }
|
|
286
|
+
if (s === "all") return [...AGENT_IDS];
|
|
287
|
+
const ids = [...new Set(s.split(",").map((x) => x.trim()).filter(Boolean))];
|
|
288
|
+
const unknown = ids.filter((i) => !Object.hasOwn(AGENTS, i));
|
|
289
|
+
if (unknown.length || !ids.length) {
|
|
290
|
+
throw new Error(`unknown agent ${unknown.join(", ") || JSON.stringify(spec)}; choose from ${AGENT_IDS.join(", ")}, auto or all`);
|
|
291
|
+
}
|
|
292
|
+
return ids;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// ---------------------------------------------------------------- config entries (runtime-neutral)
|
|
296
|
+
|
|
297
|
+
function shellSplit(s ) {
|
|
298
|
+
const outv = [];
|
|
299
|
+
let cur = "", q = null, any = false;
|
|
300
|
+
for (let i = 0; i < s.length; i++) {
|
|
301
|
+
const c = s[i];
|
|
302
|
+
if (q) {
|
|
303
|
+
if (c === q) q = null;
|
|
304
|
+
else if (c === "\\" && q === '"' && i + 1 < s.length) cur += s[++i];
|
|
305
|
+
else cur += c;
|
|
306
|
+
} else if (c === "'" || c === '"') { q = c; any = true; }
|
|
307
|
+
else if (c === "\\" && i + 1 < s.length) { cur += s[++i]; any = true; }
|
|
308
|
+
else if (/\s/.test(c)) { if (cur || any) outv.push(cur); cur = ""; any = false; }
|
|
309
|
+
else { cur += c; any = true; }
|
|
310
|
+
}
|
|
311
|
+
if (cur || any) outv.push(cur);
|
|
312
|
+
return outv;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** Each hook command inside one entry (flat or matcher-group form), as argv token lists. */
|
|
316
|
+
export function commandsIn(entry ) {
|
|
317
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) return [];
|
|
318
|
+
const e = entry ;
|
|
319
|
+
const res = [];
|
|
320
|
+
for (const h of [e, ...(Array.isArray(e.hooks) ? e.hooks : [])]) {
|
|
321
|
+
if (!h || typeof h !== "object") continue;
|
|
322
|
+
for (const key of ["command", "bash"]) {
|
|
323
|
+
if (typeof h[key] !== "string") continue;
|
|
324
|
+
const args = Array.isArray(h.args) ? h.args.map(String) : [];
|
|
325
|
+
res.push(args.length ? [h[key], ...args] : shellSplit(h[key]));
|
|
326
|
+
break;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return res;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
export function isOurs(entry , marker ) {
|
|
333
|
+
return commandsIn(entry).some((argv) => argv.includes(marker));
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** The file our command runs: the launcher under /bin/sh, else the executable's script argument. */
|
|
337
|
+
export function hookScript(argv ) {
|
|
338
|
+
if (argv.length >= 2 && argv[0] === "/bin/sh") return argv[1];
|
|
339
|
+
const i = argv.indexOf("hook");
|
|
340
|
+
if (i > 0) return argv[i - 1];
|
|
341
|
+
return argv[0] ?? null;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const listOf = (hooks , native ) => {
|
|
345
|
+
const v = hooks && typeof hooks === "object" ? (hooks )[native] : undefined;
|
|
346
|
+
return Array.isArray(v) ? v : [];
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
/** Replace this runtime's entries with fresh ones for every event the agent registers. */
|
|
350
|
+
export function applyEntries(a , data , commandFor , marker ) {
|
|
351
|
+
a.prepare(data);
|
|
352
|
+
if (!data.hooks || typeof data.hooks !== "object" || Array.isArray(data.hooks)) data.hooks = {};
|
|
353
|
+
for (const [native, canonical] of a.events) {
|
|
354
|
+
data.hooks[native] = [...listOf(data.hooks, native).filter((e) => !isOurs(e, marker)), a.entry(canonical, commandFor(canonical))];
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
export function removeEntries(a , data , marker ) {
|
|
359
|
+
if (!data.hooks || typeof data.hooks !== "object") return;
|
|
360
|
+
for (const [native] of a.events) {
|
|
361
|
+
if (Array.isArray(data.hooks[native])) data.hooks[native] = data.hooks[native].filter((e ) => !isOurs(e, marker));
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const truthy = (v ) => Array.isArray(v) ? v.length > 0 : v && typeof v === "object" ? Object.keys(v).length > 0 : !!v;
|
|
366
|
+
|
|
367
|
+
/** True when a file we own holds nothing but empty hook lists (safe to delete). */
|
|
368
|
+
export function onlyXtrom(a , data ) {
|
|
369
|
+
const hooks = data.hooks;
|
|
370
|
+
return a.ownsFile && Object.keys(data).every((k) => k === "version" || k === "hooks")
|
|
371
|
+
&& !(hooks && typeof hooks === "object" && !Array.isArray(hooks) && Object.values(hooks).some(truthy));
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
export const isInstalled = (a , data , marker ) =>
|
|
375
|
+
a.events.every(([n]) => listOf(data?.hooks, n).some((e) => isOurs(e, marker)));
|
|
376
|
+
|
|
377
|
+
export const ourScripts = (a , data , marker ) =>
|
|
378
|
+
a.events.flatMap(([n]) => listOf(data?.hooks, n).filter((e) => isOurs(e, marker)).flatMap((e) => commandsIn(e).map(hookScript)));
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Real update applier — the OS install step behind updater.Applier.
|
|
2
|
+
//
|
|
3
|
+
// SECURITY-CRITICAL: by the time this runs, the tarball bytes are ALREADY signature- + hash-verified
|
|
4
|
+
// by updater.ts. The applier's only job is to install them WITHOUT ever leaving enforcement broken.
|
|
5
|
+
// It reuses the installer's vetted deployRuntime, which stages the new runtime, SELF-TESTS it (spawns
|
|
6
|
+
// `node cli version`), and only then does an ATOMIC rename swap — so a bad build can never replace the
|
|
7
|
+
// working one (deployRuntime throws, we catch, the old runtime stays). Same safety shape as PipApplier.
|
|
8
|
+
//
|
|
9
|
+
// The OS leaves (tarball extraction + the swap) are injected so the ordering/guarantees are unit-tested
|
|
10
|
+
// offline. Post-decision delivery machinery, never the enforcement verdict.
|
|
11
|
+
import { execFileSync } from "node:child_process";
|
|
12
|
+
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
13
|
+
import { join } from "node:path";
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
/** Default extractor: write the verified tarball to disk and let the system `tar` expand it. `tar` is
|
|
28
|
+
* present on macOS, Linux and Windows 10+ (bsdtar). Never shell-interpolated — execFileSync with an
|
|
29
|
+
* argv array. The bytes are already hash-pinned, so this only expands trusted content. */
|
|
30
|
+
export function systemTarExtract(tarball , destDir ) {
|
|
31
|
+
mkdirSync(destDir, { recursive: true });
|
|
32
|
+
const tgz = join(destDir, "artifact.tgz");
|
|
33
|
+
writeFileSync(tgz, tarball, { mode: 0o600 });
|
|
34
|
+
execFileSync("tar", ["-xzf", tgz, "-C", destDir], { stdio: "ignore", timeout: 60_000 });
|
|
35
|
+
rmSync(tgz, { force: true });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export class RuntimeSwapApplier {
|
|
39
|
+
deps ;
|
|
40
|
+
constructor(deps ) { this.deps = deps; }
|
|
41
|
+
|
|
42
|
+
async apply(plan , artifact ) {
|
|
43
|
+
const work = join(this.deps.tmpRoot, `upd-${plan.version}-${process.pid}`);
|
|
44
|
+
try {
|
|
45
|
+
rmSync(work, { recursive: true, force: true });
|
|
46
|
+
mkdirSync(work, { recursive: true });
|
|
47
|
+
this.deps.extract(artifact, work);
|
|
48
|
+
// npm packs under a top-level `package/`; the runtime we deploy is its built `dist/` (mirrors the
|
|
49
|
+
// installer's packageRoot()). Fall back to package/ or work/ for non-standard layouts.
|
|
50
|
+
const pkgDist = join(work, "package", "dist");
|
|
51
|
+
const src = existsSync(pkgDist) ? pkgDist
|
|
52
|
+
: existsSync(join(work, "package")) ? join(work, "package") : work;
|
|
53
|
+
this.deps.deploy(src, this.deps.runtimeTarget); // throws on self-test fail → caught → old runtime kept
|
|
54
|
+
return true;
|
|
55
|
+
} catch {
|
|
56
|
+
return false; // fail-closed
|
|
57
|
+
} finally {
|
|
58
|
+
rmSync(work, { recursive: true, force: true });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|