@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/session.js
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
// Xtrom SDK (TypeScript) — wrap agent tools with runtime enforcement. Port of xtrom_sdk/session.py:
|
|
2
|
+
// • source tools' outputs are labeled UNTRUSTED and taint later calls (containment provenance),
|
|
3
|
+
// • every guarded call is adjudicated by the engine (ALLOW / STEP_UP / BLOCK), fail-closed,
|
|
4
|
+
// • SESSION (context) taint by default: after untrusted ingress, sink calls whose args are not
|
|
5
|
+
// provably derived from it still need approval, for the whole Session (`newTask()` keeps it),
|
|
6
|
+
// • every tool RESULT is inspected (secrets, PII, injected instructions, hidden unicode) and the
|
|
7
|
+
// flags ride on the call's single decision event — flags only, never content,
|
|
8
|
+
// • monitor mode, detection fusion, owner attribution, optional control-plane reporting.
|
|
9
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
10
|
+
import * as fs from "node:fs";
|
|
11
|
+
import { homedir } from "node:os";
|
|
12
|
+
import { DEFAULT_MEMORY_READ_ACTIONS, DEFAULT_MEMORY_WRITE_ACTIONS, FileMemoryProvenance, MemoryProvenance } from "./memory.js";
|
|
13
|
+
import {
|
|
14
|
+
decide, defaultPolicy, extractChoices, isKnownSecret, looksLikeSecret, planMatches, PLAN_CHOICES_MAX,
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
} from "./enforce.js";
|
|
18
|
+
import { heldAs, resolveWorkspaceMode, } from "./workspace.js";
|
|
19
|
+
import { attribution, decisionEvent, DecisionReporter, } from "./reporter.js";
|
|
20
|
+
import { inspectResult, } from "./inspect.js";
|
|
21
|
+
import {
|
|
22
|
+
APPROVAL_LAYER, APPROVAL_REASON_CODE, COVERABLE, dataCondition, matchAllowance,
|
|
23
|
+
} from "./allowances.js";
|
|
24
|
+
|
|
25
|
+
// Result flags that mean "this output speaks to the model": they taint the session even when the
|
|
26
|
+
// tool wasn't declared a source. A truncated result also taints, because hidden tail content was
|
|
27
|
+
// not scanned and must not become a padding bypass.
|
|
28
|
+
const STEERING_FLAGS = new Set(["instruction", "hidden_unicode", "truncated"]);
|
|
29
|
+
|
|
30
|
+
export class BlockedError extends Error {
|
|
31
|
+
decision ;
|
|
32
|
+
constructor(decision ) {
|
|
33
|
+
super(`BLOCKED [${decision.layer}] ${decision.action}: ${decision.reason}`);
|
|
34
|
+
this.name = "BlockedError";
|
|
35
|
+
this.decision = decision;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
export class StepUpRequired extends Error {
|
|
39
|
+
decision ;
|
|
40
|
+
constructor(decision ) {
|
|
41
|
+
super(`STEP-UP required for ${decision.action}: ${decision.reason}`);
|
|
42
|
+
this.name = "StepUpRequired";
|
|
43
|
+
this.decision = decision;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
function str(v ) {
|
|
59
|
+
if (typeof v === "string") return v;
|
|
60
|
+
try {
|
|
61
|
+
if (v !== null && typeof v === "object") return JSON.stringify(v) ?? String(v);
|
|
62
|
+
return String(v);
|
|
63
|
+
} catch {
|
|
64
|
+
return "<unstringable>";
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Practical cross-call provenance: record source outputs, propagate by content containment. Bounded, oldest
|
|
69
|
+
// evicted first, so a long-running agent neither leaks memory nor slows every call; session (context) taint
|
|
70
|
+
// is kept separately and never evicted, so forgotten content is still held for approval. Mirrors the Python SDK.
|
|
71
|
+
export const TRACKER_MAX_ENTRIES = 1024;
|
|
72
|
+
export const TRACKER_MAX_CHARS = 8 * 1024 * 1024;
|
|
73
|
+
|
|
74
|
+
class TaintTracker {
|
|
75
|
+
recorded = [];
|
|
76
|
+
chars = 0;
|
|
77
|
+
policy ;
|
|
78
|
+
constructor(policy ) { this.policy = policy; }
|
|
79
|
+
record(value , trust , origin ) {
|
|
80
|
+
const s = str(value);
|
|
81
|
+
if (!s) return;
|
|
82
|
+
this.recorded.push({ s, label: { trust, isSecret: looksLikeSecret(s) || isKnownSecret(this.policy, s), origin } });
|
|
83
|
+
this.chars += s.length;
|
|
84
|
+
while (this.recorded.length > TRACKER_MAX_ENTRIES || (this.chars > TRACKER_MAX_CHARS && this.recorded.length > 1)) {
|
|
85
|
+
this.chars -= this.recorded.shift() .s.length;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
get size() { return { entries: this.recorded.length, chars: this.chars }; }
|
|
89
|
+
labelFor(value ) {
|
|
90
|
+
const s = str(value);
|
|
91
|
+
let trust = "TRUSTED", origin = "arg";
|
|
92
|
+
let isSecret = looksLikeSecret(s) || isKnownSecret(this.policy, value);
|
|
93
|
+
for (const { s: rs, label } of this.recorded) {
|
|
94
|
+
if (rs && (s.includes(rs) || rs.includes(s))) {
|
|
95
|
+
if (label.trust === "UNTRUSTED") { trust = "UNTRUSTED"; origin = label.origin; }
|
|
96
|
+
if (label.isSecret) isSecret = true;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return { trust, isSecret, origin };
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Stable string form of an argument for exact-call identity (never leaves the process). */
|
|
104
|
+
function safeJson(v ) {
|
|
105
|
+
try { return typeof v === "string" ? v : JSON.stringify(v) ?? String(v); } catch { return String(v); }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
const HELD_CODES = new Set(["agent.quarantined", "agent.held"]);
|
|
144
|
+
|
|
145
|
+
export class Session {
|
|
146
|
+
decisions = [];
|
|
147
|
+
identity ;
|
|
148
|
+
sessionId ;
|
|
149
|
+
attribution ;
|
|
150
|
+
localMode ;
|
|
151
|
+
sessionTaint ;
|
|
152
|
+
/** True once the advisory detector has failed (deterministic layers unaffected). */
|
|
153
|
+
degraded = false;
|
|
154
|
+
detectFailures = 0;
|
|
155
|
+
contextOrigin = null;
|
|
156
|
+
/** Result flags of everything ingested this session. */
|
|
157
|
+
contextFlags = new Set ();
|
|
158
|
+
tracker ;
|
|
159
|
+
risk = 0;
|
|
160
|
+
policy ;
|
|
161
|
+
onStepUp ;
|
|
162
|
+
detector ;
|
|
163
|
+
reporter ;
|
|
164
|
+
allowances ;
|
|
165
|
+
inheritApprovals ;
|
|
166
|
+
exact = new Map (); // exact-call key → expiry
|
|
167
|
+
approvalTtlSeconds ;
|
|
168
|
+
spent = new Set ();
|
|
169
|
+
clock ;
|
|
170
|
+
memory ;
|
|
171
|
+
plan = [];
|
|
172
|
+
planUsed = new Set ();
|
|
173
|
+
/** List choices seen this session (docs/design/GATEWAY-PLANS.md), kept across setPlan(). */
|
|
174
|
+
choices = {};
|
|
175
|
+
|
|
176
|
+
constructor(identity , opts = {}) {
|
|
177
|
+
const mode = opts.mode ?? "enforce";
|
|
178
|
+
if (mode !== "enforce" && mode !== "monitor") throw new Error("mode must be 'enforce' or 'monitor'");
|
|
179
|
+
this.identity = identity;
|
|
180
|
+
this.localMode = mode;
|
|
181
|
+
this.policy = opts.policy ?? defaultPolicy();
|
|
182
|
+
this.tracker = new TaintTracker(this.policy);
|
|
183
|
+
this.onStepUp = opts.onStepUp;
|
|
184
|
+
this.detector = opts.detector;
|
|
185
|
+
this.sessionTaint = opts.sessionTaint ?? true;
|
|
186
|
+
this.sessionId = opts.sessionId ?? "ses_" + randomBytes(8).toString("hex");
|
|
187
|
+
this.attribution = attribution(opts.owner, opts.device, opts.client);
|
|
188
|
+
this.reporter = opts.reporter
|
|
189
|
+
?? (opts.controlPlaneUrl && opts.token ? new DecisionReporter(opts.controlPlaneUrl, opts.token) : null);
|
|
190
|
+
this.allowances = [...(opts.allowances ?? [])];
|
|
191
|
+
const inherit = opts.inheritApprovals ?? true;
|
|
192
|
+
this.inheritApprovals = inherit === true ? "exact" : inherit === false ? "off" : inherit;
|
|
193
|
+
this.approvalTtlSeconds = opts.approvalTtlSeconds ?? 3600;
|
|
194
|
+
this.clock = opts.clock ?? (() => Date.now() / 1000);
|
|
195
|
+
this.memory = opts.memory;
|
|
196
|
+
this.plan = [...(opts.plan ?? [])];
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Replace the plan (e.g. for a new user request). Never build a plan from tool output. */
|
|
200
|
+
setPlan(steps ) {
|
|
201
|
+
this.plan = [...(steps ?? [])];
|
|
202
|
+
this.planUsed = new Set();
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
planStepFor(action , args ) {
|
|
206
|
+
for (let i = 0; i < this.plan.length; i++) {
|
|
207
|
+
if (!this.planUsed.has(i) && planMatches(this.plan[i], action, args, this.choices, this.policy)) return [i, this.plan[i]];
|
|
208
|
+
}
|
|
209
|
+
return [null, null];
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Remember the list elements `action` returned, for every live plan step that may choose from it. */
|
|
213
|
+
recordChoices(action , result ) {
|
|
214
|
+
this.plan.forEach((step, i) => {
|
|
215
|
+
if (this.planUsed.has(i)) return;
|
|
216
|
+
for (const src of Object.values(step.choose_from ?? {})) {
|
|
217
|
+
if (!src || src.tool !== action) continue;
|
|
218
|
+
const field = String(src.field ?? "");
|
|
219
|
+
const byField = (this.choices[action] ??= {});
|
|
220
|
+
const have = (byField[field] ??= new Set ());
|
|
221
|
+
for (const v of extractChoices(result, field)) {
|
|
222
|
+
if (have.size >= PLAN_CHOICES_MAX) break;
|
|
223
|
+
have.add(v);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
hold(d ) {
|
|
230
|
+
// Destination key: every destination the call names (to_fp), not just the primary host.
|
|
231
|
+
return { action: d.action, reason_code: d.reasonCode, dest_fp: d.target?.to_fp ?? "",
|
|
232
|
+
session_id: this.sessionId, tainted: d.tainted, context_tainted: d.contextTainted };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
static callKey(action , args ) {
|
|
236
|
+
const canon = JSON.stringify([action, Object.keys(args ?? {}).sort().map((k) => [k, safeJson(args[k])])]);
|
|
237
|
+
return createHash("sha256").update(canon).digest("hex");
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** A held call that a live allowance covers runs, recorded as approved by that allowance. */
|
|
241
|
+
/** The workspace's quarantine (refuse every call) or SOC hold (every call waits for a person), from the
|
|
242
|
+
* directive the control plane returns (design/CONTAINMENT-ENFORCEMENT.md). */
|
|
243
|
+
applyHold(d ) {
|
|
244
|
+
const [wm] = this.reporter?.workspaceMode?.() ?? [null, null];
|
|
245
|
+
const how = heldAs(wm, this.identity, this.clock());
|
|
246
|
+
if (how === "block") {
|
|
247
|
+
return { ...d, verdict: "BLOCK", layer: "L0:quarantine", reason: "the agent is quarantined",
|
|
248
|
+
reasonCode: "agent.quarantined" };
|
|
249
|
+
}
|
|
250
|
+
if (how === "hold" && d.verdict === "ALLOW") {
|
|
251
|
+
return { ...d, verdict: "STEP_UP", layer: "L0:quarantine",
|
|
252
|
+
reason: "the agent is held by the SOC: every call waits for a person", reasonCode: "agent.held" };
|
|
253
|
+
}
|
|
254
|
+
return d;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
applyAllowance(d , key = "") {
|
|
258
|
+
const exp = this.exact.get(key);
|
|
259
|
+
if (exp !== undefined && exp > this.clock()) {
|
|
260
|
+
return { ...d, verdict: "ALLOW", layer: APPROVAL_LAYER, reasonCode: APPROVAL_REASON_CODE,
|
|
261
|
+
reason: "exact repeat of a call approved in this session" };
|
|
262
|
+
}
|
|
263
|
+
const a = matchAllowance(this.allowances, this.hold(d), this.clock(), this.spent);
|
|
264
|
+
if (!a) return d;
|
|
265
|
+
if (a.scope === "call") this.spent.add(a.id);
|
|
266
|
+
return { ...d, verdict: "ALLOW", layer: APPROVAL_LAYER, reasonCode: APPROVAL_REASON_CODE,
|
|
267
|
+
reason: `covered by approval ${a.id} (${a.scope})` };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** After a human approves a hold, cover what they saw: exact repeats ("exact"), or opted in, the same
|
|
271
|
+
* tool + destination + same-or-cleaner data ("destination", never without a destination). */
|
|
272
|
+
inherit(d , key = "") {
|
|
273
|
+
if (this.inheritApprovals === "off" || !(d.reasonCode in COVERABLE)) return;
|
|
274
|
+
if (this.inheritApprovals === "exact") {
|
|
275
|
+
if (key) this.exact.set(key, this.clock() + this.approvalTtlSeconds);
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
const h = this.hold(d);
|
|
279
|
+
if (!h.dest_fp || !(COVERABLE[d.reasonCode] ?? []).includes("session")) return;
|
|
280
|
+
this.allowances.push({ id: `local_${this.allowances.length + 1}`, action: d.action, scope: "session",
|
|
281
|
+
dest_fp: h.dest_fp, data: dataCondition(h), session_id: this.sessionId,
|
|
282
|
+
expires_at: this.clock() + this.approvalTtlSeconds });
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
get contextTainted() {
|
|
286
|
+
return this.sessionTaint && this.contextOrigin !== null;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Manually tag data brought in from an untrusted source (also taints the session context). */
|
|
290
|
+
markUntrusted(value , origin = "external") {
|
|
291
|
+
this.tracker.record(value, "UNTRUSTED", origin);
|
|
292
|
+
this.contextOrigin ??= origin;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Mark the start of a new user task. Session taint and the ingested-content flags are KEPT: the
|
|
296
|
+
* model can carry a reworded copy of earlier untrusted content into the next task, so clearing
|
|
297
|
+
* here would let it reach a sink unapproved. Context taint only ever holds sinks (reads are
|
|
298
|
+
* unaffected). For a genuinely fresh conversation, create a new Session. */
|
|
299
|
+
newTask() {}
|
|
300
|
+
|
|
301
|
+
/** The mode this session enforces in now: the workspace mode when the control plane has said one (it
|
|
302
|
+
* wins, both ways; monitor only while fresh and unexpired), else the `mode` given in code. */
|
|
303
|
+
get mode() {
|
|
304
|
+
return this.modeAndSource()[0];
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
modeAndSource() {
|
|
308
|
+
const [wm, at] = this.reporter?.workspaceMode?.() ?? [null, null];
|
|
309
|
+
return resolveWorkspaceMode(this.localMode, wm, at, this.clock() * 1000); // the session's injected clock
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** Flush and stop the reporter (if any). */
|
|
313
|
+
async close() {
|
|
314
|
+
await this.reporter?.close?.();
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
guard (action , fn , opts = {}) {
|
|
318
|
+
return async (args ) => {
|
|
319
|
+
const argValues = {};
|
|
320
|
+
for (const [k, v] of Object.entries(args ?? {})) argValues[k] = { data: v, label: this.tracker.labelFor(v) };
|
|
321
|
+
|
|
322
|
+
// Session taint applies to every call, source tools included (a dual-use tool can write).
|
|
323
|
+
const [stepI, step] = this.planStepFor(action, argValues);
|
|
324
|
+
let d = decide(action, argValues, this.policy, this.risk, {
|
|
325
|
+
identity: this.identity, contextTainted: this.contextTainted, planStep: step, planChoices: this.choices,
|
|
326
|
+
});
|
|
327
|
+
d = this.applyHold(d);
|
|
328
|
+
const key = Session.callKey(action, args );
|
|
329
|
+
if (d.verdict === "STEP_UP") d = this.applyAllowance(d, key);
|
|
330
|
+
this.decisions.push(d);
|
|
331
|
+
|
|
332
|
+
let approved = null;
|
|
333
|
+
if (d.verdict === "STEP_UP") {
|
|
334
|
+
try {
|
|
335
|
+
approved = this.onStepUp ? !!(await this.onStepUp(d)) : false;
|
|
336
|
+
} catch {
|
|
337
|
+
approved = false; // an approval hook that throws is a denial, never an approval
|
|
338
|
+
}
|
|
339
|
+
if (approved) this.inherit(d, key);
|
|
340
|
+
}
|
|
341
|
+
const priorFlags = [...this.contextFlags];
|
|
342
|
+
// A quarantine or SOC hold is enforced in monitor mode too.
|
|
343
|
+
const mode = HELD_CODES.has(String(d.reasonCode)) ? "enforce" : this.mode;
|
|
344
|
+
const runs = !(mode === "enforce" && (d.verdict === "BLOCK" || (d.verdict === "STEP_UP" && !approved)));
|
|
345
|
+
if (!runs) {
|
|
346
|
+
this.report(d, approved, !!opts.source, priorFlags, null);
|
|
347
|
+
if (d.verdict === "BLOCK") throw new BlockedError(d);
|
|
348
|
+
throw new StepUpRequired(d);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
if (stepI !== null && d.planned) this.planUsed.add(stepI); // a planned step runs once
|
|
352
|
+
// The call runs: its decision is reported once, AFTER the result is inspected, so a single
|
|
353
|
+
// evidence event carries the decision and what the call returned.
|
|
354
|
+
let result ;
|
|
355
|
+
try {
|
|
356
|
+
result = await fn(args);
|
|
357
|
+
} catch (e) {
|
|
358
|
+
this.report(d, approved, !!opts.source, priorFlags, null);
|
|
359
|
+
throw e;
|
|
360
|
+
}
|
|
361
|
+
this.recordChoices(action, result);
|
|
362
|
+
this.memoryWrite(action, args , argValues);
|
|
363
|
+
const recalledUntrusted = this.memoryRecallUntrusted(action, result);
|
|
364
|
+
const inspection = await this.ingestResult(result, !!opts.source || recalledUntrusted,
|
|
365
|
+
recalledUntrusted ? "memory" : (opts.origin ?? `tool:${action}`));
|
|
366
|
+
this.report(d, approved, !!opts.source, priorFlags, inspection);
|
|
367
|
+
return result;
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
report(d , approved , source , contextFlags ,
|
|
372
|
+
result ) {
|
|
373
|
+
if (!this.reporter) return;
|
|
374
|
+
try {
|
|
375
|
+
this.reporter.report(decisionEvent(this.identity, d, {
|
|
376
|
+
sessionId: this.sessionId, mode: this.mode, approved, taintSource: source, result, contextFlags,
|
|
377
|
+
...this.attribution,
|
|
378
|
+
}));
|
|
379
|
+
} catch { /* reporting is best-effort */ }
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
memoryStore() {
|
|
383
|
+
if (!this.memory) {
|
|
384
|
+
try {
|
|
385
|
+
const name = (this.identity || "agent").replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 80).replace(/^[.-]+|[.-]+$/g, "") || "agent";
|
|
386
|
+
this.memory = new FileMemoryProvenance(`${homedir()}/.xtrom/memory/${name}.json`, fs);
|
|
387
|
+
} catch {
|
|
388
|
+
this.memory = new MemoryProvenance(); // no usable home (containers, serverless)
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
return this.memory;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** A memory write that ran: remember whether what it stored was clean or carried untrusted data. */
|
|
395
|
+
memoryWrite(action , args , argValues ) {
|
|
396
|
+
if (!(this.policy.memoryWriteActions ?? DEFAULT_MEMORY_WRITE_ACTIONS).has(action)) return;
|
|
397
|
+
const tainted = this.contextTainted || Object.values(argValues).some((v) => v.label.trust === "UNTRUSTED");
|
|
398
|
+
try { this.memoryStore().recordWrite({ ...args }, tainted); }
|
|
399
|
+
catch { /* the tool already ran; unrecorded content reads as unknown (untrusted by default) */ }
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** Recalled memory is untrusted if any of it was written tainted or Xtrom never saw it written. */
|
|
403
|
+
memoryRecallUntrusted(action , result ) {
|
|
404
|
+
if (!(this.policy.memoryReadActions ?? DEFAULT_MEMORY_READ_ACTIONS).has(action)) return false;
|
|
405
|
+
try { return this.memoryStore().trustOf(result, this.policy.memoryUnknown ?? "untrusted") === "untrusted"; }
|
|
406
|
+
catch { return true; } // could not be judged: fail closed
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
async ingestResult(result , source , origin ) {
|
|
410
|
+
const inspection = inspectResult(result);
|
|
411
|
+
for (const f of inspection.flags) this.contextFlags.add(f);
|
|
412
|
+
const steering = inspection.flags.some((f) => STEERING_FLAGS.has(f));
|
|
413
|
+
if (source || steering) {
|
|
414
|
+
this.tracker.record(result, "UNTRUSTED", origin);
|
|
415
|
+
this.contextOrigin ??= origin;
|
|
416
|
+
if (this.detector) {
|
|
417
|
+
try {
|
|
418
|
+
const r = await this.detector.score(str(result));
|
|
419
|
+
const score = Number(r.score);
|
|
420
|
+
if (Number.isNaN(score)) throw new Error("detector returned NaN");
|
|
421
|
+
this.risk = Math.max(this.risk, score);
|
|
422
|
+
} catch {
|
|
423
|
+
// Detection is advisory: never break the call path; surface via degraded/detectFailures.
|
|
424
|
+
this.detectFailures += 1;
|
|
425
|
+
this.degraded = true;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
} else if (inspection.flags.includes("secret")) {
|
|
429
|
+
// A trusted tool returned a credential. An exfil firewall must catch BOTH verbatim and
|
|
430
|
+
// laundered reuse, so two layers: record it TRUSTED-secret so a VERBATIM copy at an egress
|
|
431
|
+
// arg hard-blocks (secret-egress), AND taint the context so a PARAPHRASED copy is stepped-up
|
|
432
|
+
// at the next sink (Rule 2b). The engine ignores context taint for non-sink reads, so this
|
|
433
|
+
// only gates egress/writes — no friction on ordinary reads.
|
|
434
|
+
this.tracker.record(result, "TRUSTED", origin);
|
|
435
|
+
this.contextOrigin ??= origin;
|
|
436
|
+
}
|
|
437
|
+
return inspection;
|
|
438
|
+
}
|
|
439
|
+
}
|
package/dist/version.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// The workspace mode, as an agent applies it (docs/design/WORKSPACE-MODE.md in the Xtrom repo).
|
|
2
|
+
// Mirrors xtrom_sdk/workspace.py. The control plane returns `workspace_mode: {mode, expires_at}` on every
|
|
3
|
+
// ingest response. The workspace wins over the local mode (install config, `new Session({mode})`,
|
|
4
|
+
// XTROM_MODE) in both directions, with one fail-safe rule: monitor loosens only while it is fresh and
|
|
5
|
+
// unexpired. Enforce, once heard, sticks.
|
|
6
|
+
|
|
7
|
+
/** An agent the workspace stops: block (quarantine, every call refused) or hold (SOC hold, every call waits for a
|
|
8
|
+
* person until `until`, epoch seconds). design/CONTAINMENT-ENFORCEMENT.md. */
|
|
9
|
+
|
|
10
|
+
/** `held` is present only in an answer the SDK accepted (verified, or unsigned without a key): an unverifiable
|
|
11
|
+
* answer leaves the agents held before held. */
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
function parseHeld(raw ) {
|
|
15
|
+
const out = {};
|
|
16
|
+
for (const h of Array.isArray(raw) ? raw : []) {
|
|
17
|
+
if (!h || typeof h !== "object") continue;
|
|
18
|
+
const { agent, mode, until } = h ;
|
|
19
|
+
if (typeof agent === "string" && (mode === "block" || mode === "hold")) {
|
|
20
|
+
out[agent] = { mode, until: typeof until === "number" && Number.isInteger(until) ? until : null };
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** How the workspace holds `identity` at `nowSeconds`: "block", "hold" (until its end) or "". */
|
|
27
|
+
export function heldAs(wm , identity , nowSeconds ) {
|
|
28
|
+
const h = wm?.held?.[identity];
|
|
29
|
+
if (!h) return "";
|
|
30
|
+
if (h.mode === "hold" && h.until !== null && nowSeconds >= h.until) return "";
|
|
31
|
+
return h.mode;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
/** Monitor heard longer ago than this no longer loosens anything. */
|
|
36
|
+
export const FRESH_MS = 15 * 60 * 1000;
|
|
37
|
+
const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;
|
|
38
|
+
|
|
39
|
+
/** A validated {mode, expires_at} from a response body, or null. Monitor needs a well-formed expiry. With a
|
|
40
|
+
* verifier (./directive.ts) the mode comes only from the signed directive; without a valid one, enforce. */
|
|
41
|
+
export function parseWorkspaceMode(payload ,
|
|
42
|
+
verifier ) {
|
|
43
|
+
let held ;
|
|
44
|
+
if (verifier) {
|
|
45
|
+
const d = verifier.verify(payload && typeof payload === "object" ? (payload ).directive : null);
|
|
46
|
+
if (!d) return { mode: "enforce", expires_at: null };
|
|
47
|
+
held = parseHeld(d.held_agents);
|
|
48
|
+
payload = { workspace_mode: d.workspace_mode };
|
|
49
|
+
} else if (payload && typeof payload === "object") {
|
|
50
|
+
held = parseHeld((payload ).held_agents);
|
|
51
|
+
}
|
|
52
|
+
const wm = payload && typeof payload === "object" ? (payload ).workspace_mode : null;
|
|
53
|
+
if (!wm || typeof wm !== "object") return null;
|
|
54
|
+
const { mode, expires_at: exp } = wm ;
|
|
55
|
+
if (mode !== "enforce" && mode !== "monitor") return null;
|
|
56
|
+
if (mode === "monitor" && !(typeof exp === "string" && ISO.test(exp))) return null;
|
|
57
|
+
const out = { mode, expires_at: mode === "monitor" ? (exp ) : null };
|
|
58
|
+
if (held) out.held = held;
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** [mode, source]. source: local (never heard from the workspace) | workspace | workspace_stale (a monitor
|
|
63
|
+
* too old or past its expiry, so enforce). `receivedAt` and `now` are epoch milliseconds. */
|
|
64
|
+
export function resolveWorkspaceMode(localMode , wm ,
|
|
65
|
+
receivedAt , now ) {
|
|
66
|
+
if (!wm || (wm.mode !== "enforce" && wm.mode !== "monitor")) return [localMode, "local"];
|
|
67
|
+
if (wm.mode === "enforce") return ["enforce", "workspace"];
|
|
68
|
+
const exp = Date.parse(String(wm.expires_at ?? ""));
|
|
69
|
+
const fresh = typeof receivedAt === "number" && Number.isFinite(receivedAt) && now - receivedAt <= FRESH_MS;
|
|
70
|
+
const live = Number.isFinite(exp) && now < exp;
|
|
71
|
+
return fresh && live ? ["monitor", "workspace"] : ["enforce", "workspace_stale"];
|
|
72
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xtrom-ai/sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.7.0",
|
|
4
|
+
"description": "Xtrom SDK — deterministic runtime enforcement for AI agent tools (taint/IFC + policy + fusion), plus a hook for coding agents (Claude Code, Copilot CLI, Cursor, Codex, Gemini CLI, Windsurf) via `npx @xtrom-ai/sdk install`.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": { "types": "./src/index.ts", "default": "./dist/index.js" },
|
|
9
|
+
"./cli": "./dist/cli.js", "./package.json": "./package.json"
|
|
10
|
+
},
|
|
11
|
+
"types": "./src/index.ts",
|
|
12
|
+
"bin": { "xtrom": "./dist/cli.js" },
|
|
13
|
+
"files": ["dist", "src", "README.md", "LICENSE"],
|
|
14
|
+
"engines": { "node": ">=20" },
|
|
15
|
+
"scripts": {
|
|
16
|
+
"build": "node scripts/build.mjs",
|
|
17
|
+
"prepack": "node scripts/build.mjs",
|
|
18
|
+
"test": "node --test test/*.test.ts"
|
|
19
|
+
},
|
|
20
|
+
"repository": { "type": "git", "url": "https://github.com/xtrom-ai/xtrom.git", "directory": "product/xtrom-sdk-ts" },
|
|
21
|
+
"homepage": "https://github.com/xtrom-ai/xtrom/tree/main/product/xtrom-sdk-ts",
|
|
22
|
+
"bugs": "https://github.com/xtrom-ai/xtrom/issues",
|
|
23
|
+
"publishConfig": { "access": "public" },
|
|
24
|
+
"keywords": ["ai-agents", "security", "prompt-injection", "taint-tracking", "mcp", "guardrails", "llm", "claude-code", "hooks"]
|
|
25
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// Allowances: a human approval for a held call (STEP_UP), scoped so the same kind of call isn't held
|
|
2
|
+
// again (design/APPROVAL-ALLOWANCES.md). Parity with xtrom-engine/xtrom/allowances.py, gated on
|
|
3
|
+
// ../xtrom-engine/allowance_golden.json.
|
|
4
|
+
//
|
|
5
|
+
// Consulted only after the engine returns STEP_UP, never for a BLOCK. Covers the same tool, the same
|
|
6
|
+
// destination and the same or cleaner data, and always expires.
|
|
7
|
+
|
|
8
|
+
export type Scope = "call" | "session" | "window";
|
|
9
|
+
export type DataCondition = "clean" | "context" | "untrusted";
|
|
10
|
+
|
|
11
|
+
export interface Allowance {
|
|
12
|
+
id: string;
|
|
13
|
+
action: string;
|
|
14
|
+
scope: Scope;
|
|
15
|
+
dest_fp?: string;
|
|
16
|
+
data: DataCondition | string;
|
|
17
|
+
session_id?: string;
|
|
18
|
+
call_fp?: string;
|
|
19
|
+
expires_at: number; // epoch seconds
|
|
20
|
+
revoked_at?: number;
|
|
21
|
+
uses_left?: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface Hold {
|
|
25
|
+
action: string;
|
|
26
|
+
reason_code: string;
|
|
27
|
+
dest_fp?: string;
|
|
28
|
+
session_id?: string;
|
|
29
|
+
call_fp?: string;
|
|
30
|
+
tainted?: boolean;
|
|
31
|
+
context_tainted?: boolean;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export const COVERABLE: Readonly<Record<string, readonly Scope[]>> = Object.freeze({
|
|
35
|
+
"ifc.untrusted_content_stepup": ["call", "session", "window"],
|
|
36
|
+
"ifc.context_tainted_stepup": ["call", "session", "window"],
|
|
37
|
+
"policy.destructive_prod_stepup": ["call", "session", "window"],
|
|
38
|
+
"policy.transfer_threshold_stepup": ["call"],
|
|
39
|
+
"egress.secret_to_durable_sink": ["call"],
|
|
40
|
+
});
|
|
41
|
+
const DATA_RANK: Readonly<Record<string, number>> = { clean: 0, context: 1, untrusted: 2 };
|
|
42
|
+
const SCOPE_ORDER: Readonly<Record<string, number>> = { call: 0, session: 1, window: 2 };
|
|
43
|
+
export const APPROVAL_REASON_CODE = "approval.allowance";
|
|
44
|
+
export const APPROVAL_LAYER = "L4:approval";
|
|
45
|
+
|
|
46
|
+
export function dataCondition(h: Hold): DataCondition {
|
|
47
|
+
if (h.tainted) return "untrusted";
|
|
48
|
+
if (h.context_tainted) return "context";
|
|
49
|
+
return "clean";
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The live allowance covering `hold`, narrowest scope first, or null. `spent`: call allowances
|
|
53
|
+
* already used locally. `now` is epoch seconds. */
|
|
54
|
+
export function matchAllowance(allowances: readonly Allowance[], hold: Hold, now: number,
|
|
55
|
+
spent: ReadonlySet<string> = new Set()): Allowance | null {
|
|
56
|
+
const scopes = COVERABLE[hold.reason_code ?? ""];
|
|
57
|
+
if (!scopes) return null;
|
|
58
|
+
const cond = DATA_RANK[dataCondition(hold)];
|
|
59
|
+
const sorted = [...allowances].sort((a, b) =>
|
|
60
|
+
(SCOPE_ORDER[a.scope] ?? 9) - (SCOPE_ORDER[b.scope] ?? 9) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
61
|
+
for (const a of sorted) {
|
|
62
|
+
if (a.revoked_at || !(Number(a.expires_at) > now)) continue;
|
|
63
|
+
if (a.action !== hold.action || !scopes.includes(a.scope)) continue;
|
|
64
|
+
if (!(a.data in DATA_RANK) || DATA_RANK[a.data] < cond) continue; // same or cleaner data only
|
|
65
|
+
if (a.scope === "call") {
|
|
66
|
+
if (hold.call_fp && a.call_fp === hold.call_fp && !spent.has(a.id) && (a.uses_left ?? 1) > 0) return a;
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
if (!a.dest_fp || a.dest_fp !== hold.dest_fp) continue; // a wider scope names a destination
|
|
70
|
+
if (a.scope === "session" && (!a.session_id || a.session_id !== hold.session_id)) continue;
|
|
71
|
+
return a;
|
|
72
|
+
}
|
|
73
|
+
return null;
|
|
74
|
+
}
|