@vorim/sdk 4.2.0 → 4.3.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 (42) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/integrations/eu-providers.cjs +463 -0
  5. package/dist/integrations/eu-providers.cjs.map +1 -0
  6. package/dist/integrations/eu-providers.d.cts +123 -0
  7. package/dist/integrations/eu-providers.d.ts +123 -0
  8. package/dist/integrations/eu-providers.js +420 -0
  9. package/dist/integrations/eu-providers.js.map +1 -0
  10. package/dist/integrations/grok.cjs +9 -3
  11. package/dist/integrations/grok.cjs.map +1 -1
  12. package/dist/integrations/grok.js +9 -3
  13. package/dist/integrations/grok.js.map +1 -1
  14. package/dist/integrations/langchain.cjs +26 -7
  15. package/dist/integrations/langchain.cjs.map +1 -1
  16. package/dist/integrations/langchain.js +26 -7
  17. package/dist/integrations/langchain.js.map +1 -1
  18. package/dist/integrations/mistral.cjs +487 -0
  19. package/dist/integrations/mistral.cjs.map +1 -0
  20. package/dist/integrations/mistral.d.cts +133 -0
  21. package/dist/integrations/mistral.d.ts +133 -0
  22. package/dist/integrations/mistral.js +439 -0
  23. package/dist/integrations/mistral.js.map +1 -0
  24. package/dist/integrations/muse.cjs +9 -3
  25. package/dist/integrations/muse.cjs.map +1 -1
  26. package/dist/integrations/muse.js +9 -3
  27. package/dist/integrations/muse.js.map +1 -1
  28. package/dist/integrations/openai.cjs +9 -3
  29. package/dist/integrations/openai.cjs.map +1 -1
  30. package/dist/integrations/openai.d.cts +10 -0
  31. package/dist/integrations/openai.d.ts +10 -0
  32. package/dist/integrations/openai.js +9 -3
  33. package/dist/integrations/openai.js.map +1 -1
  34. package/dist/integrations/openrouter.cjs +9 -3
  35. package/dist/integrations/openrouter.cjs.map +1 -1
  36. package/dist/integrations/openrouter.js +9 -3
  37. package/dist/integrations/openrouter.js.map +1 -1
  38. package/dist/integrations/perplexity.cjs +9 -3
  39. package/dist/integrations/perplexity.cjs.map +1 -1
  40. package/dist/integrations/perplexity.js +9 -3
  41. package/dist/integrations/perplexity.js.map +1 -1
  42. package/package.json +21 -1
