@vorim/sdk 3.19.0 → 3.20.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.
@@ -0,0 +1,429 @@
1
+ // src/integrations/_runtime-gate.ts
2
+ function isAllowVerdict(decision) {
3
+ return decision === "allow" || decision === "modify";
4
+ }
5
+ async function runtimeGate(vorim, agentId, actionTarget, scope, payload, opts = {}) {
6
+ const onEscalation = opts.onEscalation ?? "wait";
7
+ const onTransportFailure = opts.onTransportFailure ?? "deny";
8
+ const d = await vorim.beforeAction(
9
+ { agentId, actionType: "tool_call", actionTarget, requiredScope: scope, payload },
10
+ { throwOnDeny: false }
11
+ );
12
+ if (d.isFallback || d.decision === "fallback") {
13
+ if (onTransportFailure === "allow") {
14
+ return { allowed: true, reason: d.reason ?? "control plane unreachable (fail-open)", decisionId: d.decisionId || void 0 };
15
+ }
16
+ return { allowed: false, reason: d.reason ?? "control plane unreachable (failed closed)", decisionId: d.decisionId || void 0 };
17
+ }
18
+ if (d.decision !== "escalate") {
19
+ return { allowed: isAllowVerdict(d.decision), reason: d.reason, decisionId: d.decisionId || void 0 };
20
+ }
21
+ if (onEscalation === "allow") {
22
+ return { allowed: true, reason: d.reason ?? "escalated (auto-allowed)", decisionId: d.decisionId || void 0 };
23
+ }
24
+ if (onEscalation === "deny") {
25
+ return { allowed: false, reason: d.reason ?? "escalated (auto-denied \u2014 awaiting human)", decisionId: d.decisionId || void 0 };
26
+ }
27
+ if (!d.decisionId) {
28
+ return { allowed: false, reason: "escalated but no decisionId to poll", decisionId: void 0 };
29
+ }
30
+ try {
31
+ const resolved = await vorim.waitForDecisionResolution(d.decisionId, { timeoutMs: opts.escalationTimeoutMs });
32
+ return { allowed: isAllowVerdict(resolved.decision), reason: resolved.reason, decisionId: resolved.decisionId || d.decisionId };
33
+ } catch {
34
+ return { allowed: false, reason: "escalation not resolved before timeout", decisionId: d.decisionId };
35
+ }
36
+ }
37
+
38
+ // src/integrations/commerce-agents.ts
39
+ var SHOPPING_OPERATION_SCOPE = {
40
+ // Catalogue and customer reads.
41
+ search_products: "agent:read",
42
+ get_product_details: "agent:read",
43
+ get_cart: "agent:read",
44
+ get_preferences: "agent:read",
45
+ get_account_context: "agent:read",
46
+ get_orders: "agent:read",
47
+ get_order: "agent:read",
48
+ search_policies: "agent:read",
49
+ get_disclosure: "agent:read",
50
+ get_fulfillment_options: "agent:read",
51
+ // Cart writes — reversible, but they change what the customer is about to buy.
52
+ add_to_cart: "agent:write",
53
+ update_cart_item: "agent:write",
54
+ remove_from_cart: "agent:write",
55
+ // The money moment. No money moves here (the host completes checkout), but
56
+ // this is the call that produces a payable cart, so it takes agent:transact.
57
+ checkout_handoff: "agent:transact"
58
+ };
59
+ var MERCHANT_OPERATION_SCOPE = {
60
+ // Analytics and catalogue reads.
61
+ get_business_snapshot: "agent:read",
62
+ query_metrics: "agent:read",
63
+ get_campaign_performance: "agent:read",
64
+ search_listings: "agent:read",
65
+ get_listing: "agent:read",
66
+ get_inventory_alerts: "agent:read",
67
+ get_order_issues: "agent:read",
68
+ get_pricing_context: "agent:read",
69
+ get_pending_changes: "agent:read",
70
+ get_analysis_schema: "agent:read",
71
+ get_merchant_context: "agent:read",
72
+ // The analysis delegate's read-only SQL. Read-only by contract in the
73
+ // blueprint; it still runs model-authored SQL, so hold it to a higher trust
74
+ // floor if your warehouse has rows the shopper-facing agent should not see.
75
+ execute_analysis_query: "agent:read",
76
+ // Staged writes: nothing is live yet, and every one of them is discardable.
77
+ stage_listing_update: "agent:write",
78
+ stage_price_update: "agent:write",
79
+ stage_inventory_action: "agent:write",
80
+ stage_promotion: "agent:write",
81
+ stage_campaign: "agent:write",
82
+ discard_change: "agent:write",
83
+ // The live-store write. Irreversible from the agent's side, so it is held to
84
+ // agent:elevate and escalated to a human under runtime control.
85
+ apply_change: "agent:elevate"
86
+ };
87
+ var HUMAN_APPROVAL_OPERATIONS = ["checkout_handoff", "apply_change"];
88
+ var APPROVE_CHANGE = "approve_change";
89
+ var CommerceDeniedError = class extends Error {
90
+ receipt;
91
+ constructor(message, receipt) {
92
+ super(message);
93
+ this.name = "CommerceDeniedError";
94
+ this.receipt = receipt;
95
+ }
96
+ };
97
+ var RESOURCE_KEYS = [
98
+ "change_id",
99
+ "changeId",
100
+ "product_id",
101
+ "productId",
102
+ "order_id",
103
+ "orderId",
104
+ "listing_id",
105
+ "listingId",
106
+ "campaign_id",
107
+ "campaignId",
108
+ "promotion_id",
109
+ "promotionId"
110
+ ];
111
+ var ID_AFTER_SESSION = /* @__PURE__ */ new Set([
112
+ "get_product_details",
113
+ "add_to_cart",
114
+ "update_cart_item",
115
+ "remove_from_cart",
116
+ "get_order",
117
+ "get_disclosure",
118
+ "get_listing",
119
+ "stage_listing_update",
120
+ "apply_change",
121
+ "discard_change"
122
+ ]);
123
+ function normalizeOperation(operation) {
124
+ return operation.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
125
+ }
126
+ function isSessionContext(value) {
127
+ if (!value || typeof value !== "object") return false;
128
+ const v = value;
129
+ return "session_id" in v || "sessionId" in v;
130
+ }
131
+ async function sha256Hex(input) {
132
+ try {
133
+ const bytes = new TextEncoder().encode(input);
134
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
135
+ return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
136
+ } catch {
137
+ return void 0;
138
+ }
139
+ }
140
+ async function describeCommerceCall(operation, args) {
141
+ const action = { operation: normalizeOperation(operation) };
142
+ const rest = [];
143
+ for (const arg of args) {
144
+ if (isSessionContext(arg) && !action.sessionId) {
145
+ const session = arg;
146
+ action.sessionId = session.session_id ?? session.sessionId;
147
+ action.humanId = session.user_id ?? session.userId ?? session.operator;
148
+ continue;
149
+ }
150
+ rest.push(arg);
151
+ }
152
+ if (ID_AFTER_SESSION.has(action.operation) && typeof rest[0] === "string" && rest[0]) {
153
+ action.resourceId = rest[0];
154
+ }
155
+ for (const arg of rest) {
156
+ if (arg && typeof arg === "object" && !Array.isArray(arg)) {
157
+ const record = arg;
158
+ for (const key of RESOURCE_KEYS) {
159
+ const value = record[key];
160
+ if (!action.resourceId && typeof value === "string" && value) action.resourceId = value;
161
+ }
162
+ }
163
+ }
164
+ if (rest.length) {
165
+ try {
166
+ action.payload = { args: JSON.parse(JSON.stringify(rest)) };
167
+ action.inputHash = await sha256Hex(JSON.stringify(action.payload));
168
+ } catch {
169
+ action.payload = void 0;
170
+ }
171
+ }
172
+ return action;
173
+ }
174
+ var VorimCommerceGuard = class {
175
+ sdk;
176
+ agentId;
177
+ role;
178
+ humanId;
179
+ storeId;
180
+ minTrustScore;
181
+ onError;
182
+ unknownScope;
183
+ useRuntimeControl;
184
+ onEscalation;
185
+ escalationTimeoutMs;
186
+ onTransportFailure;
187
+ onDenied;
188
+ constructor(sdk, config) {
189
+ if (!config?.agentId) throw new Error("[vorim] commerce-agents integration requires an agentId.");
190
+ if (config.role !== "shopping" && config.role !== "merchant") {
191
+ throw new Error("[vorim] commerce-agents role must be 'shopping' or 'merchant'.");
192
+ }
193
+ this.sdk = sdk;
194
+ this.agentId = config.agentId;
195
+ this.role = config.role;
196
+ this.humanId = config.humanId;
197
+ this.storeId = config.storeId;
198
+ this.minTrustScore = config.minTrustScore ?? 0;
199
+ this.onError = config.onError ?? "closed";
200
+ this.unknownScope = config.unknownScope ?? "agent:write";
201
+ this.useRuntimeControl = config.useRuntimeControl ?? false;
202
+ this.onEscalation = config.onEscalation ?? "wait";
203
+ this.escalationTimeoutMs = config.escalationTimeoutMs;
204
+ this.onTransportFailure = config.onTransportFailure ?? "deny";
205
+ this.onDenied = config.onDenied;
206
+ }
207
+ /** The scope map for this guard's role. */
208
+ get scopes() {
209
+ return this.role === "shopping" ? SHOPPING_OPERATION_SCOPE : MERCHANT_OPERATION_SCOPE;
210
+ }
211
+ /** Whether an operation is one this guard's role knows how to classify. */
212
+ knows(operation) {
213
+ return normalizeOperation(operation) in this.scopes;
214
+ }
215
+ /** The Vorim scope an operation requires; unknown methods take unknownScope. */
216
+ scopeFor(operation) {
217
+ const name = normalizeOperation(operation);
218
+ if (name === APPROVE_CHANGE) return "agent:elevate";
219
+ return this.scopes[name] ?? this.unknownScope;
220
+ }
221
+ /**
222
+ * Check whether the acting agent may run this operation, before it runs.
223
+ * Static path: trust floor, then permission scope. Runtime path: a
224
+ * beforeAction decision, with `escalate` resolved per onEscalation.
225
+ */
226
+ async authorize(action) {
227
+ const scope = this.scopeFor(action.operation);
228
+ try {
229
+ if (this.useRuntimeControl) {
230
+ const target = `commerce:${this.role}:${normalizeOperation(action.operation)}${action.resourceId ? " " + action.resourceId : ""}`;
231
+ const gate = await runtimeGate(this.sdk, this.agentId, target, scope, action.payload, {
232
+ onEscalation: this.onEscalation,
233
+ escalationTimeoutMs: this.escalationTimeoutMs,
234
+ onTransportFailure: this.onTransportFailure
235
+ });
236
+ return { authorized: gate.allowed, reason: gate.reason, decisionId: gate.decisionId };
237
+ }
238
+ if (this.minTrustScore > 0) {
239
+ const trust = await this.sdk.verify(this.agentId);
240
+ if ((trust?.trust_score ?? 0) < this.minTrustScore) {
241
+ return { authorized: false, reason: `trust score below ${this.minTrustScore}` };
242
+ }
243
+ }
244
+ const perm = await this.sdk.check(this.agentId, scope);
245
+ return perm.allowed ? { authorized: true } : { authorized: false, reason: perm.reason ?? `missing scope ${scope}` };
246
+ } catch (e) {
247
+ return this.onError === "open" ? { authorized: true, reason: "vorim unreachable, failed open" } : { authorized: false, reason: `vorim unreachable: ${e?.message ?? "error"}` };
248
+ }
249
+ }
250
+ /**
251
+ * Emit a source-signed audit event and return whether it was recorded. The
252
+ * event names the agent, the store, the session and the person the agent acts
253
+ * for, so a cart write or a live price move is attributable and independently
254
+ * verifiable offline.
255
+ */
256
+ async record(action, result, reason, decisionId) {
257
+ const operation = normalizeOperation(action.operation);
258
+ try {
259
+ await this.sdk.emit(
260
+ {
261
+ agent_id: this.agentId,
262
+ event_type: "tool_call",
263
+ action: `commerce:${this.role}:${operation}${action.resourceId ? " " + action.resourceId : ""}`,
264
+ resource: action.resourceId || this.storeId,
265
+ permission: this.scopeFor(operation),
266
+ result,
267
+ input_hash: action.inputHash,
268
+ metadata: {
269
+ integration: "commerce-agents",
270
+ role: this.role,
271
+ store: this.storeId,
272
+ acts_for_human: action.humanId ?? this.humanId,
273
+ session_id: action.sessionId,
274
+ operation,
275
+ ...reason ? { reason } : {},
276
+ ...decisionId ? { decision_id: decisionId } : {}
277
+ }
278
+ },
279
+ { sign: true }
280
+ // source-signed: the agent's key signs the record
281
+ );
282
+ return true;
283
+ } catch {
284
+ return false;
285
+ }
286
+ }
287
+ /**
288
+ * The full flow for one backend call: authorize, run it if allowed, sign a
289
+ * receipt either way. If not authorized, `run` is never called — the
290
+ * catalogue is never queried, the cart is never written, nothing goes live.
291
+ * An error from `run` is recorded and rethrown with the receipt attached as
292
+ * `vorimReceipt`, so the executor's failure ladder still sees the real
293
+ * failure.
294
+ */
295
+ async guard(action, run) {
296
+ const auth = await this.authorize(action);
297
+ if (!auth.authorized) {
298
+ const recorded = await this.record(action, "denied", auth.reason, auth.decisionId);
299
+ return {
300
+ receipt: this.receipt(action, false, "denied", auth.reason, recorded, auth.decisionId)
301
+ };
302
+ }
303
+ try {
304
+ const value = await run();
305
+ const recorded = await this.record(action, "success", void 0, auth.decisionId);
306
+ return {
307
+ receipt: this.receipt(action, true, "success", void 0, recorded, auth.decisionId),
308
+ value
309
+ };
310
+ } catch (e) {
311
+ const recorded = await this.record(action, "error", e?.message, auth.decisionId);
312
+ throw Object.assign(e ?? new Error("commerce backend call failed"), {
313
+ vorimReceipt: this.receipt(action, true, "error", e?.message, recorded, auth.decisionId)
314
+ });
315
+ }
316
+ }
317
+ /**
318
+ * Ask a human to approve a staged merchant change, and mark it approved on the
319
+ * session state when they do.
320
+ *
321
+ * This is the bridge to MerchantAgentConfig.require_host_approval:
322
+ * commerce-agents applies a change only for ids in
323
+ * MerchantSessionState.approved_change_ids, and this fills that set from a
324
+ * signed human decision rather than from host code that trusted the
325
+ * conversation. With useRuntimeControl off there is nobody to escalate to, so
326
+ * it falls back to the static scope check — which proves the agent *may* apply
327
+ * changes, not that a person approved this one.
328
+ */
329
+ async approveChange(changeId, opts = {}) {
330
+ const payload = { change_id: changeId, ...opts.payload ?? {} };
331
+ const action = {
332
+ operation: APPROVE_CHANGE,
333
+ resourceId: changeId,
334
+ sessionId: opts.sessionId,
335
+ payload,
336
+ inputHash: await sha256Hex(JSON.stringify(payload))
337
+ };
338
+ const { receipt } = await this.guard(action, async () => void 0);
339
+ if (receipt.authorized && opts.state) {
340
+ const approved = opts.state.approved_change_ids ?? opts.state.approvedChangeIds;
341
+ if (!approved) {
342
+ throw new TypeError(
343
+ "[vorim] approveChange expected a MerchantSessionState with approved_change_ids."
344
+ );
345
+ }
346
+ approved.add(changeId);
347
+ }
348
+ return receipt;
349
+ }
350
+ /** The error a guarded backend method throws on a denial. */
351
+ denialError(receipt) {
352
+ if (this.onDenied) return this.onDenied(receipt);
353
+ return new CommerceDeniedError(
354
+ `${receipt.operation} was not authorized for ${receipt.agentId} (${receipt.scope}): ${receipt.reason ?? "denied"}`,
355
+ receipt
356
+ );
357
+ }
358
+ receipt(action, authorized, result, reason, recorded, decisionId) {
359
+ return {
360
+ authorized,
361
+ agentId: this.agentId,
362
+ role: this.role,
363
+ operation: normalizeOperation(action.operation),
364
+ result,
365
+ scope: this.scopeFor(action.operation),
366
+ recorded,
367
+ storeId: this.storeId,
368
+ humanId: action.humanId ?? this.humanId,
369
+ sessionId: action.sessionId,
370
+ resourceId: action.resourceId,
371
+ inputHash: action.inputHash,
372
+ reason,
373
+ decisionId
374
+ };
375
+ }
376
+ };
377
+ var UNGUARDED = /* @__PURE__ */ Symbol.for("vorim.commerce.inner");
378
+ function guardBackend(backend, guard, options = {}) {
379
+ const guardUnknown = options.guardUnknown ?? true;
380
+ return new Proxy(backend, {
381
+ get(target, property, receiver) {
382
+ if (property === UNGUARDED) return target;
383
+ const value = Reflect.get(target, property, receiver);
384
+ if (typeof property !== "string" || typeof value !== "function") return value;
385
+ if (!guard.knows(property) && !guardUnknown) return value;
386
+ return async (...args) => {
387
+ const action = await describeCommerceCall(property, args);
388
+ const { receipt, value: result } = await guard.guard(
389
+ action,
390
+ async () => value.apply(target, args)
391
+ );
392
+ if (!receipt.authorized) throw guard.denialError(receipt);
393
+ return result;
394
+ };
395
+ }
396
+ });
397
+ }
398
+ function guardStorefrontBackend(backend, guard, options) {
399
+ if (guard.role !== "shopping") {
400
+ throw new Error("[vorim] guardStorefrontBackend needs a guard built with role: 'shopping'.");
401
+ }
402
+ return guardBackend(backend, guard, options);
403
+ }
404
+ function guardMerchantBackend(backend, guard, options) {
405
+ if (guard.role !== "merchant") {
406
+ throw new Error("[vorim] guardMerchantBackend needs a guard built with role: 'merchant'.");
407
+ }
408
+ return guardBackend(backend, guard, options);
409
+ }
410
+ function createVorimCommerceGuard(sdk, config) {
411
+ return new VorimCommerceGuard(sdk, config);
412
+ }
413
+ var commerce_agents_default = createVorimCommerceGuard;
414
+ export {
415
+ APPROVE_CHANGE,
416
+ CommerceDeniedError,
417
+ HUMAN_APPROVAL_OPERATIONS,
418
+ MERCHANT_OPERATION_SCOPE,
419
+ SHOPPING_OPERATION_SCOPE,
420
+ UNGUARDED,
421
+ VorimCommerceGuard,
422
+ createVorimCommerceGuard,
423
+ commerce_agents_default as default,
424
+ describeCommerceCall,
425
+ guardMerchantBackend,
426
+ guardStorefrontBackend,
427
+ normalizeOperation
428
+ };
429
+ //# sourceMappingURL=commerce-agents.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/integrations/_runtime-gate.ts","../../src/integrations/commerce-agents.ts"],"sourcesContent":["// ============================================================================\n// VORIM SDK — Shared runtime-gate helper for framework integrations\n//\n// All tool-wrapping integrations (Vercel, OpenAI, Anthropic, …) turn a\n// `beforeAction` runtime decision into a simple { allowed, reason, decisionId }\n// the wrapper can act on. The subtlety is the `escalate` verdict: it is NOT a\n// denial — it means a human must approve the action. Folding it into\n// `allowed=false` silently breaks every human-in-the-loop flow; folding it into\n// `allowed=true` is a fail-open security hole. So this helper resolves the\n// escalation explicitly, driven by the caller's `onEscalation` preference.\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { RuntimeDecision, PermissionScope } from '../types.js';\n\n/**\n * How a framework integration should treat a runtime `escalate` verdict.\n * - `wait` — block and poll {@link VorimSDK.waitForDecisionResolution} until a\n * human approves/denies (or the timeout elapses → deny). The correct\n * default for human-in-the-loop: an escalation means \"ask a human\".\n * - `deny` — treat escalate as a denial (fail closed without waiting).\n * - `allow` — treat escalate as allowed (fail OPEN — only for trusted/dev use).\n */\nexport type EscalationPolicy = 'wait' | 'deny' | 'allow';\n\n/**\n * How a framework integration should treat a transport-failure `fallback`\n * decision (the control plane was unreachable and the SDK's\n * `runtimeFailOpen` produced a synthetic `decision: 'fallback'`,\n * `isFallback: true`).\n * - `deny` — fail closed: a control-plane outage denies the tool call.\n * The correct default for a SECURITY gate the caller opted into\n * via `useRuntimeControl: true`.\n * - `allow` — fail open: let the action proceed when the policy plane is\n * down (matches the raw SDK `runtimeFailOpen` behaviour).\n */\nexport type TransportFailurePolicy = 'deny' | 'allow';\n\nexport interface RuntimeGateOptions {\n /** What to do on an `escalate` verdict. @default 'wait' */\n onEscalation?: EscalationPolicy;\n /** Timeout (ms) for `onEscalation: 'wait'`. @default 300000 (5 min) */\n escalationTimeoutMs?: number;\n /**\n * What to do when the control plane is unreachable and `beforeAction`\n * returns a synthetic `fallback` decision. @default 'deny'\n *\n * The gate fails CLOSED on a policy-plane outage by default: a user who\n * turned on `useRuntimeControl: true` wants live deny/escalate\n * enforcement, so an outage should not silently auto-allow. Set to\n * `'allow'` to keep the old fail-open behaviour.\n */\n onTransportFailure?: TransportFailurePolicy;\n}\n\nexport interface GateResult {\n allowed: boolean;\n reason?: string;\n decisionId?: string;\n}\n\n/**\n * True for verdicts that permit the action to proceed. `escalate` is handled\n * separately. `fallback` is NOT treated as an allow here — a transport-failure\n * fallback is resolved explicitly via `onTransportFailure` so a control-plane\n * outage can't silently auto-allow inside a security gate.\n */\nfunction isAllowVerdict(decision: RuntimeDecision['decision']): boolean {\n return decision === 'allow' || decision === 'modify';\n}\n\n/**\n * Run a `beforeAction` runtime decision and collapse it to a {@link GateResult},\n * resolving `escalate` per {@link RuntimeGateOptions.onEscalation}.\n *\n * Requires (for `onEscalation: 'wait'`) an API key with the `runtime:decide`\n * scope — the same scope `beforeAction` itself uses.\n */\nexport async function runtimeGate(\n vorim: VorimSDK,\n agentId: string,\n actionTarget: string,\n scope: PermissionScope,\n payload: Record<string, unknown> | undefined,\n opts: RuntimeGateOptions = {},\n): Promise<GateResult> {\n const onEscalation = opts.onEscalation ?? 'wait';\n const onTransportFailure = opts.onTransportFailure ?? 'deny';\n const d = await vorim.beforeAction(\n { agentId, actionType: 'tool_call', actionTarget, requiredScope: scope, payload },\n { throwOnDeny: false },\n );\n\n // Control-plane outage: beforeAction returned a synthetic fallback\n // (isFallback). Govern it by onTransportFailure (default 'deny') rather\n // than auto-allowing — the caller turned on runtime control for live\n // enforcement, so an outage should fail closed unless they opt out.\n if (d.isFallback || d.decision === 'fallback') {\n if (onTransportFailure === 'allow') {\n return { allowed: true, reason: d.reason ?? 'control plane unreachable (fail-open)', decisionId: d.decisionId || undefined };\n }\n return { allowed: false, reason: d.reason ?? 'control plane unreachable (failed closed)', decisionId: d.decisionId || undefined };\n }\n\n if (d.decision !== 'escalate') {\n return { allowed: isAllowVerdict(d.decision), reason: d.reason, decisionId: d.decisionId || undefined };\n }\n\n // escalate ── a human must decide.\n if (onEscalation === 'allow') {\n return { allowed: true, reason: d.reason ?? 'escalated (auto-allowed)', decisionId: d.decisionId || undefined };\n }\n if (onEscalation === 'deny') {\n return { allowed: false, reason: d.reason ?? 'escalated (auto-denied — awaiting human)', decisionId: d.decisionId || undefined };\n }\n // 'wait' — poll for the human decision. On timeout, fail closed (deny).\n if (!d.decisionId) {\n return { allowed: false, reason: 'escalated but no decisionId to poll', decisionId: undefined };\n }\n try {\n const resolved = await vorim.waitForDecisionResolution(d.decisionId, { timeoutMs: opts.escalationTimeoutMs });\n return { allowed: isAllowVerdict(resolved.decision), reason: resolved.reason, decisionId: resolved.decisionId || d.decisionId };\n } catch {\n // ESCALATION_TIMEOUT (or any poll error) → fail closed.\n return { allowed: false, reason: 'escalation not resolved before timeout', decisionId: d.decisionId };\n }\n}\n","// ============================================================================\n// Vorim AI — Anthropic Commerce Agents (shopping + merchant) Integration\n//\n// This guards an agent built on Anthropic's `commerce-agents` blueprint\n// (https://github.com/anthropics/commerce-agents) — the shopping agent that\n// searches a catalogue, fills a cart and hands off to checkout, and the\n// merchant agent that reads store performance, stages listing / price /\n// inventory / promotion / campaign changes and applies them to the live store.\n//\n// The blueprint plugs into a deployment through two backend contracts,\n// StorefrontBackend and MerchantBackend: every tool the model calls ends up in\n// one of their methods, executed server-side. That makes the backend the one\n// place worth guarding, and this integration wraps it. It mirrors the Python\n// `vorim.integrations.commerce_agents` connector.\n//\n// WHY A GUARD ON A COMMERCE AGENT\n// commerce-agents already fences the model: cart writes accept only product ids\n// the session actually saw (provenance), staged merchant changes are checked\n// against guardrails, and apply_change refuses an id the host has not marked\n// approved. Those gates are real, but they are *in-process* — they live and die\n// with the running turn, they are unsigned, and they cannot answer the questions\n// that matter after the fact: which agent ran this, on whose authority, was it\n// allowed to at the time, and who approved the price change that went live at\n// 03:00. This layer sits beside those gates and supplies exactly that.\n//\n// It never replaces the blueprint's own gates. Provenance and guardrails still\n// run inside the executor; Vorim adds who, and by what authority.\n//\n// SCOPE MAPPING (uses Vorim's real scopes)\n// catalogue / order / policy / analytics reads -> agent:read\n// cart writes, staged merchant changes -> agent:write\n// checkout handoff (the money moment) -> agent:transact\n// applyChange (the live-store write) -> agent:elevate\n//\n// applyChange is the only method here that changes what shoppers see, and it is\n// irreversible from the agent's side — so it is held to agent:elevate and, with\n// runtime control on, escalated to a named human like an Okta role grant.\n// Staging is cheap and reversible; applying is not.\n//\n// THE APPROVAL BRIDGE\n// MerchantAgentConfig.require_host_approval (on by default) means apply_change\n// succeeds only for change ids the host put in\n// MerchantSessionState.approved_change_ids. `approveChange()` is the honest way\n// to fill that set: it raises a Vorim escalation, waits for a human to approve\n// it, and only then marks the id — so the mark is backed by a signed human\n// decision rather than by host code that trusted the conversation.\n//\n// Method names are matched in either spelling: a TypeScript host that fronts\n// these contracts as `searchProducts` is understood the same as the blueprint's\n// `search_products`.\n//\n// Usage:\n// import createVorim from '@vorim/sdk';\n// import {\n// createVorimCommerceGuard,\n// guardStorefrontBackend,\n// } from '@vorim/sdk/integrations/commerce-agents';\n//\n// const vorim = createVorim({ apiKey: 'agid_sk_...' });\n// const guard = createVorimCommerceGuard(vorim, {\n// agentId: 'agid_shopper_1',\n// role: 'shopping',\n// humanId: 'cust_42', // the customer the agent acts for\n// storeId: 'acme-retail',\n// minTrustScore: 60,\n// });\n//\n// const backend = guardStorefrontBackend(new AcmeStorefront(), guard);\n// await backend.addToCart(session, 'sku_1', 2); // gated + signed\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope } from '../types.js';\nimport { runtimeGate, type EscalationPolicy, type TransportFailurePolicy } from './_runtime-gate.js';\n\nexport type CommerceRole = 'shopping' | 'merchant';\n\n/** StorefrontBackend methods -> the least scope that should be required.\n * Keyed by the blueprint's own (snake_case) method names; a camelCase host\n * method resolves to the same entry. */\nexport const SHOPPING_OPERATION_SCOPE: Record<string, PermissionScope> = {\n // Catalogue and customer reads.\n search_products: 'agent:read',\n get_product_details: 'agent:read',\n get_cart: 'agent:read',\n get_preferences: 'agent:read',\n get_account_context: 'agent:read',\n get_orders: 'agent:read',\n get_order: 'agent:read',\n search_policies: 'agent:read',\n get_disclosure: 'agent:read',\n get_fulfillment_options: 'agent:read',\n // Cart writes — reversible, but they change what the customer is about to buy.\n add_to_cart: 'agent:write',\n update_cart_item: 'agent:write',\n remove_from_cart: 'agent:write',\n // The money moment. No money moves here (the host completes checkout), but\n // this is the call that produces a payable cart, so it takes agent:transact.\n checkout_handoff: 'agent:transact',\n};\n\n/** MerchantBackend methods -> the least scope that should be required. */\nexport const MERCHANT_OPERATION_SCOPE: Record<string, PermissionScope> = {\n // Analytics and catalogue reads.\n get_business_snapshot: 'agent:read',\n query_metrics: 'agent:read',\n get_campaign_performance: 'agent:read',\n search_listings: 'agent:read',\n get_listing: 'agent:read',\n get_inventory_alerts: 'agent:read',\n get_order_issues: 'agent:read',\n get_pricing_context: 'agent:read',\n get_pending_changes: 'agent:read',\n get_analysis_schema: 'agent:read',\n get_merchant_context: 'agent:read',\n // The analysis delegate's read-only SQL. Read-only by contract in the\n // blueprint; it still runs model-authored SQL, so hold it to a higher trust\n // floor if your warehouse has rows the shopper-facing agent should not see.\n execute_analysis_query: 'agent:read',\n // Staged writes: nothing is live yet, and every one of them is discardable.\n stage_listing_update: 'agent:write',\n stage_price_update: 'agent:write',\n stage_inventory_action: 'agent:write',\n stage_promotion: 'agent:write',\n stage_campaign: 'agent:write',\n discard_change: 'agent:write',\n // The live-store write. Irreversible from the agent's side, so it is held to\n // agent:elevate and escalated to a human under runtime control.\n apply_change: 'agent:elevate',\n};\n\n/** The two operations that leave the sandbox: one produces a payable cart, the\n * other writes to the live store. Give each a Vorim policy rule that escalates\n * it to a named human — the guard resolves that escalation per `onEscalation`,\n * and `approveChange()` is the purpose-built path for apply_change. Escalation\n * is a policy decision, so nothing here can conjure one: with no rule\n * configured, a plain allow runs. */\nexport const HUMAN_APPROVAL_OPERATIONS = ['checkout_handoff', 'apply_change'] as const;\n\n/** The approval bridge's own operation label. */\nexport const APPROVE_CHANGE = 'approve_change';\n\n/** An offline-verifiable receipt for one commerce backend operation. */\nexport interface CommerceReceipt {\n authorized: boolean;\n agentId: string;\n role: CommerceRole;\n operation: string;\n result: 'success' | 'denied' | 'error';\n scope: PermissionScope;\n /** True once the audit event was signed and ingested. */\n recorded: boolean;\n storeId?: string;\n humanId?: string;\n sessionId?: string;\n resourceId?: string;\n /** sha256 over the call's arguments, so the receipt covers the exact input\n * without the guard storing it. */\n inputHash?: string;\n /** Reason a check failed, when authorized is false. */\n reason?: string;\n /** The runtime decision this call was resolved by, when runtime control is on. */\n decisionId?: string;\n}\n\n/** Thrown by a guarded backend method when Vorim denied the call. */\nexport class CommerceDeniedError extends Error {\n readonly receipt: CommerceReceipt;\n constructor(message: string, receipt: CommerceReceipt) {\n super(message);\n this.name = 'CommerceDeniedError';\n this.receipt = receipt;\n }\n}\n\nexport interface CommerceGuardConfig {\n /** The acting agent's Vorim id (agid_...). */\n agentId: string;\n /** 'shopping' or 'merchant' — picks the scope map and labels the audit\n * record. A deployment running both agents builds one guard per role, each\n * with its own agent id, so a shopper-facing agent can never be mistaken for\n * the one that moves prices. */\n role: CommerceRole;\n /** The customer or operator the agent acts for. Falls back to the per-request\n * session context (userId/user_id, operator) when the call carries one. */\n humanId?: string;\n /** The store / merchant this agent operates on. Recorded on every receipt. */\n storeId?: string;\n /** Minimum trust score the acting agent must hold. Default 0 (off). */\n minTrustScore?: number;\n /** Fail closed (deny on any Vorim error) or fail open. Default 'closed'. */\n onError?: 'closed' | 'open';\n /** Scope required by a backend method the maps do not know. Default\n * 'agent:write' — a method we cannot classify is assumed to write. */\n unknownScope?: PermissionScope;\n /** Route decisions through beforeAction (live policy, budgets, human\n * escalation) instead of a static check/verify. Default false. */\n useRuntimeControl?: boolean;\n /** What to do on an `escalate` verdict. Default 'wait'. */\n onEscalation?: EscalationPolicy;\n /** Timeout (ms) for onEscalation: 'wait'. */\n escalationTimeoutMs?: number;\n /** What to do when the control plane is unreachable. Default 'deny'. */\n onTransportFailure?: TransportFailurePolicy;\n /** Turn a denial receipt into the error the backend should throw. Use it to\n * return commerce-agents' own NotOffered / Unavailable so the model gets the\n * blueprint's wording instead of the generic failure text. */\n onDenied?: (receipt: CommerceReceipt) => Error;\n}\n\n/** What one guarded call is about, pulled off the bound arguments. */\nexport interface CommerceAction {\n operation: string;\n resourceId?: string;\n sessionId?: string;\n humanId?: string;\n payload?: Record<string, unknown>;\n inputHash?: string;\n}\n\n/** Argument names that identify the thing an operation acts on, in the order a\n * call's arguments are searched. */\nconst RESOURCE_KEYS = [\n 'change_id',\n 'changeId',\n 'product_id',\n 'productId',\n 'order_id',\n 'orderId',\n 'listing_id',\n 'listingId',\n 'campaign_id',\n 'campaignId',\n 'promotion_id',\n 'promotionId',\n];\n\n/** Operations whose first argument after the session context IS the id they act\n * on. Everything else carries its ids inside an object argument (a\n * PriceUpdateItem, a PromotionDraft) and is read through RESOURCE_KEYS. */\nconst ID_AFTER_SESSION = new Set([\n 'get_product_details',\n 'add_to_cart',\n 'update_cart_item',\n 'remove_from_cart',\n 'get_order',\n 'get_disclosure',\n 'get_listing',\n 'stage_listing_update',\n 'apply_change',\n 'discard_change',\n]);\n\n/** camelCase -> snake_case, so a TypeScript host's `searchProducts` finds the\n * blueprint's `search_products` entry. */\nexport function normalizeOperation(operation: string): string {\n return operation.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase();\n}\n\nfunction isSessionContext(value: unknown): boolean {\n if (!value || typeof value !== 'object') return false;\n const v = value as Record<string, unknown>;\n return 'session_id' in v || 'sessionId' in v;\n}\n\nasync function sha256Hex(input: string): Promise<string | undefined> {\n try {\n const bytes = new TextEncoder().encode(input);\n const digest = await globalThis.crypto.subtle.digest('SHA-256', bytes);\n return Array.from(new Uint8Array(digest))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n } catch {\n return undefined; // no WebCrypto here — the receipt simply carries no hash\n }\n}\n\n/**\n * Describe one backend call: which resource it touches, whose session it runs\n * in, and a JSON-safe payload for payload-conditioned policy rules.\n *\n * The blueprint's per-request context (ShoppingSessionContext /\n * MerchantSessionContext) is always the first argument; it is the host's own\n * object, so it is read for identity and then left out of the payload rather\n * than shipped to the policy engine.\n */\nexport async function describeCommerceCall(\n operation: string,\n args: unknown[],\n): Promise<CommerceAction> {\n const action: CommerceAction = { operation: normalizeOperation(operation) };\n const rest: unknown[] = [];\n\n for (const arg of args) {\n if (isSessionContext(arg) && !action.sessionId) {\n const session = arg as Record<string, unknown>;\n action.sessionId = (session.session_id ?? session.sessionId) as string | undefined;\n action.humanId = (session.user_id ?? session.userId ?? session.operator) as string | undefined;\n continue;\n }\n rest.push(arg);\n }\n\n // The blueprint passes the id it acts on right after the session — but only\n // for the operations listed here. Taking any leading string would file a\n // search query ('a two-person tent') as a resource id.\n if (ID_AFTER_SESSION.has(action.operation) && typeof rest[0] === 'string' && rest[0]) {\n action.resourceId = rest[0];\n }\n for (const arg of rest) {\n if (arg && typeof arg === 'object' && !Array.isArray(arg)) {\n const record = arg as Record<string, unknown>;\n for (const key of RESOURCE_KEYS) {\n const value = record[key];\n if (!action.resourceId && typeof value === 'string' && value) action.resourceId = value;\n }\n }\n }\n\n if (rest.length) {\n // JavaScript has no named parameters, so the arguments travel positionally\n // under `args` — the same shape _runtime-gate's Python twin sends. The\n // policy engine sees the values either way.\n try {\n action.payload = { args: JSON.parse(JSON.stringify(rest)) };\n action.inputHash = await sha256Hex(JSON.stringify(action.payload));\n } catch {\n action.payload = undefined; // unserialisable arguments must not break the gate\n }\n }\n return action;\n}\n\nexport class VorimCommerceGuard {\n private sdk: VorimSDK;\n private agentId: string;\n readonly role: CommerceRole;\n private humanId?: string;\n private storeId?: string;\n private minTrustScore: number;\n private onError: 'closed' | 'open';\n private unknownScope: PermissionScope;\n private useRuntimeControl: boolean;\n private onEscalation: EscalationPolicy;\n private escalationTimeoutMs?: number;\n private onTransportFailure: TransportFailurePolicy;\n private onDenied?: (receipt: CommerceReceipt) => Error;\n\n constructor(sdk: VorimSDK, config: CommerceGuardConfig) {\n if (!config?.agentId) throw new Error('[vorim] commerce-agents integration requires an agentId.');\n if (config.role !== 'shopping' && config.role !== 'merchant') {\n throw new Error(\"[vorim] commerce-agents role must be 'shopping' or 'merchant'.\");\n }\n this.sdk = sdk;\n this.agentId = config.agentId;\n this.role = config.role;\n this.humanId = config.humanId;\n this.storeId = config.storeId;\n this.minTrustScore = config.minTrustScore ?? 0;\n this.onError = config.onError ?? 'closed';\n this.unknownScope = config.unknownScope ?? 'agent:write';\n this.useRuntimeControl = config.useRuntimeControl ?? false;\n this.onEscalation = config.onEscalation ?? 'wait';\n this.escalationTimeoutMs = config.escalationTimeoutMs;\n this.onTransportFailure = config.onTransportFailure ?? 'deny';\n this.onDenied = config.onDenied;\n }\n\n /** The scope map for this guard's role. */\n get scopes(): Record<string, PermissionScope> {\n return this.role === 'shopping' ? SHOPPING_OPERATION_SCOPE : MERCHANT_OPERATION_SCOPE;\n }\n\n /** Whether an operation is one this guard's role knows how to classify. */\n knows(operation: string): boolean {\n return normalizeOperation(operation) in this.scopes;\n }\n\n /** The Vorim scope an operation requires; unknown methods take unknownScope. */\n scopeFor(operation: string): PermissionScope {\n const name = normalizeOperation(operation);\n if (name === APPROVE_CHANGE) return 'agent:elevate';\n return this.scopes[name] ?? this.unknownScope;\n }\n\n /**\n * Check whether the acting agent may run this operation, before it runs.\n * Static path: trust floor, then permission scope. Runtime path: a\n * beforeAction decision, with `escalate` resolved per onEscalation.\n */\n async authorize(\n action: CommerceAction,\n ): Promise<{ authorized: boolean; reason?: string; decisionId?: string }> {\n const scope = this.scopeFor(action.operation);\n try {\n if (this.useRuntimeControl) {\n const target = `commerce:${this.role}:${normalizeOperation(action.operation)}${\n action.resourceId ? ' ' + action.resourceId : ''\n }`;\n const gate = await runtimeGate(this.sdk, this.agentId, target, scope, action.payload, {\n onEscalation: this.onEscalation,\n escalationTimeoutMs: this.escalationTimeoutMs,\n onTransportFailure: this.onTransportFailure,\n });\n return { authorized: gate.allowed, reason: gate.reason, decisionId: gate.decisionId };\n }\n // Trust floor (optional): refuse low-trust agents up front.\n if (this.minTrustScore > 0) {\n const trust = await this.sdk.verify(this.agentId);\n if ((trust?.trust_score ?? 0) < this.minTrustScore) {\n return { authorized: false, reason: `trust score below ${this.minTrustScore}` };\n }\n }\n const perm = await this.sdk.check(this.agentId, scope);\n return perm.allowed\n ? { authorized: true }\n : { authorized: false, reason: perm.reason ?? `missing scope ${scope}` };\n } catch (e: any) {\n // Fail closed by default: a check we could not complete is a deny.\n return this.onError === 'open'\n ? { authorized: true, reason: 'vorim unreachable, failed open' }\n : { authorized: false, reason: `vorim unreachable: ${e?.message ?? 'error'}` };\n }\n }\n\n /**\n * Emit a source-signed audit event and return whether it was recorded. The\n * event names the agent, the store, the session and the person the agent acts\n * for, so a cart write or a live price move is attributable and independently\n * verifiable offline.\n */\n async record(\n action: CommerceAction,\n result: 'success' | 'denied' | 'error',\n reason?: string,\n decisionId?: string,\n ): Promise<boolean> {\n const operation = normalizeOperation(action.operation);\n try {\n await this.sdk.emit(\n {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: `commerce:${this.role}:${operation}${action.resourceId ? ' ' + action.resourceId : ''}`,\n resource: action.resourceId || this.storeId,\n permission: this.scopeFor(operation),\n result,\n input_hash: action.inputHash,\n metadata: {\n integration: 'commerce-agents',\n role: this.role,\n store: this.storeId,\n acts_for_human: action.humanId ?? this.humanId,\n session_id: action.sessionId,\n operation,\n ...(reason ? { reason } : {}),\n ...(decisionId ? { decision_id: decisionId } : {}),\n },\n },\n { sign: true }, // source-signed: the agent's key signs the record\n );\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * The full flow for one backend call: authorize, run it if allowed, sign a\n * receipt either way. If not authorized, `run` is never called — the\n * catalogue is never queried, the cart is never written, nothing goes live.\n * An error from `run` is recorded and rethrown with the receipt attached as\n * `vorimReceipt`, so the executor's failure ladder still sees the real\n * failure.\n */\n async guard<T>(\n action: CommerceAction,\n run: () => Promise<T>,\n ): Promise<{ receipt: CommerceReceipt; value?: T }> {\n const auth = await this.authorize(action);\n if (!auth.authorized) {\n const recorded = await this.record(action, 'denied', auth.reason, auth.decisionId);\n return {\n receipt: this.receipt(action, false, 'denied', auth.reason, recorded, auth.decisionId),\n };\n }\n try {\n const value = await run();\n const recorded = await this.record(action, 'success', undefined, auth.decisionId);\n return {\n receipt: this.receipt(action, true, 'success', undefined, recorded, auth.decisionId),\n value,\n };\n } catch (e: any) {\n const recorded = await this.record(action, 'error', e?.message, auth.decisionId);\n throw Object.assign(e ?? new Error('commerce backend call failed'), {\n vorimReceipt: this.receipt(action, true, 'error', e?.message, recorded, auth.decisionId),\n });\n }\n }\n\n /**\n * Ask a human to approve a staged merchant change, and mark it approved on the\n * session state when they do.\n *\n * This is the bridge to MerchantAgentConfig.require_host_approval:\n * commerce-agents applies a change only for ids in\n * MerchantSessionState.approved_change_ids, and this fills that set from a\n * signed human decision rather than from host code that trusted the\n * conversation. With useRuntimeControl off there is nobody to escalate to, so\n * it falls back to the static scope check — which proves the agent *may* apply\n * changes, not that a person approved this one.\n */\n async approveChange(\n changeId: string,\n opts: { state?: { approved_change_ids?: Set<string>; approvedChangeIds?: Set<string> }; sessionId?: string; payload?: Record<string, unknown> } = {},\n ): Promise<CommerceReceipt> {\n const payload = { change_id: changeId, ...(opts.payload ?? {}) };\n const action: CommerceAction = {\n operation: APPROVE_CHANGE,\n resourceId: changeId,\n sessionId: opts.sessionId,\n payload,\n inputHash: await sha256Hex(JSON.stringify(payload)),\n };\n const { receipt } = await this.guard(action, async () => undefined);\n if (receipt.authorized && opts.state) {\n const approved = opts.state.approved_change_ids ?? opts.state.approvedChangeIds;\n if (!approved) {\n throw new TypeError(\n '[vorim] approveChange expected a MerchantSessionState with approved_change_ids.',\n );\n }\n approved.add(changeId);\n }\n return receipt;\n }\n\n /** The error a guarded backend method throws on a denial. */\n denialError(receipt: CommerceReceipt): Error {\n if (this.onDenied) return this.onDenied(receipt);\n return new CommerceDeniedError(\n `${receipt.operation} was not authorized for ${receipt.agentId} (${receipt.scope}): ${\n receipt.reason ?? 'denied'\n }`,\n receipt,\n );\n }\n\n private receipt(\n action: CommerceAction,\n authorized: boolean,\n result: 'success' | 'denied' | 'error',\n reason: string | undefined,\n recorded: boolean,\n decisionId?: string,\n ): CommerceReceipt {\n return {\n authorized,\n agentId: this.agentId,\n role: this.role,\n operation: normalizeOperation(action.operation),\n result,\n scope: this.scopeFor(action.operation),\n recorded,\n storeId: this.storeId,\n humanId: action.humanId ?? this.humanId,\n sessionId: action.sessionId,\n resourceId: action.resourceId,\n inputHash: action.inputHash,\n reason,\n decisionId,\n };\n }\n}\n\n/** Reaches the unguarded backend behind a proxy, for host code that\n * legitimately bypasses the agent path (a nightly sync, a support tool). */\nexport const UNGUARDED = Symbol.for('vorim.commerce.inner');\n\nexport interface GuardBackendOptions {\n /** Gate a method neither scope map knows, at `unknownScope`, rather than\n * waving it through: a backend that grew a method since these maps were\n * written should not be the hole. Default true. Note that a guarded method\n * always returns a promise — turn this off if your backend exposes\n * synchronous helpers. */\n guardUnknown?: boolean;\n}\n\n/**\n * Wrap a backend so every method in the role's scope map is authorized and\n * signed before it runs and after it returns; anything else passes straight\n * through. Denials throw (see `denialError`) rather than returning empty\n * results, because a silent empty catalogue reads to the model as \"this store\n * has nothing\" — a denial should sound like one.\n */\nfunction guardBackend<B extends object>(\n backend: B,\n guard: VorimCommerceGuard,\n options: GuardBackendOptions = {},\n): B {\n const guardUnknown = options.guardUnknown ?? true;\n return new Proxy(backend, {\n get(target, property, receiver) {\n if (property === UNGUARDED) return target;\n const value = Reflect.get(target, property, receiver);\n if (typeof property !== 'string' || typeof value !== 'function') return value;\n if (!guard.knows(property) && !guardUnknown) return value;\n\n return async (...args: unknown[]) => {\n const action = await describeCommerceCall(property, args);\n const { receipt, value: result } = await guard.guard(action, async () =>\n (value as (...a: unknown[]) => unknown).apply(target, args),\n );\n if (!receipt.authorized) throw guard.denialError(receipt);\n return result;\n };\n },\n }) as B;\n}\n\n/** Wrap a StorefrontBackend so every shopping tool call is authorized and\n * signed. The guard's role must be 'shopping'. */\nexport function guardStorefrontBackend<B extends object>(\n backend: B,\n guard: VorimCommerceGuard,\n options?: GuardBackendOptions,\n): B {\n if (guard.role !== 'shopping') {\n throw new Error(\"[vorim] guardStorefrontBackend needs a guard built with role: 'shopping'.\");\n }\n return guardBackend(backend, guard, options);\n}\n\n/** Wrap a MerchantBackend so every merchant tool call — reads, staged changes,\n * and the live applyChange — is authorized and signed. The guard's role must\n * be 'merchant'. */\nexport function guardMerchantBackend<B extends object>(\n backend: B,\n guard: VorimCommerceGuard,\n options?: GuardBackendOptions,\n): B {\n if (guard.role !== 'merchant') {\n throw new Error(\"[vorim] guardMerchantBackend needs a guard built with role: 'merchant'.\");\n }\n return guardBackend(backend, guard, options);\n}\n\n/** Create a {@link VorimCommerceGuard}. See {@link CommerceGuardConfig}. */\nexport function createVorimCommerceGuard(\n sdk: VorimSDK,\n config: CommerceGuardConfig,\n): VorimCommerceGuard {\n return new VorimCommerceGuard(sdk, config);\n}\n\nexport default createVorimCommerceGuard;\n"],"mappings":";AAmEA,SAAS,eAAe,UAAgD;AACtE,SAAO,aAAa,WAAW,aAAa;AAC9C;AASA,eAAsB,YACpB,OACA,SACA,cACA,OACA,SACA,OAA2B,CAAC,GACP;AACrB,QAAM,eAAe,KAAK,gBAAgB;AAC1C,QAAM,qBAAqB,KAAK,sBAAsB;AACtD,QAAM,IAAI,MAAM,MAAM;AAAA,IACpB,EAAE,SAAS,YAAY,aAAa,cAAc,eAAe,OAAO,QAAQ;AAAA,IAChF,EAAE,aAAa,MAAM;AAAA,EACvB;AAMA,MAAI,EAAE,cAAc,EAAE,aAAa,YAAY;AAC7C,QAAI,uBAAuB,SAAS;AAClC,aAAO,EAAE,SAAS,MAAM,QAAQ,EAAE,UAAU,yCAAyC,YAAY,EAAE,cAAc,OAAU;AAAA,IAC7H;AACA,WAAO,EAAE,SAAS,OAAO,QAAQ,EAAE,UAAU,6CAA6C,YAAY,EAAE,cAAc,OAAU;AAAA,EAClI;AAEA,MAAI,EAAE,aAAa,YAAY;AAC7B,WAAO,EAAE,SAAS,eAAe,EAAE,QAAQ,GAAG,QAAQ,EAAE,QAAQ,YAAY,EAAE,cAAc,OAAU;AAAA,EACxG;AAGA,MAAI,iBAAiB,SAAS;AAC5B,WAAO,EAAE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,QAAQ,UAAU,UAAU;AAC9B,UAAI,aAAa,UAAW,QAAO;AACnC,YAAM,QAAQ,QAAQ,IAAI,QAAQ,UAAU,QAAQ;AACpD,UAAI,OAAO,aAAa,YAAY,OAAO,UAAU,WAAY,QAAO;AACxE,UAAI,CAAC,MAAM,MAAM,QAAQ,KAAK,CAAC,aAAc,QAAO;AAEpD,aAAO,UAAU,SAAoB;AACnC,cAAM,SAAS,MAAM,qBAAqB,UAAU,IAAI;AACxD,cAAM,EAAE,SAAS,OAAO,OAAO,IAAI,MAAM,MAAM;AAAA,UAAM;AAAA,UAAQ,YAC1D,MAAuC,MAAM,QAAQ,IAAI;AAAA,QAC5D;AACA,YAAI,CAAC,QAAQ,WAAY,OAAM,MAAM,YAAY,OAAO;AACxD,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAIO,SAAS,uBACd,SACA,OACA,SACG;AACH,MAAI,MAAM,SAAS,YAAY;AAC7B,UAAM,IAAI,MAAM,2EAA2E;AAAA,EAC7F;AACA,SAAO,aAAa,SAAS,OAAO,OAAO;AAC7C;AAKO,SAAS,qBACd,SACA,OACA,SACG;AACH,MAAI,MAAM,SAAS,YAAY;AAC7B,UAAM,IAAI,MAAM,yEAAyE;AAAA,EAC3F;AACA,SAAO,aAAa,SAAS,OAAO,OAAO;AAC7C;AAGO,SAAS,yBACd,KACA,QACoB;AACpB,SAAO,IAAI,mBAAmB,KAAK,MAAM;AAC3C;AAEA,IAAO,0BAAQ;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vorim/sdk",
3
- "version": "3.19.0",
3
+ "version": "3.20.0",
4
4
  "description": "Official TypeScript SDK for Vorim AI — AI Agent Identity, Permissions & Audit",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -277,6 +277,16 @@
277
277
  "default": "./dist/integrations/shopify.cjs"
278
278
  }
279
279
  },
280
+ "./integrations/commerce-agents": {
281
+ "import": {
282
+ "types": "./dist/integrations/commerce-agents.d.ts",
283
+ "default": "./dist/integrations/commerce-agents.js"
284
+ },
285
+ "require": {
286
+ "types": "./dist/integrations/commerce-agents.d.cts",
287
+ "default": "./dist/integrations/commerce-agents.cjs"
288
+ }
289
+ },
280
290
  "./integrations/linear": {
281
291
  "import": {
282
292
  "types": "./dist/integrations/linear.d.ts",