@vorim/sdk 3.18.1 → 3.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.d.cts +2 -2
  3. package/dist/index.d.ts +2 -2
  4. package/dist/index.js +1 -1
  5. package/dist/integrations/anthropic.d.cts +1 -1
  6. package/dist/integrations/anthropic.d.ts +1 -1
  7. package/dist/integrations/ap2.d.cts +1 -1
  8. package/dist/integrations/ap2.d.ts +1 -1
  9. package/dist/integrations/aws-iam.d.cts +1 -1
  10. package/dist/integrations/aws-iam.d.ts +1 -1
  11. package/dist/integrations/bank-rails.d.cts +1 -1
  12. package/dist/integrations/bank-rails.d.ts +1 -1
  13. package/dist/integrations/circle.d.cts +1 -1
  14. package/dist/integrations/circle.d.ts +1 -1
  15. package/dist/integrations/cloudflare.d.cts +1 -1
  16. package/dist/integrations/cloudflare.d.ts +1 -1
  17. package/dist/integrations/coinbase-cdp.d.cts +1 -1
  18. package/dist/integrations/coinbase-cdp.d.ts +1 -1
  19. package/dist/integrations/crewai.d.cts +1 -1
  20. package/dist/integrations/crewai.d.ts +1 -1
  21. package/dist/integrations/entra.d.cts +1 -1
  22. package/dist/integrations/entra.d.ts +1 -1
  23. package/dist/integrations/fhir.d.cts +1 -1
  24. package/dist/integrations/fhir.d.ts +1 -1
  25. package/dist/integrations/grok.d.cts +1 -1
  26. package/dist/integrations/grok.d.ts +1 -1
  27. package/dist/integrations/guidewire.d.cts +1 -1
  28. package/dist/integrations/guidewire.d.ts +1 -1
  29. package/dist/integrations/hermes.d.cts +1 -1
  30. package/dist/integrations/hermes.d.ts +1 -1
  31. package/dist/integrations/jira.cjs +190 -0
  32. package/dist/integrations/jira.cjs.map +1 -0
  33. package/dist/integrations/jira.d.cts +162 -0
  34. package/dist/integrations/jira.d.ts +162 -0
  35. package/dist/integrations/jira.js +164 -0
  36. package/dist/integrations/jira.js.map +1 -0
  37. package/dist/integrations/langchain.d.cts +1 -1
  38. package/dist/integrations/langchain.d.ts +1 -1
  39. package/dist/integrations/langgraph.d.cts +1 -1
  40. package/dist/integrations/langgraph.d.ts +1 -1
  41. package/dist/integrations/legal.d.cts +1 -1
  42. package/dist/integrations/legal.d.ts +1 -1
  43. package/dist/integrations/life-sciences.d.cts +1 -1
  44. package/dist/integrations/life-sciences.d.ts +1 -1
  45. package/dist/integrations/linear.cjs +193 -0
  46. package/dist/integrations/linear.cjs.map +1 -0
  47. package/dist/integrations/linear.d.cts +173 -0
  48. package/dist/integrations/linear.d.ts +173 -0
  49. package/dist/integrations/linear.js +167 -0
  50. package/dist/integrations/linear.js.map +1 -0
  51. package/dist/integrations/lithic.d.cts +1 -1
  52. package/dist/integrations/lithic.d.ts +1 -1
  53. package/dist/integrations/llamaindex.d.cts +1 -1
  54. package/dist/integrations/llamaindex.d.ts +1 -1
  55. package/dist/integrations/marqeta.d.cts +1 -1
  56. package/dist/integrations/marqeta.d.ts +1 -1
  57. package/dist/integrations/modern-treasury.d.cts +1 -1
  58. package/dist/integrations/modern-treasury.d.ts +1 -1
  59. package/dist/integrations/nekuda.d.cts +1 -1
  60. package/dist/integrations/nekuda.d.ts +1 -1
  61. package/dist/integrations/okta.d.cts +1 -1
  62. package/dist/integrations/okta.d.ts +1 -1
  63. package/dist/integrations/openai.d.cts +1 -1
  64. package/dist/integrations/openai.d.ts +1 -1
  65. package/dist/integrations/openrouter.cjs +1 -1
  66. package/dist/integrations/openrouter.cjs.map +1 -1
  67. package/dist/integrations/openrouter.d.cts +5 -5
  68. package/dist/integrations/openrouter.d.ts +5 -5
  69. package/dist/integrations/openrouter.js +1 -1
  70. package/dist/integrations/openrouter.js.map +1 -1
  71. package/dist/integrations/paypal-agent.d.cts +1 -1
  72. package/dist/integrations/paypal-agent.d.ts +1 -1
  73. package/dist/integrations/perplexity.cjs +430 -0
  74. package/dist/integrations/perplexity.cjs.map +1 -0
  75. package/dist/integrations/perplexity.d.cts +65 -0
  76. package/dist/integrations/perplexity.d.ts +65 -0
  77. package/dist/integrations/perplexity.js +388 -0
  78. package/dist/integrations/perplexity.js.map +1 -0
  79. package/dist/integrations/plaid.d.cts +1 -1
  80. package/dist/integrations/plaid.d.ts +1 -1
  81. package/dist/integrations/ramp.d.cts +1 -1
  82. package/dist/integrations/ramp.d.ts +1 -1
  83. package/dist/integrations/shopify.d.cts +1 -1
  84. package/dist/integrations/shopify.d.ts +1 -1
  85. package/dist/integrations/siem.d.cts +1 -1
  86. package/dist/integrations/siem.d.ts +1 -1
  87. package/dist/integrations/skyfire.d.cts +1 -1
  88. package/dist/integrations/skyfire.d.ts +1 -1
  89. package/dist/integrations/stripe-acp.d.cts +1 -1
  90. package/dist/integrations/stripe-acp.d.ts +1 -1
  91. package/dist/integrations/stripe-issuing.d.cts +1 -1
  92. package/dist/integrations/stripe-issuing.d.ts +1 -1
  93. package/dist/integrations/truanon.d.cts +1 -1
  94. package/dist/integrations/truanon.d.ts +1 -1
  95. package/dist/integrations/ucp.d.cts +1 -1
  96. package/dist/integrations/ucp.d.ts +1 -1
  97. package/dist/integrations/vercel-ai.d.cts +1 -1
  98. package/dist/integrations/vercel-ai.d.ts +1 -1
  99. package/dist/integrations/x402.d.cts +1 -1
  100. package/dist/integrations/x402.d.ts +1 -1
  101. package/dist/{types-Lp1iHEDz.d.cts → types-BmeluKHI.d.cts} +1 -1
  102. package/dist/{types-Lp1iHEDz.d.ts → types-BmeluKHI.d.ts} +1 -1
  103. package/package.json +31 -1