@@ -0,0 +1,439 @@
1
+ // src/integrations/_runtime-gate.ts
2
+ function isAllowVerdict(decision) {
3
+ return decision === "allow" || decision === "modify";
4
+ }
5
+ async function runtimeGate(vorim, agentId, actionTarget, scope, payload, opts = {}) {
6
+ const onEscalation = opts.onEscalation ?? "wait";
7
+ const onTransportFailure = opts.onTransportFailure ?? "deny";
8
+ const d = await vorim.beforeAction(
9
+ { agentId, actionType: "tool_call", actionTarget, requiredScope: scope, payload },
10
+ { throwOnDeny: false }
11
+ );
12
+ if (d.isFallback || d.decision === "fallback") {
13
+ if (onTransportFailure === "allow") {
14
+ return { allowed: true, reason: d.reason ?? "control plane unreachable (fail-open)", decisionId: d.decisionId || void 0 };
15
+ }
16
+ return { allowed: false, reason: d.reason ?? "control plane unreachable (failed closed)", decisionId: d.decisionId || void 0 };
17
+ }
18
+ if (d.decision !== "escalate") {
19
+ return { allowed: isAllowVerdict(d.decision), reason: d.reason, decisionId: d.decisionId || void 0 };
20
+ }
21
+ if (onEscalation === "allow") {
22
+ return { allowed: true, reason: d.reason ?? "escalated (auto-allowed)", decisionId: d.decisionId || void 0 };
23
+ }
24
+ if (onEscalation === "deny") {
25
+ return { allowed: false, reason: d.reason ?? "escalated (auto-denied \u2014 awaiting human)", decisionId: d.decisionId || void 0 };
26
+ }
27
+ if (!d.decisionId) {
28
+ return { allowed: false, reason: "escalated but no decisionId to poll", decisionId: void 0 };
29
+ }
30
+ try {
31
+ const resolved = await vorim.waitForDecisionResolution(d.decisionId, { timeoutMs: opts.escalationTimeoutMs });
32
+ return { allowed: isAllowVerdict(resolved.decision), reason: resolved.reason, decisionId: resolved.decisionId || d.decisionId };
33
+ } catch {
34
+ return { allowed: false, reason: "escalation not resolved before timeout", decisionId: d.decisionId };
35
+ }
36
+ }
37
+
38
+ // src/replay.ts
39
+ function jcsCanonicalise(value) {
40
+ if (value === null) return "null";
41
+ if (value === true) return "true";
42
+ if (value === false) return "false";
43
+ if (typeof value === "number") {
44
+ if (!Number.isFinite(value)) {
45
+ throw new Error("jcsCanonicalise: NaN and Infinity are not JCS-valid");
46
+ }
47
+ const abs = Math.abs(value);
48
+ if (value !== 0 && (abs >= 1e21 || abs < 1e-4 || Number.isInteger(value) && abs > 2 ** 53)) {
49
+ throw new Error(
50
+ `jcsCanonicalise: numbers in the ranges where JS and Python formatting diverge (|x| >= 1e21, |x| < 1e-4, or integer |x| > 2^53) are not supported in signed metadata. Use a string instead of ${value}.`
51
+ );
52
+ }
53
+ return value.toString();
54
+ }
55
+ if (typeof value === "string") {
56
+ return JSON.stringify(value);
57
+ }
58
+ if (Array.isArray(value)) {
59
+ return "[" + value.map(jcsCanonicalise).join(",") + "]";
60
+ }
61
+ if (typeof value === "object") {
62
+ const obj = value;
63
+ const keys = Object.keys(obj).filter((k) => obj[k] !== void 0).sort();
64
+ const parts = keys.map((k) => JSON.stringify(k) + ":" + jcsCanonicalise(obj[k]));
65
+ return "{" + parts.join(",") + "}";
66
+ }
67
+ throw new Error(`jcsCanonicalise: unsupported value type: ${typeof value}`);
68
+ }
69
+ async function sha256Hex(input) {
70
+ const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
71
+ const subtle = globalThis.crypto?.subtle;
72
+ if (subtle) {
73
+ const buf = await subtle.digest("SHA-256", bytes);
74
+ return Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, "0")).join("");
75
+ }
76
+ const nodeCrypto = await import("crypto");
77
+ return nodeCrypto.createHash("sha256").update(bytes).digest("hex");
78
+ }
79
+ async function hashTool(tool) {
80
+ const normalised = {
81
+ name: tool.name,
82
+ description: tool.description ?? "",
83
+ schema: tool.schema ?? {}
84
+ };
85
+ const hex = await sha256Hex(jcsCanonicalise(normalised));
86
+ return `sha256:${hex}`;
87
+ }
88
+ async function hashToolCatalogue(tools) {
89
+ if (tools.length === 0) {
90
+ return `sha256:${await sha256Hex("[]")}`;
91
+ }
92
+ const perTool = await Promise.all(tools.map(hashTool));
93
+ perTool.sort();
94
+ const hex = await sha256Hex(perTool.join(""));
95
+ return `sha256:${hex}`;
96
+ }
97
+ async function hashSystemPrompt(prompt) {
98
+ const hex = await sha256Hex(prompt);
99
+ return `sha256:${hex}`;
100
+ }
101
+ async function prepareReplayContext(inputs) {
102
+ const ctx = {};
103
+ if (inputs.modelVersion) ctx.model_version = inputs.modelVersion;
104
+ if (inputs.tools) ctx.tool_catalogue_hash = await hashToolCatalogue(inputs.tools);
105
+ if (inputs.systemPrompt) ctx.system_prompt_hash = await hashSystemPrompt(inputs.systemPrompt);
106
+ return ctx;
107
+ }
108
+
109
+ // src/integrations/openai.ts
110
+ var VorimToolRegistry = class {
111
+ vorim;
112
+ agentId;
113
+ defaultPermission;
114
+ asyncAudit;
115
+ useRuntimeControl;
116
+ onEscalation;
117
+ escalationTimeoutMs;
118
+ onTransportFailure;
119
+ tools = /* @__PURE__ */ new Map();
120
+ replayInputs;
121
+ replayCache = null;
122
+ framework;
123
+ constructor(config) {
124
+ this.framework = config.framework ?? "openai";
125
+ this.vorim = config.vorim;
126
+ this.agentId = config.agentId;
127
+ this.defaultPermission = config.defaultPermission ?? "agent:execute";
128
+ this.asyncAudit = config.asyncAudit ?? true;
129
+ this.useRuntimeControl = config.useRuntimeControl ?? false;
130
+ this.onEscalation = config.onEscalation;
131
+ this.escalationTimeoutMs = config.escalationTimeoutMs;
132
+ this.onTransportFailure = config.onTransportFailure;
133
+ this.replayInputs = config.replay;
134
+ }
135
+ /**
136
+ * Gate a tool call. When useRuntimeControl is on, run the full runtime
137
+ * decision (beforeAction) and surface its decisionId for audit linkage;
138
+ * otherwise use the lightweight permission check.
139
+ */
140
+ async gate(scope, actionTarget, payload) {
141
+ if (this.useRuntimeControl) {
142
+ try {
143
+ return await runtimeGate(this.vorim, this.agentId, actionTarget, scope, payload, {
144
+ onEscalation: this.onEscalation,
145
+ escalationTimeoutMs: this.escalationTimeoutMs,
146
+ onTransportFailure: this.onTransportFailure
147
+ });
148
+ } catch {
149
+ return { allowed: false, reason: "runtime gate unavailable (failed closed)" };
150
+ }
151
+ }
152
+ try {
153
+ const { allowed, reason } = await this.vorim.check(this.agentId, scope);
154
+ return { allowed, reason };
155
+ } catch {
156
+ return { allowed: false, reason: "permission check unavailable (failed closed)" };
157
+ }
158
+ }
159
+ async getReplayContext() {
160
+ if (!this.replayInputs) return {};
161
+ if (!this.replayCache) {
162
+ const inputs = {
163
+ ...this.replayInputs,
164
+ tools: this.replayInputs.tools ?? this.deriveCatalogue()
165
+ };
166
+ this.replayCache = prepareReplayContext(inputs);
167
+ }
168
+ return this.replayCache;
169
+ }
170
+ deriveCatalogue() {
171
+ return [...this.tools.values()].map((t) => ({
172
+ name: t.name,
173
+ description: t.description,
174
+ schema: t.parameters
175
+ }));
176
+ }
177
+ /** Register a tool. Invalidates the cached tool-catalogue hash. */
178
+ add(definition) {
179
+ this.tools.set(definition.name, definition);
180
+ this.replayCache = null;
181
+ return this;
182
+ }
183
+ /** Register multiple tools. */
184
+ /** Whether a tool with this name is registered. */
185
+ has(name) {
186
+ return this.tools.has(name);
187
+ }
188
+ addAll(definitions) {
189
+ for (const def of definitions) this.add(def);
190
+ return this;
191
+ }
192
+ /** Convert registered tools to OpenAI's ChatCompletionTool format. */
193
+ toOpenAITools() {
194
+ return [...this.tools.values()].map((t) => ({
195
+ type: "function",
196
+ function: {
197
+ name: t.name,
198
+ description: t.description,
199
+ parameters: t.parameters,
200
+ ...t.strict != null ? { strict: t.strict } : {}
201
+ }
202
+ }));
203
+ }
204
+ /**
205
+ * Execute tool calls from an OpenAI chat completion response.
206
+ * Each call is checked against Vorim permissions and audited.
207
+ * Returns an array of tool messages ready to append to the conversation.
208
+ */
209
+ async executeToolCalls(toolCalls) {
210
+ const results = await Promise.all(
211
+ toolCalls.map((tc) => this.executeSingleCall(tc))
212
+ );
213
+ return results;
214
+ }
215
+ async executeSingleCall(toolCall) {
216
+ const { id, function: fn } = toolCall;
217
+ const definition = this.tools.get(fn.name);
218
+ if (!definition) {
219
+ return {
220
+ role: "tool",
221
+ tool_call_id: id,
222
+ content: JSON.stringify({ error: `Unknown tool: ${fn.name}` })
223
+ };
224
+ }
225
+ const scope = definition.permission ?? this.defaultPermission;
226
+ let args;
227
+ try {
228
+ args = JSON.parse(fn.arguments);
229
+ } catch {
230
+ return {
231
+ role: "tool",
232
+ tool_call_id: id,
233
+ content: JSON.stringify({ error: `Invalid JSON arguments for ${fn.name}` })
234
+ };
235
+ }
236
+ const { allowed, reason, decisionId } = await this.gate(scope, fn.name, args);
237
+ const replayCtx = await this.getReplayContext();
238
+ if (!allowed) {
239
+ const event = {
240
+ agent_id: this.agentId,
241
+ event_type: "tool_call",
242
+ action: fn.name,
243
+ resource: truncate(fn.arguments, 500),
244
+ permission: scope,
245
+ result: "denied",
246
+ ...decisionId ? { decision_id: decisionId } : {},
247
+ metadata: { reason, framework: this.framework },
248
+ ...replayCtx
249
+ };
250
+ await this.emitAudit(event);
251
+ return {
252
+ role: "tool",
253
+ tool_call_id: id,
254
+ content: JSON.stringify({ error: `Permission denied: ${scope}${reason ? ` \u2014 ${reason}` : ""}` })
255
+ };
256
+ }
257
+ const start = Date.now();
258
+ try {
259
+ const result = await definition.execute(args);
260
+ const content = typeof result === "string" ? result : JSON.stringify(result);
261
+ const event = {
262
+ agent_id: this.agentId,
263
+ event_type: "tool_call",
264
+ action: fn.name,
265
+ resource: truncate(fn.arguments, 500),
266
+ permission: scope,
267
+ result: "success",
268
+ latency_ms: Date.now() - start,
269
+ ...decisionId ? { decision_id: decisionId } : {},
270
+ metadata: { framework: this.framework },
271
+ ...replayCtx
272
+ };
273
+ await this.emitAudit(event);
274
+ return { role: "tool", tool_call_id: id, content };
275
+ } catch (err) {
276
+ const errMsg = err instanceof Error ? err.message : String(err);
277
+ const event = {
278
+ agent_id: this.agentId,
279
+ event_type: "tool_call",
280
+ action: fn.name,
281
+ resource: truncate(fn.arguments, 500),
282
+ permission: scope,
283
+ result: "error",
284
+ latency_ms: Date.now() - start,
285
+ error_code: err instanceof Error ? err.name : "UNKNOWN",
286
+ ...decisionId ? { decision_id: decisionId } : {},
287
+ metadata: { error: errMsg, framework: this.framework },
288
+ ...replayCtx
289
+ };
290
+ await this.emitAudit(event);
291
+ return {
292
+ role: "tool",
293
+ tool_call_id: id,
294
+ content: JSON.stringify({ error: errMsg })
295
+ };
296
+ }
297
+ }
298
+ async emitAudit(event) {
299
+ if (this.asyncAudit) {
300
+ this.vorim.emit(event).catch(() => {
301
+ });
302
+ } else {
303
+ try {
304
+ await this.vorim.emit(event);
305
+ } catch {
306
+ }
307
+ }
308
+ }
309
+ };
310
+ function truncate(str, max) {
311
+ return str.length > max ? str.slice(0, max) + "\u2026" : str;
312
+ }
313
+
314
+ // src/integrations/mistral.ts
315
+ var MISTRAL_BASE_URL = "https://api.mistral.ai/v1";
316
+ var MISTRAL_EU_BASE_URL = "https://api.eu.mistral.ai/v1";
317
+ var MISTRAL_US_BASE_URL = "https://api.us.mistral.ai/v1";
318
+ var DEFAULT_MISTRAL_MODEL = "mistral-medium-latest";
319
+ var MISTRAL_SMALL_MODEL = "mistral-small-latest";
320
+ var MISTRAL_CODE_MODEL = "codestral-latest";
321
+ function createMistralRegistry(config) {
322
+ return new VorimToolRegistry({ ...config, framework: config.framework ?? "mistral" });
323
+ }
324
+ function normaliseMistralToolCalls(calls) {
325
+ return (calls ?? []).map((c, i) => ({
326
+ id: c.id && c.id !== "null" ? c.id : `mistral_call_${i}`,
327
+ type: "function",
328
+ function: {
329
+ name: c.function.name,
330
+ arguments: typeof c.function.arguments === "string" ? c.function.arguments : JSON.stringify(c.function.arguments ?? {})
331
+ }
332
+ }));
333
+ }
334
+ function isSdkClient(c) {
335
+ return typeof c?.chat?.complete === "function";
336
+ }
337
+ async function runMistralAgentLoop(config) {
338
+ const { mistral, registry, userMessage, systemPrompt, model = DEFAULT_MISTRAL_MODEL, maxIterations = 10 } = config;
339
+ const sdk = isSdkClient(mistral);
340
+ const messages = [];
341
+ if (systemPrompt) messages.push({ role: "system", content: systemPrompt });
342
+ messages.push({ role: "user", content: userMessage });
343
+ const tools = registry.toOpenAITools();
344
+ for (let i = 0; i < maxIterations; i++) {
345
+ const args = { model, messages, ...tools.length ? { tools } : {} };
346
+ if (config.parallelToolCalls != null) args[sdk ? "parallelToolCalls" : "parallel_tool_calls"] = config.parallelToolCalls;
347
+ const res = sdk ? await mistral.chat.complete(args) : await mistral.chat.completions.create(args);
348
+ const choice = res?.choices?.[0];
349
+ if (!choice) return "";
350
+ const msg = choice.message ?? {};
351
+ const rawCalls = sdk ? msg.toolCalls : msg.tool_calls;
352
+ const finish = sdk ? choice.finishReason : choice.finish_reason;
353
+ const calls = normaliseMistralToolCalls(rawCalls);
354
+ if (!calls.length || finish !== "tool_calls") {
355
+ return typeof msg.content === "string" ? msg.content : contentText(msg.content);
356
+ }
357
+ messages.push(sdk ? { role: "assistant", content: msg.content ?? "", toolCalls: calls } : { role: "assistant", content: msg.content ?? "", tool_calls: calls });
358
+ const results = await registry.executeToolCalls(calls);
359
+ for (const r of results) {
360
+ const name = calls.find((c) => c.id === r.tool_call_id)?.function.name;
361
+ messages.push(sdk ? { role: "tool", toolCallId: r.tool_call_id, name, content: r.content } : { role: "tool", tool_call_id: r.tool_call_id, name, content: r.content });
362
+ }
363
+ }
364
+ const last = messages[messages.length - 1];
365
+ return typeof last?.content === "string" ? last.content : "";
366
+ }
367
+ function contentText(content) {
368
+ if (!Array.isArray(content)) return "";
369
+ return content.map((c) => c?.type === "text" && typeof c.text === "string" ? c.text : "").join("");
370
+ }
371
+ var callId = (e, i) => e.tool_call_id ?? e.toolCallId ?? `mistral_call_${i}`;
372
+ var pending = (e) => (e.confirmation_status ?? e.confirmationStatus) === "pending";
373
+ async function executeMistralFunctionCalls(registry, outputs) {
374
+ const calls = (outputs ?? []).map((e, i) => ({ e, id: callId(e, i) })).filter(({ e }) => e.type === "function.call" && !pending(e) && registry.has(e.name));
375
+ if (!calls.length) return [];
376
+ const results = await registry.executeToolCalls(normaliseMistralToolCalls(
377
+ calls.map(({ e, id }) => ({ id, function: { name: e.name, arguments: e.arguments } }))
378
+ ));
379
+ return results.map((r) => ({ type: "function.result", tool_call_id: r.tool_call_id, result: r.content }));
380
+ }
381
+ async function decideMistralConfirmations(config, outputs) {
382
+ const out = [];
383
+ const entries = (outputs ?? []).map((e, i) => ({ e, id: callId(e, i) })).filter(({ e }) => e.type === "function.call" && pending(e));
384
+ for (const { e, id } of entries) {
385
+ const scope = config.scopes?.[e.name] ?? config.defaultPermission ?? "agent:execute";
386
+ const argsText = typeof e.arguments === "string" ? e.arguments : JSON.stringify(e.arguments ?? {});
387
+ let payload;
388
+ try {
389
+ payload = typeof e.arguments === "string" ? JSON.parse(e.arguments) : e.arguments;
390
+ } catch {
391
+ payload = void 0;
392
+ }
393
+ let allowed = false;
394
+ let reason;
395
+ let decisionId;
396
+ try {
397
+ if (config.useRuntimeControl) {
398
+ ({ allowed, reason, decisionId } = await runtimeGate(config.vorim, config.agentId, e.name, scope, payload, {
399
+ onEscalation: config.onEscalation,
400
+ escalationTimeoutMs: config.escalationTimeoutMs,
401
+ onTransportFailure: config.onTransportFailure
402
+ }));
403
+ } else {
404
+ ({ allowed, reason } = await config.vorim.check(config.agentId, scope));
405
+ }
406
+ } catch {
407
+ allowed = false;
408
+ reason = "Vorim unavailable (failed closed)";
409
+ }
410
+ out.push({ tool_call_id: id, confirmation: allowed ? "allow" : "deny" });
411
+ config.vorim.emit({
412
+ agent_id: config.agentId,
413
+ event_type: "tool_call",
414
+ action: e.name,
415
+ resource: argsText.slice(0, 500),
416
+ permission: scope,
417
+ result: allowed ? "success" : "denied",
418
+ ...decisionId ? { decision_id: decisionId } : {},
419
+ metadata: { framework: "mistral", stage: "confirmation", executed_by: "mistral", ...reason ? { reason } : {} }
420
+ }).catch(() => {
421
+ });
422
+ }
423
+ return out;
424
+ }
425
+ export {
426
+ DEFAULT_MISTRAL_MODEL,
427
+ MISTRAL_BASE_URL,
428
+ MISTRAL_CODE_MODEL,
429
+ MISTRAL_EU_BASE_URL,
430
+ MISTRAL_SMALL_MODEL,
431
+ MISTRAL_US_BASE_URL,
432
+ VorimToolRegistry,
433
+ createMistralRegistry,
434
+ decideMistralConfirmations,
435
+ executeMistralFunctionCalls,
436
+ normaliseMistralToolCalls,
437
+ runMistralAgentLoop
438
+ };
439
+ //# sourceMappingURL=mistral.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/integrations/_runtime-gate.ts","../../src/replay.ts","../../src/integrations/openai.ts","../../src/integrations/mistral.ts"],"sourcesContent":["// ============================================================================\n// VORIM SDK — Shared runtime-gate helper for framework integrations\n//\n// All tool-wrapping integrations (Vercel, OpenAI, Anthropic, …) turn a\n// `beforeAction` runtime decision into a simple { allowed, reason, decisionId }\n// the wrapper can act on. The subtlety is the `escalate` verdict: it is NOT a\n// denial — it means a human must approve the action. Folding it into\n// `allowed=false` silently breaks every human-in-the-loop flow; folding it into\n// `allowed=true` is a fail-open security hole. So this helper resolves the\n// escalation explicitly, driven by the caller's `onEscalation` preference.\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { RuntimeDecision, PermissionScope } from '../types.js';\n\n/**\n * How a framework integration should treat a runtime `escalate` verdict.\n * - `wait` — block and poll {@link VorimSDK.waitForDecisionResolution} until a\n * human approves/denies (or the timeout elapses → deny). The correct\n * default for human-in-the-loop: an escalation means \"ask a human\".\n * - `deny` — treat escalate as a denial (fail closed without waiting).\n * - `allow` — treat escalate as allowed (fail OPEN — only for trusted/dev use).\n */\nexport type EscalationPolicy = 'wait' | 'deny' | 'allow';\n\n/**\n * How a framework integration should treat a transport-failure `fallback`\n * decision (the control plane was unreachable and the SDK's\n * `runtimeFailOpen` produced a synthetic `decision: 'fallback'`,\n * `isFallback: true`).\n * - `deny` — fail closed: a control-plane outage denies the tool call.\n * The correct default for a SECURITY gate the caller opted into\n * via `useRuntimeControl: true`.\n * - `allow` — fail open: let the action proceed when the policy plane is\n * down (matches the raw SDK `runtimeFailOpen` behaviour).\n */\nexport type TransportFailurePolicy = 'deny' | 'allow';\n\nexport interface RuntimeGateOptions {\n /** What to do on an `escalate` verdict. @default 'wait' */\n onEscalation?: EscalationPolicy;\n /** Timeout (ms) for `onEscalation: 'wait'`. @default 300000 (5 min) */\n escalationTimeoutMs?: number;\n /**\n * What to do when the control plane is unreachable and `beforeAction`\n * returns a synthetic `fallback` decision. @default 'deny'\n *\n * The gate fails CLOSED on a policy-plane outage by default: a user who\n * turned on `useRuntimeControl: true` wants live deny/escalate\n * enforcement, so an outage should not silently auto-allow. Set to\n * `'allow'` to keep the old fail-open behaviour.\n */\n onTransportFailure?: TransportFailurePolicy;\n}\n\nexport interface GateResult {\n allowed: boolean;\n reason?: string;\n decisionId?: string;\n}\n\n/**\n * True for verdicts that permit the action to proceed. `escalate` is handled\n * separately. `fallback` is NOT treated as an allow here — a transport-failure\n * fallback is resolved explicitly via `onTransportFailure` so a control-plane\n * outage can't silently auto-allow inside a security gate.\n */\nfunction isAllowVerdict(decision: RuntimeDecision['decision']): boolean {\n return decision === 'allow' || decision === 'modify';\n}\n\n/**\n * Run a `beforeAction` runtime decision and collapse it to a {@link GateResult},\n * resolving `escalate` per {@link RuntimeGateOptions.onEscalation}.\n *\n * Requires (for `onEscalation: 'wait'`) an API key with the `runtime:decide`\n * scope — the same scope `beforeAction` itself uses.\n */\nexport async function runtimeGate(\n vorim: VorimSDK,\n agentId: string,\n actionTarget: string,\n scope: PermissionScope,\n payload: Record<string, unknown> | undefined,\n opts: RuntimeGateOptions = {},\n): Promise<GateResult> {\n const onEscalation = opts.onEscalation ?? 'wait';\n const onTransportFailure = opts.onTransportFailure ?? 'deny';\n const d = await vorim.beforeAction(\n { agentId, actionType: 'tool_call', actionTarget, requiredScope: scope, payload },\n { throwOnDeny: false },\n );\n\n // Control-plane outage: beforeAction returned a synthetic fallback\n // (isFallback). Govern it by onTransportFailure (default 'deny') rather\n // than auto-allowing — the caller turned on runtime control for live\n // enforcement, so an outage should fail closed unless they opt out.\n if (d.isFallback || d.decision === 'fallback') {\n if (onTransportFailure === 'allow') {\n return { allowed: true, reason: d.reason ?? 'control plane unreachable (fail-open)', decisionId: d.decisionId || undefined };\n }\n return { allowed: false, reason: d.reason ?? 'control plane unreachable (failed closed)', decisionId: d.decisionId || undefined };\n }\n\n if (d.decision !== 'escalate') {\n return { allowed: isAllowVerdict(d.decision), reason: d.reason, decisionId: d.decisionId || undefined };\n }\n\n // escalate ── a human must decide.\n if (onEscalation === 'allow') {\n return { allowed: true, reason: d.reason ?? 'escalated (auto-allowed)', decisionId: d.decisionId || undefined };\n }\n if (onEscalation === 'deny') {\n return { allowed: false, reason: d.reason ?? 'escalated (auto-denied — awaiting human)', decisionId: d.decisionId || undefined };\n }\n // 'wait' — poll for the human decision. On timeout, fail closed (deny).\n if (!d.decisionId) {\n return { allowed: false, reason: 'escalated but no decisionId to poll', decisionId: undefined };\n }\n try {\n const resolved = await vorim.waitForDecisionResolution(d.decisionId, { timeoutMs: opts.escalationTimeoutMs });\n return { allowed: isAllowVerdict(resolved.decision), reason: resolved.reason, decisionId: resolved.decisionId || d.decisionId };\n } catch {\n // ESCALATION_TIMEOUT (or any poll error) → fail closed.\n return { allowed: false, reason: 'escalation not resolved before timeout', decisionId: d.decisionId };\n }\n}\n","/**\n * 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 * Provider label written to each audit event's `metadata.framework`, so the\n * audit log says which API the call came through (e.g. `'mistral'`,\n * `'scaleway'`). Advisory, not covered by the signature.\n * @default 'openai'\n */\n framework?: string;\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 private framework: string;\n\n constructor(config: VorimOpenAIConfig) {\n this.framework = config.framework ?? 'openai';\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 /** Whether a tool with this name is registered. */\n has(name: string): boolean {\n return this.tools.has(name);\n }\n\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: this.framework },\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: this.framework },\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: this.framework },\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","// ============================================================================\n// VORIM SDK — Mistral AI Integration\n//\n// Gates and signs every custom function-tool call an agent makes through\n// Mistral, with the same VorimToolRegistry used for OpenAI. Works with either\n// client:\n// - the official Mistral SDK (`@mistralai/mistralai`, `mistral.chat.complete`,\n// camelCase fields: toolCalls, toolCallId, finishReason), or\n// - any OpenAI-compatible client pointed at MISTRAL_BASE_URL\n// (`chat.completions.create`, snake_case fields).\n// Mistral may return `function.arguments` as an object instead of a JSON\n// string, and tool-call ids are short strings (sometimes absent); the adapter\n// below normalises both before the registry sees them.\n//\n// Agents / Conversations API (beta at Mistral): custom function tools come\n// back as `function.call` outputs that YOUR code runs, so\n// `executeMistralFunctionCalls` gates + signs them and returns the\n// `function.result` entries to append. Tools that run on Mistral's side\n// (web_search, code_interpreter, image_generation, document_library, MCP\n// connectors) never pass through your code, BUT Mistral can pause them for\n// approval (`tool_configuration.requires_confirmation`). Pass those pending\n// calls to `decideMistralConfirmations` and Vorim answers allow / deny and\n// records the decision. A server-side tool without requires_confirmation is\n// not Vorim-attestable.\n//\n// EU data residency: `MISTRAL_EU_BASE_URL` (api.eu.mistral.ai) keeps inference\n// in EU/EFTA data centres. Per Mistral's docs, function calling is the only\n// tool supported there; Agents, Conversations and connectors are global-only.\n//\n// Built from Mistral's documentation and SDK sources (checked 2026-10-29) and\n// tested against mocked clients; not yet run against a live Mistral account.\n//\n// Peer dependency (pick one): @mistralai/mistralai >=1 or openai >=4.\n//\n// Usage:\n// import { Mistral } from '@mistralai/mistralai';\n// import createVorim from '@vorim/sdk';\n// import { createMistralRegistry, runMistralAgentLoop } from '@vorim/sdk/integrations/mistral';\n//\n// const vorim = createVorim({ apiKey: 'agid_sk_...' });\n// const mistral = new Mistral({ apiKey: process.env.MISTRAL_API_KEY, server: 'eu' });\n// const registry = createMistralRegistry({ vorim, agentId });\n// registry.add({ name: 'refund', description: '...', parameters: {...},\n// permission: 'agent:transact', execute: async (args) => {...} });\n// const answer = await runMistralAgentLoop({ vorim, agentId, mistral, registry,\n// userMessage: 'Refund order 1042' });\n//\n// MODEL IDS ARE CONFIG. `mistral-medium-latest` (Medium 3.5) is the current\n// general recommendation; Magistral and Devstral were retired on 2026-07-31.\n// Confirm against `GET /v1/models` and let callers override.\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope } from '../types.js';\nimport { VorimToolRegistry, type VorimOpenAIConfig } from './openai.js';\nimport { runtimeGate, type EscalationPolicy, type TransportFailurePolicy } from './_runtime-gate.js';\n\nexport { VorimToolRegistry } from './openai.js';\nexport type { VorimToolDefinition } from './openai.js';\n\n/** Global endpoint (Mistral does not commit to a location). */\nexport const MISTRAL_BASE_URL = 'https://api.mistral.ai/v1';\n/** EU/EFTA-only inference. Function calling only; no Agents or connectors. */\nexport const MISTRAL_EU_BASE_URL = 'https://api.eu.mistral.ai/v1';\n/** US-only inference. */\nexport const MISTRAL_US_BASE_URL = 'https://api.us.mistral.ai/v1';\n\n/** General-purpose default (alias of Mistral Medium 3.5). Overridable. */\nexport const DEFAULT_MISTRAL_MODEL = 'mistral-medium-latest';\n/** Small, cheap model (alias of Mistral Small 4). */\nexport const MISTRAL_SMALL_MODEL = 'mistral-small-latest';\n/** Code model (alias of Codestral). */\nexport const MISTRAL_CODE_MODEL = 'codestral-latest';\n\n/** A registry whose audit events say `framework: 'mistral'`. */\nexport function createMistralRegistry(config: Omit<VorimOpenAIConfig, 'framework'> & { framework?: string }): VorimToolRegistry {\n return new VorimToolRegistry({ ...config, framework: config.framework ?? 'mistral' });\n}\n\n// ─── Shape adapter ─────────────────────────────────────────────────────────\n\n/** A tool call as either client returns it. */\nexport interface MistralToolCallLike {\n id?: string | null;\n type?: string | null;\n function: { name: string; arguments: string | Record<string, unknown> };\n}\n\n/** The OpenAI shape the registry consumes (arguments always a JSON string). */\nexport interface NormalisedToolCall {\n id: string;\n type: 'function';\n function: { name: string; arguments: string };\n}\n\n/**\n * Normalise Mistral tool calls: stringify object arguments and give a missing\n * id a stable placeholder so the result can still be matched to its call.\n */\nexport function normaliseMistralToolCalls(calls: MistralToolCallLike[] | null | undefined): NormalisedToolCall[] {\n return (calls ?? []).map((c, i) => ({\n id: c.id && c.id !== 'null' ? c.id : `mistral_call_${i}`,\n type: 'function' as const,\n function: {\n name: c.function.name,\n arguments: typeof c.function.arguments === 'string' ? c.function.arguments : JSON.stringify(c.function.arguments ?? {}),\n },\n }));\n}\n\n// ─── Chat Completions agent loop ───────────────────────────────────────────\n\n/** Official SDK: `mistral.chat.complete(...)` with camelCase fields. */\ninterface MistralSdkClient { chat: { complete: (args: Record<string, unknown>) => Promise<any> } }\n/** OpenAI-compatible client pointed at a Mistral base URL. */\ninterface OpenAICompatibleClient { chat: { completions: { create: (args: Record<string, unknown>) => Promise<any> } } }\n\nexport interface RunMistralAgentLoopConfig {\n vorim: VorimSDK;\n agentId: string;\n /** `new Mistral({...})` from @mistralai/mistralai, or an OpenAI client with `baseURL: MISTRAL_BASE_URL`. */\n mistral: MistralSdkClient | OpenAICompatibleClient;\n registry: VorimToolRegistry;\n userMessage: string;\n /** @default DEFAULT_MISTRAL_MODEL */\n model?: string;\n systemPrompt?: string;\n /** @default 10 */\n maxIterations?: number;\n /** Forwarded as `parallelToolCalls` / `parallel_tool_calls` when set. */\n parallelToolCalls?: boolean;\n}\n\nfunction isSdkClient(c: unknown): c is MistralSdkClient {\n return typeof (c as any)?.chat?.complete === 'function';\n}\n\n/**\n * Run a Mistral tool-calling loop. Every custom tool call is permission-checked\n * (or decided by your runtime rules) and signed before it executes; denied\n * calls go back to the model as an error result.\n */\nexport async function runMistralAgentLoop(config: RunMistralAgentLoopConfig): Promise<string> {\n const { mistral, registry, userMessage, systemPrompt, model = DEFAULT_MISTRAL_MODEL, maxIterations = 10 } = config;\n const sdk = isSdkClient(mistral);\n const messages: any[] = [];\n if (systemPrompt) messages.push({ role: 'system', content: systemPrompt });\n messages.push({ role: 'user', content: userMessage });\n const tools = registry.toOpenAITools();\n\n for (let i = 0; i < maxIterations; i++) {\n const args: Record<string, unknown> = { model, messages, ...(tools.length ? { tools } : {}) };\n if (config.parallelToolCalls != null) args[sdk ? 'parallelToolCalls' : 'parallel_tool_calls'] = config.parallelToolCalls;\n const res = sdk ? await (mistral as MistralSdkClient).chat.complete(args) : await (mistral as OpenAICompatibleClient).chat.completions.create(args);\n const choice = res?.choices?.[0];\n if (!choice) return '';\n const msg = choice.message ?? {};\n const rawCalls: MistralToolCallLike[] | undefined = sdk ? msg.toolCalls : msg.tool_calls;\n const finish: string | undefined = sdk ? choice.finishReason : choice.finish_reason;\n const calls = normaliseMistralToolCalls(rawCalls);\n\n if (!calls.length || finish !== 'tool_calls') {\n return typeof msg.content === 'string' ? msg.content : contentText(msg.content);\n }\n\n // Echo the assistant turn back with ids that match the results we send.\n messages.push(sdk\n ? { role: 'assistant', content: msg.content ?? '', toolCalls: calls }\n : { role: 'assistant', content: msg.content ?? '', tool_calls: calls });\n\n const results = await registry.executeToolCalls(calls);\n for (const r of results) {\n const name = calls.find(c => c.id === r.tool_call_id)?.function.name;\n messages.push(sdk\n ? { role: 'tool', toolCallId: r.tool_call_id, name, content: r.content }\n : { role: 'tool', tool_call_id: r.tool_call_id, name, content: r.content });\n }\n }\n const last = messages[messages.length - 1];\n return typeof last?.content === 'string' ? last.content : '';\n}\n\nfunction contentText(content: unknown): string {\n if (!Array.isArray(content)) return '';\n return content.map((c: any) => (c?.type === 'text' && typeof c.text === 'string' ? c.text : '')).join('');\n}\n\n// ─── Agents / Conversations API ────────────────────────────────────────────\n\n/** A `function.call` entry from a conversation's `outputs[]`. */\nexport interface MistralFunctionCallEntry {\n type: string;\n tool_call_id?: string; toolCallId?: string;\n name: string;\n arguments: string | Record<string, unknown>;\n confirmation_status?: string | null; confirmationStatus?: string | null;\n}\n\n/** A `function.result` entry to append to the conversation. */\nexport interface MistralFunctionResultEntry { type: 'function.result'; tool_call_id: string; result: string }\n\nconst callId = (e: MistralFunctionCallEntry, i: number) => e.tool_call_id ?? e.toolCallId ?? `mistral_call_${i}`;\nconst pending = (e: MistralFunctionCallEntry) => (e.confirmation_status ?? e.confirmationStatus) === 'pending';\n\n/**\n * Gate + sign the custom function calls in a conversation response and return\n * the `function.result` entries to send back (`conversations.append`). Entries\n * awaiting confirmation, and calls to tools the registry does not hold\n * (built-in or connector tools run by Mistral), are skipped.\n */\nexport async function executeMistralFunctionCalls(\n registry: VorimToolRegistry,\n outputs: MistralFunctionCallEntry[] | null | undefined,\n): Promise<MistralFunctionResultEntry[]> {\n const calls = (outputs ?? [])\n .map((e, i) => ({ e, id: callId(e, i) }))\n .filter(({ e }) => e.type === 'function.call' && !pending(e) && registry.has(e.name));\n if (!calls.length) return [];\n const results = await registry.executeToolCalls(normaliseMistralToolCalls(\n calls.map(({ e, id }) => ({ id, function: { name: e.name, arguments: e.arguments } })),\n ));\n return results.map(r => ({ type: 'function.result' as const, tool_call_id: r.tool_call_id, result: r.content }));\n}\n\nexport interface DecideConfirmationsConfig {\n vorim: VorimSDK;\n agentId: string;\n /** Scope per tool name; others use defaultPermission. */\n scopes?: Record<string, PermissionScope>;\n /** @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Use runtime rules (allow / deny / escalate) instead of the permission check. @default false */\n useRuntimeControl?: boolean;\n onEscalation?: EscalationPolicy;\n escalationTimeoutMs?: number;\n onTransportFailure?: TransportFailurePolicy;\n}\n\nexport interface MistralToolConfirmation { tool_call_id: string; confirmation: 'allow' | 'deny' }\n\n/**\n * Answer Mistral's pending tool confirmations with Vorim. For each\n * `function.call` with `confirmation_status: 'pending'` (a built-in, connector\n * or deferred tool you listed in `requires_confirmation`), Vorim checks the\n * agent's permission (or your runtime rules), records a signed audit event and\n * returns `allow` or `deny`. Send the result as `tool_confirmations` when you\n * resume the conversation. Any failure answers `deny` (fails closed).\n */\nexport async function decideMistralConfirmations(\n config: DecideConfirmationsConfig,\n outputs: MistralFunctionCallEntry[] | null | undefined,\n): Promise<MistralToolConfirmation[]> {\n const out: MistralToolConfirmation[] = [];\n const entries = (outputs ?? []).map((e, i) => ({ e, id: callId(e, i) })).filter(({ e }) => e.type === 'function.call' && pending(e));\n for (const { e, id } of entries) {\n const scope = config.scopes?.[e.name] ?? config.defaultPermission ?? 'agent:execute';\n const argsText = typeof e.arguments === 'string' ? e.arguments : JSON.stringify(e.arguments ?? {});\n let payload: Record<string, unknown> | undefined;\n try { payload = typeof e.arguments === 'string' ? JSON.parse(e.arguments) : e.arguments; } catch { payload = undefined; }\n let allowed = false; let reason: string | undefined; let decisionId: string | undefined;\n try {\n if (config.useRuntimeControl) {\n ({ allowed, reason, decisionId } = await runtimeGate(config.vorim, config.agentId, e.name, scope, payload, {\n onEscalation: config.onEscalation, escalationTimeoutMs: config.escalationTimeoutMs, onTransportFailure: config.onTransportFailure,\n }));\n } else {\n ({ allowed, reason } = await config.vorim.check(config.agentId, scope));\n }\n } catch {\n allowed = false; reason = 'Vorim unavailable (failed closed)';\n }\n out.push({ tool_call_id: id, confirmation: allowed ? 'allow' : 'deny' });\n config.vorim.emit({\n agent_id: config.agentId,\n event_type: 'tool_call',\n action: e.name,\n resource: argsText.slice(0, 500),\n permission: scope,\n result: allowed ? 'success' : 'denied',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { framework: 'mistral', stage: 'confirmation', executed_by: 'mistral', ...(reason ? { reason } : {}) },\n }).catch(() => {});\n }\n return out;\n}\n"],"mappings":";AAmEA,SAAS,eAAe,UAAgD;AACtE,SAAO,aAAa,WAAW,aAAa;AAC9C;AASA,eAAsB,YACpB,OACA,SACA,cACA,OACA,SACA,OAA2B,CAAC,GACP;AACrB,QAAM,eAAe,KAAK,gBAAgB;AAC1C,QAAM,qBAAqB,KAAK,sBAAsB;AACtD,QAAM,IAAI,MAAM,MAAM;AAAA,IACpB,EAAE,SAAS,YAAY,aAAa,cAAc,eAAe,OAAO,QAAQ;AAAA,IAChF,EAAE,aAAa,MAAM;AAAA,EACvB;AAMA,MAAI,EAAE,cAAc,EAAE,aAAa,YAAY;AAC7C,QAAI,uBAAuB,SAAS;AAClC,aAAO,EAAE,SAAS,MAAM,QAAQ,EAAE,UAAU,yCAAyC,YAAY,EAAE,cAAc,OAAU;AAAA,IAC7H;AACA,WAAO,EAAE,SAAS,OAAO,QAAQ,EAAE,UAAU,6CAA6C,YAAY,EA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ACN,gBAAU;AAAO,eAAS;AAAA,IAC5B;AACA,QAAI,KAAK,EAAE,cAAc,IAAI,cAAc,UAAU,UAAU,OAAO,CAAC;AACvE,WAAO,MAAM,KAAK;AAAA,MAChB,UAAU,OAAO;AAAA,MACjB,YAAY;AAAA,MACZ,QAAQ,EAAE;AAAA,MACV,UAAU,SAAS,MAAM,GAAG,GAAG;AAAA,MAC/B,YAAY;AAAA,MACZ,QAAQ,UAAU,YAAY;AAAA,MAC9B,GAAI,aAAa,EAAE,aAAa,WAAW,IAAI,CAAC;AAAA,MAChD,UAAU,EAAE,WAAW,WAAW,OAAO,gBAAgB,aAAa,WAAW,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC,EAAG;AAAA,IACjH,CAAC,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAAA,EACnB;AACA,SAAO;AACT;","names":[]}
@@ -161,7 +161,9 @@ var VorimToolRegistry = class {
161
161
  tools = /* @__PURE__ */ new Map();
162
162
  replayInputs;
163
163
  replayCache = null;
164
+ framework;
164
165
  constructor(config) {
166
+ this.framework = config.framework ?? "openai";
165
167
  this.vorim = config.vorim;
166
168
  this.agentId = config.agentId;
167
169
  this.defaultPermission = config.defaultPermission ?? "agent:execute";
@@ -221,6 +223,10 @@ var VorimToolRegistry = class {
221
223
  return this;
222
224
  }
223
225
  /** Register multiple tools. */
226
+ /** Whether a tool with this name is registered. */
227
+ has(name) {
228
+ return this.tools.has(name);
229
+ }
224
230
  addAll(definitions) {
225
231
  for (const def of definitions) this.add(def);
226
232
  return this;
@@ -280,7 +286,7 @@ var VorimToolRegistry = class {
280
286
  permission: scope,
281
287
  result: "denied",
282
288
  ...decisionId ? { decision_id: decisionId } : {},
283
- metadata: { reason, framework: "openai" },
289
+ metadata: { reason, framework: this.framework },
284
290
  ...replayCtx
285
291
  };
286
292
  await this.emitAudit(event);
@@ -303,7 +309,7 @@ var VorimToolRegistry = class {
303
309
  result: "success",
304
310
  latency_ms: Date.now() - start,
305
311
  ...decisionId ? { decision_id: decisionId } : {},
306
- metadata: { framework: "openai" },
312
+ metadata: { framework: this.framework },
307
313
  ...replayCtx
308
314
  };
309
315
  await this.emitAudit(event);
@@ -320,7 +326,7 @@ var VorimToolRegistry = class {
320
326
  latency_ms: Date.now() - start,
321
327
  error_code: err instanceof Error ? err.name : "UNKNOWN",
322
328
  ...decisionId ? { decision_id: decisionId } : {},
323
- metadata: { error: errMsg, framework: "openai" },
329
+ metadata: { error: errMsg, framework: this.framework },
324
330
  ...replayCtx
325
331
  };
326
332
  await this.emitAudit(event);