@vorim/sdk 4.0.0 → 4.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/_commerce-core-Dyr_dHVP.d.ts +156 -0
  3. package/dist/_commerce-core-wY2jC6rC.d.cts +156 -0
  4. package/dist/index.cjs +6 -1
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.cts +5 -0
  7. package/dist/index.d.ts +5 -0
  8. package/dist/index.js +6 -1
  9. package/dist/index.js.map +1 -1
  10. package/dist/integrations/amazon.cjs +358 -0
  11. package/dist/integrations/amazon.cjs.map +1 -0
  12. package/dist/integrations/amazon.d.cts +88 -0
  13. package/dist/integrations/amazon.d.ts +88 -0
  14. package/dist/integrations/amazon.js +329 -0
  15. package/dist/integrations/amazon.js.map +1 -0
  16. package/dist/integrations/delivery.cjs +328 -0
  17. package/dist/integrations/delivery.cjs.map +1 -0
  18. package/dist/integrations/delivery.d.cts +33 -0
  19. package/dist/integrations/delivery.d.ts +33 -0
  20. package/dist/integrations/delivery.js +297 -0
  21. package/dist/integrations/delivery.js.map +1 -0
  22. package/dist/integrations/ebay.cjs +351 -0
  23. package/dist/integrations/ebay.cjs.map +1 -0
  24. package/dist/integrations/ebay.d.cts +73 -0
  25. package/dist/integrations/ebay.d.ts +73 -0
  26. package/dist/integrations/ebay.js +322 -0
  27. package/dist/integrations/ebay.js.map +1 -0
  28. package/dist/integrations/etsy.cjs +331 -0
  29. package/dist/integrations/etsy.cjs.map +1 -0
  30. package/dist/integrations/etsy.d.cts +41 -0
  31. package/dist/integrations/etsy.d.ts +41 -0
  32. package/dist/integrations/etsy.js +302 -0
  33. package/dist/integrations/etsy.js.map +1 -0
  34. package/dist/integrations/google-merchant.cjs +333 -0
  35. package/dist/integrations/google-merchant.cjs.map +1 -0
  36. package/dist/integrations/google-merchant.d.cts +43 -0
  37. package/dist/integrations/google-merchant.d.ts +43 -0
  38. package/dist/integrations/google-merchant.js +304 -0
  39. package/dist/integrations/google-merchant.js.map +1 -0
  40. package/dist/integrations/meta.cjs +376 -0
  41. package/dist/integrations/meta.cjs.map +1 -0
  42. package/dist/integrations/meta.d.cts +83 -0
  43. package/dist/integrations/meta.d.ts +83 -0
  44. package/dist/integrations/meta.js +347 -0
  45. package/dist/integrations/meta.js.map +1 -0
  46. package/dist/integrations/social-ads.cjs +329 -0
  47. package/dist/integrations/social-ads.cjs.map +1 -0
  48. package/dist/integrations/social-ads.d.cts +36 -0
  49. package/dist/integrations/social-ads.d.ts +36 -0
  50. package/dist/integrations/social-ads.js +298 -0
  51. package/dist/integrations/social-ads.js.map +1 -0
  52. package/dist/integrations/tiktok-shop.cjs +335 -0
  53. package/dist/integrations/tiktok-shop.cjs.map +1 -0
  54. package/dist/integrations/tiktok-shop.d.cts +44 -0
  55. package/dist/integrations/tiktok-shop.d.ts +44 -0
  56. package/dist/integrations/tiktok-shop.js +306 -0
  57. package/dist/integrations/tiktok-shop.js.map +1 -0
  58. package/dist/integrations/walmart.cjs +345 -0
  59. package/dist/integrations/walmart.cjs.map +1 -0
  60. package/dist/integrations/walmart.d.cts +60 -0
  61. package/dist/integrations/walmart.d.ts +60 -0
  62. package/dist/integrations/walmart.js +316 -0
  63. package/dist/integrations/walmart.js.map +1 -0
  64. package/package.json +92 -2