@@ -0,0 +1,167 @@
1
+ // src/integrations/linear.ts
2
+ var OPERATION_SCOPE = {
3
+ read: "agent:read",
4
+ issueCreate: "agent:write",
5
+ issueUpdate: "agent:write",
6
+ issueDelete: "agent:write",
7
+ issueArchive: "agent:write",
8
+ projectUpdate: "agent:write",
9
+ issueBatchUpdate: "agent:write",
10
+ commentCreate: "agent:communicate"
11
+ };
12
+ var VorimLinear = class {
13
+ sdk;
14
+ agentId;
15
+ workspaceKey;
16
+ humanId;
17
+ minTrustScore;
18
+ onError;
19
+ constructor(sdk, config) {
20
+ if (!config?.agentId) throw new Error("[vorim] Linear integration requires an agentId.");
21
+ if (!config?.workspaceKey) throw new Error("[vorim] Linear integration requires a workspaceKey.");
22
+ this.sdk = sdk;
23
+ this.agentId = config.agentId;
24
+ this.workspaceKey = config.workspaceKey;
25
+ this.humanId = config.humanId;
26
+ this.minTrustScore = config.minTrustScore ?? 0;
27
+ this.onError = config.onError ?? "closed";
28
+ }
29
+ /** The Vorim scope a given operation requires. Unknown mutations fall back to
30
+ * agent:write (a mutation is at least a write). */
31
+ scopeFor(operation) {
32
+ return OPERATION_SCOPE[operation] ?? "agent:write";
33
+ }
34
+ /**
35
+ * Check whether the acting agent may run this workspace operation, before it
36
+ * runs. Enforces (in order): trust floor, permission scope. Returns
37
+ * { authorized, reason }.
38
+ */
39
+ async authorize(action) {
40
+ const scope = this.scopeFor(action.operation);
41
+ try {
42
+ if (this.minTrustScore > 0) {
43
+ const trust = await this.sdk.verify(this.agentId);
44
+ if ((trust?.trust_score ?? 0) < this.minTrustScore) {
45
+ return { authorized: false, reason: `trust score below ${this.minTrustScore}` };
46
+ }
47
+ }
48
+ const perm = await this.sdk.check(this.agentId, scope);
49
+ return perm.allowed ? { authorized: true } : { authorized: false, reason: perm.reason ?? `missing scope ${scope}` };
50
+ } catch (e) {
51
+ return this.onError === "open" ? { authorized: true, reason: "vorim unreachable, failed open" } : { authorized: false, reason: `vorim unreachable: ${e?.message ?? "error"}` };
52
+ }
53
+ }
54
+ /**
55
+ * Emit a source-signed audit event for a workspace operation and return
56
+ * whether it was recorded. Called after the mutation runs (or after a
57
+ * denial). The event names the agent, the workspace, and the human the agent
58
+ * acts for, so the record is attributable and independently verifiable
59
+ * offline.
60
+ */
61
+ async record(action, result, reason) {
62
+ const scope = this.scopeFor(action.operation);
63
+ try {
64
+ await this.sdk.emit({
65
+ agent_id: this.agentId,
66
+ event_type: "api_request",
67
+ action: `linear:${action.operation}${action.resourceId ? " " + action.resourceId : ""}`,
68
+ resource: action.resourceId || this.workspaceKey,
69
+ permission: scope,
70
+ result,
71
+ input_hash: action.inputHash,
72
+ metadata: {
73
+ integration: "linear",
74
+ workspace: this.workspaceKey,
75
+ acts_for_human: this.humanId,
76
+ operation: action.operation,
77
+ ...reason ? { reason } : {}
78
+ }
79
+ }, { sign: true });
80
+ return true;
81
+ } catch {
82
+ return false;
83
+ }
84
+ }
85
+ /**
86
+ * The full flow for one workspace operation: authorize, run the Linear
87
+ * GraphQL mutation if allowed, sign a receipt either way. If not authorized,
88
+ * `run` is never called (the mutation does not happen). Rethrows an error from
89
+ * `run` after recording it, with the receipt attached as `vorimReceipt`, so
90
+ * your handler still sees Linear failures.
91
+ */
92
+ async guard(action, run) {
93
+ const auth = await this.authorize(action);
94
+ if (!auth.authorized) {
95
+ const recorded = await this.record(action, "denied", auth.reason);
96
+ return { receipt: this.receipt(action, false, "denied", auth.reason, recorded) };
97
+ }
98
+ try {
99
+ const value = await run();
100
+ const recorded = await this.record(action, "success");
101
+ return { receipt: this.receipt(action, true, "success", void 0, recorded), value };
102
+ } catch (e) {
103
+ const recorded = await this.record(action, "error", e?.message);
104
+ throw Object.assign(e ?? new Error("linear operation failed"), {
105
+ vorimReceipt: this.receipt(action, true, "error", e?.message, recorded)
106
+ });
107
+ }
108
+ }
109
+ // --- Named helpers for the Linear mutations --------------------------------
110
+ // Each wraps guard() with the right operation label so the scope and receipt
111
+ // are correct without the caller having to remember the mapping. You pass the
112
+ // GraphQL call as `run`; this layer never talks to Linear itself.
113
+ /** Guard an `issueCreate`. Requires agent:write. */
114
+ issueCreate(meta, run) {
115
+ return this.guard({ operation: "issueCreate", resourceId: meta.issueId, inputHash: meta.inputHash }, run);
116
+ }
117
+ /** Guard an `issueUpdate` (edit or state transition). Requires agent:write. */
118
+ issueUpdate(meta, run) {
119
+ return this.guard({ operation: "issueUpdate", resourceId: meta.issueId, inputHash: meta.inputHash }, run);
120
+ }
121
+ /** Guard an `issueDelete`. Requires agent:write. DESTRUCTIVE — it removes an
122
+ * issue rather than editing it; consider a higher trust floor. */
123
+ issueDelete(meta, run) {
124
+ return this.guard({ operation: "issueDelete", resourceId: meta.issueId, inputHash: meta.inputHash }, run);
125
+ }
126
+ /** Guard a `commentCreate`. Requires agent:communicate — an agent posting a
127
+ * comment is communication, not just a data write. */
128
+ commentCreate(meta, run) {
129
+ return this.guard({ operation: "commentCreate", resourceId: meta.issueId, inputHash: meta.inputHash }, run);
130
+ }
131
+ /** Guard an `issueArchive`. Requires agent:write. */
132
+ issueArchive(meta, run) {
133
+ return this.guard({ operation: "issueArchive", resourceId: meta.issueId, inputHash: meta.inputHash }, run);
134
+ }
135
+ /** Guard a `projectUpdate`. Requires agent:write. */
136
+ projectUpdate(meta, run) {
137
+ return this.guard({ operation: "projectUpdate", resourceId: meta.projectId, inputHash: meta.inputHash }, run);
138
+ }
139
+ /** Guard an `issueBatchUpdate`. Requires agent:write. BULK — one call can
140
+ * rewrite many issues at once (higher blast radius); consider a higher trust
141
+ * floor or a tighter grant. */
142
+ issueBatchUpdate(meta, run) {
143
+ return this.guard({ operation: "issueBatchUpdate", resourceId: meta.resourceId, inputHash: meta.inputHash }, run);
144
+ }
145
+ receipt(action, authorized, result, reason, recorded) {
146
+ return {
147
+ authorized,
148
+ agentId: this.agentId,
149
+ humanId: this.humanId,
150
+ workspace: this.workspaceKey,
151
+ operation: action.operation,
152
+ resourceId: action.resourceId,
153
+ result,
154
+ scope: this.scopeFor(action.operation),
155
+ reason,
156
+ recorded
157
+ };
158
+ }
159
+ };
160
+ function createVorimLinear(sdk, config) {
161
+ return new VorimLinear(sdk, config);
162
+ }
163
+ export {
164
+ VorimLinear,
165
+ createVorimLinear
166
+ };
167
+ //# sourceMappingURL=linear.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/integrations/linear.ts"],"sourcesContent":["// ============================================================================\n// Vorim AI — Linear (issue-tracker mutation guard) Integration\n//\n// This guards an AI agent that WORKS a Linear workspace through the Linear\n// GraphQL API — creating and updating issues, transitioning and archiving them,\n// commenting, editing projects, and running bulk issue changes. Before each\n// mutation runs it checks the acting agent holds the right permission, then\n// signs a tamper-evident audit record of what the agent did.\n//\n// WHY A GUARD ON LINEAR\n// On Linear's GraphQL API an agent authenticates with a single API key or OAuth\n// token and coarse scopes: every agent on that token looks identical, there is\n// no way to cap a sub-agent below \"write\", and nothing proves agent X (not\n// agent Y) ran a given issueDelete or issueBatchUpdate. That is the gap this\n// fills. It sits BESIDE Linear's own auth rather than replacing it: Linear still\n// authenticates the token; Vorim proves which agent, acting for which human,\n// ran which mutation — and signs a record you can verify offline.\n//\n// SCOPE MAPPING (uses Vorim's real scopes)\n// read workspace data -> agent:read\n// mutate the workspace -> agent:write (issueCreate, issueUpdate,\n// issueDelete, issueArchive,\n// projectUpdate, issueBatchUpdate)\n// post a comment -> agent:communicate (an agent commenting is\n// communication, not just\n// a data write)\n//\n// Two operations carry more blast radius and are called out below:\n// - issueDelete destructive: it removes an issue, not just edits it.\n// - issueBatchUpdate bulk: one call can rewrite many issues at once.\n// Both still map to agent:write here; gate them with a higher trust floor or a\n// tighter permission grant if you want them held to a stricter bar.\n//\n// This layer never holds a Linear token and never calls Linear itself. You pass\n// it the mutation to run; it authorizes, runs it, and signs the receipt.\n//\n// Usage:\n// import createVorim from '@vorim/sdk';\n// import { createVorimLinear } from '@vorim/sdk/integrations/linear';\n//\n// const vorim = createVorim({ apiKey: 'agid_sk_...' });\n// const linear = createVorimLinear(vorim, {\n// agentId: 'agid_abc123',\n// workspaceKey: 'acme', // the workspace URL key / slug\n// humanId: 'user_42', // the person the agent acts for\n// minTrustScore: 60, // optional trust floor\n// });\n//\n// // Wrap the Linear GraphQL call you were going to make anyway:\n// const { receipt, value } = await linear.issueUpdate(\n// { issueId: 'ISS-123', inputHash },\n// () => linearClient.updateIssue('ISS-123', { stateId }),\n// );\n// if (!receipt.authorized) console.warn(receipt.reason);\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope } from '../types.js';\n\n/** The Linear GraphQL mutations this guard knows how to classify. Any other\n * label is accepted too; it just defaults to the 'write' risk tier. */\nexport type LinearOperation =\n | 'issueCreate'\n | 'issueUpdate'\n | 'issueDelete'\n | 'commentCreate'\n | 'issueArchive'\n | 'projectUpdate'\n | 'issueBatchUpdate'\n | 'read';\n\n/** Map each Linear mutation to the least Vorim scope that should be required to\n * run it. Reads need read; workspace mutations need write; an agent posting a\n * comment needs communicate, the scope Vorim requires for any agent-authored\n * message. issueDelete (destructive) and issueBatchUpdate (bulk) still map to\n * write here — hold them to a stricter bar via minTrustScore or the grant. */\nconst OPERATION_SCOPE: Record<string, PermissionScope> = {\n read: 'agent:read',\n issueCreate: 'agent:write',\n issueUpdate: 'agent:write',\n issueDelete: 'agent:write',\n issueArchive: 'agent:write',\n projectUpdate: 'agent:write',\n issueBatchUpdate: 'agent:write',\n commentCreate: 'agent:communicate',\n};\n\nexport interface LinearGuardConfig {\n /** The acting agent's Vorim id (agid_...). */\n agentId: string;\n /** The workspace this agent operates on, e.g. 'acme' (the URL key / slug).\n * Recorded in every receipt so an action is attributable to a specific\n * workspace. */\n workspaceKey: string;\n /** The human/principal the agent acts for. Recorded in every receipt so a\n * workspace action is attributable to a person, not just a machine. */\n humanId?: string;\n /** Minimum trust score the acting agent must hold before any mutation runs.\n * Default 0 (off). */\n minTrustScore?: number;\n /** Fail closed (deny on any Vorim error) or fail open. Default 'closed'. */\n onError?: 'closed' | 'open';\n}\n\nexport interface LinearAction {\n /** The Linear GraphQL mutation being run, e.g. 'issueUpdate'. Drives the\n * scope requirement. Unknown labels default to the 'write' tier. */\n operation: LinearOperation | string;\n /** The Linear resource the action targets, e.g. an issue or project id. */\n resourceId?: string;\n /** Optional hash of the mutation variables so the receipt covers the exact\n * input without the guard storing it. */\n inputHash?: string;\n}\n\n/** An offline-verifiable receipt for one Linear workspace operation. */\nexport interface LinearReceipt {\n authorized: boolean;\n agentId: string;\n humanId?: string;\n workspace: string;\n operation: string;\n resourceId?: string;\n result: 'success' | 'denied' | 'error';\n scope: PermissionScope;\n /** Reason a check failed, when authorized is false. */\n reason?: string;\n /** True once the audit event was signed and ingested. */\n recorded: boolean;\n}\n\nexport class VorimLinear {\n private sdk: VorimSDK;\n private agentId: string;\n private workspaceKey: string;\n private humanId?: string;\n private minTrustScore: number;\n private onError: 'closed' | 'open';\n\n constructor(sdk: VorimSDK, config: LinearGuardConfig) {\n if (!config?.agentId) throw new Error('[vorim] Linear integration requires an agentId.');\n if (!config?.workspaceKey) throw new Error('[vorim] Linear integration requires a workspaceKey.');\n this.sdk = sdk;\n this.agentId = config.agentId;\n this.workspaceKey = config.workspaceKey;\n this.humanId = config.humanId;\n this.minTrustScore = config.minTrustScore ?? 0;\n this.onError = config.onError ?? 'closed';\n }\n\n /** The Vorim scope a given operation requires. Unknown mutations fall back to\n * agent:write (a mutation is at least a write). */\n private scopeFor(operation: string): PermissionScope {\n return OPERATION_SCOPE[operation] ?? 'agent:write';\n }\n\n /**\n * Check whether the acting agent may run this workspace operation, before it\n * runs. Enforces (in order): trust floor, permission scope. Returns\n * { authorized, reason }.\n */\n async authorize(action: LinearAction): Promise<{ authorized: boolean; reason?: string }> {\n const scope = this.scopeFor(action.operation);\n\n try {\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 for a workspace operation and return\n * whether it was recorded. Called after the mutation runs (or after a\n * denial). The event names the agent, the workspace, and the human the agent\n * acts for, so the record is attributable and independently verifiable\n * offline.\n */\n async record(action: LinearAction, result: 'success' | 'denied' | 'error', reason?: string): Promise<boolean> {\n const scope = this.scopeFor(action.operation);\n try {\n await this.sdk.emit({\n agent_id: this.agentId,\n event_type: 'api_request',\n action: `linear:${action.operation}${action.resourceId ? ' ' + action.resourceId : ''}`,\n resource: action.resourceId || this.workspaceKey,\n permission: scope,\n result,\n input_hash: action.inputHash,\n metadata: {\n integration: 'linear',\n workspace: this.workspaceKey,\n acts_for_human: this.humanId,\n operation: action.operation,\n ...(reason ? { reason } : {}),\n },\n }, { sign: true }); // source-signed: the agent's key signs the record\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * The full flow for one workspace operation: authorize, run the Linear\n * GraphQL mutation if allowed, sign a receipt either way. If not authorized,\n * `run` is never called (the mutation does not happen). Rethrows an error from\n * `run` after recording it, with the receipt attached as `vorimReceipt`, so\n * your handler still sees Linear failures.\n */\n async guard<T>(action: LinearAction, run: () => Promise<T>): Promise<{ receipt: LinearReceipt; value?: T }> {\n const auth = await this.authorize(action);\n if (!auth.authorized) {\n const recorded = await this.record(action, 'denied', auth.reason);\n return { receipt: this.receipt(action, false, 'denied', auth.reason, recorded) };\n }\n try {\n const value = await run();\n const recorded = await this.record(action, 'success');\n return { receipt: this.receipt(action, true, 'success', undefined, recorded), value };\n } catch (e: any) {\n const recorded = await this.record(action, 'error', e?.message);\n throw Object.assign(e ?? new Error('linear operation failed'), {\n vorimReceipt: this.receipt(action, true, 'error', e?.message, recorded),\n });\n }\n }\n\n // --- Named helpers for the Linear mutations --------------------------------\n // Each wraps guard() with the right operation label so the scope and receipt\n // are correct without the caller having to remember the mapping. You pass the\n // GraphQL call as `run`; this layer never talks to Linear itself.\n\n /** Guard an `issueCreate`. Requires agent:write. */\n issueCreate<T>(meta: { issueId?: string; inputHash?: string }, run: () => Promise<T>) {\n return this.guard({ operation: 'issueCreate', resourceId: meta.issueId, inputHash: meta.inputHash }, run);\n }\n\n /** Guard an `issueUpdate` (edit or state transition). Requires agent:write. */\n issueUpdate<T>(meta: { issueId?: string; inputHash?: string }, run: () => Promise<T>) {\n return this.guard({ operation: 'issueUpdate', resourceId: meta.issueId, inputHash: meta.inputHash }, run);\n }\n\n /** Guard an `issueDelete`. Requires agent:write. DESTRUCTIVE — it removes an\n * issue rather than editing it; consider a higher trust floor. */\n issueDelete<T>(meta: { issueId?: string; inputHash?: string }, run: () => Promise<T>) {\n return this.guard({ operation: 'issueDelete', resourceId: meta.issueId, inputHash: meta.inputHash }, run);\n }\n\n /** Guard a `commentCreate`. Requires agent:communicate — an agent posting a\n * comment is communication, not just a data write. */\n commentCreate<T>(meta: { issueId?: string; inputHash?: string }, run: () => Promise<T>) {\n return this.guard({ operation: 'commentCreate', resourceId: meta.issueId, inputHash: meta.inputHash }, run);\n }\n\n /** Guard an `issueArchive`. Requires agent:write. */\n issueArchive<T>(meta: { issueId?: string; inputHash?: string }, run: () => Promise<T>) {\n return this.guard({ operation: 'issueArchive', resourceId: meta.issueId, inputHash: meta.inputHash }, run);\n }\n\n /** Guard a `projectUpdate`. Requires agent:write. */\n projectUpdate<T>(meta: { projectId?: string; inputHash?: string }, run: () => Promise<T>) {\n return this.guard({ operation: 'projectUpdate', resourceId: meta.projectId, inputHash: meta.inputHash }, run);\n }\n\n /** Guard an `issueBatchUpdate`. Requires agent:write. BULK — one call can\n * rewrite many issues at once (higher blast radius); consider a higher trust\n * floor or a tighter grant. */\n issueBatchUpdate<T>(meta: { resourceId?: string; inputHash?: string }, run: () => Promise<T>) {\n return this.guard({ operation: 'issueBatchUpdate', resourceId: meta.resourceId, inputHash: meta.inputHash }, run);\n }\n\n private receipt(\n action: LinearAction,\n authorized: boolean,\n result: 'success' | 'denied' | 'error',\n reason: string | undefined,\n recorded: boolean,\n ): LinearReceipt {\n return {\n authorized,\n agentId: this.agentId,\n humanId: this.humanId,\n workspace: this.workspaceKey,\n operation: action.operation,\n resourceId: action.resourceId,\n result,\n scope: this.scopeFor(action.operation),\n reason,\n recorded,\n };\n }\n}\n\n/**\n * Create a VorimLinear guard around a Vorim SDK instance.\n *\n * @example\n * ```typescript\n * import createVorim from '@vorim/sdk';\n * import { createVorimLinear } from '@vorim/sdk/integrations/linear';\n *\n * const vorim = createVorim({ apiKey: 'agid_sk_...' });\n * const linear = createVorimLinear(vorim, {\n * agentId: 'agid_abc123',\n * workspaceKey: 'acme',\n * humanId: 'user_42',\n * minTrustScore: 60,\n * });\n *\n * const { receipt, value } = await linear.issueUpdate(\n * { issueId: 'ISS-123', inputHash },\n * () => linearClient.updateIssue('ISS-123', { stateId }),\n * );\n * ```\n */\nexport function createVorimLinear(sdk: VorimSDK, config: LinearGuardConfig): VorimLinear {\n return new VorimLinear(sdk, config);\n}\n"],"mappings":";AA4EA,IAAM,kBAAmD;AAAA,EACvD,MAAM;AAAA,EACN,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA,EACb,cAAc;AAAA,EACd,eAAe;AAAA,EACf,kBAAkB;AAAA,EAClB,eAAe;AACjB;AA8CO,IAAM,cAAN,MAAkB;AAAA,EACf;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAER,YAAY,KAAe,QAA2B;AACpD,QAAI,CAAC,QAAQ,QAAS,OAAM,IAAI,MAAM,iDAAiD;AACvF,QAAI,CAAC,QAAQ,aAAc,OAAM,IAAI,MAAM,qDAAqD;AAChG,SAAK,MAAM;AACX,SAAK,UAAU,OAAO;AACtB,SAAK,eAAe,OAAO;AAC3B,SAAK,UAAU,OAAO;AACtB,SAAK,gBAAgB,OAAO,iBAAiB;AAC7C,SAAK,UAAU,OAAO,WAAW;AAAA,EACnC;AAAA;AAAA;AAAA,EAIQ,SAAS,WAAoC;AACnD,WAAO,gBAAgB,SAAS,KAAK;AAAA,EACvC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,UAAU,QAAyE;AACvF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;AAAA;AAAA,EAIA,cAAiB,MAAgD,KAAuB;AACtF,WAAO,KAAK,MAAM,EAAE,WAAW,iBAAiB,YAAY,KAAK,SAAS,WAAW,KAAK,UAAU,GAAG,GAAG;AAAA,EAC5G;AAAA;AAAA,EAGA,aAAgB,MAAgD,KAAuB;AACrF,WAAO,KAAK,MAAM,EAAE,WAAW,gBAAgB,YAAY,KAAK,SAAS,WAAW,KAAK,UAAU,GAAG,GAAG;AAAA,EAC3G;AAAA;AAAA,EAGA,cAAiB,MAAkD,KAAuB;AACxF,WAAO,KAAK,MAAM,EAAE,WAAW,iBAAiB,YAAY,KAAK,WAAW,WAAW,KAAK,UAAU,GAAG,GAAG;AAAA,EAC9G;AAAA;AAAA;AAAA;AAAA,EAKA,iBAAoB,MAAmD,KAAuB;AAC5F,WAAO,KAAK,MAAM,EAAE,WAAW,oBAAoB,YAAY,KAAK,YAAY,WAAW,KAAK,UAAU,GAAG,GAAG;AAAA,EAClH;AAAA,EAEQ,QACN,QACA,YACA,QACA,QACA,UACe;AACf,WAAO;AAAA,MACL;AAAA,MACA,SAAS,KAAK;AAAA,MACd,SAAS,KAAK;AAAA,MACd,WAAW,KAAK;AAAA,MAChB,WAAW,OAAO;AAAA,MAClB,YAAY,OAAO;AAAA,MACnB;AAAA,MACA,OAAO,KAAK,SAAS,OAAO,SAAS;AAAA,MACrC;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AAwBO,SAAS,kBAAkB,KAAe,QAAwC;AACvF,SAAO,IAAI,YAAY,KAAK,MAAM;AACpC;","names":[]}
@@ -1,5 +1,5 @@
1
1
  import { VorimSDK } from '../index.cjs';
