@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.
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
package/src/session.ts 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.ts";
13
+ import {
14
+ decide, defaultPolicy, extractChoices, isKnownSecret, looksLikeSecret, planMatches, PLAN_CHOICES_MAX, type PlanChoices,
15
+ type PlanStep,
16
+ type Decision, type Label, type Policy, type Trust, type Value,
17
+ } from "./enforce.ts";
18
+ import { heldAs, resolveWorkspaceMode, type WorkspaceMode, type WorkspaceSource } from "./workspace.ts";
19
+ import { attribution, decisionEvent, DecisionReporter, type Attribution, type WireEvent } from "./reporter.ts";
20
+ import { inspectResult, type ResultInspection } from "./inspect.ts";
21
+ import {
22
+ APPROVAL_LAYER, APPROVAL_REASON_CODE, COVERABLE, dataCondition, matchAllowance, type Allowance, type Hold,
23
+ } from "./allowances.ts";
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: Decision;
32
+ constructor(decision: 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: Decision;
40
+ constructor(decision: Decision) {
41
+ super(`STEP-UP required for ${decision.action}: ${decision.reason}`);
42
+ this.name = "StepUpRequired";
43
+ this.decision = decision;
44
+ }
45
+ }
46
+
47
+ export interface Detector { score(text: string): { score: number } | Promise<{ score: number }> }
48
+ export interface Reporter {
49
+ report(event: WireEvent): void;
50
+ close?(): Promise<void>;
51
+ /** The workspace mode the control plane last returned, and when (epoch ms). Optional for custom reporters. */
52
+ workspaceMode?(): [WorkspaceMode | null, number | null];
53
+ }
54
+
55
+ type ToolFn<A> = (args: A) => unknown | Promise<unknown>;
56
+ export interface GuardOpts { source?: boolean; origin?: string }
57
+
58
+ function str(v: unknown): string {
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
+ private recorded: Array<{ s: string; label: Label }> = [];
76
+ private chars = 0;
77
+ private policy: Policy;
78
+ constructor(policy: Policy) { this.policy = policy; }
79
+ record(value: unknown, trust: Trust, origin: string) {
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(): { entries: number; chars: number } { return { entries: this.recorded.length, chars: this.chars }; }
89
+ labelFor(value: unknown): Label {
90
+ const s = str(value);
91
+ let trust: 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: unknown): string {
105
+ try { return typeof v === "string" ? v : JSON.stringify(v) ?? String(v); } catch { return String(v); }
106
+ }
107
+
108
+ export interface SessionOpts {
109
+ policy?: Policy;
110
+ mode?: "enforce" | "monitor";
111
+ /** Human approval for STEP_UP. Return (or resolve) true to approve. */
112
+ onStepUp?: (d: Decision) => boolean | Promise<boolean>;
113
+ detector?: Detector;
114
+ /** Session (context) taint — on by default. */
115
+ sessionTaint?: boolean;
116
+ sessionId?: string;
117
+ owner?: string;
118
+ device?: string;
119
+ client?: string;
120
+ /** Control-plane reporting (metadata only, never blocks). Both required to enable. */
121
+ controlPlaneUrl?: string;
122
+ token?: string;
123
+ /** Inject a reporter (tests, custom transports). Overrides controlPlaneUrl/token. */
124
+ reporter?: Reporter;
125
+ /** Scoped approvals (e.g. the control plane's allowance bundle) that let a held call run. */
126
+ allowances?: Allowance[];
127
+ /** What an approval from onStepUp covers, for approvalTtlSeconds in this session: true / "exact"
128
+ * (default) = exact repeats of the approved call only; "destination" (opt-in) = any content to the same
129
+ * destination with same-or-cleaner data — measured, that lets an injection ride a legitimate approval;
130
+ * false = nothing. */
131
+ inheritApprovals?: boolean | "exact" | "destination";
132
+ approvalTtlSeconds?: number;
133
+ /** Epoch seconds for allowance expiry — the only time-dependent verdict input. Default: system clock. */
134
+ clock?: () => number;
135
+ /** Plan-then-execute: steps written from the user's request alone (never from tool output). A call
136
+ * matching an unused step may carry untrusted data in its slots; each step is used once. */
137
+ plan?: PlanStep[];
138
+ /** Memory provenance (docs/design/MEMORY-PROVENANCE.md). Default: a private file per agent under
139
+ * ~/.xtrom/memory, or this process only when there is no usable home. */
140
+ memory?: MemoryProvenance;
141
+ }
142
+
143
+ const HELD_CODES = new Set(["agent.quarantined", "agent.held"]);
144
+
145
+ export class Session {
146
+ readonly decisions: Decision[] = [];
147
+ readonly identity: string;
148
+ readonly sessionId: string;
149
+ readonly attribution: Attribution;
150
+ private localMode: "enforce" | "monitor";
151
+ sessionTaint: boolean;
152
+ /** True once the advisory detector has failed (deterministic layers unaffected). */
153
+ degraded = false;
154
+ detectFailures = 0;
155
+ private contextOrigin: string | null = null;
156
+ /** Result flags of everything ingested this session. */
157
+ readonly contextFlags = new Set<string>();
158
+ private tracker: TaintTracker;
159
+ private risk = 0;
160
+ private policy: Policy;
161
+ private onStepUp?: SessionOpts["onStepUp"];
162
+ private detector?: Detector;
163
+ private reporter: Reporter | null;
164
+ readonly allowances: Allowance[];
165
+ private inheritApprovals: "exact" | "destination" | "off";
166
+ private exact = new Map<string, number>(); // exact-call key → expiry
167
+ private approvalTtlSeconds: number;
168
+ private spent = new Set<string>();
169
+ private clock: () => number;
170
+ private memory: MemoryProvenance | undefined;
171
+ private plan: PlanStep[] = [];
172
+ private planUsed = new Set<number>();
173
+ /** List choices seen this session (docs/design/GATEWAY-PLANS.md), kept across setPlan(). */
174
+ private choices: PlanChoices = {};
175
+
176
+ constructor(identity: string, opts: SessionOpts = {}) {
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: PlanStep[]) {
201
+ this.plan = [...(steps ?? [])];
202
+ this.planUsed = new Set();
203
+ }
204
+
205
+ private planStepFor(action: string, args: Record<string, unknown>): [number, PlanStep] | [null, null] {
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
+ private recordChoices(action: string, result: unknown) {
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<string>());
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
+ private hold(d: Decision): Hold {
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
+ private static callKey(action: string, args: Record<string, unknown>): string {
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
+ private applyHold(d: Decision): Decision {
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
+ private applyAllowance(d: Decision, key = ""): Decision {
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
+ private inherit(d: Decision, 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(): boolean {
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: unknown, 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(): "enforce" | "monitor" {
304
+ return this.modeAndSource()[0];
305
+ }
306
+
307
+ modeAndSource(): ["enforce" | "monitor", WorkspaceSource] {
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(): Promise<void> {
314
+ await this.reporter?.close?.();
315
+ }
316
+
317
+ guard<A extends Record<string, unknown>>(action: string, fn: ToolFn<A>, opts: GuardOpts = {}) {
318
+ return async (args: A): Promise<unknown> => {
319
+ const argValues: Record<string, Value> = {};
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 as Record<string, unknown>);
329
+ if (d.verdict === "STEP_UP") d = this.applyAllowance(d, key);
330
+ this.decisions.push(d);
331
+
332
+ let approved: boolean | null = 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: unknown;
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 as Record<string, unknown>, 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
+ private report(d: Decision, approved: boolean | null, source: boolean, contextFlags: string[],
372
+ result: ResultInspection | null) {
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
+ private memoryStore(): MemoryProvenance {
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
+ private memoryWrite(action: string, args: Record<string, unknown>, argValues: Record<string, Value>): void {
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
+ private memoryRecallUntrusted(action: string, result: unknown): boolean {
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
+ private async ingestResult(result: unknown, source: boolean, origin: string): Promise<ResultInspection> {
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/src/version.ts ADDED
@@ -0,0 +1,2 @@
1
+ export const SDK_VERSION = "0.7.0";
2
+ export const API_VERSION = "1";
@@ -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
+ export type HeldAgent = { mode: "block" | "hold"; until: number | null };
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
+ export type WorkspaceMode = { mode: "enforce" | "monitor"; expires_at: string | null; held?: Record<string, HeldAgent> };
13
+
14
+ function parseHeld(raw: unknown): Record<string, HeldAgent> {
15
+ const out: Record<string, HeldAgent> = {};
16
+ for (const h of Array.isArray(raw) ? raw : []) {
17
+ if (!h || typeof h !== "object") continue;
18
+ const { agent, mode, until } = h as Record<string, unknown>;
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: WorkspaceMode | null | undefined, identity: string, nowSeconds: number): "block" | "hold" | "" {
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
+ export type WorkspaceSource = "local" | "workspace" | "workspace_stale";
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: unknown,
42
+ verifier?: { verify(envelope: unknown): Record<string, unknown> | null } | null): WorkspaceMode | null {
43
+ let held: Record<string, HeldAgent> | undefined;
44
+ if (verifier) {
45
+ const d = verifier.verify(payload && typeof payload === "object" ? (payload as Record<string, unknown>).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 as Record<string, unknown>).held_agents);
51
+ }
52
+ const wm = payload && typeof payload === "object" ? (payload as Record<string, unknown>).workspace_mode : null;
53
+ if (!wm || typeof wm !== "object") return null;
54
+ const { mode, expires_at: exp } = wm as Record<string, unknown>;
55
+ if (mode !== "enforce" && mode !== "monitor") return null;
56
+ if (mode === "monitor" && !(typeof exp === "string" && ISO.test(exp))) return null;
57
+ const out: WorkspaceMode = { mode, expires_at: mode === "monitor" ? (exp as string) : 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: "enforce" | "monitor", wm: WorkspaceMode | null | undefined,
65
+ receivedAt: number | null | undefined, now: number): ["enforce" | "monitor", WorkspaceSource] {
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
+ }