@@ -0,0 +1,376 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/integrations/meta.ts
21
+ var meta_exports = {};
22
+ __export(meta_exports, {
23
+ META_PROFILE: () => META_PROFILE,
24
+ VorimMeta: () => VorimMeta,
25
+ createVorimMeta: () => createVorimMeta
26
+ });
27
+ module.exports = __toCommonJS(meta_exports);
28
+
29
+ // src/integrations/_runtime-gate.ts
30
+ function isAllowVerdict(decision) {
31
+ return decision === "allow" || decision === "modify";
32
+ }
33
+ async function runtimeGate(vorim, agentId, actionTarget, scope, payload, opts = {}) {
34
+ const onEscalation = opts.onEscalation ?? "wait";
35
+ const onTransportFailure = opts.onTransportFailure ?? "deny";
36
+ const d = await vorim.beforeAction(
37
+ { agentId, actionType: "tool_call", actionTarget, requiredScope: scope, payload },
38
+ { throwOnDeny: false }
39
+ );
40
+ if (d.isFallback || d.decision === "fallback") {
41
+ if (onTransportFailure === "allow") {
42
+ return { allowed: true, reason: d.reason ?? "control plane unreachable (fail-open)", decisionId: d.decisionId || void 0 };
43
+ }
44
+ return { allowed: false, reason: d.reason ?? "control plane unreachable (failed closed)", decisionId: d.decisionId || void 0 };
45
+ }
46
+ if (d.decision !== "escalate") {
47
+ return { allowed: isAllowVerdict(d.decision), reason: d.reason, decisionId: d.decisionId || void 0 };
48
+ }
49
+ if (onEscalation === "allow") {
50
+ return { allowed: true, reason: d.reason ?? "escalated (auto-allowed)", decisionId: d.decisionId || void 0 };
51
+ }
52
+ if (onEscalation === "deny") {
53
+ return { allowed: false, reason: d.reason ?? "escalated (auto-denied \u2014 awaiting human)", decisionId: d.decisionId || void 0 };
54
+ }
55
+ if (!d.decisionId) {
56
+ return { allowed: false, reason: "escalated but no decisionId to poll", decisionId: void 0 };
57
+ }
58
+ try {
59
+ const resolved = await vorim.waitForDecisionResolution(d.decisionId, { timeoutMs: opts.escalationTimeoutMs });
60
+ return { allowed: isAllowVerdict(resolved.decision), reason: resolved.reason, decisionId: resolved.decisionId || d.decisionId };
61
+ } catch {
62
+ return { allowed: false, reason: "escalation not resolved before timeout", decisionId: d.decisionId };
63
+ }
64
+ }
65
+
66
+ // src/integrations/_commerce-core.ts
67
+ var DEFAULT_SPEC = { scope: "agent:write", risk: "write" };
68
+ function priceChangePercent(previous, next) {
69
+ if (typeof previous !== "number" || typeof next !== "number" || !(previous > 0)) return void 0;
70
+ return Math.round(Math.abs(next - previous) / previous * 1e4) / 100;
71
+ }
72
+ var VorimCommerceGuard = class {
73
+ sdk;
74
+ profile;
75
+ cfg;
76
+ constructor(sdk, profile, config) {
77
+ if (!config?.agentId) throw new Error(`[vorim] ${profile.display} integration requires an agentId.`);
78
+ if (!config?.accountId) throw new Error(`[vorim] ${profile.display} integration requires an accountId.`);
79
+ this.sdk = sdk;
80
+ this.profile = profile;
81
+ this.cfg = {
82
+ agentId: config.agentId,
83
+ accountId: config.accountId,
84
+ humanId: config.humanId,
85
+ environment: config.environment ?? "production",
86
+ limits: config.limits ?? {},
87
+ overLimit: config.overLimit ?? "deny",
88
+ approverId: config.approverId ?? config.humanId,
89
+ escalationTimeoutMs: config.escalationTimeoutMs ?? 3e5,
90
+ useRuntimeControl: config.useRuntimeControl ?? false,
91
+ onEscalation: config.onEscalation ?? "wait",
92
+ minTrustScore: config.minTrustScore ?? 0,
93
+ onError: config.onError ?? "closed"
94
+ };
95
+ }
96
+ /** The spec an operation resolves to (unknown labels are writes). */
97
+ specFor(operation) {
98
+ return this.profile.operations[operation] ?? DEFAULT_SPEC;
99
+ }
100
+ /** The first ceiling this action breaks, or null. */
101
+ breach(action) {
102
+ const spec = this.specFor(action.operation);
103
+ const l = this.cfg.limits;
104
+ for (const kind of spec.limits ?? []) {
105
+ if (kind === "order" && l.maxOrderAmount != null && (action.amount ?? 0) > l.maxOrderAmount)
106
+ return `order value ${action.amount} exceeds this agent's ceiling of ${l.maxOrderAmount}`;
107
+ if (kind === "refund" && l.maxRefundAmount != null && (action.amount ?? 0) > l.maxRefundAmount)
108
+ return `refund ${action.amount} exceeds this agent's ceiling of ${l.maxRefundAmount}`;
109
+ if (kind === "budget" && l.maxBudgetAmount != null && (action.amount ?? 0) > l.maxBudgetAmount)
110
+ return `budget ${action.amount} exceeds this agent's ceiling of ${l.maxBudgetAmount}`;
111
+ if (kind === "price" && l.maxPriceChangePercent != null) {
112
+ const pct = priceChangePercent(action.previousPrice, action.newPrice);
113
+ if (pct == null && typeof action.newPrice === "number")
114
+ return "price change needs previousPrice so the change can be checked against the ceiling";
115
+ if (pct != null && pct > l.maxPriceChangePercent)
116
+ return `price change of ${pct}% exceeds this agent's ceiling of ${l.maxPriceChangePercent}%`;
117
+ }
118
+ if (kind === "batch" && l.maxBatchSize != null && (action.itemCount ?? 1) > l.maxBatchSize)
119
+ return `batch of ${action.itemCount} exceeds this agent's ceiling of ${l.maxBatchSize}`;
120
+ }
121
+ return null;
122
+ }
123
+ payloadFor(action) {
124
+ const p = { ...action.attributes ?? {}, platform: this.profile.platform, account_id: this.cfg.accountId };
125
+ if (action.amount != null) p.amount = action.amount;
126
+ if (action.currency) p.currency = action.currency;
127
+ const pct = priceChangePercent(action.previousPrice, action.newPrice);
128
+ if (pct != null) p.price_change_pct = pct;
129
+ if (action.itemCount != null) p.item_count = action.itemCount;
130
+ if (action.marketplace) p.marketplace = action.marketplace;
131
+ if (action.resourceId) p.resource_id = action.resourceId;
132
+ return p;
133
+ }
134
+ /** Decide whether the action may run. Never calls the platform. */
135
+ async authorize(action) {
136
+ const spec = this.specFor(action.operation);
137
+ const refused = this.profile.validate?.(action) ?? null;
138
+ if (refused) return { authorized: false, reason: refused, outcome: "within" };
139
+ const breached = this.breach(action);
140
+ const over = breached ?? (spec.alwaysApprove ? "this operation always needs a named approver" : null);
141
+ try {
142
+ if (this.cfg.minTrustScore > 0 && spec.risk !== "read") {
143
+ const trust = await this.sdk.verify(this.cfg.agentId);
144
+ if ((trust?.trust_score ?? 0) < this.cfg.minTrustScore) {
145
+ return { authorized: false, reason: `trust score below ${this.cfg.minTrustScore}`, outcome: over ? "over-ceiling" : "within" };
146
+ }
147
+ }
148
+ if (over) {
149
+ if (breached && this.cfg.overLimit !== "escalate") return { authorized: false, reason: breached, outcome: "over-ceiling" };
150
+ return await this.escalate(action, spec, over);
151
+ }
152
+ if (this.cfg.useRuntimeControl) {
153
+ const g = await runtimeGate(
154
+ this.sdk,
155
+ this.cfg.agentId,
156
+ `${this.profile.platform}:${action.operation}`,
157
+ spec.scope,
158
+ this.payloadFor(action),
159
+ { onEscalation: this.cfg.onEscalation, escalationTimeoutMs: this.cfg.escalationTimeoutMs, onTransportFailure: this.cfg.onError === "open" ? "allow" : "deny" }
160
+ );
161
+ return { authorized: g.allowed, reason: g.allowed ? void 0 : g.reason, outcome: "within", decisionId: g.decisionId };
162
+ }
163
+ const perm = await this.sdk.check(this.cfg.agentId, spec.scope);
164
+ return perm.allowed ? { authorized: true, outcome: "within" } : { authorized: false, reason: perm.reason ?? `missing scope ${spec.scope}`, outcome: "within" };
165
+ } catch (e) {
166
+ return this.cfg.onError === "open" ? { authorized: true, reason: "vorim unreachable, failed open", outcome: over ? "over-ceiling" : "within" } : { authorized: false, reason: `vorim unreachable: ${e?.message ?? "error"}`, outcome: over ? "over-ceiling" : "within" };
167
+ }
168
+ }
169
+ async escalate(action, spec, why) {
170
+ const d = await this.sdk.beforeAction(
171
+ {
172
+ agentId: this.cfg.agentId,
173
+ actionType: "api_request",
174
+ actionTarget: `${this.profile.platform}:${action.operation}`,
175
+ requiredScope: spec.scope,
176
+ payload: { ...this.payloadFor(action), over_ceiling: why },
177
+ context: { integration: this.profile.platform, requires_named_approver: true, approver_hint: this.cfg.approverId }
178
+ },
179
+ { throwOnDeny: false }
180
+ );
181
+ if (d.decision === "escalate") {
182
+ try {
183
+ const r = await this.sdk.waitForDecisionResolution(d.decisionId, { timeoutMs: this.cfg.escalationTimeoutMs });
184
+ const ok = r.decision === "allow" || r.escalationResolution === "approved";
185
+ return { authorized: ok, reason: ok ? void 0 : "named approver denied", outcome: ok ? "escalated-approved" : "escalated-denied", approverId: this.cfg.approverId, decisionId: d.decisionId };
186
+ } catch {
187
+ return { authorized: false, reason: "approval not given before timeout", outcome: "escalated-denied", approverId: this.cfg.approverId, decisionId: d.decisionId };
188
+ }
189
+ }
190
+ if (d.decision === "allow" || d.decision === "modify") {
191
+ return { authorized: false, reason: `${why}; add an escalate rule for ${this.profile.platform}:${action.operation} to route it to an approver`, outcome: "over-ceiling", decisionId: d.decisionId };
192
+ }
193
+ if (d.decision === "fallback") {
194
+ return { authorized: this.cfg.onError === "open", reason: "runtime unreachable", outcome: "over-ceiling", decisionId: d.decisionId };
195
+ }
196
+ return { authorized: false, reason: d.reason ?? "denied", outcome: "escalated-denied", decisionId: d.decisionId };
197
+ }
198
+ /** Sign and ingest the audit event for one action. */
199
+ async record(action, result, a = {}) {
200
+ const spec = this.specFor(action.operation);
201
+ const pct = priceChangePercent(action.previousPrice, action.newPrice);
202
+ const metadata = {
203
+ ...action.attributes ?? {},
204
+ integration: this.profile.platform,
205
+ account_id: this.cfg.accountId,
206
+ environment: this.cfg.environment,
207
+ operation: action.operation,
208
+ risk: spec.risk,
209
+ ...this.cfg.humanId ? { acts_for_human: this.cfg.humanId } : {},
210
+ ...action.amount != null ? { amount: action.amount } : {},
211
+ ...action.currency ? { currency: action.currency } : {},
212
+ ...pct != null ? { price_change_pct: pct } : {},
213
+ ...action.itemCount != null ? { item_count: action.itemCount } : {},
214
+ ...action.marketplace ? { marketplace: action.marketplace } : {},
215
+ ...a.outcome ? { limit_outcome: a.outcome } : {},
216
+ ...a.approverId ? { approver_id: a.approverId } : {},
217
+ ...a.reason ? { reason: a.reason } : {}
218
+ };
219
+ try {
220
+ await this.sdk.emit(
221
+ {
222
+ agent_id: this.cfg.agentId,
223
+ event_type: "api_request",
224
+ action: `${this.profile.platform}:${action.operation}${action.resourceId ? " " + action.resourceId : ""}`,
225
+ resource: action.resourceId || this.cfg.accountId,
226
+ permission: spec.scope,
227
+ result,
228
+ input_hash: action.inputHash,
229
+ ...a.decisionId ? { decision_id: a.decisionId } : {},
230
+ metadata
231
+ },
232
+ { sign: true }
233
+ );
234
+ return true;
235
+ } catch {
236
+ return false;
237
+ }
238
+ }
239
+ /**
240
+ * Authorize, run the platform call if allowed, sign a receipt either way.
241
+ * When not authorized, `run` is never called. An error from `run` is
242
+ * recorded and rethrown with the receipt attached as `vorimReceipt`.
243
+ */
244
+ async guard(action, run) {
245
+ const a = await this.authorize(action);
246
+ if (!a.authorized) {
247
+ const recorded = await this.record(action, "denied", a);
248
+ return { receipt: this.receipt(action, a, "denied", recorded) };
249
+ }
250
+ try {
251
+ const value = await run();
252
+ const recorded = await this.record(action, "success", { ...a, reason: void 0 });
253
+ return { receipt: this.receipt(action, { ...a, reason: void 0 }, "success", recorded), value };
254
+ } catch (e) {
255
+ const recorded = await this.record(action, "error", { ...a, reason: e?.message });
256
+ throw Object.assign(e ?? new Error(`${this.profile.display} call failed`), {
257
+ vorimReceipt: this.receipt(action, { ...a, reason: e?.message }, "error", recorded)
258
+ });
259
+ }
260
+ }
261
+ /** Shorthand for guard({ operation, ...fields }, run). */
262
+ op(operation, fields, run) {
263
+ return this.guard({ operation, ...fields }, run);
264
+ }
265
+ receipt(action, a, result, recorded) {
266
+ const spec = this.specFor(action.operation);
267
+ return {
268
+ authorized: result !== "denied",
269
+ platform: this.profile.platform,
270
+ agentId: this.cfg.agentId,
271
+ humanId: this.cfg.humanId,
272
+ accountId: this.cfg.accountId,
273
+ environment: this.cfg.environment,
274
+ operation: action.operation,
275
+ risk: spec.risk,
276
+ scope: spec.scope,
277
+ resourceId: action.resourceId,
278
+ amount: action.amount,
279
+ currency: action.currency,
280
+ priceChangePercent: priceChangePercent(action.previousPrice, action.newPrice),
281
+ itemCount: action.itemCount,
282
+ limitOutcome: a.outcome ?? "within",
283
+ approverId: a.approverId,
284
+ decisionId: a.decisionId,
285
+ result,
286
+ reason: a.reason,
287
+ recorded
288
+ };
289
+ }
290
+ };
291
+
292
+ // src/integrations/meta.ts
293
+ function metaRules(a) {
294
+ const at = a.attributes ?? {};
295
+ if (a.operation === "whatsappSendFreeform" && at.withinServiceWindow !== true)
296
+ return "WhatsApp free-form messages are only allowed inside the 24-hour customer service window; send an approved template instead";
297
+ if (a.operation === "whatsappSendTemplate" && at.optedIn !== true)
298
+ return "WhatsApp business-initiated templates need the recipients' opt-in (set attributes.optedIn once you hold it)";
299
+ if (a.operation === "messengerSend") {
300
+ const tag = typeof at.messageTag === "string" ? at.messageTag : void 0;
301
+ if (at.withinServiceWindow !== true && !tag)
302
+ return "Messenger messages outside the 24-hour window need a message tag";
303
+ if (tag && at.promotional === true)
304
+ return "Messenger message tags cannot carry promotional content";
305
+ if (tag === "HUMAN_AGENT")
306
+ return "the HUMAN_AGENT tag is for replies written by people, not by an agent";
307
+ }
308
+ return null;
309
+ }
310
+ var META_PROFILE = {
311
+ platform: "meta",
312
+ display: "Meta",
313
+ validate: metaRules,
314
+ operations: {
315
+ read: { scope: "agent:read", risk: "read" },
316
+ adsCreateCampaign: { scope: "agent:transact", risk: "spend", limits: ["budget"] },
317
+ adsUpdateBudget: { scope: "agent:transact", risk: "spend", limits: ["budget"] },
318
+ adsSetSpendCap: { scope: "agent:transact", risk: "spend", limits: ["budget"] },
319
+ adsActivate: { scope: "agent:transact", risk: "spend" },
320
+ adsPause: { scope: "agent:write", risk: "write" },
321
+ catalogItemsBatch: { scope: "agent:write", risk: "publish", limits: ["price", "batch"] },
322
+ catalogDeleteItems: { scope: "agent:write", risk: "publish", limits: ["batch"] },
323
+ whatsappCreateTemplate: { scope: "agent:write", risk: "write" },
324
+ whatsappSendTemplate: { scope: "agent:communicate", risk: "message", limits: ["batch"] },
325
+ whatsappSendFreeform: { scope: "agent:communicate", risk: "message", limits: ["batch"] },
326
+ whatsappRequestPayment: { scope: "agent:transact", risk: "money", limits: ["order"] },
327
+ messengerSend: { scope: "agent:communicate", risk: "message", limits: ["batch"] }
328
+ }
329
+ };
330
+ var VorimMeta = class extends VorimCommerceGuard {
331
+ constructor(sdk, config) {
332
+ super(sdk, META_PROFILE, config);
333
+ }
334
+ /** Set a campaign or ad set daily/lifetime budget. Checked against maxBudgetAmount. */
335
+ adsUpdateBudget(m, run) {
336
+ return this.op("adsUpdateBudget", { resourceId: m.objectId, amount: m.amount, currency: m.currency, attributes: { budget_kind: m.kind ?? "daily" } }, run);
337
+ }
338
+ /** Turn a campaign/ad set/ad ACTIVE (starts spending). */
339
+ adsActivate(m, run) {
340
+ return this.op("adsActivate", { resourceId: m.objectId }, run);
341
+ }
342
+ /** items_batch catalog update. Pass previous/new price for a single price change. */
343
+ catalogItemsBatch(m, run) {
344
+ return this.op("catalogItemsBatch", { resourceId: m.catalogId, itemCount: m.itemCount, previousPrice: m.previousPrice, newPrice: m.newPrice, inputHash: m.inputHash }, run);
345
+ }
346
+ /** Send an approved WhatsApp template. Needs optedIn; recipients checked against maxBatchSize. */
347
+ whatsappSendTemplate(m, run) {
348
+ return this.op("whatsappSendTemplate", { resourceId: m.template, itemCount: m.recipients, attributes: { category: m.category, optedIn: m.optedIn, ...m.useCase ? { useCase: m.useCase } : {} } }, run);
349
+ }
350
+ /** Send a free-form WhatsApp reply. Only inside the 24-hour customer service window. */
351
+ whatsappSendFreeform(m, run) {
352
+ return this.op("whatsappSendFreeform", { resourceId: m.conversationId, itemCount: 1, attributes: { withinServiceWindow: m.withinServiceWindow, ...m.useCase ? { useCase: m.useCase } : {} } }, run);
353
+ }
354
+ /** Request a WhatsApp payment (order_details: UPI in India, Pix in Brazil). Checked against maxOrderAmount. */
355
+ whatsappRequestPayment(m, run) {
356
+ return this.op("whatsappRequestPayment", { resourceId: m.orderId, amount: m.amount, currency: m.currency }, run);
357
+ }
358
+ /** Send a Messenger or Instagram message. Outside the window it needs a non-promotional tag. */
359
+ messengerSend(m, run) {
360
+ return this.op("messengerSend", {
361
+ resourceId: m.recipientId,
362
+ itemCount: 1,
363
+ attributes: { withinServiceWindow: m.withinServiceWindow, promotional: m.promotional ?? false, ...m.messageTag ? { messageTag: m.messageTag } : {} }
364
+ }, run);
365
+ }
366
+ };
367
+ function createVorimMeta(sdk, config) {
368
+ return new VorimMeta(sdk, config);
369
+ }
370
+ // Annotate the CommonJS export names for ESM import in node:
371
+ 0 && (module.exports = {
372
+ META_PROFILE,
373
+ VorimMeta,
374
+ createVorimMeta
375
+ });
376
+ //# sourceMappingURL=meta.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/integrations/meta.ts","../../src/integrations/_runtime-gate.ts","../../src/integrations/_commerce-core.ts"],"sourcesContent":["// ============================================================================\n// Vorim AI — Meta (Marketing API, Catalog, WhatsApp Business, Messenger)\n//\n// Guards an AI agent that spends and sells on Meta: ad campaigns and budgets\n// (Marketing API), product catalog prices and availability (Catalog API, which\n// feeds Facebook/Instagram Shops and Advantage+ catalog ads), WhatsApp Business\n// Platform messages and, where Meta supports it, payments, and Messenger /\n// Instagram messages.\n//\n// HONEST SCOPE (checked October 2026)\n// - Checkout left Facebook and Instagram Shops in 2025: buyers now pay on the\n// merchant's site. On Meta an agent changes ads, catalog and messages; it\n// takes payment only through WhatsApp payments (India UPI, Brazil Pix).\n// - WhatsApp rules this guard enforces before any Vorim call:\n// * free-form messages only inside the 24-hour customer service window\n// (pass attributes.withinServiceWindow);\n// * business-initiated templates only to opted-in users\n// (pass attributes.optedIn);\n// Messenger rules: outside the 24-hour window a message tag is needed, tags\n// cannot carry promotions, and HUMAN_AGENT is for people, not automation.\n// - WhatsApp's Business Solution Terms bar general-purpose AI assistants where\n// the AI itself is the product (from 15 Jan 2026 for existing users, with EU\n// and Italy carve-outs). Business AI (support, bookings, sales, order\n// tracking) is allowed. Record which you are in `attributes.useCase`.\n// - Messaging limits are shared by every number in a business portfolio, so\n// run several messaging agents as one Vorim swarm and cap them together.\n// - This layer never holds Meta tokens (system user or OAuth): pass the Graph\n// API call as a closure.\n//\n// SCOPE MAPPING\n// reads and insights -> agent:read\n// catalog writes, pausing, template creation -> agent:write\n// WhatsApp / Messenger / Instagram messages -> agent:communicate\n// creating, activating or funding ads; WhatsApp payments -> agent:transact\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport { VorimCommerceGuard, type CommerceAction, type CommerceGuardConfig, type CommerceProfile } from './_commerce-core.js';\n\nfunction metaRules(a: CommerceAction): string | null {\n const at = a.attributes ?? {};\n if (a.operation === 'whatsappSendFreeform' && at.withinServiceWindow !== true)\n return 'WhatsApp free-form messages are only allowed inside the 24-hour customer service window; send an approved template instead';\n if (a.operation === 'whatsappSendTemplate' && at.optedIn !== true)\n return 'WhatsApp business-initiated templates need the recipients\\' opt-in (set attributes.optedIn once you hold it)';\n if (a.operation === 'messengerSend') {\n const tag = typeof at.messageTag === 'string' ? at.messageTag : undefined;\n if (at.withinServiceWindow !== true && !tag)\n return 'Messenger messages outside the 24-hour window need a message tag';\n if (tag && at.promotional === true)\n return 'Messenger message tags cannot carry promotional content';\n if (tag === 'HUMAN_AGENT')\n return 'the HUMAN_AGENT tag is for replies written by people, not by an agent';\n }\n return null;\n}\n\nexport const META_PROFILE: CommerceProfile = {\n platform: 'meta',\n display: 'Meta',\n validate: metaRules,\n operations: {\n read: { scope: 'agent:read', risk: 'read' },\n adsCreateCampaign: { scope: 'agent:transact', risk: 'spend', limits: ['budget'] },\n adsUpdateBudget: { scope: 'agent:transact', risk: 'spend', limits: ['budget'] },\n adsSetSpendCap: { scope: 'agent:transact', risk: 'spend', limits: ['budget'] },\n adsActivate: { scope: 'agent:transact', risk: 'spend' },\n adsPause: { scope: 'agent:write', risk: 'write' },\n catalogItemsBatch: { scope: 'agent:write', risk: 'publish', limits: ['price', 'batch'] },\n catalogDeleteItems: { scope: 'agent:write', risk: 'publish', limits: ['batch'] },\n whatsappCreateTemplate: { scope: 'agent:write', risk: 'write' },\n whatsappSendTemplate: { scope: 'agent:communicate', risk: 'message', limits: ['batch'] },\n whatsappSendFreeform: { scope: 'agent:communicate', risk: 'message', limits: ['batch'] },\n whatsappRequestPayment: { scope: 'agent:transact', risk: 'money', limits: ['order'] },\n messengerSend: { scope: 'agent:communicate', risk: 'message', limits: ['batch'] },\n },\n};\n\nexport type MetaConfig = CommerceGuardConfig;\n\nexport class VorimMeta extends VorimCommerceGuard {\n constructor(sdk: VorimSDK, config: MetaConfig) {\n super(sdk, META_PROFILE, config);\n }\n\n /** Set a campaign or ad set daily/lifetime budget. Checked against maxBudgetAmount. */\n adsUpdateBudget<T>(m: { objectId: string; amount: number; currency?: string; kind?: 'daily' | 'lifetime' }, run: () => Promise<T>) {\n return this.op('adsUpdateBudget', { resourceId: m.objectId, amount: m.amount, currency: m.currency, attributes: { budget_kind: m.kind ?? 'daily' } }, run);\n }\n\n /** Turn a campaign/ad set/ad ACTIVE (starts spending). */\n adsActivate<T>(m: { objectId: string }, run: () => Promise<T>) {\n return this.op('adsActivate', { resourceId: m.objectId }, run);\n }\n\n /** items_batch catalog update. Pass previous/new price for a single price change. */\n catalogItemsBatch<T>(m: { catalogId: string; itemCount: number; previousPrice?: number; newPrice?: number; inputHash?: string }, run: () => Promise<T>) {\n return this.op('catalogItemsBatch', { resourceId: m.catalogId, itemCount: m.itemCount, previousPrice: m.previousPrice, newPrice: m.newPrice, inputHash: m.inputHash }, run);\n }\n\n /** Send an approved WhatsApp template. Needs optedIn; recipients checked against maxBatchSize. */\n whatsappSendTemplate<T>(m: { template: string; category: 'marketing' | 'utility' | 'authentication'; recipients: number; optedIn: boolean; useCase?: string }, run: () => Promise<T>) {\n return this.op('whatsappSendTemplate', { resourceId: m.template, itemCount: m.recipients, attributes: { category: m.category, optedIn: m.optedIn, ...(m.useCase ? { useCase: m.useCase } : {}) } }, run);\n }\n\n /** Send a free-form WhatsApp reply. Only inside the 24-hour customer service window. */\n whatsappSendFreeform<T>(m: { conversationId: string; withinServiceWindow: boolean; useCase?: string }, run: () => Promise<T>) {\n return this.op('whatsappSendFreeform', { resourceId: m.conversationId, itemCount: 1, attributes: { withinServiceWindow: m.withinServiceWindow, ...(m.useCase ? { useCase: m.useCase } : {}) } }, run);\n }\n\n /** Request a WhatsApp payment (order_details: UPI in India, Pix in Brazil). Checked against maxOrderAmount. */\n whatsappRequestPayment<T>(m: { orderId: string; amount: number; currency: string }, run: () => Promise<T>) {\n return this.op('whatsappRequestPayment', { resourceId: m.orderId, amount: m.amount, currency: m.currency }, run);\n }\n\n /** Send a Messenger or Instagram message. Outside the window it needs a non-promotional tag. */\n messengerSend<T>(m: { recipientId: string; withinServiceWindow: boolean; messageTag?: string; promotional?: boolean }, run: () => Promise<T>) {\n return this.op('messengerSend', {\n resourceId: m.recipientId, itemCount: 1,\n attributes: { withinServiceWindow: m.withinServiceWindow, promotional: m.promotional ?? false, ...(m.messageTag ? { messageTag: m.messageTag } : {}) },\n }, run);\n }\n}\n\n/** Create a guard for an agent spending and selling on Meta. */\nexport function createVorimMeta(sdk: VorimSDK, config: MetaConfig): VorimMeta {\n return new VorimMeta(sdk, config);\n}\n","// ============================================================================\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 — shared core for marketplace / social-commerce integrations\n//\n// Amazon, eBay, Walmart, Etsy, TikTok Shop, Meta, Google Merchant and the rest\n// differ in API shape but ask the same question before an agent acts: is THIS\n// agent allowed to do THIS to the store, the ad account or the customer, for\n// THIS amount, right now? Each platform module supplies a profile (operation ->\n// scope, risk, which ceiling applies) and named helpers; this core does the\n// checking, the escalation to a named person and the signed record.\n//\n// What it enforces, in order, before the platform call runs:\n// 1. trust floor (optional)\n// 2. ceilings the platform's own tokens cannot express: order value, refund\n// value, ad budget, price change percent, batch size (items or message\n// recipients). Over a ceiling the action is denied, or escalated to a\n// named approver when `overLimit: 'escalate'`.\n// 3. either the agent's scope (`check`) or, with `useRuntimeControl`, the\n// full runtime gate, so the org's own rules (amount thresholds, velocity,\n// tripwires, budgets) apply too.\n// After it runs, the agent signs an audit event naming the platform, account,\n// operation and the person the agent acts for.\n//\n// This layer never holds a platform token and never calls the platform. You\n// pass the API call as a closure; it authorizes, runs it, signs the receipt.\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope } from '../types.js';\nimport { runtimeGate, type EscalationPolicy } from './_runtime-gate.js';\n\n/** What a ceiling an operation is measured against. */\nexport type CommerceLimitKind = 'order' | 'refund' | 'budget' | 'price' | 'batch';\n\n/** How dangerous an operation is. Recorded on every receipt. */\nexport type CommerceRisk = 'read' | 'write' | 'publish' | 'money' | 'spend' | 'message';\n\nexport interface CommerceOperationSpec {\n /** Least Vorim scope the operation needs. */\n scope: PermissionScope;\n risk: CommerceRisk;\n /** Ceilings this operation is checked against. */\n limits?: CommerceLimitKind[];\n /** Always needs a named person's approval, whatever the amount (e.g. eBay\n * purchases, which eBay's User Agreement requires a human to review). */\n alwaysApprove?: boolean;\n}\n\nexport interface CommerceProfile {\n /** Short platform key used in action targets and metadata, e.g. 'amazon-sp'. */\n platform: string;\n /** Human name, e.g. 'Amazon Selling Partner API'. */\n display: string;\n operations: Record<string, CommerceOperationSpec>;\n /** Platform rules beyond ceilings (e.g. WhatsApp's 24-hour window). Return a\n * reason to refuse, or null. Runs before any Vorim call. */\n validate?: (action: CommerceAction) => string | null;\n}\n\nexport interface CommerceLimits {\n /** Max value of one order or purchase, minor units (cents). */\n maxOrderAmount?: number;\n /** Max value of one refund, minor units. */\n maxRefundAmount?: number;\n /** Max daily/lifetime budget an agent may set on an ad, minor units. */\n maxBudgetAmount?: number;\n /** Max price move in one update, percent of the previous price (e.g. 20). */\n maxPriceChangePercent?: number;\n /** Max items / listings / recipients touched in one call. */\n maxBatchSize?: number;\n}\n\nexport interface CommerceGuardConfig {\n /** The acting agent's Vorim id (agid_...). */\n agentId: string;\n /** The seller / shop / ad / business account the agent operates on. */\n accountId: string;\n /** The person the agent acts for. Recorded; default escalation target. */\n humanId?: string;\n /** 'sandbox' or 'production'. Recorded on every receipt. Default 'production'. */\n environment?: 'sandbox' | 'production';\n limits?: CommerceLimits;\n /** Over a ceiling: deny (default) or escalate to a named approver. */\n overLimit?: 'deny' | 'escalate';\n /** Named approver for over-ceiling actions. Defaults to humanId. */\n approverId?: string;\n /** Max wait for an approver or an escalating rule, ms. Default 300000. */\n escalationTimeoutMs?: number;\n /** Run every action through the runtime gate so org rules apply. Needs a key\n * with runtime:decide. Default false (scope check only). */\n useRuntimeControl?: boolean;\n /** With useRuntimeControl, what an `escalate` verdict does. Default 'wait'. */\n onEscalation?: EscalationPolicy;\n /** Minimum trust score before any non-read action. Default 0 (off). */\n minTrustScore?: number;\n /** Fail closed (deny on any Vorim error, the default) or open. */\n onError?: 'closed' | 'open';\n}\n\nexport interface CommerceAction {\n /** The platform operation, e.g. 'createRefund'. Unknown labels are writes. */\n operation: string;\n /** Order, listing, SKU, campaign, conversation… the action targets. */\n resourceId?: string;\n /** Order / refund / budget value in minor units. */\n amount?: number;\n currency?: string;\n /** For price updates: old and new price, same unit. */\n previousPrice?: number;\n newPrice?: number;\n /** Items, listings or message recipients touched by this call. */\n itemCount?: number;\n /** Marketplace / region, e.g. 'ATVPDKIKX0DER' or 'EBAY_GB'. */\n marketplace?: string;\n /** Hash of the request body, so the receipt covers it without storing it. */\n inputHash?: string;\n /** Platform facts a profile's rules read (e.g. withinServiceWindow, optedIn). */\n attributes?: Record<string, string | number | boolean>;\n}\n\nexport type LimitOutcome = 'within' | 'over-ceiling' | 'escalated-approved' | 'escalated-denied';\n\nexport interface CommerceReceipt {\n authorized: boolean;\n platform: string;\n agentId: string;\n humanId?: string;\n accountId: string;\n environment: 'sandbox' | 'production';\n operation: string;\n risk: CommerceRisk;\n scope: PermissionScope;\n resourceId?: string;\n amount?: number;\n currency?: string;\n priceChangePercent?: number;\n itemCount?: number;\n limitOutcome: LimitOutcome;\n approverId?: string;\n decisionId?: string;\n result: 'success' | 'denied' | 'error';\n reason?: string;\n /** True once the signed audit event was ingested. */\n recorded: boolean;\n}\n\ninterface Authz {\n authorized: boolean;\n reason?: string;\n outcome: LimitOutcome;\n approverId?: string;\n decisionId?: string;\n}\n\nconst DEFAULT_SPEC: CommerceOperationSpec = { scope: 'agent:write', risk: 'write' };\n\n/** Percent move from previous to new price, rounded to 2 dp; undefined if unknowable. */\nexport function priceChangePercent(previous?: number, next?: number): number | undefined {\n if (typeof previous !== 'number' || typeof next !== 'number' || !(previous > 0)) return undefined;\n return Math.round((Math.abs(next - previous) / previous) * 10000) / 100;\n}\n\nexport class VorimCommerceGuard {\n protected sdk: VorimSDK;\n protected profile: CommerceProfile;\n protected cfg: Required<Pick<CommerceGuardConfig, 'agentId' | 'accountId' | 'environment' | 'overLimit' | 'escalationTimeoutMs' | 'useRuntimeControl' | 'onEscalation' | 'minTrustScore' | 'onError'>> & {\n humanId?: string; approverId?: string; limits: CommerceLimits;\n };\n\n constructor(sdk: VorimSDK, profile: CommerceProfile, config: CommerceGuardConfig) {\n if (!config?.agentId) throw new Error(`[vorim] ${profile.display} integration requires an agentId.`);\n if (!config?.accountId) throw new Error(`[vorim] ${profile.display} integration requires an accountId.`);\n this.sdk = sdk;\n this.profile = profile;\n this.cfg = {\n agentId: config.agentId,\n accountId: config.accountId,\n humanId: config.humanId,\n environment: config.environment ?? 'production',\n limits: config.limits ?? {},\n overLimit: config.overLimit ?? 'deny',\n approverId: config.approverId ?? config.humanId,\n escalationTimeoutMs: config.escalationTimeoutMs ?? 300_000,\n useRuntimeControl: config.useRuntimeControl ?? false,\n onEscalation: config.onEscalation ?? 'wait',\n minTrustScore: config.minTrustScore ?? 0,\n onError: config.onError ?? 'closed',\n };\n }\n\n /** The spec an operation resolves to (unknown labels are writes). */\n specFor(operation: string): CommerceOperationSpec {\n return this.profile.operations[operation] ?? DEFAULT_SPEC;\n }\n\n /** The first ceiling this action breaks, or null. */\n breach(action: CommerceAction): string | null {\n const spec = this.specFor(action.operation);\n const l = this.cfg.limits;\n for (const kind of spec.limits ?? []) {\n if (kind === 'order' && l.maxOrderAmount != null && (action.amount ?? 0) > l.maxOrderAmount)\n return `order value ${action.amount} exceeds this agent's ceiling of ${l.maxOrderAmount}`;\n if (kind === 'refund' && l.maxRefundAmount != null && (action.amount ?? 0) > l.maxRefundAmount)\n return `refund ${action.amount} exceeds this agent's ceiling of ${l.maxRefundAmount}`;\n if (kind === 'budget' && l.maxBudgetAmount != null && (action.amount ?? 0) > l.maxBudgetAmount)\n return `budget ${action.amount} exceeds this agent's ceiling of ${l.maxBudgetAmount}`;\n if (kind === 'price' && l.maxPriceChangePercent != null) {\n const pct = priceChangePercent(action.previousPrice, action.newPrice);\n if (pct == null && typeof action.newPrice === 'number')\n return 'price change needs previousPrice so the change can be checked against the ceiling';\n if (pct != null && pct > l.maxPriceChangePercent)\n return `price change of ${pct}% exceeds this agent's ceiling of ${l.maxPriceChangePercent}%`;\n }\n if (kind === 'batch' && l.maxBatchSize != null && (action.itemCount ?? 1) > l.maxBatchSize)\n return `batch of ${action.itemCount} exceeds this agent's ceiling of ${l.maxBatchSize}`;\n }\n return null;\n }\n\n private payloadFor(action: CommerceAction): Record<string, unknown> {\n // Platform facts first, so they can never overwrite the fields below.\n const p: Record<string, unknown> = { ...(action.attributes ?? {}), platform: this.profile.platform, account_id: this.cfg.accountId };\n if (action.amount != null) p.amount = action.amount;\n if (action.currency) p.currency = action.currency;\n const pct = priceChangePercent(action.previousPrice, action.newPrice);\n if (pct != null) p.price_change_pct = pct;\n if (action.itemCount != null) p.item_count = action.itemCount;\n if (action.marketplace) p.marketplace = action.marketplace;\n if (action.resourceId) p.resource_id = action.resourceId;\n return p;\n }\n\n /** Decide whether the action may run. Never calls the platform. */\n async authorize(action: CommerceAction): Promise<Authz> {\n const spec = this.specFor(action.operation);\n const refused = this.profile.validate?.(action) ?? null;\n if (refused) return { authorized: false, reason: refused, outcome: 'within' };\n // A breached ceiling is a hard stop unless overLimit is 'escalate'; an\n // alwaysApprove operation within its ceilings still goes to a person.\n const breached = this.breach(action);\n const over = breached ?? (spec.alwaysApprove ? 'this operation always needs a named approver' : null);\n try {\n if (this.cfg.minTrustScore > 0 && spec.risk !== 'read') {\n const trust = await this.sdk.verify(this.cfg.agentId);\n if ((trust?.trust_score ?? 0) < this.cfg.minTrustScore) {\n return { authorized: false, reason: `trust score below ${this.cfg.minTrustScore}`, outcome: over ? 'over-ceiling' : 'within' };\n }\n }\n if (over) {\n if (breached && this.cfg.overLimit !== 'escalate') return { authorized: false, reason: breached, outcome: 'over-ceiling' };\n return await this.escalate(action, spec, over);\n }\n if (this.cfg.useRuntimeControl) {\n const g = await runtimeGate(\n this.sdk, this.cfg.agentId, `${this.profile.platform}:${action.operation}`, spec.scope, this.payloadFor(action),\n { onEscalation: this.cfg.onEscalation, escalationTimeoutMs: this.cfg.escalationTimeoutMs, onTransportFailure: this.cfg.onError === 'open' ? 'allow' : 'deny' },\n );\n return { authorized: g.allowed, reason: g.allowed ? undefined : g.reason, outcome: 'within', decisionId: g.decisionId };\n }\n const perm = await this.sdk.check(this.cfg.agentId, spec.scope);\n return perm.allowed\n ? { authorized: true, outcome: 'within' }\n : { authorized: false, reason: perm.reason ?? `missing scope ${spec.scope}`, outcome: 'within' };\n } catch (e: any) {\n return this.cfg.onError === 'open'\n ? { authorized: true, reason: 'vorim unreachable, failed open', outcome: over ? 'over-ceiling' : 'within' }\n : { authorized: false, reason: `vorim unreachable: ${e?.message ?? 'error'}`, outcome: over ? 'over-ceiling' : 'within' };\n }\n }\n\n private async escalate(action: CommerceAction, spec: CommerceOperationSpec, why: string): Promise<Authz> {\n const d = await this.sdk.beforeAction(\n {\n agentId: this.cfg.agentId,\n actionType: 'api_request',\n actionTarget: `${this.profile.platform}:${action.operation}`,\n requiredScope: spec.scope,\n payload: { ...this.payloadFor(action), over_ceiling: why },\n context: { integration: this.profile.platform, requires_named_approver: true, approver_hint: this.cfg.approverId },\n },\n { throwOnDeny: false },\n );\n if (d.decision === 'escalate') {\n try {\n const r = await this.sdk.waitForDecisionResolution(d.decisionId, { timeoutMs: this.cfg.escalationTimeoutMs });\n const ok = r.decision === 'allow' || (r as any).escalationResolution === 'approved';\n return { authorized: ok, reason: ok ? undefined : 'named approver denied', outcome: ok ? 'escalated-approved' : 'escalated-denied', approverId: this.cfg.approverId, decisionId: d.decisionId };\n } catch {\n return { authorized: false, reason: 'approval not given before timeout', outcome: 'escalated-denied', approverId: this.cfg.approverId, decisionId: d.decisionId };\n }\n }\n // No escalation rule matched: an over-ceiling action still needs a person.\n // Allowing here would let a missing rule lift the ceiling, so deny.\n if (d.decision === 'allow' || d.decision === 'modify') {\n return { authorized: false, reason: `${why}; add an escalate rule for ${this.profile.platform}:${action.operation} to route it to an approver`, outcome: 'over-ceiling', decisionId: d.decisionId };\n }\n if (d.decision === 'fallback') {\n return { authorized: this.cfg.onError === 'open', reason: 'runtime unreachable', outcome: 'over-ceiling', decisionId: d.decisionId };\n }\n return { authorized: false, reason: d.reason ?? 'denied', outcome: 'escalated-denied', decisionId: d.decisionId };\n }\n\n /** Sign and ingest the audit event for one action. */\n async record(action: CommerceAction, result: 'success' | 'denied' | 'error', a: Partial<Authz> & { reason?: string } = {}): Promise<boolean> {\n const spec = this.specFor(action.operation);\n const pct = priceChangePercent(action.previousPrice, action.newPrice);\n const metadata: Record<string, unknown> = {\n ...(action.attributes ?? {}),\n integration: this.profile.platform,\n account_id: this.cfg.accountId,\n environment: this.cfg.environment,\n operation: action.operation,\n risk: spec.risk,\n ...(this.cfg.humanId ? { acts_for_human: this.cfg.humanId } : {}),\n ...(action.amount != null ? { amount: action.amount } : {}),\n ...(action.currency ? { currency: action.currency } : {}),\n ...(pct != null ? { price_change_pct: pct } : {}),\n ...(action.itemCount != null ? { item_count: action.itemCount } : {}),\n ...(action.marketplace ? { marketplace: action.marketplace } : {}),\n ...(a.outcome ? { limit_outcome: a.outcome } : {}),\n ...(a.approverId ? { approver_id: a.approverId } : {}),\n ...(a.reason ? { reason: a.reason } : {}),\n };\n try {\n await this.sdk.emit(\n {\n agent_id: this.cfg.agentId,\n event_type: 'api_request',\n action: `${this.profile.platform}:${action.operation}${action.resourceId ? ' ' + action.resourceId : ''}`,\n resource: action.resourceId || this.cfg.accountId,\n permission: spec.scope,\n result,\n input_hash: action.inputHash,\n ...(a.decisionId ? { decision_id: a.decisionId } : {}),\n metadata,\n } as any,\n { sign: true },\n );\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Authorize, run the platform call if allowed, sign a receipt either way.\n * When not authorized, `run` is never called. An error from `run` is\n * recorded and rethrown with the receipt attached as `vorimReceipt`.\n */\n async guard<T>(action: CommerceAction, run: () => Promise<T>): Promise<{ receipt: CommerceReceipt; value?: T }> {\n const a = await this.authorize(action);\n if (!a.authorized) {\n const recorded = await this.record(action, 'denied', a);\n return { receipt: this.receipt(action, a, 'denied', recorded) };\n }\n try {\n const value = await run();\n const recorded = await this.record(action, 'success', { ...a, reason: undefined });\n return { receipt: this.receipt(action, { ...a, reason: undefined }, 'success', recorded), value };\n } catch (e: any) {\n const recorded = await this.record(action, 'error', { ...a, reason: e?.message });\n throw Object.assign(e ?? new Error(`${this.profile.display} call failed`), {\n vorimReceipt: this.receipt(action, { ...a, reason: e?.message }, 'error', recorded),\n });\n }\n }\n\n /** Shorthand for guard({ operation, ...fields }, run). */\n op<T>(operation: string, fields: Omit<CommerceAction, 'operation'>, run: () => Promise<T>) {\n return this.guard({ operation, ...fields }, run);\n }\n\n protected receipt(action: CommerceAction, a: Partial<Authz>, result: 'success' | 'denied' | 'error', recorded: boolean): CommerceReceipt {\n const spec = this.specFor(action.operation);\n return {\n authorized: result !== 'denied',\n platform: this.profile.platform,\n agentId: this.cfg.agentId,\n humanId: this.cfg.humanId,\n accountId: this.cfg.accountId,\n environment: this.cfg.environment,\n operation: action.operation,\n risk: spec.risk,\n scope: spec.scope,\n resourceId: action.resourceId,\n amount: action.amount,\n currency: action.currency,\n priceChangePercent: priceChangePercent(action.previousPrice, action.newPrice),\n itemCount: action.itemCount,\n limitOutcome: a.outcome ?? 'within',\n approverId: a.approverId,\n decisionId: a.decisionId,\n result,\n reason: a.reason,\n recorded,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACmEA,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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C6rC.cjs';
2
+ import { VorimSDK } from '../index.cjs';
3
+ import '../types-DphtTyIC.cjs';
4
+ import '../_runtime-gate-DOJUKJBu.cjs';
5
+ import '@vorim/shared-types';
6
+ import '../httpSignatures.cjs';
7
+
8
+ declare const META_PROFILE: CommerceProfile;
9
+ type MetaConfig = CommerceGuardConfig;
10
+ declare class VorimMeta extends VorimCommerceGuard {
11
+ constructor(sdk: VorimSDK, config: MetaConfig);
12
+ /** Set a campaign or ad set daily/lifetime budget. Checked against maxBudgetAmount. */
13
+ adsUpdateBudget<T>(m: {
14
+ objectId: string;
15
+ amount: number;
16
+ currency?: string;
17
+ kind?: 'daily' | 'lifetime';
18
+ }, run: () => Promise<T>): Promise<{
19
+ receipt: CommerceReceipt;
20
+ value?: T | undefined;
21
+ }>;
22
+ /** Turn a campaign/ad set/ad ACTIVE (starts spending). */
23
+ adsActivate<T>(m: {
24
+ objectId: string;
25
+ }, run: () => Promise<T>): Promise<{
26
+ receipt: CommerceReceipt;
27
+ value?: T | undefined;
28
+ }>;
29
+ /** items_batch catalog update. Pass previous/new price for a single price change. */
30
+ catalogItemsBatch<T>(m: {
31
+ catalogId: string;
32
+ itemCount: number;
33
+ previousPrice?: number;
34
+ newPrice?: number;
35
+ inputHash?: string;
36
+ }, run: () => Promise<T>): Promise<{
37
+ receipt: CommerceReceipt;
38
+ value?: T | undefined;
39
+ }>;
40
+ /** Send an approved WhatsApp template. Needs optedIn; recipients checked against maxBatchSize. */
41
+ whatsappSendTemplate<T>(m: {
42
+ template: string;
43
+ category: 'marketing' | 'utility' | 'authentication';
44
+ recipients: number;
45
+ optedIn: boolean;
46
+ useCase?: string;
47
+ }, run: () => Promise<T>): Promise<{
48
+ receipt: CommerceReceipt;
49
+ value?: T | undefined;
50
+ }>;
51
+ /** Send a free-form WhatsApp reply. Only inside the 24-hour customer service window. */
52
+ whatsappSendFreeform<T>(m: {
53
+ conversationId: string;
54
+ withinServiceWindow: boolean;
55
+ useCase?: string;
56
+ }, run: () => Promise<T>): Promise<{
57
+ receipt: CommerceReceipt;
58
+ value?: T | undefined;
59
+ }>;
60
+ /** Request a WhatsApp payment (order_details: UPI in India, Pix in Brazil). Checked against maxOrderAmount. */
61
+ whatsappRequestPayment<T>(m: {
62
+ orderId: string;
63
+ amount: number;
64
+ currency: string;
65
+ }, run: () => Promise<T>): Promise<{
66
+ receipt: CommerceReceipt;
67
+ value?: T | undefined;
68
+ }>;
69
+ /** Send a Messenger or Instagram message. Outside the window it needs a non-promotional tag. */
70
+ messengerSend<T>(m: {
71
+ recipientId: string;
72
+ withinServiceWindow: boolean;
73
+ messageTag?: string;
74
+ promotional?: boolean;
75
+ }, run: () => Promise<T>): Promise<{
76
+ receipt: CommerceReceipt;
77
+ value?: T | undefined;
78
+ }>;
79
+ }
80
+ /** Create a guard for an agent spending and selling on Meta. */
81
+ declare function createVorimMeta(sdk: VorimSDK, config: MetaConfig): VorimMeta;
82
+
83
+ export { META_PROFILE, type MetaConfig, VorimMeta, createVorimMeta };
@@ -0,0 +1,83 @@
1
+ import { C as CommerceProfile, a as CommerceGuardConfig, V as VorimCommerceGuard, b as CommerceReceipt } from '../_commerce-core-Dyr_dHVP.js';
2
+ import { VorimSDK } from '../index.js';
3
+ import '../types-DphtTyIC.js';
4
+ import '../_runtime-gate-DOJUKJBu.js';
5
+ import '@vorim/shared-types';
6
+ import '../httpSignatures.js';
7
+
8
+ declare const META_PROFILE: CommerceProfile;
9
+ type MetaConfig = CommerceGuardConfig;
10
+ declare class VorimMeta extends VorimCommerceGuard {
11
+ constructor(sdk: VorimSDK, config: MetaConfig);
12
+ /** Set a campaign or ad set daily/lifetime budget. Checked against maxBudgetAmount. */
13
+ adsUpdateBudget<T>(m: {
14
+ objectId: string;
15
+ amount: number;
16
+ currency?: string;
17
+ kind?: 'daily' | 'lifetime';
18
+ }, run: () => Promise<T>): Promise<{
19
+ receipt: CommerceReceipt;
20
+ value?: T | undefined;
21
+ }>;
22
+ /** Turn a campaign/ad set/ad ACTIVE (starts spending). */
23
+ adsActivate<T>(m: {
24
+ objectId: string;
25
+ }, run: () => Promise<T>): Promise<{
26
+ receipt: CommerceReceipt;
27
+ value?: T | undefined;
28
+ }>;
29
+ /** items_batch catalog update. Pass previous/new price for a single price change. */
30
+ catalogItemsBatch<T>(m: {
31
+ catalogId: string;
32
+ itemCount: number;
33
+ previousPrice?: number;
34
+ newPrice?: number;
35
+ inputHash?: string;
36
+ }, run: () => Promise<T>): Promise<{
37
+ receipt: CommerceReceipt;
38
+ value?: T | undefined;
39
+ }>;
40
+ /** Send an approved WhatsApp template. Needs optedIn; recipients checked against maxBatchSize. */
41
+ whatsappSendTemplate<T>(m: {
42
+ template: string;
43
+ category: 'marketing' | 'utility' | 'authentication';
44
+ recipients: number;
45
+ optedIn: boolean;
46
+ useCase?: string;
47
+ }, run: () => Promise<T>): Promise<{
48
+ receipt: CommerceReceipt;
49
+ value?: T | undefined;
50
+ }>;
51
+ /** Send a free-form WhatsApp reply. Only inside the 24-hour customer service window. */
52
+ whatsappSendFreeform<T>(m: {
53
+ conversationId: string;
54
+ withinServiceWindow: boolean;
55
+ useCase?: string;
56
+ }, run: () => Promise<T>): Promise<{
57
+ receipt: CommerceReceipt;
58
+ value?: T | undefined;
59
+ }>;
60
+ /** Request a WhatsApp payment (order_details: UPI in India, Pix in Brazil). Checked against maxOrderAmount. */
61
+ whatsappRequestPayment<T>(m: {
62
+ orderId: string;
63
+ amount: number;
64
+ currency: string;
65
+ }, run: () => Promise<T>): Promise<{
66
+ receipt: CommerceReceipt;
67
+ value?: T | undefined;
68
+ }>;
69
+ /** Send a Messenger or Instagram message. Outside the window it needs a non-promotional tag. */
70
+ messengerSend<T>(m: {
71
+ recipientId: string;
72
+ withinServiceWindow: boolean;
73
+ messageTag?: string;
74
+ promotional?: boolean;
75
+ }, run: () => Promise<T>): Promise<{
76
+ receipt: CommerceReceipt;
77
+ value?: T | undefined;
78
+ }>;
79
+ }
80
+ /** Create a guard for an agent spending and selling on Meta. */
81
+ declare function createVorimMeta(sdk: VorimSDK, config: MetaConfig): VorimMeta;
82
+
83
+ export { META_PROFILE, type MetaConfig, VorimMeta, createVorimMeta };