2
- import { P as PermissionScope } from '../types-Lp1iHEDz.cjs';
2
+ import { P as PermissionScope } from '../types-BmeluKHI.cjs';
3
3
 
4
4
  /** Lithic card types. SINGLE_USE and MERCHANT_LOCKED are the agent-friendly
5
5
  * ones (one-shot / merchant-pinned delegated spend). */
@@ -1,5 +1,5 @@
1
1
  import { VorimSDK } from '../index.js';
2
- import { P as PermissionScope } from '../types-Lp1iHEDz.js';
2
+ import { P as PermissionScope } from '../types-BmeluKHI.js';
3
3
 
4
4
  /** Lithic card types. SINGLE_USE and MERCHANT_LOCKED are the agent-friendly
5
5
  * ones (one-shot / merchant-pinned delegated spend). */
@@ -1,4 +1,4 @@
1
- import { P as PermissionScope, A as AgentRegistrationResult } from '../types-Lp1iHEDz.cjs';
1
+ import { P as PermissionScope, A as AgentRegistrationResult } from '../types-BmeluKHI.cjs';
2
2
  import { VorimSDK, ReplayInputs } from '../index.cjs';
3
3
  import { E as EscalationPolicy, T as TransportFailurePolicy } from '../_runtime-gate-DOJUKJBu.cjs';
4
4
 
@@ -1,4 +1,4 @@
1
- import { P as PermissionScope, A as AgentRegistrationResult } from '../types-Lp1iHEDz.js';
1
+ import { P as PermissionScope, A as AgentRegistrationResult } from '../types-BmeluKHI.js';
2
2
  import { VorimSDK, ReplayInputs } from '../index.js';
3
3
  import { E as EscalationPolicy, T as TransportFailurePolicy } from '../_runtime-gate-DOJUKJBu.js';
4
4
 
@@ -1,5 +1,5 @@
1
1
  import { VorimSDK } from '../index.cjs';
2
- import { P as PermissionScope } from '../types-Lp1iHEDz.cjs';
2
+ import { P as PermissionScope } from '../types-BmeluKHI.cjs';
3
3
 
4
4
  type MarqetaOperation = 'createCard' | 'velocityControl' | 'jitFunding' | 'suspendCard';
5
5
  interface MarqetaConfig {
@@ -1,5 +1,5 @@
1
1
  import { VorimSDK } from '../index.js';
2
- import { P as PermissionScope } from '../types-Lp1iHEDz.js';
2
+ import { P as PermissionScope } from '../types-BmeluKHI.js';
3
3
 
4
4
  type MarqetaOperation = 'createCard' | 'velocityControl' | 'jitFunding' | 'suspendCard';
5
5
  interface MarqetaConfig {
@@ -1,5 +1,5 @@
1
1
  import { VorimSDK } from '../index.cjs';
2
- import '../types-Lp1iHEDz.cjs';
2
+ import '../types-BmeluKHI.cjs';
3
3
 
4
4
  type MTEnvironment = 'sandbox' | 'production';
5
5
  type MTPaymentType = 'ach' | 'wire' | 'rtp' | 'book' | 'check' | 'card' | 'stablecoin';
@@ -1,5 +1,5 @@
1
1
  import { VorimSDK } from '../index.js';
2
- import '../types-Lp1iHEDz.js';
2
+ import '../types-BmeluKHI.js';
3
3
 
4
4
  type MTEnvironment = 'sandbox' | 'production';
5
5
  type MTPaymentType = 'ach' | 'wire' | 'rtp' | 'book' | 'check' | 'card' | 'stablecoin';
@@ -1,5 +1,5 @@
1
1
  import { VorimSDK } from '../index.cjs';
2
- import '../types-Lp1iHEDz.cjs';
2
+ import '../types-BmeluKHI.cjs';
3
3
 
4
4
  interface NekudaConfig {
5
5
  apiKey: string;
@@ -1,5 +1,5 @@
1
1
  import { VorimSDK } from '../index.js';
2
- import '../types-Lp1iHEDz.js';
2
+ import '../types-BmeluKHI.js';
3
3
 
4
4
  interface NekudaConfig {
5
5
  apiKey: string;
@@ -1,5 +1,5 @@
1
1
  import { VorimSDK } from '../index.cjs';
2
- import { P as PermissionScope } from '../types-Lp1iHEDz.cjs';
2
+ import { P as PermissionScope } from '../types-BmeluKHI.cjs';
3
3
 
4
4
  /** The Okta Management API operations this guard classifies. */
5
5
  type OktaOperation = 'createUser' | 'deactivateUser' | 'assignAppToUser' | 'addUserToGroup' | 'grantRole' | 'createApiToken' | 'read';
@@ -1,5 +1,5 @@
1
1
  import { VorimSDK } from '../index.js';
2
- import { P as PermissionScope } from '../types-Lp1iHEDz.js';
2
+ import { P as PermissionScope } from '../types-BmeluKHI.js';
3
3
 
4
4
  /** The Okta Management API operations this guard classifies. */
5
5
  type OktaOperation = 'createUser' | 'deactivateUser' | 'assignAppToUser' | 'addUserToGroup' | 'grantRole' | 'createApiToken' | 'read';
@@ -1,4 +1,4 @@
1
- import { P as PermissionScope, A as AgentRegistrationResult } from '../types-Lp1iHEDz.cjs';
1
+ import { P as PermissionScope, A as AgentRegistrationResult } from '../types-BmeluKHI.cjs';
2
2
  import { VorimSDK, ReplayInputs } from '../index.cjs';
3
3
  import { E as EscalationPolicy, T as TransportFailurePolicy } from '../_runtime-gate-DOJUKJBu.cjs';
4
4
 
@@ -1,4 +1,4 @@
1
- import { P as PermissionScope, A as AgentRegistrationResult } from '../types-Lp1iHEDz.js';
1
+ import { P as PermissionScope, A as AgentRegistrationResult } from '../types-BmeluKHI.js';
2
2
  import { VorimSDK, ReplayInputs } from '../index.js';
3
3
  import { E as EscalationPolicy, T as TransportFailurePolicy } from '../_runtime-gate-DOJUKJBu.js';
4
4
 
@@ -388,7 +388,7 @@ function truncate(str, max) {
388
388
 
389
389
  // src/integrations/openrouter.ts
390
390
  var OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
391
- var DEFAULT_OPENROUTER_MODEL = "anthropic/claude-sonnet-4-6";
391
+ var DEFAULT_OPENROUTER_MODEL = "anthropic/claude-fable-5";
392
392
  async function runOpenRouterAgentLoop(config) {
393
393
  const {
394
394
  openrouter,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/integrations/openrouter.ts","../../src/integrations/_runtime-gate.ts","../../src/replay.ts","../../src/integrations/openai.ts"],"sourcesContent":["// ============================================================================\n// VORIM SDK — OpenRouter Integration\n//\n// OpenRouter (https://openrouter.ai) is a unified gateway to 500+ models from\n// 60+ providers (OpenAI, Anthropic, Google, Meta, xAI, ...) behind ONE\n// OpenAI-compatible endpoint. Point the OpenAI client at\n// `https://openrouter.ai/api/v1`, pick a model id like\n// `anthropic/claude-sonnet-4-6` or `openai/gpt-latest`, and the request/response\n// shape (including `tools` / `tool_calls`) matches OpenAI's Chat Completions.\n//\n// So Vorim gates and signs OpenRouter's *custom* function tools with exactly the\n// same registry it uses for OpenAI and Grok — this module is a thin\n// OpenRouter-flavoured wrapper over that registry plus an agent loop, with one\n// OpenRouter-specific extra: a `models` FALLBACK ARRAY so the loop can ask\n// OpenRouter to try several models in order on error.\n//\n// The value: the model underneath can change (routing, fallbacks, cost), and\n// Vorim stays the ONE identity + permission + signed-audit layer over every\n// tool call, whichever model OpenRouter picks.\n//\n// Peer dependency: openai >=4.0.0 (the OpenAI Node SDK, pointed at OpenRouter).\n//\n// Usage:\n// import OpenAI from 'openai';\n// import createVorim from '@vorim/sdk';\n// import {\n// VorimToolRegistry, runOpenRouterAgentLoop, OPENROUTER_BASE_URL,\n// } from '@vorim/sdk/integrations/openrouter';\n//\n// const vorim = createVorim({ apiKey: 'agid_sk_...' });\n// const openrouter = new OpenAI({\n// apiKey: process.env.OPENROUTER_API_KEY,\n// baseURL: OPENROUTER_BASE_URL,\n// });\n//\n// const registry = new VorimToolRegistry({ vorim, agentId });\n// registry.add({ name: 'search', description: '...', parameters: {...},\n// permission: 'agent:execute', execute: async (args) => {...} });\n//\n// const answer = await runOpenRouterAgentLoop({\n// vorim, agentId, openrouter, registry,\n// userMessage: 'Find our onboarding docs',\n// model: 'anthropic/claude-sonnet-4-6',\n// // Optional fallback chain OpenRouter walks on error:\n// models: ['anthropic/claude-sonnet-4-6', 'openai/gpt-latest'],\n// });\n//\n// IMPORTANT — what Vorim can and cannot attest here:\n// Vorim gates + signs the CUSTOM function tools you define and execute in the\n// registry. Any model's BUILT-IN / provider-side tools that run inside the\n// upstream provider (not through your executor) never pass through this gate\n// and are not Vorim-attestable. If you need every action signed, keep the work\n// in custom tools you execute.\n//\n// MODEL IDS ARE CONFIG, NOT CONSTANTS. OpenRouter's catalog changes constantly.\n// The default below is a sensible starting point; confirm against\n// `GET https://openrouter.ai/api/v1/models` at runtime and let callers override.\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\n\n// The gate-and-sign core is model-agnostic: OpenRouter uses OpenAI's tool shape,\n// so the same registry does the work. Re-exported here so an OpenRouter user\n// imports everything from one module without also reaching into the OpenAI one.\nexport {\n VorimToolRegistry,\n runAgentLoop,\n createVorimOpenAIAgent as createVorimOpenRouterAgent,\n} from './openai.js';\nexport type {\n VorimToolDefinition,\n VorimOpenAIConfig as VorimOpenRouterConfig,\n VorimAgentLoopConfig,\n} from './openai.js';\n\nimport { VorimToolRegistry } from './openai.js';\n\n/** OpenRouter API base URL (OpenAI-SDK compatible). */\nexport const OPENROUTER_BASE_URL = 'https://openrouter.ai/api/v1';\n\n/**\n * Sensible, overridable default model. Treat as config: confirm against the live\n * `/api/v1/models` list and let callers override. OpenRouter model ids are\n * `provider/model` (e.g. `anthropic/claude-sonnet-4-6`, `openai/gpt-latest`).\n */\nexport const DEFAULT_OPENROUTER_MODEL = 'anthropic/claude-sonnet-4-6';\n\n/**\n * Minimal shape of the OpenAI Node client, pointed at OpenRouter. We only touch\n * `chat.completions.create`. Declared here so `openai` stays a peer dependency\n * and isn't bundled.\n */\ninterface OpenRouterChatClient {\n chat: {\n completions: {\n create: (args: Record<string, unknown>) => Promise<any>;\n };\n };\n}\n\nexport interface RunOpenRouterAgentLoopConfig {\n vorim: VorimSDK;\n agentId: string;\n /** An OpenAI-compatible client constructed with `baseURL: OPENROUTER_BASE_URL`. */\n openrouter: OpenRouterChatClient;\n /** The tool registry (custom, Vorim-gated tools). */\n registry: VorimToolRegistry;\n /** The user's message to the agent. */\n userMessage: string;\n /** OpenRouter model id. @default DEFAULT_OPENROUTER_MODEL — override freely. */\n model?: string;\n /**\n * Optional OpenRouter model FALLBACK ARRAY. When provided, it is sent as the\n * `models` field so OpenRouter walks the list in order on error. `model` is\n * still sent as the primary; keep it as the first entry for clarity.\n * @see https://openrouter.ai/docs/features/model-routing\n */\n models?: string[];\n /** Optional system prompt. */\n systemPrompt?: string;\n /** Max agent-loop turns before giving up. @default 10 */\n maxIterations?: number;\n}\n\n/**\n * Run an OpenRouter tool-calling agent loop over Vorim-gated custom tools.\n *\n * Identical control flow to the OpenAI/Grok loop (OpenRouter mirrors the Chat\n * Completions `tools` / `tool_calls` shape); the differences are the client is\n * pointed at OpenRouter, the default model is an OpenRouter id, and an optional\n * `models` fallback array is forwarded so OpenRouter can route across providers.\n * Every custom tool call is permission-checked and signed by the registry before\n * it executes — whichever model OpenRouter ends up using.\n *\n * @example\n * ```ts\n * const answer = await runOpenRouterAgentLoop({\n * vorim, agentId, openrouter, registry,\n * userMessage: 'Reconcile the July invoices',\n * model: 'anthropic/claude-sonnet-4-6',\n * models: ['anthropic/claude-sonnet-4-6', 'openai/gpt-latest'],\n * });\n * ```\n */\nexport async function runOpenRouterAgentLoop(config: RunOpenRouterAgentLoopConfig): Promise<string> {\n const {\n openrouter,\n model = DEFAULT_OPENROUTER_MODEL,\n models,\n systemPrompt,\n maxIterations = 10,\n registry,\n userMessage,\n } = config;\n\n const messages: any[] = [];\n if (systemPrompt) messages.push({ role: 'system', content: systemPrompt });\n messages.push({ role: 'user', content: userMessage });\n\n const tools = registry.toOpenAITools();\n\n for (let i = 0; i < maxIterations; i++) {\n const response = await openrouter.chat.completions.create({\n model,\n messages,\n // OpenRouter-specific: forward the fallback chain if the caller gave one.\n ...(models && models.length > 0 ? { models } : {}),\n ...(tools.length > 0 ? { tools } : {}),\n });\n\n const choice = response.choices[0];\n messages.push(choice.message);\n\n if (choice.finish_reason === 'stop' || !choice.message.tool_calls?.length) {\n return choice.message.content ?? '';\n }\n\n // Each custom tool call is gated + signed by the registry before running.\n const toolMessages = await registry.executeToolCalls(choice.message.tool_calls);\n messages.push(...toolMessages);\n }\n\n return messages[messages.length - 1]?.content ?? '';\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 * Replayable agent decision evidence helpers.\n *\n * Canonical-form hashing for the VAIP -02 schema fields that the SDK\n * attaches to audit events. The hashes recorded in audit_events.tool_catalogue_hash\n * and audit_events.system_prompt_hash use these functions, so the bytes\n * an auditor or counterparty reconstructs must match what the SDK produced.\n *\n * These helpers are intentionally separate from the signing path. The\n * v0 canonical signature form (event_type|action|resource|input_hash|\n * output_hash|result) does NOT cover model_version, tool_catalogue_hash,\n * or system_prompt_hash. They will enter the canonical bytes in v1\n * (RFC 8785 JCS) in a follow-up release.\n *\n * Stable across SDK versions: the canonical-form version is documented\n * in CANONICAL_TOOL_CATALOGUE_VERSION. Future changes get a v2 etc;\n * never edit the existing v1 logic, or already-recorded hashes lose\n * their meaning.\n */\n\n// ─── Versioning ───────────────────────────────────────────────────────────\n\n/**\n * Canonical-form version for tool catalogue hashes produced by this SDK.\n * Recorded in tool_catalogue_canon_version on the event metadata (when\n * the metadata field is used) so verifiers know which hash recipe to\n * reproduce. Increment ONLY if the algorithm changes in a way that\n * would change the hash for the same logical catalogue.\n */\nexport const CANONICAL_TOOL_CATALOGUE_VERSION = 'v1' as const;\n\n// ─── Types ────────────────────────────────────────────────────────────────\n\n/**\n * Minimum shape a tool needs for catalogue hashing. The framework\n * integrations adapt their native tool objects to this shape before\n * calling hashToolCatalogue.\n */\nexport interface CatalogueTool {\n /** The name the model sees and calls. Required. */\n name: string;\n /** Human-readable description shown to the model. Optional; absent ↔ empty string. */\n description?: string;\n /**\n * JSON Schema describing the tool's input parameters. Optional;\n * absent ↔ empty object `{}`. The schema gets RFC 8785 JCS-canonicalised\n * before hashing so semantically-equivalent variations (key order,\n * whitespace) produce the same hash.\n */\n schema?: Record<string, unknown> | null;\n}\n\n// ─── RFC 8785 JCS subset ──────────────────────────────────────────────────\n\n/**\n * RFC 8785 JSON Canonicalization Scheme, sufficient subset for tool\n * catalogue values.\n *\n * Rules:\n * - Object keys sorted lexicographically by UTF-16 code units (which\n * is what JS string comparison does naturally).\n * - No whitespace between tokens.\n * - Numbers: integers as integers, finite floats per ECMAScript\n * Number.prototype.toString. JCS forbids NaN and Infinity.\n * - Strings: JSON-escape using minimal set per RFC 8259 § 7.\n * - null, true, false, arrays: as JSON.stringify produces them, since\n * JSON.stringify already produces the canonical form for these.\n *\n * Not vendoring a full library because tool schemas don't carry\n * non-integer numbers in practice and the JS spec for Number.toString\n * happens to coincide with JCS § 3.2.2.2 for the integer case.\n */\nexport function jcsCanonicalise(value: unknown): string {\n if (value === null) return 'null';\n if (value === true) return 'true';\n if (value === false) return 'false';\n\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new Error('jcsCanonicalise: NaN and Infinity are not JCS-valid');\n }\n // Fail closed on magnitudes where JS .toString() and CPython diverge, so TS\n // and Python sign byte-identical bytes (or both reject). JS switches\n // integer-valued floats to exponent form at |x| >= 1e21 (Python expands to\n // full digits); in [1e-7, 1e-4) JS keeps decimals while Python repr() uses\n // exponent form. Keeping both engines in lockstep preserves cross-SDK\n // signature verifiability.\n const abs = Math.abs(value);\n // Reject ranges where JS Number.toString() and CPython diverge: |x| >= 1e21,\n // |x| < 1e-4, and integer-valued |x| > 2^53 (JS shortest-round-trip vs\n // Python exact int expansion — they only coincide for \"round\" values there).\n if (value !== 0 && (abs >= 1e21 || abs < 1e-4 || (Number.isInteger(value) && abs > 2 ** 53))) {\n throw new Error(\n `jcsCanonicalise: numbers in the ranges where JS and Python formatting ` +\n `diverge (|x| >= 1e21, |x| < 1e-4, or integer |x| > 2^53) are not ` +\n `supported in signed metadata. Use a string instead of ${value}.`,\n );\n }\n // For integers in safe range and ordinary decimals, .toString() matches JCS\n // (modern JS engines use the shortest round-trip representation).\n return value.toString();\n }\n\n if (typeof value === 'string') {\n return JSON.stringify(value);\n }\n\n if (Array.isArray(value)) {\n return '[' + value.map(jcsCanonicalise).join(',') + ']';\n }\n\n if (typeof value === 'object') {\n const obj = value as Record<string, unknown>;\n // Filter undefined-valued fields, matching @vorim/verify and\n // @vorim/shared-types. Without this the SDK throws on { a: 1, b: undefined }\n // while the verifier silently drops b — a cross-module canonical-form\n // divergence that would break signature verification on such events.\n const keys = Object.keys(obj).filter(k => obj[k] !== undefined).sort();\n const parts = keys.map(k => JSON.stringify(k) + ':' + jcsCanonicalise(obj[k]));\n return '{' + parts.join(',') + '}';\n }\n\n // undefined, function, symbol, bigint — not JSON-representable\n throw new Error(`jcsCanonicalise: unsupported value type: ${typeof value}`);\n}\n\n// ─── SHA-256 ──────────────────────────────────────────────────────────────\n\nasync function sha256Hex(input: string | Uint8Array): Promise<string> {\n const bytes = typeof input === 'string' ? new TextEncoder().encode(input) : input;\n\n // Node.js Web Crypto (Node 18+) supports digest. Browser Web Crypto does too.\n // Fall back to node:crypto if Web Crypto is unavailable.\n const subtle = (globalThis as any).crypto?.subtle;\n if (subtle) {\n const buf = await subtle.digest('SHA-256', bytes);\n return Array.from(new Uint8Array(buf))\n .map(b => b.toString(16).padStart(2, '0'))\n .join('');\n }\n\n // Node fallback\n const nodeCrypto = await import('node:crypto');\n return nodeCrypto.createHash('sha256').update(bytes).digest('hex');\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────\n\n/**\n * Hash a single tool definition. Returns `sha256:<hex>`.\n *\n * Canonical form (v1):\n * JCS-canonicalised JSON of `{name, description, schema}` where\n * absent fields substitute `description: \"\"` and `schema: {}`.\n */\nexport async function hashTool(tool: CatalogueTool): Promise<string> {\n const normalised = {\n name: tool.name,\n description: tool.description ?? '',\n schema: tool.schema ?? {},\n };\n const hex = await sha256Hex(jcsCanonicalise(normalised));\n return `sha256:${hex}`;\n}\n\n/**\n * Hash an entire tool catalogue. Returns `sha256:<hex>`.\n *\n * Reordering tools does NOT change the hash (tool hashes sorted\n * lexicographically before concatenation). Adding, removing, or\n * modifying a tool DOES change the hash.\n *\n * Per-tool hashing first means a verifier comparing two catalogue\n * hashes that differ can also be given the per-tool hashes to\n * identify which specific tool changed.\n */\nexport async function hashToolCatalogue(tools: CatalogueTool[]): Promise<string> {\n if (tools.length === 0) {\n // Empty catalogue has a deterministic, stable hash distinct from \"no field\"\n return `sha256:${await sha256Hex('[]')}`;\n }\n const perTool = await Promise.all(tools.map(hashTool));\n perTool.sort();\n const hex = await sha256Hex(perTool.join(''));\n return `sha256:${hex}`;\n}\n\n/**\n * Hash a system prompt. Returns `sha256:<hex>`.\n *\n * The prompt is UTF-8 encoded and hashed verbatim — no normalisation.\n * If a caller wants to ignore whitespace or comment differences, they\n * should normalise before calling. The intent here is deterministic\n * reproducibility, not semantic equivalence.\n */\nexport async function hashSystemPrompt(prompt: string): Promise<string> {\n const hex = await sha256Hex(prompt);\n return `sha256:${hex}`;\n}\n\n/**\n * Convenience: hash the previous event's canonical bytes for use in\n * the prev_event_hash field of hash-chained ingest. Caller provides\n * the canonical bytes (use canonicalPayloadV0 from the main module).\n */\nexport async function hashPreviousEvent(canonicalBytes: string): Promise<string> {\n const hex = await sha256Hex(canonicalBytes);\n return `sha256:${hex}`;\n}\n\n// ─── Replay context — framework integration helper ────────────────────────\n\n/**\n * Raw inputs the integration captures from the framework. Set by the\n * integration's config; turned into hashes by {@link prepareReplayContext}.\n */\nexport interface ReplayInputs {\n /** Stable identifier for the model. E.g. `\"anthropic:claude-opus-4-8\"`. */\n modelVersion?: string;\n /** Tools available to the agent at call time. Hashed via {@link hashToolCatalogue}. */\n tools?: CatalogueTool[];\n /** System prompt active at call time. Hashed via {@link hashSystemPrompt}. */\n systemPrompt?: string;\n}\n\n/**\n * Pre-computed hashes ready to attach to audit events. The three keys\n * match the audit_events column names.\n */\nexport interface ReplayContext {\n model_version?: string;\n tool_catalogue_hash?: string;\n system_prompt_hash?: string;\n}\n\n/**\n * Compute replay context once from raw inputs. Use at integration\n * setup time so each emit can attach the hashes without re-hashing.\n *\n * Returns an object suitable for spreading into an AuditEventInput:\n * `await vorim.emit({ ...event, ...replayContext })`\n *\n * If a field is absent in the inputs, it is absent in the result\n * (not the empty string). That keeps the event lean.\n */\nexport async function prepareReplayContext(\n inputs: ReplayInputs,\n): Promise<ReplayContext> {\n const ctx: ReplayContext = {};\n if (inputs.modelVersion) ctx.model_version = inputs.modelVersion;\n if (inputs.tools) ctx.tool_catalogue_hash = await hashToolCatalogue(inputs.tools);\n if (inputs.systemPrompt) ctx.system_prompt_hash = await hashSystemPrompt(inputs.systemPrompt);\n return ctx;\n}\n","// ============================================================================\n// VORIM SDK — OpenAI Integration\n// Wraps OpenAI function calling with Vorim permission checks, audit trails,\n// and agent identity. Works with the OpenAI Node.js SDK (chat completions\n// with tool use).\n//\n// Peer dependency: openai >=4.0.0\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope, AuditEventInput } from '../types.js';\nimport { runtimeGate, type EscalationPolicy, type TransportFailurePolicy } from './_runtime-gate.js';\nimport {\n prepareReplayContext,\n type ReplayInputs,\n type ReplayContext,\n type CatalogueTool,\n} from '../replay.js';\n\n// ─── Re-declared OpenAI types (peer dependency — not bundled) ─────────────\n\ninterface ChatCompletionTool {\n type: 'function';\n function: {\n name: string;\n description?: string;\n parameters?: Record<string, unknown>;\n strict?: boolean;\n };\n}\n\ninterface ToolCall {\n id: string;\n type: 'function';\n function: {\n name: string;\n arguments: string;\n };\n}\n\ninterface ToolMessage {\n role: 'tool';\n tool_call_id: string;\n content: string;\n}\n\n// ─── Configuration ────────────────────────────────────────────────────────\n\nexport interface VorimToolDefinition<TArgs = Record<string, unknown>, TResult = unknown> {\n /** Tool name (must match the function name sent to OpenAI). */\n name: string;\n /** Description shown to the LLM. */\n description: string;\n /** JSON Schema for the tool's parameters. */\n parameters: Record<string, unknown>;\n /** The function to execute when the tool is called. */\n execute: (args: TArgs) => Promise<TResult>;\n /** Vorim permission scope required. @default 'agent:execute' */\n permission?: PermissionScope;\n /** Whether to use strict mode for OpenAI structured outputs. */\n strict?: boolean;\n}\n\nexport interface VorimOpenAIConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id. */\n agentId: string;\n /** Default permission scope for tools without an explicit one. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Whether to emit audit events asynchronously. @default true */\n asyncAudit?: boolean;\n /**\n * Gate each tool call through the runtime-control decision API\n * (`beforeAction`) instead of the lightweight permission check.\n * @default false\n *\n * When true, every tool call is evaluated against your live policy rules\n * (allow/deny/escalate) and the returned `decisionId` is linked onto each\n * audit event's `decision_id`, so runtime decisions tie back to the audit\n * trail. Requires the runtime_control plan feature (Growth+) and consumes\n * decision quota. When false (default) the integration uses the\n * fast permission check and emits audit events with no decision linkage.\n */\n useRuntimeControl?: boolean;\n /**\n * What to do when a runtime decision returns `escalate` (a human must\n * approve). Only applies when `useRuntimeControl` is true.\n * - `wait` (default) block and poll until a human approves/denies, or the\n * timeout elapses (→ deny). Requires the `runtime:decide` scope.\n * - `deny` fail closed without waiting.\n * - `allow` proceed (fail OPEN — dev/trusted use only).\n * @default 'wait'\n */\n onEscalation?: EscalationPolicy;\n /** Timeout (ms) for `onEscalation: 'wait'`. @default 300000 */\n escalationTimeoutMs?: number;\n /**\n * Policy when the runtime gate can't reach the control plane.\n * `'deny'` fails closed (secure default); `'allow'` fails open.\n * @default 'deny'\n */\n onTransportFailure?: TransportFailurePolicy;\n /**\n * Replayable agent decision evidence (VAIP -02). When provided, the\n * hashes are attached to every audit event the registry emits.\n * If `replay.tools` is not given, the registry's own tool catalogue\n * (the tools you `add()`) is used automatically.\n *\n * Not covered by the v0 canonical signature form; advisory only.\n */\n replay?: ReplayInputs;\n}\n\n// ─── Tool Registry ────────────────────────────────────────────────────────\n\n/**\n * Manages a set of tools with Vorim permission checks and audit logging.\n * Converts tools to OpenAI's `ChatCompletionTool` format and handles\n * execution of tool calls from the model's response.\n *\n * @example\n * ```ts\n * import OpenAI from \"openai\";\n * import createVorim from \"@vorim/sdk\";\n * import { VorimToolRegistry } from \"@vorim/sdk/integrations/openai\";\n *\n * const vorim = createVorim({ apiKey: \"agid_sk_live_...\" });\n * const openai = new OpenAI();\n *\n * const registry = new VorimToolRegistry({\n * vorim,\n * agentId: \"agid_acme_a1b2c3d4\",\n * });\n *\n * registry.add({\n * name: \"search_docs\",\n * description: \"Search internal documents\",\n * parameters: {\n * type: \"object\",\n * properties: { query: { type: \"string\" } },\n * required: [\"query\"],\n * },\n * execute: async ({ query }) => searchDocs(query),\n * permission: \"agent:read\",\n * });\n *\n * // Use with OpenAI chat completions\n * const response = await openai.chat.completions.create({\n * model: \"gpt-4o\",\n * messages,\n * tools: registry.toOpenAITools(),\n * });\n *\n * // Execute tool calls from the response\n * const toolMessages = await registry.executeToolCalls(\n * response.choices[0].message.tool_calls ?? []\n * );\n * ```\n */\nexport class VorimToolRegistry {\n private vorim: VorimSDK;\n private agentId: string;\n private defaultPermission: PermissionScope;\n private asyncAudit: boolean;\n private useRuntimeControl: boolean;\n private onEscalation?: EscalationPolicy;\n private escalationTimeoutMs?: number;\n private onTransportFailure?: TransportFailurePolicy;\n private tools = new Map<string, VorimToolDefinition>();\n private replayInputs: ReplayInputs | undefined;\n private replayCache: Promise<ReplayContext> | null = null;\n\n constructor(config: VorimOpenAIConfig) {\n this.vorim = config.vorim;\n this.agentId = config.agentId;\n this.defaultPermission = config.defaultPermission ?? 'agent:execute';\n this.asyncAudit = config.asyncAudit ?? true;\n this.useRuntimeControl = config.useRuntimeControl ?? false;\n this.onEscalation = config.onEscalation;\n this.escalationTimeoutMs = config.escalationTimeoutMs;\n this.onTransportFailure = config.onTransportFailure;\n this.replayInputs = config.replay;\n }\n\n /**\n * Gate a tool call. When useRuntimeControl is on, run the full runtime\n * decision (beforeAction) and surface its decisionId for audit linkage;\n * otherwise use the lightweight permission check.\n */\n private async gate(\n scope: PermissionScope,\n actionTarget: string,\n payload?: Record<string, unknown>,\n ): Promise<{ allowed: boolean; reason?: string; decisionId?: string }> {\n if (this.useRuntimeControl) {\n // runtimeGate handles transport-failure fallbacks internally, but a\n // non-transport VorimError from beforeAction (e.g. 403 missing\n // runtime:decide scope, 400 validation) still throws — wrap so it\n // fails closed instead of crashing the host tool loop. Matches the\n // Python _gate try/except.\n try {\n return await runtimeGate(this.vorim, this.agentId, actionTarget, scope, payload, {\n onEscalation: this.onEscalation,\n escalationTimeoutMs: this.escalationTimeoutMs,\n onTransportFailure: this.onTransportFailure,\n });\n } catch {\n return { allowed: false, reason: 'runtime gate unavailable (failed closed)' };\n }\n }\n // Fail closed on a permission-check transport error (API down, 5xx,\n // network/DNS/timeout) instead of letting the rejection crash the host\n // tool loop. Mirrors the Python _safe_check fail-closed behaviour.\n try {\n const { allowed, reason } = await this.vorim.check(this.agentId, scope);\n return { allowed, reason };\n } catch {\n return { allowed: false, reason: 'permission check unavailable (failed closed)' };\n }\n }\n\n private async getReplayContext(): Promise<ReplayContext> {\n if (!this.replayInputs) return {};\n if (!this.replayCache) {\n // If caller didn't supply tools, derive them from the registry.\n const inputs: ReplayInputs = {\n ...this.replayInputs,\n tools: this.replayInputs.tools ?? this.deriveCatalogue(),\n };\n this.replayCache = prepareReplayContext(inputs);\n }\n return this.replayCache;\n }\n\n private deriveCatalogue(): CatalogueTool[] {\n return [...this.tools.values()].map(t => ({\n name: t.name,\n description: t.description,\n schema: t.parameters,\n }));\n }\n\n /** Register a tool. Invalidates the cached tool-catalogue hash. */\n add<TArgs, TResult>(definition: VorimToolDefinition<TArgs, TResult>): this {\n this.tools.set(definition.name, definition as VorimToolDefinition);\n this.replayCache = null;\n return this;\n }\n\n /** Register multiple tools. */\n addAll(definitions: VorimToolDefinition[]): this {\n for (const def of definitions) this.add(def);\n return this;\n }\n\n /** Convert registered tools to OpenAI's ChatCompletionTool format. */\n toOpenAITools(): ChatCompletionTool[] {\n return [...this.tools.values()].map(t => ({\n type: 'function' as const,\n function: {\n name: t.name,\n description: t.description,\n parameters: t.parameters,\n ...(t.strict != null ? { strict: t.strict } : {}),\n },\n }));\n }\n\n /**\n * Execute tool calls from an OpenAI chat completion response.\n * Each call is checked against Vorim permissions and audited.\n * Returns an array of tool messages ready to append to the conversation.\n */\n async executeToolCalls(toolCalls: ToolCall[]): Promise<ToolMessage[]> {\n const results = await Promise.all(\n toolCalls.map(tc => this.executeSingleCall(tc)),\n );\n return results;\n }\n\n private async executeSingleCall(toolCall: ToolCall): Promise<ToolMessage> {\n const { id, function: fn } = toolCall;\n const definition = this.tools.get(fn.name);\n\n if (!definition) {\n return {\n role: 'tool',\n tool_call_id: id,\n content: JSON.stringify({ error: `Unknown tool: ${fn.name}` }),\n };\n }\n\n const scope = definition.permission ?? this.defaultPermission;\n let args: unknown;\n try {\n args = JSON.parse(fn.arguments);\n } catch {\n return {\n role: 'tool',\n tool_call_id: id,\n content: JSON.stringify({ error: `Invalid JSON arguments for ${fn.name}` }),\n };\n }\n\n // 1. Gate: runtime decision (with decisionId linkage) or permission check.\n const { allowed, reason, decisionId } = await this.gate(scope, fn.name, args as Record<string, unknown>);\n const replayCtx = await this.getReplayContext();\n\n if (!allowed) {\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: fn.name,\n resource: truncate(fn.arguments, 500),\n permission: scope,\n result: 'denied',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { reason, framework: 'openai' },\n ...replayCtx,\n };\n await this.emitAudit(event);\n return {\n role: 'tool',\n tool_call_id: id,\n content: JSON.stringify({ error: `Permission denied: ${scope}${reason ? ` — ${reason}` : ''}` }),\n };\n }\n\n // 2. Execute\n const start = Date.now();\n try {\n const result = await definition.execute(args as any);\n const content = typeof result === 'string' ? result : JSON.stringify(result);\n\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: fn.name,\n resource: truncate(fn.arguments, 500),\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { framework: 'openai' },\n ...replayCtx,\n };\n await this.emitAudit(event);\n\n return { role: 'tool', tool_call_id: id, content };\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: fn.name,\n resource: truncate(fn.arguments, 500),\n permission: scope,\n result: 'error',\n latency_ms: Date.now() - start,\n error_code: err instanceof Error ? err.name : 'UNKNOWN',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { error: errMsg, framework: 'openai' },\n ...replayCtx,\n };\n await this.emitAudit(event);\n\n return {\n role: 'tool',\n tool_call_id: id,\n content: JSON.stringify({ error: errMsg }),\n };\n }\n }\n\n private async emitAudit(event: AuditEventInput): Promise<void> {\n if (this.asyncAudit) {\n // Fire-and-forget: don't block the tool pipeline on the audit write.\n this.vorim.emit(event).catch(() => {});\n } else {\n // Synchronous mode: actually await so the audit is flushed before the\n // caller continues. (Previously both branches were identical and the\n // promise was never awaited — asyncAudit=false did nothing.)\n try { await this.vorim.emit(event); } catch { /* best-effort */ }\n }\n }\n}\n\n// ─── Agent Loop ───────────────────────────────────────────────────────────\n\nexport interface VorimAgentLoopConfig extends VorimOpenAIConfig {\n /** OpenAI client instance. */\n openai: OpenAIClient;\n /** Model to use. @default 'gpt-4o' */\n model?: string;\n /** System prompt for the agent. */\n systemPrompt?: string;\n /** Maximum iterations before stopping. @default 10 */\n maxIterations?: number;\n}\n\n/** Minimal OpenAI client interface (avoids importing the full SDK). */\ninterface OpenAIClient {\n chat: {\n completions: {\n create(params: any): Promise<any>;\n };\n };\n}\n\n/**\n * Runs a complete agent loop with OpenAI function calling, Vorim\n * permission enforcement, and audit logging.\n *\n * @example\n * ```ts\n * import OpenAI from \"openai\";\n * import createVorim from \"@vorim/sdk\";\n * import { runAgentLoop, VorimToolRegistry } from \"@vorim/sdk/integrations/openai\";\n *\n * const registry = new VorimToolRegistry({ vorim, agentId });\n * registry.add({ name: \"search\", ... });\n *\n * const response = await runAgentLoop({\n * vorim,\n * agentId,\n * openai: new OpenAI(),\n * model: \"gpt-4o\",\n * systemPrompt: \"You are a helpful assistant.\",\n * registry,\n * userMessage: \"Find docs about onboarding\",\n * });\n * ```\n */\nexport async function runAgentLoop(\n config: VorimAgentLoopConfig & {\n registry: VorimToolRegistry;\n userMessage: string;\n },\n): Promise<string> {\n const { openai, model = 'gpt-4o', systemPrompt, maxIterations = 10, registry, userMessage } = config;\n\n const messages: any[] = [];\n if (systemPrompt) messages.push({ role: 'system', content: systemPrompt });\n messages.push({ role: 'user', content: userMessage });\n\n const tools = registry.toOpenAITools();\n\n for (let i = 0; i < maxIterations; i++) {\n const response = await openai.chat.completions.create({\n model,\n messages,\n ...(tools.length > 0 ? { tools } : {}),\n });\n\n const choice = response.choices[0];\n messages.push(choice.message);\n\n // If the model is done (no tool calls), return the response\n if (choice.finish_reason === 'stop' || !choice.message.tool_calls?.length) {\n return choice.message.content ?? '';\n }\n\n // Execute tool calls and add results to messages\n const toolMessages = await registry.executeToolCalls(choice.message.tool_calls);\n messages.push(...toolMessages);\n }\n\n return messages[messages.length - 1]?.content ?? '';\n}\n\n// ─── Agent Registration Helper ───────────────────────────────────────────\n\n/**\n * Registers a new agent with Vorim and returns a ready-to-use tool registry.\n *\n * @example\n * ```ts\n * const { agentId, registry } = await createVorimOpenAIAgent({\n * vorim,\n * name: \"support-agent\",\n * capabilities: [\"search\", \"email\"],\n * scopes: [\"agent:read\", \"agent:execute\", \"agent:communicate\"],\n * tools: [searchTool, emailTool],\n * });\n * ```\n */\nexport async function createVorimOpenAIAgent(config: {\n vorim: VorimSDK;\n name: string;\n description?: string;\n capabilities: string[];\n scopes: PermissionScope[];\n tools: VorimToolDefinition[];\n}) {\n const { vorim, name, description, capabilities, scopes, tools } = config;\n\n const registration = await vorim.register({\n name,\n description,\n capabilities,\n scopes,\n });\n\n const agentId = registration.agent.agent_id;\n\n const registry = new VorimToolRegistry({ vorim, agentId });\n registry.addAll(tools);\n\n return {\n agentId,\n registration,\n registry,\n privateKey: registration.private_key,\n };\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────────\n\nfunction truncate(str: string, max: number): string {\n return str.length > max ? str.slice(0, max) + '…' : str;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAA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BAAsB;AAO5B,IAAM,2BAA2B;AA2DxC,eAAsB,uBAAuB,QAAuD;AAClG,QAAM;AAAA,IACJ;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,IAChB;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,QAAM,WAAkB,CAAC;AACzB,MAAI,aAAc,UAAS,KAAK,EAAE,MAAM,UAAU,SAAS,aAAa,CAAC;AACzE,WAAS,KAAK,EAAE,MAAM,QAAQ,SAAS,YAAY,CAAC;AAEpD,QAAM,QAAQ,SAAS,cAAc;AAErC,WAAS,IAAI,GAAG,IAAI,eAAe,KAAK;AACtC,UAAM,WAAW,MAAM,WAAW,KAAK,YAAY,OAAO;AAAA,MACxD;AAAA,MACA;AAAA;AAAA,MAEA,GAAI,UAAU,OAAO,SAAS,IAAI,EAAE,OAAO,IAAI,CAAC;AAAA,MAChD,GAAI,MAAM,SAAS,IAAI,EAAE,MAAM,IAAI,CAAC;AAAA,IACtC,CAAC;AAED,UAAM,SAAS,SAAS,QAAQ,CAAC;AACjC,aAAS,KAAK,OAAO,OAAO;AAE5B,QAAI,OAAO,kBAAkB,UAAU,CAAC,OAAO,QAAQ,YAAY,QAAQ;AACzE,aAAO,OAAO,QAAQ,WAAW;AAAA,IACnC;AAGA,UAAM,eAAe,MAAM,SAAS,iBAAiB,OAAO,QAAQ,UAAU;AAC9E,aAAS,KAAK,GAAG,YAAY;AAAA,EAC/B;AAEA,SAAO,SAAS,SAAS,SAAS,CAAC,GAAG,WAAW;AACnD;","names":[]}
1
+ {"version":3,"sources":["../../src/integrations/openrouter.ts","../../src/integrations/_runtime-gate.ts","../../src/replay.ts","../../src/integrations/openai.ts"],"sourcesContent":["// ============================================================================\n// VORIM SDK — OpenRouter Integration\n//\n// OpenRouter (https://openrouter.ai) is a unified gateway to 500+ models from\n// 60+ providers (OpenAI, Anthropic, Google, Meta, xAI, ...) behind ONE\n// OpenAI-compatible endpoint. Point the OpenAI client at\n// `https://openrouter.ai/api/v1`, pick a model id like\n// `anthropic/claude-fable-5` or `openai/gpt-latest`, and the request/response\n// shape (including `tools` / `tool_calls`) matches OpenAI's Chat Completions.\n//\n// So Vorim gates and signs OpenRouter's *custom* function tools with exactly the\n// same registry it uses for OpenAI and Grok — this module is a thin\n// OpenRouter-flavoured wrapper over that registry plus an agent loop, with one\n// OpenRouter-specific extra: a `models` FALLBACK ARRAY so the loop can ask\n// OpenRouter to try several models in order on error.\n//\n// The value: the model underneath can change (routing, fallbacks, cost), and\n// Vorim stays the ONE identity + permission + signed-audit layer over every\n// tool call, whichever model OpenRouter picks.\n//\n// Peer dependency: openai >=4.0.0 (the OpenAI Node SDK, pointed at OpenRouter).\n//\n// Usage:\n// import OpenAI from 'openai';\n// import createVorim from '@vorim/sdk';\n// import {\n// VorimToolRegistry, runOpenRouterAgentLoop, OPENROUTER_BASE_URL,\n// } from '@vorim/sdk/integrations/openrouter';\n//\n// const vorim = createVorim({ apiKey: 'agid_sk_...' });\n// const openrouter = new OpenAI({\n// apiKey: process.env.OPENROUTER_API_KEY,\n// baseURL: OPENROUTER_BASE_URL,\n// });\n//\n// const registry = new VorimToolRegistry({ vorim, agentId });\n// registry.add({ name: 'search', description: '...', parameters: {...},\n// permission: 'agent:execute', execute: async (args) => {...} });\n//\n// const answer = await runOpenRouterAgentLoop({\n// vorim, agentId, openrouter, registry,\n// userMessage: 'Find our onboarding docs',\n// model: 'anthropic/claude-fable-5',\n// // Optional fallback chain OpenRouter walks on error:\n// models: ['anthropic/claude-fable-5', 'openai/gpt-latest'],\n// });\n//\n// IMPORTANT — what Vorim can and cannot attest here:\n// Vorim gates + signs the CUSTOM function tools you define and execute in the\n// registry. Any model's BUILT-IN / provider-side tools that run inside the\n// upstream provider (not through your executor) never pass through this gate\n// and are not Vorim-attestable. If you need every action signed, keep the work\n// in custom tools you execute.\n//\n// MODEL IDS ARE CONFIG, NOT CONSTANTS. OpenRouter's catalog changes constantly.\n// The default below is a sensible starting point; confirm against\n// `GET https://openrouter.ai/api/v1/models` at runtime and let callers override.\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\n\n// The gate-and-sign core is model-agnostic: OpenRouter uses OpenAI's tool shape,\n// so the same registry does the work. Re-exported here so an OpenRouter user\n// imports everything from one module without also reaching into the OpenAI one.\nexport {\n VorimToolRegistry,\n runAgentLoop,\n createVorimOpenAIAgent as createVorimOpenRouterAgent,\n} from './openai.js';\nexport type {\n VorimToolDefinition,\n VorimOpenAIConfig as VorimOpenRouterConfig,\n VorimAgentLoopConfig,\n} from './openai.js';\n\nimport { VorimToolRegistry } from './openai.js';\n\n/** OpenRouter API base URL (OpenAI-SDK compatible). */\nexport const OPENROUTER_BASE_URL = 'https://openrouter.ai/api/v1';\n\n/**\n * Sensible, overridable default model. Treat as config: confirm against the live\n * `/api/v1/models` list and let callers override. OpenRouter model ids are\n * `provider/model` (e.g. `anthropic/claude-fable-5`, `openai/gpt-latest`).\n */\nexport const DEFAULT_OPENROUTER_MODEL = 'anthropic/claude-fable-5';\n\n/**\n * Minimal shape of the OpenAI Node client, pointed at OpenRouter. We only touch\n * `chat.completions.create`. Declared here so `openai` stays a peer dependency\n * and isn't bundled.\n */\ninterface OpenRouterChatClient {\n chat: {\n completions: {\n create: (args: Record<string, unknown>) => Promise<any>;\n };\n };\n}\n\nexport interface RunOpenRouterAgentLoopConfig {\n vorim: VorimSDK;\n agentId: string;\n /** An OpenAI-compatible client constructed with `baseURL: OPENROUTER_BASE_URL`. */\n openrouter: OpenRouterChatClient;\n /** The tool registry (custom, Vorim-gated tools). */\n registry: VorimToolRegistry;\n /** The user's message to the agent. */\n userMessage: string;\n /** OpenRouter model id. @default DEFAULT_OPENROUTER_MODEL — override freely. */\n model?: string;\n /**\n * Optional OpenRouter model FALLBACK ARRAY. When provided, it is sent as the\n * `models` field so OpenRouter walks the list in order on error. `model` is\n * still sent as the primary; keep it as the first entry for clarity.\n * @see https://openrouter.ai/docs/features/model-routing\n */\n models?: string[];\n /** Optional system prompt. */\n systemPrompt?: string;\n /** Max agent-loop turns before giving up. @default 10 */\n maxIterations?: number;\n}\n\n/**\n * Run an OpenRouter tool-calling agent loop over Vorim-gated custom tools.\n *\n * Identical control flow to the OpenAI/Grok loop (OpenRouter mirrors the Chat\n * Completions `tools` / `tool_calls` shape); the differences are the client is\n * pointed at OpenRouter, the default model is an OpenRouter id, and an optional\n * `models` fallback array is forwarded so OpenRouter can route across providers.\n * Every custom tool call is permission-checked and signed by the registry before\n * it executes — whichever model OpenRouter ends up using.\n *\n * @example\n * ```ts\n * const answer = await runOpenRouterAgentLoop({\n * vorim, agentId, openrouter, registry,\n * userMessage: 'Reconcile the July invoices',\n * model: 'anthropic/claude-fable-5',\n * models: ['anthropic/claude-fable-5', 'openai/gpt-latest'],\n * });\n * ```\n */\nexport async function runOpenRouterAgentLoop(config: RunOpenRouterAgentLoopConfig): Promise<string> {\n const {\n openrouter,\n model = DEFAULT_OPENROUTER_MODEL,\n models,\n systemPrompt,\n maxIterations = 10,\n registry,\n userMessage,\n } = config;\n\n const messages: any[] = [];\n if (systemPrompt) messages.push({ role: 'system', content: systemPrompt });\n messages.push({ role: 'user', content: userMessage });\n\n const tools = registry.toOpenAITools();\n\n for (let i = 0; i < maxIterations; i++) {\n const response = await openrouter.chat.completions.create({\n model,\n messages,\n // OpenRouter-specific: forward the fallback chain if the caller gave one.\n ...(models && models.length > 0 ? { models } : {}),\n ...(tools.length > 0 ? { tools } : {}),\n });\n\n const choice = response.choices[0];\n messages.push(choice.message);\n\n if (choice.finish_reason === 'stop' || !choice.message.tool_calls?.length) {\n return choice.message.content ?? '';\n }\n\n // Each custom tool call is gated + signed by the registry before running.\n const toolMessages = await registry.executeToolCalls(choice.message.tool_calls);\n messages.push(...toolMessages);\n }\n\n return messages[messages.length - 1]?.content ?? '';\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 * Replayable agent decision evidence helpers.\n *\n * Canonical-form hashing for the VAIP -02 schema fields that the SDK\n * attaches to audit events. The hashes recorded in audit_events.tool_catalogue_hash\n * and audit_events.system_prompt_hash use these functions, so the bytes\n * an auditor or counterparty reconstructs must match what the SDK produced.\n *\n * These helpers are intentionally separate from the signing path. The\n * v0 canonical signature form (event_type|action|resource|input_hash|\n * output_hash|result) does NOT cover model_version, tool_catalogue_hash,\n * or system_prompt_hash. They will enter the canonical bytes in v1\n * (RFC 8785 JCS) in a follow-up release.\n *\n * Stable across SDK versions: the canonical-form version is documented\n * in CANONICAL_TOOL_CATALOGUE_VERSION. Future changes get a v2 etc;\n * never edit the existing v1 logic, or already-recorded hashes lose\n * their meaning.\n */\n\n// ─── Versioning ───────────────────────────────────────────────────────────\n\n/**\n * Canonical-form version for tool catalogue hashes produced by this SDK.\n * Recorded in tool_catalogue_canon_version on the event metadata (when\n * the metadata field is used) so verifiers know which hash recipe to\n * reproduce. Increment ONLY if the algorithm changes in a way that\n * would change the hash for the same logical catalogue.\n */\nexport const CANONICAL_TOOL_CATALOGUE_VERSION = 'v1' as const;\n\n// ─── Types ────────────────────────────────────────────────────────────────\n\n/**\n * Minimum shape a tool needs for catalogue hashing. The framework\n * integrations adapt their native tool objects to this shape before\n * calling hashToolCatalogue.\n */\nexport interface CatalogueTool {\n /** The name the model sees and calls. Required. */\n name: string;\n /** Human-readable description shown to the model. Optional; absent ↔ empty string. */\n description?: string;\n /**\n * JSON Schema describing the tool's input parameters. Optional;\n * absent ↔ empty object `{}`. The schema gets RFC 8785 JCS-canonicalised\n * before hashing so semantically-equivalent variations (key order,\n * whitespace) produce the same hash.\n */\n schema?: Record<string, unknown> | null;\n}\n\n// ─── RFC 8785 JCS subset ──────────────────────────────────────────────────\n\n/**\n * RFC 8785 JSON Canonicalization Scheme, sufficient subset for tool\n * catalogue values.\n *\n * Rules:\n * - Object keys sorted lexicographically by UTF-16 code units (which\n * is what JS string comparison does naturally).\n * - No whitespace between tokens.\n * - Numbers: integers as integers, finite floats per ECMAScript\n * Number.prototype.toString. JCS forbids NaN and Infinity.\n * - Strings: JSON-escape using minimal set per RFC 8259 § 7.\n * - null, true, false, arrays: as JSON.stringify produces them, since\n * JSON.stringify already produces the canonical form for these.\n *\n * Not vendoring a full library because tool schemas don't carry\n * non-integer numbers in practice and the JS spec for Number.toString\n * happens to coincide with JCS § 3.2.2.2 for the integer case.\n */\nexport function jcsCanonicalise(value: unknown): string {\n if (value === null) return 'null';\n if (value === true) return 'true';\n if (value === false) return 'false';\n\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new Error('jcsCanonicalise: NaN and Infinity are not JCS-valid');\n }\n // Fail closed on magnitudes where JS .toString() and CPython diverge, so TS\n // and Python sign byte-identical bytes (or both reject). JS switches\n // integer-valued floats to exponent form at |x| >= 1e21 (Python expands to\n // full digits); in [1e-7, 1e-4) JS keeps decimals while Python repr() uses\n // exponent form. Keeping both engines in lockstep preserves cross-SDK\n // signature verifiability.\n const abs = Math.abs(value);\n // Reject ranges where JS Number.toString() and CPython diverge: |x| >= 1e21,\n // |x| < 1e-4, and integer-valued |x| > 2^53 (JS shortest-round-trip vs\n // Python exact int expansion — they only coincide for \"round\" values there).\n if (value !== 0 && (abs >= 1e21 || abs < 1e-4 || (Number.isInteger(value) && abs > 2 ** 53))) {\n throw new Error(\n `jcsCanonicalise: numbers in the ranges where JS and Python formatting ` +\n `diverge (|x| >= 1e21, |x| < 1e-4, or integer |x| > 2^53) are not ` +\n `supported in signed metadata. Use a string instead of ${value}.`,\n );\n }\n // For integers in safe range and ordinary decimals, .toString() matches JCS\n // (modern JS engines use the shortest round-trip representation).\n return value.toString();\n }\n\n if (typeof value === 'string') {\n return JSON.stringify(value);\n }\n\n if (Array.isArray(value)) {\n return '[' + value.map(jcsCanonicalise).join(',') + ']';\n }\n\n if (typeof value === 'object') {\n const obj = value as Record<string, unknown>;\n // Filter undefined-valued fields, matching @vorim/verify and\n // @vorim/shared-types. Without this the SDK throws on { a: 1, b: undefined }\n // while the verifier silently drops b — a cross-module canonical-form\n // divergence that would break signature verification on such events.\n const keys = Object.keys(obj).filter(k => obj[k] !== undefined).sort();\n const parts = keys.map(k => JSON.stringify(k) + ':' + jcsCanonicalise(obj[k]));\n return '{' + parts.join(',') + '}';\n }\n\n // undefined, function, symbol, bigint — not JSON-representable\n throw new Error(`jcsCanonicalise: unsupported value type: ${typeof value}`);\n}\n\n// ─── SHA-256 ──────────────────────────────────────────────────────────────\n\nasync function sha256Hex(input: string | Uint8Array): Promise<string> {\n const bytes = typeof input === 'string' ? new TextEncoder().encode(input) : input;\n\n // Node.js Web Crypto (Node 18+) supports digest. Browser Web Crypto does too.\n // Fall back to node:crypto if Web Crypto is unavailable.\n const subtle = (globalThis as any).crypto?.subtle;\n if (subtle) {\n const buf = await subtle.digest('SHA-256', bytes);\n return Array.from(new Uint8Array(buf))\n .map(b => b.toString(16).padStart(2, '0'))\n .join('');\n }\n\n // Node fallback\n const nodeCrypto = await import('node:crypto');\n return nodeCrypto.createHash('sha256').update(bytes).digest('hex');\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────\n\n/**\n * Hash a single tool definition. Returns `sha256:<hex>`.\n *\n * Canonical form (v1):\n * JCS-canonicalised JSON of `{name, description, schema}` where\n * absent fields substitute `description: \"\"` and `schema: {}`.\n */\nexport async function hashTool(tool: CatalogueTool): Promise<string> {\n const normalised = {\n name: tool.name,\n description: tool.description ?? '',\n schema: tool.schema ?? {},\n };\n const hex = await sha256Hex(jcsCanonicalise(normalised));\n return `sha256:${hex}`;\n}\n\n/**\n * Hash an entire tool catalogue. Returns `sha256:<hex>`.\n *\n * Reordering tools does NOT change the hash (tool hashes sorted\n * lexicographically before concatenation). Adding, removing, or\n * modifying a tool DOES change the hash.\n *\n * Per-tool hashing first means a verifier comparing two catalogue\n * hashes that differ can also be given the per-tool hashes to\n * identify which specific tool changed.\n */\nexport async function hashToolCatalogue(tools: CatalogueTool[]): Promise<string> {\n if (tools.length === 0) {\n // Empty catalogue has a deterministic, stable hash distinct from \"no field\"\n return `sha256:${await sha256Hex('[]')}`;\n }\n const perTool = await Promise.all(tools.map(hashTool));\n perTool.sort();\n const hex = await sha256Hex(perTool.join(''));\n return `sha256:${hex}`;\n}\n\n/**\n * Hash a system prompt. Returns `sha256:<hex>`.\n *\n * The prompt is UTF-8 encoded and hashed verbatim — no normalisation.\n * If a caller wants to ignore whitespace or comment differences, they\n * should normalise before calling. The intent here is deterministic\n * reproducibility, not semantic equivalence.\n */\nexport async function hashSystemPrompt(prompt: string): Promise<string> {\n const hex = await sha256Hex(prompt);\n return `sha256:${hex}`;\n}\n\n/**\n * Convenience: hash the previous event's canonical bytes for use in\n * the prev_event_hash field of hash-chained ingest. Caller provides\n * the canonical bytes (use canonicalPayloadV0 from the main module).\n */\nexport async function hashPreviousEvent(canonicalBytes: string): Promise<string> {\n const hex = await sha256Hex(canonicalBytes);\n return `sha256:${hex}`;\n}\n\n// ─── Replay context — framework integration helper ────────────────────────\n\n/**\n * Raw inputs the integration captures from the framework. Set by the\n * integration's config; turned into hashes by {@link prepareReplayContext}.\n */\nexport interface ReplayInputs {\n /** Stable identifier for the model. E.g. `\"anthropic:claude-opus-4-8\"`. */\n modelVersion?: string;\n /** Tools available to the agent at call time. Hashed via {@link hashToolCatalogue}. */\n tools?: CatalogueTool[];\n /** System prompt active at call time. Hashed via {@link hashSystemPrompt}. */\n systemPrompt?: string;\n}\n\n/**\n * Pre-computed hashes ready to attach to audit events. The three keys\n * match the audit_events column names.\n */\nexport interface ReplayContext {\n model_version?: string;\n tool_catalogue_hash?: string;\n system_prompt_hash?: string;\n}\n\n/**\n * Compute replay context once from raw inputs. Use at integration\n * setup time so each emit can attach the hashes without re-hashing.\n *\n * Returns an object suitable for spreading into an AuditEventInput:\n * `await vorim.emit({ ...event, ...replayContext })`\n *\n * If a field is absent in the inputs, it is absent in the result\n * (not the empty string). That keeps the event lean.\n */\nexport async function prepareReplayContext(\n inputs: ReplayInputs,\n): Promise<ReplayContext> {\n const ctx: ReplayContext = {};\n if (inputs.modelVersion) ctx.model_version = inputs.modelVersion;\n if (inputs.tools) ctx.tool_catalogue_hash = await hashToolCatalogue(inputs.tools);\n if (inputs.systemPrompt) ctx.system_prompt_hash = await hashSystemPrompt(inputs.systemPrompt);\n return ctx;\n}\n","// ============================================================================\n// VORIM SDK — OpenAI Integration\n// Wraps OpenAI function calling with Vorim permission checks, audit trails,\n// and agent identity. Works with the OpenAI Node.js SDK (chat completions\n// with tool use).\n//\n// Peer dependency: openai >=4.0.0\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope, AuditEventInput } from '../types.js';\nimport { runtimeGate, type EscalationPolicy, type TransportFailurePolicy } from './_runtime-gate.js';\nimport {\n prepareReplayContext,\n type ReplayInputs,\n type ReplayContext,\n type CatalogueTool,\n} from '../replay.js';\n\n// ─── Re-declared OpenAI types (peer dependency — not bundled) ─────────────\n\ninterface ChatCompletionTool {\n type: 'function';\n function: {\n name: string;\n description?: string;\n parameters?: Record<string, unknown>;\n strict?: boolean;\n };\n}\n\ninterface ToolCall {\n id: string;\n type: 'function';\n function: {\n name: string;\n arguments: string;\n };\n}\n\ninterface ToolMessage {\n role: 'tool';\n tool_call_id: string;\n content: string;\n}\n\n// ─── Configuration ────────────────────────────────────────────────────────\n\nexport interface VorimToolDefinition<TArgs = Record<string, unknown>, TResult = unknown> {\n /** Tool name (must match the function name sent to OpenAI). */\n name: string;\n /** Description shown to the LLM. */\n description: string;\n /** JSON Schema for the tool's parameters. */\n parameters: Record<string, unknown>;\n /** The function to execute when the tool is called. */\n execute: (args: TArgs) => Promise<TResult>;\n /** Vorim permission scope required. @default 'agent:execute' */\n permission?: PermissionScope;\n /** Whether to use strict mode for OpenAI structured outputs. */\n strict?: boolean;\n}\n\nexport interface VorimOpenAIConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id. */\n agentId: string;\n /** Default permission scope for tools without an explicit one. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Whether to emit audit events asynchronously. @default true */\n asyncAudit?: boolean;\n /**\n * Gate each tool call through the runtime-control decision API\n * (`beforeAction`) instead of the lightweight permission check.\n * @default false\n *\n * When true, every tool call is evaluated against your live policy rules\n * (allow/deny/escalate) and the returned `decisionId` is linked onto each\n * audit event's `decision_id`, so runtime decisions tie back to the audit\n * trail. Requires the runtime_control plan feature (Growth+) and consumes\n * decision quota. When false (default) the integration uses the\n * fast permission check and emits audit events with no decision linkage.\n */\n useRuntimeControl?: boolean;\n /**\n * What to do when a runtime decision returns `escalate` (a human must\n * approve). Only applies when `useRuntimeControl` is true.\n * - `wait` (default) block and poll until a human approves/denies, or the\n * timeout elapses (→ deny). Requires the `runtime:decide` scope.\n * - `deny` fail closed without waiting.\n * - `allow` proceed (fail OPEN — dev/trusted use only).\n * @default 'wait'\n */\n onEscalation?: EscalationPolicy;\n /** Timeout (ms) for `onEscalation: 'wait'`. @default 300000 */\n escalationTimeoutMs?: number;\n /**\n * Policy when the runtime gate can't reach the control plane.\n * `'deny'` fails closed (secure default); `'allow'` fails open.\n * @default 'deny'\n */\n onTransportFailure?: TransportFailurePolicy;\n /**\n * Replayable agent decision evidence (VAIP -02). When provided, the\n * hashes are attached to every audit event the registry emits.\n * If `replay.tools` is not given, the registry's own tool catalogue\n * (the tools you `add()`) is used automatically.\n *\n * Not covered by the v0 canonical signature form; advisory only.\n */\n replay?: ReplayInputs;\n}\n\n// ─── Tool Registry ────────────────────────────────────────────────────────\n\n/**\n * Manages a set of tools with Vorim permission checks and audit logging.\n * Converts tools to OpenAI's `ChatCompletionTool` format and handles\n * execution of tool calls from the model's response.\n *\n * @example\n * ```ts\n * import OpenAI from \"openai\";\n * import createVorim from \"@vorim/sdk\";\n * import { VorimToolRegistry } from \"@vorim/sdk/integrations/openai\";\n *\n * const vorim = createVorim({ apiKey: \"agid_sk_live_...\" });\n * const openai = new OpenAI();\n *\n * const registry = new VorimToolRegistry({\n * vorim,\n * agentId: \"agid_acme_a1b2c3d4\",\n * });\n *\n * registry.add({\n * name: \"search_docs\",\n * description: \"Search internal documents\",\n * parameters: {\n * type: \"object\",\n * properties: { query: { type: \"string\" } },\n * required: [\"query\"],\n * },\n * execute: async ({ query }) => searchDocs(query),\n * permission: \"agent:read\",\n * });\n *\n * // Use with OpenAI chat completions\n * const response = await openai.chat.completions.create({\n * model: \"gpt-4o\",\n * messages,\n * tools: registry.toOpenAITools(),\n * });\n *\n * // Execute tool calls from the response\n * const toolMessages = await registry.executeToolCalls(\n * response.choices[0].message.tool_calls ?? []\n * );\n * ```\n */\nexport class VorimToolRegistry {\n private vorim: VorimSDK;\n private agentId: string;\n private defaultPermission: PermissionScope;\n private asyncAudit: boolean;\n private useRuntimeControl: boolean;\n private onEscalation?: EscalationPolicy;\n private escalationTimeoutMs?: number;\n private onTransportFailure?: TransportFailurePolicy;\n private tools = new Map<string, VorimToolDefinition>();\n private replayInputs: ReplayInputs | undefined;\n private replayCache: Promise<ReplayContext> | null = null;\n\n constructor(config: VorimOpenAIConfig) {\n this.vorim = config.vorim;\n this.agentId = config.agentId;\n this.defaultPermission = config.defaultPermission ?? 'agent:execute';\n this.asyncAudit = config.asyncAudit ?? true;\n this.useRuntimeControl = config.useRuntimeControl ?? false;\n this.onEscalation = config.onEscalation;\n this.escalationTimeoutMs = config.escalationTimeoutMs;\n this.onTransportFailure = config.onTransportFailure;\n this.replayInputs = config.replay;\n }\n\n /**\n * Gate a tool call. When useRuntimeControl is on, run the full runtime\n * decision (beforeAction) and surface its decisionId for audit linkage;\n * otherwise use the lightweight permission check.\n */\n private async gate(\n scope: PermissionScope,\n actionTarget: string,\n payload?: Record<string, unknown>,\n ): Promise<{ allowed: boolean; reason?: string; decisionId?: string }> {\n if (this.useRuntimeControl) {\n // runtimeGate handles transport-failure fallbacks internally, but a\n // non-transport VorimError from beforeAction (e.g. 403 missing\n // runtime:decide scope, 400 validation) still throws — wrap so it\n // fails closed instead of crashing the host tool loop. Matches the\n // Python _gate try/except.\n try {\n return await runtimeGate(this.vorim, this.agentId, actionTarget, scope, payload, {\n onEscalation: this.onEscalation,\n escalationTimeoutMs: this.escalationTimeoutMs,\n onTransportFailure: this.onTransportFailure,\n });\n } catch {\n return { allowed: false, reason: 'runtime gate unavailable (failed closed)' };\n }\n }\n // Fail closed on a permission-check transport error (API down, 5xx,\n // network/DNS/timeout) instead of letting the rejection crash the host\n // tool loop. Mirrors the Python _safe_check fail-closed behaviour.\n try {\n const { allowed, reason } = await this.vorim.check(this.agentId, scope);\n return { allowed, reason };\n } catch {\n return { allowed: false, reason: 'permission check unavailable (failed closed)' };\n }\n }\n\n private async getReplayContext(): Promise<ReplayContext> {\n if (!this.replayInputs) return {};\n if (!this.replayCache) {\n // If caller didn't supply tools, derive them from the registry.\n const inputs: ReplayInputs = {\n ...this.replayInputs,\n tools: this.replayInputs.tools ?? this.deriveCatalogue(),\n };\n this.replayCache = prepareReplayContext(inputs);\n }\n return this.replayCache;\n }\n\n private deriveCatalogue(): CatalogueTool[] {\n return [...this.tools.values()].map(t => ({\n name: t.name,\n description: t.description,\n schema: t.parameters,\n }));\n }\n\n /** Register a tool. Invalidates the cached tool-catalogue hash. */\n add<TArgs, TResult>(definition: VorimToolDefinition<TArgs, TResult>): this {\n this.tools.set(definition.name, definition as VorimToolDefinition);\n this.replayCache = null;\n return this;\n }\n\n /** Register multiple tools. */\n addAll(definitions: VorimToolDefinition[]): this {\n for (const def of definitions) this.add(def);\n return this;\n }\n\n /** Convert registered tools to OpenAI's ChatCompletionTool format. */\n toOpenAITools(): ChatCompletionTool[] {\n return [...this.tools.values()].map(t => ({\n type: 'function' as const,\n function: {\n name: t.name,\n description: t.description,\n parameters: t.parameters,\n ...(t.strict != null ? { strict: t.strict } : {}),\n },\n }));\n }\n\n /**\n * Execute tool calls from an OpenAI chat completion response.\n * Each call is checked against Vorim permissions and audited.\n * Returns an array of tool messages ready to append to the conversation.\n */\n async executeToolCalls(toolCalls: ToolCall[]): Promise<ToolMessage[]> {\n const results = await Promise.all(\n toolCalls.map(tc => this.executeSingleCall(tc)),\n );\n return results;\n }\n\n private async executeSingleCall(toolCall: ToolCall): Promise<ToolMessage> {\n const { id, function: fn } = toolCall;\n const definition = this.tools.get(fn.name);\n\n if (!definition) {\n return {\n role: 'tool',\n tool_call_id: id,\n content: JSON.stringify({ error: `Unknown tool: ${fn.name}` }),\n };\n }\n\n const scope = definition.permission ?? this.defaultPermission;\n let args: unknown;\n try {\n args = JSON.parse(fn.arguments);\n } catch {\n return {\n role: 'tool',\n tool_call_id: id,\n content: JSON.stringify({ error: `Invalid JSON arguments for ${fn.name}` }),\n };\n }\n\n // 1. Gate: runtime decision (with decisionId linkage) or permission check.\n const { allowed, reason, decisionId } = await this.gate(scope, fn.name, args as Record<string, unknown>);\n const replayCtx = await this.getReplayContext();\n\n if (!allowed) {\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: fn.name,\n resource: truncate(fn.arguments, 500),\n permission: scope,\n result: 'denied',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { reason, framework: 'openai' },\n ...replayCtx,\n };\n await this.emitAudit(event);\n return {\n role: 'tool',\n tool_call_id: id,\n content: JSON.stringify({ error: `Permission denied: ${scope}${reason ? ` — ${reason}` : ''}` }),\n };\n }\n\n // 2. Execute\n const start = Date.now();\n try {\n const result = await definition.execute(args as any);\n const content = typeof result === 'string' ? result : JSON.stringify(result);\n\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: fn.name,\n resource: truncate(fn.arguments, 500),\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { framework: 'openai' },\n ...replayCtx,\n };\n await this.emitAudit(event);\n\n return { role: 'tool', tool_call_id: id, content };\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: fn.name,\n resource: truncate(fn.arguments, 500),\n permission: scope,\n result: 'error',\n latency_ms: Date.now() - start,\n error_code: err instanceof Error ? err.name : 'UNKNOWN',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { error: errMsg, framework: 'openai' },\n ...replayCtx,\n };\n await this.emitAudit(event);\n\n return {\n role: 'tool',\n tool_call_id: id,\n content: JSON.stringify({ error: errMsg }),\n };\n }\n }\n\n private async emitAudit(event: AuditEventInput): Promise<void> {\n if (this.asyncAudit) {\n // Fire-and-forget: don't block the tool pipeline on the audit write.\n this.vorim.emit(event).catch(() => {});\n } else {\n // Synchronous mode: actually await so the audit is flushed before the\n // caller continues. (Previously both branches were identical and the\n // promise was never awaited — asyncAudit=false did nothing.)\n try { await this.vorim.emit(event); } catch { /* best-effort */ }\n }\n }\n}\n\n// ─── Agent Loop ───────────────────────────────────────────────────────────\n\nexport interface VorimAgentLoopConfig extends VorimOpenAIConfig {\n /** OpenAI client instance. */\n openai: OpenAIClient;\n /** Model to use. @default 'gpt-4o' */\n model?: string;\n /** System prompt for the agent. */\n systemPrompt?: string;\n /** Maximum iterations before stopping. @default 10 */\n maxIterations?: number;\n}\n\n/** Minimal OpenAI client interface (avoids importing the full SDK). */\ninterface OpenAIClient {\n chat: {\n completions: {\n create(params: any): Promise<any>;\n };\n };\n}\n\n/**\n * Runs a complete agent loop with OpenAI function calling, Vorim\n * permission enforcement, and audit logging.\n *\n * @example\n * ```ts\n * import OpenAI from \"openai\";\n * import createVorim from \"@vorim/sdk\";\n * import { runAgentLoop, VorimToolRegistry } from \"@vorim/sdk/integrations/openai\";\n *\n * const registry = new VorimToolRegistry({ vorim, agentId });\n * registry.add({ name: \"search\", ... });\n *\n * const response = await runAgentLoop({\n * vorim,\n * agentId,\n * openai: new OpenAI(),\n * model: \"gpt-4o\",\n * systemPrompt: \"You are a helpful assistant.\",\n * registry,\n * userMessage: \"Find docs about onboarding\",\n * });\n * ```\n */\nexport async function runAgentLoop(\n config: VorimAgentLoopConfig & {\n registry: VorimToolRegistry;\n userMessage: string;\n },\n): Promise<string> {\n const { openai, model = 'gpt-4o', systemPrompt, maxIterations = 10, registry, userMessage } = config;\n\n const messages: any[] = [];\n if (systemPrompt) messages.push({ role: 'system', content: systemPrompt });\n messages.push({ role: 'user', content: userMessage });\n\n const tools = registry.toOpenAITools();\n\n for (let i = 0; i < maxIterations; i++) {\n const response = await openai.chat.completions.create({\n model,\n messages,\n ...(tools.length > 0 ? { tools } : {}),\n });\n\n const choice = response.choices[0];\n messages.push(choice.message);\n\n // If the model is done (no tool calls), return the response\n if (choice.finish_reason === 'stop' || !choice.message.tool_calls?.length) {\n return choice.message.content ?? '';\n }\n\n // Execute tool calls and add results to messages\n const toolMessages = await registry.executeToolCalls(choice.message.tool_calls);\n messages.push(...toolMessages);\n }\n\n return messages[messages.length - 1]?.content ?? '';\n}\n\n// ─── Agent Registration Helper ───────────────────────────────────────────\n\n/**\n * Registers a new agent with Vorim and returns a ready-to-use tool registry.\n *\n * @example\n * ```ts\n * const { agentId, registry } = await createVorimOpenAIAgent({\n * vorim,\n * name: \"support-agent\",\n * capabilities: [\"search\", \"email\"],\n * scopes: [\"agent:read\", \"agent:execute\", \"agent:communicate\"],\n * tools: [searchTool, emailTool],\n * });\n * ```\n */\nexport async function createVorimOpenAIAgent(config: {\n vorim: VorimSDK;\n name: string;\n description?: string;\n capabilities: string[];\n scopes: PermissionScope[];\n tools: VorimToolDefinition[];\n}) {\n const { vorim, name, description, capabilities, scopes, tools } = config;\n\n const registration = await vorim.register({\n name,\n description,\n capabilities,\n scopes,\n });\n\n const agentId = registration.agent.agent_id;\n\n const registry = new VorimToolRegistry({ vorim, agentId });\n registry.addAll(tools);\n\n return {\n agentId,\n registration,\n registry,\n privateKey: registration.private_key,\n };\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────────\n\nfunction truncate(str: string, max: number): string {\n return str.length > max ? str.slice(0, max) + '…' : str;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;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,MAAI,iBAAiB,SAAS;AAC5B,WAAO,EAAE,SAAS,MAAM,QAAQ,EAAE,UAAU,4BAA4B,YAAY,EAAE,cAA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