@vorim/sdk 3.6.4 → 3.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/index.cjs +7 -1
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.js +7 -1
  5. package/dist/index.js.map +1 -1
  6. package/dist/integrations/anthropic.cjs +6 -0
  7. package/dist/integrations/anthropic.cjs.map +1 -1
  8. package/dist/integrations/anthropic.js +6 -0
  9. package/dist/integrations/anthropic.js.map +1 -1
  10. package/dist/integrations/langchain.cjs +6 -0
  11. package/dist/integrations/langchain.cjs.map +1 -1
  12. package/dist/integrations/langchain.js +6 -0
  13. package/dist/integrations/langchain.js.map +1 -1
  14. package/dist/integrations/langgraph.cjs +6 -0
  15. package/dist/integrations/langgraph.cjs.map +1 -1
  16. package/dist/integrations/langgraph.js +6 -0
  17. package/dist/integrations/langgraph.js.map +1 -1
  18. package/dist/integrations/llamaindex.cjs +6 -0
  19. package/dist/integrations/llamaindex.cjs.map +1 -1
  20. package/dist/integrations/llamaindex.js +6 -0
  21. package/dist/integrations/llamaindex.js.map +1 -1
  22. package/dist/integrations/openai.cjs +6 -0
  23. package/dist/integrations/openai.cjs.map +1 -1
  24. package/dist/integrations/openai.js +6 -0
  25. package/dist/integrations/openai.js.map +1 -1
  26. package/dist/integrations/ucp.cjs +224 -0
  27. package/dist/integrations/ucp.cjs.map +1 -0
  28. package/dist/integrations/ucp.d.cts +102 -0
  29. package/dist/integrations/ucp.d.ts +102 -0
  30. package/dist/integrations/ucp.js +198 -0
  31. package/dist/integrations/ucp.js.map +1 -0
  32. package/dist/integrations/vercel-ai.cjs +6 -0
  33. package/dist/integrations/vercel-ai.cjs.map +1 -1
  34. package/dist/integrations/vercel-ai.js +6 -0
  35. package/dist/integrations/vercel-ai.js.map +1 -1
  36. package/package.json +11 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/integrations/ucp.ts"],"sourcesContent":["// ============================================================================\n// Vorim AI — Universal Commerce Protocol (UCP) Integration\n//\n// UCP is Google's open agentic-commerce protocol (announced Jan 2026, NRF). It\n// standardises how an AI agent transacts with a merchant across the shopping\n// journey — discovery, checkout, payment (via AP2), and order management — over\n// REST / JSON-RPC, with A2A and MCP bindings.\n//\n// What UCP does NOT answer is the question Vorim exists to answer: *which* agent\n// is this, is it *allowed* to spend on this merchant for this amount, and can you\n// produce a tamper-evident record of what it bought that a counterparty can\n// verify independently. This integration adds exactly that layer around the UCP\n// commerce lifecycle.\n//\n// Design note: this wrapper is deliberately agnostic about UCP's internal wire\n// payloads. It operates on the commerce facts Vorim needs — agent id, merchant,\n// amount, currency, and an opaque UCP order/checkout reference — so it stays\n// correct as the UCP schema evolves. It does not invent UCP field names; the\n// caller passes the UCP order id it already holds. Where it does touch\n// UCP-specific vocabulary (the checkout-session status values and the\n// `ap2_mandate` extension's `checkout_mandate`), it matches the UCP spec,\n// version 2026-04-08. Spec: https://ucp.dev/latest/specification/overview/\n//\n// Usage:\n// import createVorim from '@vorim/sdk';\n// import { createVorimUCP } from '@vorim/sdk/integrations/ucp';\n//\n// const vorim = createVorim({ apiKey: 'agid_sk_...' });\n// const ucp = createVorimUCP(vorim, { minTrustScore: 60 });\n//\n// // Before an agent initiates a UCP checkout:\n// const auth = await ucp.authorizePurchase({\n// agentId: 'agid_abc123',\n// merchant: 'acme-store',\n// amount: 4999,\n// currency: 'usd',\n// });\n// if (!auth.authorized) throw new Error(auth.reason);\n//\n// // ...run the UCP checkout, then record the signed audit trail:\n// await ucp.logOrderPlaced('agid_abc123', ucpOrderId, 'acme-store', 4999);\n// await ucp.logOrderFulfilled('agid_abc123', ucpOrderId);\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\n\nexport interface UCPConfig {\n apiKey: string;\n baseUrl?: string;\n minTrustScore?: number;\n requiredScope?: string;\n}\n\nexport interface PurchaseAuthorizationRequest {\n agentId: string;\n /** UCP merchant / seller identifier the agent is transacting with. */\n merchant?: string;\n /** Amount in the smallest currency unit (e.g. cents), as UCP/AP2 uses. */\n amount?: number;\n currency?: string;\n minTrustScore?: number;\n}\n\nexport interface PurchaseAuthorization {\n authorized: boolean;\n agentId: string;\n trustScore: number;\n status: string;\n reason?: string;\n scopeVerified: boolean;\n}\n\nexport class VorimUCP {\n private sdk: VorimSDK;\n private minTrustScore: number;\n private requiredScope: string;\n\n constructor(sdk: VorimSDK, config?: Partial<UCPConfig>) {\n this.sdk = sdk;\n this.minTrustScore = config?.minTrustScore ?? 50;\n this.requiredScope = config?.requiredScope ?? 'agent:transact';\n }\n\n /**\n * Verify an agent is authorized to initiate a UCP purchase: it holds the\n * transact scope, is active, and meets the trust-score threshold. Every\n * decision (allow or deny) is recorded as a signed audit event.\n */\n async authorizePurchase(req: PurchaseAuthorizationRequest): Promise<PurchaseAuthorization> {\n const threshold = req.minTrustScore ?? this.minTrustScore;\n\n // 1. Permission: agent must hold the transact scope.\n try {\n const perm = await this.sdk.check(req.agentId, this.requiredScope as any);\n if (!(perm as any).allowed) {\n await this.logEvent(req.agentId, 'ucp.purchase.authorize', 'denied', req, { reason: `Missing ${this.requiredScope}` });\n return {\n authorized: false,\n agentId: req.agentId,\n trustScore: 0,\n status: 'unknown',\n reason: `Agent does not have ${this.requiredScope} permission`,\n scopeVerified: false,\n };\n }\n } catch (e: any) {\n await this.logEvent(req.agentId, 'ucp.purchase.authorize', 'denied', req, { reason: e.message });\n return {\n authorized: false,\n agentId: req.agentId,\n trustScore: 0,\n status: 'unknown',\n reason: `Permission check failed: ${e.message}`,\n scopeVerified: false,\n };\n }\n\n // 2. Trust: agent must be active and above the score threshold.\n let score = 0;\n let status = 'unknown';\n try {\n const trust = await this.sdk.verify(req.agentId);\n score = (trust as any).trust_score ?? 0;\n status = (trust as any).status ?? 'unknown';\n } catch {\n // Trust verification failed; treated as not-active below.\n }\n\n if (status !== 'active') {\n await this.logEvent(req.agentId, 'ucp.purchase.authorize', 'denied', req, { reason: `Status: ${status}` });\n return {\n authorized: false,\n agentId: req.agentId,\n trustScore: score,\n status,\n reason: `Agent is ${status}, not active`,\n scopeVerified: true,\n };\n }\n\n if (score < threshold) {\n await this.logEvent(req.agentId, 'ucp.purchase.authorize', 'denied', req, { reason: `Score ${score} < ${threshold}` });\n return {\n authorized: false,\n agentId: req.agentId,\n trustScore: score,\n status,\n reason: `Trust score ${score} is below minimum ${threshold}`,\n scopeVerified: true,\n };\n }\n\n await this.logEvent(req.agentId, 'ucp.purchase.authorize', 'success', req, { trust_score: score });\n\n return {\n authorized: true,\n agentId: req.agentId,\n trustScore: score,\n status,\n scopeVerified: true,\n };\n }\n\n /**\n * Record the UCP commerce lifecycle as signed, offline-verifiable audit\n * events. The id passed is the UCP checkout-session / order reference the\n * caller already holds (UCP spec 2026-04-08) — Vorim does not parse UCP\n * payloads, it attests to them.\n */\n async logCartCreated(agentId: string, ucpOrderId: string, merchant?: string): Promise<void> {\n await this.logEvent(agentId, 'ucp.cart.created', 'success', { agentId, merchant }, { ucp_order_id: ucpOrderId });\n }\n\n async logOrderPlaced(agentId: string, ucpOrderId: string, merchant?: string, amount?: number): Promise<void> {\n await this.logEvent(agentId, 'ucp.order.placed', 'success', { agentId, merchant, amount }, { ucp_order_id: ucpOrderId });\n }\n\n async logOrderFulfilled(agentId: string, ucpOrderId: string, merchant?: string): Promise<void> {\n await this.logEvent(agentId, 'ucp.order.fulfilled', 'success', { agentId, merchant }, { ucp_order_id: ucpOrderId });\n }\n\n async logOrderCanceled(agentId: string, ucpOrderId: string, reason?: string): Promise<void> {\n await this.logEvent(agentId, 'ucp.order.canceled', 'success', { agentId }, { ucp_order_id: ucpOrderId, cancel_reason: reason });\n }\n\n /**\n * Record the outcome of a UCP checkout-session completion, keyed to the real\n * UCP status vocabulary. The spec's `complete` response carries a status of\n * `completed` | `incomplete` | `requires_escalation` | `error`; this maps it\n * to the audit `result` so an outside party can verify the agent's purchase\n * outcome. `requires_escalation` is recorded as a denial pending human\n * approval — the natural hand-off point for Vorim runtime control.\n */\n async logCheckoutSession(\n agentId: string,\n sessionId: string,\n status: 'completed' | 'incomplete' | 'requires_escalation' | 'error',\n opts?: { merchant?: string; amount?: number },\n ): Promise<void> {\n const result: 'success' | 'denied' | 'error' =\n status === 'completed' ? 'success' : status === 'error' ? 'error' : 'denied';\n await this.logEvent(\n agentId,\n 'ucp.checkout_session.complete',\n result,\n { agentId, merchant: opts?.merchant, amount: opts?.amount },\n { ucp_order_id: sessionId, ucp_status: status },\n );\n }\n\n /**\n * Record the AP2 payment mandate (UCP's `dev.ucp.shopping.ap2_mandate`\n * extension) for an autonomous purchase. The `checkout_mandate` is a signed\n * JWT proof that the agent was authorised to pay; capturing it in the Vorim\n * audit links UCP's own cryptographic payment proof to Vorim's signed,\n * independently-verifiable record of the action.\n */\n async logAp2Mandate(\n agentId: string,\n sessionId: string,\n checkoutMandate: string,\n opts?: { merchant?: string; amount?: number },\n ): Promise<void> {\n await this.logEvent(\n agentId,\n 'ucp.ap2.mandate',\n 'success',\n { agentId, merchant: opts?.merchant, amount: opts?.amount },\n { ucp_order_id: sessionId, ap2_checkout_mandate: checkoutMandate },\n );\n }\n\n /**\n * Express/Connect middleware that gates a UCP checkout endpoint on agent\n * authorization. Expects the agent id in the `x-vorim-agent-id` header\n * (configurable) and the merchant/amount in the request body.\n */\n middleware(options?: { agentIdHeader?: string; minTrustScore?: number }) {\n const header = options?.agentIdHeader ?? 'x-vorim-agent-id';\n const threshold = options?.minTrustScore ?? this.minTrustScore;\n\n return async (req: any, res: any, next: any) => {\n const agentId = req.headers?.[header] || req.headers?.[header.toLowerCase()] || '';\n\n if (!agentId) {\n res.status(401).json({\n error: { code: 'MISSING_AGENT_ID', message: `Agent ID required in ${header} header` },\n });\n return;\n }\n\n const auth = await this.authorizePurchase({\n agentId,\n merchant: req.body?.merchant || req.body?.seller || '',\n amount: req.body?.amount || 0,\n currency: req.body?.currency || 'usd',\n minTrustScore: threshold,\n });\n\n if (!auth.authorized) {\n res.status(403).json({\n error: {\n code: 'UNAUTHORIZED_AGENT',\n message: auth.reason || 'Agent not authorized for UCP transactions',\n trust_score: auth.trustScore,\n status: auth.status,\n },\n });\n return;\n }\n\n req.vorimAuthorization = auth;\n next();\n };\n }\n\n private async logEvent(\n agentId: string,\n action: string,\n result: 'success' | 'denied' | 'error',\n req?: any,\n metadata?: Record<string, any>,\n ): Promise<void> {\n try {\n // Canonical audit contract: event_type from the AuditEventType enum\n // ('api_request' for a commerce action) and `result` (not `outcome`)\n // from the AuditResult enum.\n await this.sdk.emit({\n agent_id: agentId,\n event_type: 'api_request',\n action,\n result,\n resource: req?.merchant || '',\n metadata: {\n protocol: 'ucp',\n merchant: req?.merchant || '',\n amount: req?.amount || 0,\n currency: req?.currency || '',\n ...metadata,\n },\n });\n } catch {\n // Never block the commerce flow on an audit failure.\n }\n }\n}\n\n/**\n * Create a VorimUCP instance.\n *\n * @example\n * ```typescript\n * import createVorim from '@vorim/sdk';\n * import { createVorimUCP } from '@vorim/sdk/integrations/ucp';\n *\n * const vorim = createVorim({ apiKey: 'agid_sk_...' });\n * const ucp = createVorimUCP(vorim, { minTrustScore: 70 });\n *\n * // Verify before a UCP checkout\n * const auth = await ucp.authorizePurchase({ agentId: 'agid_abc123', merchant: 'shop', amount: 4999 });\n *\n * // Express middleware on your UCP checkout route\n * app.post('/ucp/checkout', ucp.middleware(), createCheckoutHandler);\n * ```\n */\nexport function createVorimUCP(sdk: VorimSDK, config?: Partial<UCPConfig>): VorimUCP {\n return new VorimUCP(sdk, config);\n}\n"],"mappings":";AAwEO,IAAM,WAAN,MAAe;AAAA,EACZ;AAAA,EACA;AAAA,EACA;AAAA,EAER,YAAY,KAAe,QAA6B;AACtD,SAAK,MAAM;AACX,SAAK,gBAAgB,QAAQ,iBAAiB;AAC9C,SAAK,gBAAgB,QAAQ,iBAAiB;AAAA,EAChD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,kBAAkB,KAAmE;AACzF,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KAAK;AAAA,UACf;AAAA,QACF,CAAC;AACD;AAAA,MACF;AAEA,UAAI,qBAAqB;AACzB,WAAK;AAAA,IACP;AAAA,EACF;AAAA,EAEA,MAAc,SACZ,SACA,QACA,QACA,KACA,UACe;AACf,QAAI;AAIF,YAAM,KAAK,IAAI,KAAK;AAAA,QAClB,UAAU;AAAA,QACV,YAAY;AAAA,QACZ;AAAA,QACA;AAAA,QACA,UAAU,KAAK,YAAY;AAAA,QAC3B,UAAU;AAAA,UACR,UAAU;AAAA,UACV,UAAU,KAAK,YAAY;AAAA,UAC3B,QAAQ,KAAK,UAAU;AAAA,UACvB,UAAU,KAAK,YAAY;AAAA,UAC3B,GAAG;AAAA,QACL;AAAA,MACF,CAAC;AAAA,IACH,QAAQ;AAAA,IAER;AAAA,EACF;AACF;AAoBO,SAAS,eAAe,KAAe,QAAuC;AACnF,SAAO,IAAI,SAAS,KAAK,MAAM;AACjC;","names":[]}
@@ -74,6 +74,12 @@ function jcsCanonicalise(value) {
74
74
  if (!Number.isFinite(value)) {
75
75
  throw new Error("jcsCanonicalise: NaN and Infinity are not JCS-valid");
76
76
  }
77
+ const abs = Math.abs(value);
78
+ if (value !== 0 && (abs >= 1e21 || abs < 1e-4 || Number.isInteger(value) && abs > 2 ** 53)) {
79
+ throw new Error(
80
+ `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}.`
81
+ );
82
+ }
77
83
  return value.toString();
78
84
  }
79
85
  if (typeof value === "string") {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/integrations/vercel-ai.ts","../../src/integrations/_runtime-gate.ts","../../src/replay.ts"],"sourcesContent":["// ============================================================================\n// VORIM SDK — Vercel AI SDK Integration\n// Wraps Vercel AI SDK tools with Vorim permission checks, runtime control,\n// and signed audit trails. Works with the `tool()` helper from the `ai`\n// package (v3/v4): each tool is an object with an async `execute(args, opts)`.\n//\n// Peer dependency: ai >=3.0.0\n//\n// Usage:\n// import { tool } from 'ai';\n// import createVorim from '@vorim/sdk';\n// import { wrapVercelTools } from '@vorim/sdk/integrations/vercel-ai';\n//\n// const vorim = createVorim({ apiKey: 'agid_sk_live_...' });\n//\n// const tools = wrapVercelTools(\n// {\n// searchDocs: tool({ description: '...', parameters: z.object({...}), execute: async ({ query }) => ... }),\n// sendEmail: tool({ description: '...', parameters: z.object({...}), execute: async ({ to }) => ... }),\n// },\n// { vorim, agentId: 'agid_acme_a1b2c3d4', permissionMap: { sendEmail: 'agent:communicate' } },\n// );\n//\n// const result = await generateText({ model, tools, prompt });\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope, AuditEventInput } from '../types.js';\nimport { runtimeGate, type EscalationPolicy } from './_runtime-gate.js';\nimport {\n prepareReplayContext,\n type ReplayInputs,\n type ReplayContext,\n type CatalogueTool,\n} from '../replay.js';\n\n// ─── Re-declared Vercel AI SDK shape (peer dependency — not bundled) ───────\n//\n// A Vercel `tool()` result. We only touch `execute`; everything else\n// (description, parameters/inputSchema) is passed through untouched, so this\n// stays compatible across AI SDK minor versions that rename schema fields.\ninterface VercelTool {\n description?: string;\n parameters?: unknown; // AI SDK v3/early v4\n inputSchema?: unknown; // AI SDK v4+\n execute?: (args: any, options?: any) => Promise<any> | any;\n [k: string]: unknown;\n}\n\n// ─── Configuration ──────────────────────────────────────────────────────────\n\nexport interface VorimVercelConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id (e.g. agid_acme_a1b2c3d4). */\n agentId: string;\n /** Per-tool permission scope override, keyed by tool name. */\n permissionMap?: Record<string, PermissionScope>;\n /** Default scope for tools without an entry in permissionMap. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Emit audit events fire-and-forget. @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. @default false\n *\n * When true, each call is evaluated against your live policy rules and the\n * returned decisionId is linked onto every audit event's decision_id.\n * Requires the runtime_control plan feature (Growth+) and consumes decision\n * quota. When false (default) the fast permission check is used.\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 * Replayable agent decision evidence (VAIP -02). When provided, the hashes\n * are attached to every audit event. If `replay.tools` is not given, the\n * wrapped tools' own catalogue is derived automatically.\n */\n replay?: ReplayInputs;\n}\n\nfunction truncate(s: string, max: number): string {\n return s.length > max ? s.slice(0, max) + '…' : s;\n}\n\nasync function gate(\n cfg: VorimVercelConfig,\n scope: PermissionScope,\n actionTarget: string,\n payload?: Record<string, unknown>,\n): Promise<{ allowed: boolean; reason?: string; decisionId?: string }> {\n if (cfg.useRuntimeControl) {\n return runtimeGate(cfg.vorim, cfg.agentId, actionTarget, scope, payload, {\n onEscalation: cfg.onEscalation,\n escalationTimeoutMs: cfg.escalationTimeoutMs,\n });\n }\n const { allowed, reason } = await cfg.vorim.check(cfg.agentId, scope);\n return { allowed, reason };\n}\n\nfunction emitAudit(vorim: VorimSDK, event: AuditEventInput, asyncAudit: boolean): Promise<void> | void {\n if (asyncAudit) {\n vorim.emit(event).catch(() => {});\n return;\n }\n return vorim.emit(event).then(() => undefined).catch(() => undefined);\n}\n\n/** Lazy replay-context getter — computes hashes once, reuses thereafter. */\nfunction makeReplayGetter(replay: ReplayInputs | undefined): () => Promise<ReplayContext> {\n if (!replay) return async () => ({});\n let cached: Promise<ReplayContext> | null = null;\n return () => {\n if (!cached) cached = prepareReplayContext(replay);\n return cached;\n };\n}\n\n// ─── Wrappers ────────────────────────────────────────────────────────────────\n\n/**\n * Wrap a single Vercel AI SDK tool so every execution is gated by a Vorim\n * permission/runtime check and recorded in the signed audit trail. A denied\n * call throws (so the AI SDK records a tool error) and is audited as `denied`.\n * Tools with no `execute` (client-side / provider-executed tools) pass through\n * unchanged.\n */\nexport function wrapVercelTool(name: string, tool: VercelTool, config: VorimVercelConfig): VercelTool {\n const { vorim, defaultPermission = 'agent:execute', permissionMap = {}, asyncAudit = true } = config;\n if (typeof tool.execute !== 'function') return tool; // nothing to guard\n\n const originalExecute = tool.execute.bind(tool);\n const getReplay = makeReplayGetter(config.replay);\n const scope = permissionMap[name] ?? defaultPermission;\n\n const guarded: VercelTool = {\n ...tool,\n execute: async (args: any, options?: any): Promise<any> => {\n const { allowed, reason, decisionId } = await gate(config, scope, name, args as Record<string, unknown>);\n const replayCtx = await getReplay();\n const resource = truncate(safeJson(args), 500);\n\n if (!allowed) {\n await emitAudit(vorim, {\n agent_id: config.agentId,\n event_type: 'tool_call',\n action: name,\n resource,\n permission: scope,\n result: 'denied',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { reason, framework: 'vercel-ai' },\n ...replayCtx,\n }, asyncAudit);\n throw new Error(`Vorim: permission denied for \"${name}\" — scope \"${scope}\"${reason ? `: ${reason}` : ''}`);\n }\n\n const start = Date.now();\n try {\n const result = await originalExecute(args, options);\n await emitAudit(vorim, {\n agent_id: config.agentId,\n event_type: 'tool_call',\n action: name,\n resource,\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { framework: 'vercel-ai' },\n ...replayCtx,\n }, asyncAudit);\n return result;\n } catch (err) {\n await emitAudit(vorim, {\n agent_id: config.agentId,\n event_type: 'tool_call',\n action: name,\n resource,\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: err instanceof Error ? err.message : String(err), framework: 'vercel-ai' },\n ...replayCtx,\n }, asyncAudit);\n throw err;\n }\n },\n };\n\n return guarded;\n}\n\n/**\n * Wrap the `tools` object you pass to generateText / streamText. Returns a new\n * object with every executable tool guarded. If `replay.tools` was not provided,\n * the tool catalogue is derived from these tools automatically.\n */\nexport function wrapVercelTools(\n tools: Record<string, VercelTool>,\n config: VorimVercelConfig,\n): Record<string, VercelTool> {\n // Auto-derive the replay tool catalogue from the tools when not supplied.\n const cfg: VorimVercelConfig =\n config.replay && !config.replay.tools\n ? { ...config, replay: { ...config.replay, tools: deriveCatalogue(tools) } }\n : config;\n\n const out: Record<string, VercelTool> = {};\n for (const [name, tool] of Object.entries(tools)) {\n out[name] = wrapVercelTool(name, tool, cfg);\n }\n return out;\n}\n\nfunction deriveCatalogue(tools: Record<string, VercelTool>): CatalogueTool[] {\n return Object.entries(tools).map(([name, t]) => ({\n name,\n description: typeof t.description === 'string' ? t.description : '',\n schema: (t.inputSchema ?? t.parameters ?? {}) as Record<string, unknown>,\n }));\n}\n\nfunction safeJson(v: unknown): string {\n try {\n return JSON.stringify(v);\n } catch {\n return String(v);\n }\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\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\nexport interface GateResult {\n allowed: boolean;\n reason?: string;\n decisionId?: string;\n}\n\n/** True for verdicts that permit the action to proceed. `escalate` is handled separately. */\nfunction isAllowVerdict(decision: RuntimeDecision['decision']): boolean {\n return decision === 'allow' || decision === 'modify' || decision === 'fallback';\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 d = await vorim.beforeAction(\n { agentId, actionType: 'tool_call', actionTarget, requiredScope: scope, payload },\n { throwOnDeny: false },\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 // For integers in safe range, .toString() matches JCS. For\n // non-integer floats, .toString() also matches in modern JS\n // engines (V8, JavaScriptCore, SpiderMonkey all use the shortest\n // round-trip representation, which is what JCS § 3.2.2.2 requires).\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA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T;AAEA,SAAS,gBAAgB,OAAoD;AAC3E,SAAO,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,MAAM,CAAC,OAAO;AAAA,IAC/C;AAAA,IACA,aAAa,OAAO,EAAE,gBAAgB,WAAW,EAAE,cAAc;AAAA,IACjE,QAAS,EAAE,eAAe,EAAE,cAAc,CAAC;AAAA,EAC7C,EAAE;AACJ;AAEA,SAAS,SAAS,GAAoB;AACpC,MAAI;AACF,WAAO,KAAK,UAAU,CAAC;AAAA,EACzB,QAAQ;AACN,WAAO,OAAO,CAAC;AAAA,EACjB;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/integrations/vercel-ai.ts","../../src/integrations/_runtime-gate.ts","../../src/replay.ts"],"sourcesContent":["// ============================================================================\n// VORIM SDK — Vercel AI SDK Integration\n// Wraps Vercel AI SDK tools with Vorim permission checks, runtime control,\n// and signed audit trails. Works with the `tool()` helper from the `ai`\n// package (v3/v4): each tool is an object with an async `execute(args, opts)`.\n//\n// Peer dependency: ai >=3.0.0\n//\n// Usage:\n// import { tool } from 'ai';\n// import createVorim from '@vorim/sdk';\n// import { wrapVercelTools } from '@vorim/sdk/integrations/vercel-ai';\n//\n// const vorim = createVorim({ apiKey: 'agid_sk_live_...' });\n//\n// const tools = wrapVercelTools(\n// {\n// searchDocs: tool({ description: '...', parameters: z.object({...}), execute: async ({ query }) => ... }),\n// sendEmail: tool({ description: '...', parameters: z.object({...}), execute: async ({ to }) => ... }),\n// },\n// { vorim, agentId: 'agid_acme_a1b2c3d4', permissionMap: { sendEmail: 'agent:communicate' } },\n// );\n//\n// const result = await generateText({ model, tools, prompt });\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope, AuditEventInput } from '../types.js';\nimport { runtimeGate, type EscalationPolicy } from './_runtime-gate.js';\nimport {\n prepareReplayContext,\n type ReplayInputs,\n type ReplayContext,\n type CatalogueTool,\n} from '../replay.js';\n\n// ─── Re-declared Vercel AI SDK shape (peer dependency — not bundled) ───────\n//\n// A Vercel `tool()` result. We only touch `execute`; everything else\n// (description, parameters/inputSchema) is passed through untouched, so this\n// stays compatible across AI SDK minor versions that rename schema fields.\ninterface VercelTool {\n description?: string;\n parameters?: unknown; // AI SDK v3/early v4\n inputSchema?: unknown; // AI SDK v4+\n execute?: (args: any, options?: any) => Promise<any> | any;\n [k: string]: unknown;\n}\n\n// ─── Configuration ──────────────────────────────────────────────────────────\n\nexport interface VorimVercelConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id (e.g. agid_acme_a1b2c3d4). */\n agentId: string;\n /** Per-tool permission scope override, keyed by tool name. */\n permissionMap?: Record<string, PermissionScope>;\n /** Default scope for tools without an entry in permissionMap. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Emit audit events fire-and-forget. @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. @default false\n *\n * When true, each call is evaluated against your live policy rules and the\n * returned decisionId is linked onto every audit event's decision_id.\n * Requires the runtime_control plan feature (Growth+) and consumes decision\n * quota. When false (default) the fast permission check is used.\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 * Replayable agent decision evidence (VAIP -02). When provided, the hashes\n * are attached to every audit event. If `replay.tools` is not given, the\n * wrapped tools' own catalogue is derived automatically.\n */\n replay?: ReplayInputs;\n}\n\nfunction truncate(s: string, max: number): string {\n return s.length > max ? s.slice(0, max) + '…' : s;\n}\n\nasync function gate(\n cfg: VorimVercelConfig,\n scope: PermissionScope,\n actionTarget: string,\n payload?: Record<string, unknown>,\n): Promise<{ allowed: boolean; reason?: string; decisionId?: string }> {\n if (cfg.useRuntimeControl) {\n return runtimeGate(cfg.vorim, cfg.agentId, actionTarget, scope, payload, {\n onEscalation: cfg.onEscalation,\n escalationTimeoutMs: cfg.escalationTimeoutMs,\n });\n }\n const { allowed, reason } = await cfg.vorim.check(cfg.agentId, scope);\n return { allowed, reason };\n}\n\nfunction emitAudit(vorim: VorimSDK, event: AuditEventInput, asyncAudit: boolean): Promise<void> | void {\n if (asyncAudit) {\n vorim.emit(event).catch(() => {});\n return;\n }\n return vorim.emit(event).then(() => undefined).catch(() => undefined);\n}\n\n/** Lazy replay-context getter — computes hashes once, reuses thereafter. */\nfunction makeReplayGetter(replay: ReplayInputs | undefined): () => Promise<ReplayContext> {\n if (!replay) return async () => ({});\n let cached: Promise<ReplayContext> | null = null;\n return () => {\n if (!cached) cached = prepareReplayContext(replay);\n return cached;\n };\n}\n\n// ─── Wrappers ────────────────────────────────────────────────────────────────\n\n/**\n * Wrap a single Vercel AI SDK tool so every execution is gated by a Vorim\n * permission/runtime check and recorded in the signed audit trail. A denied\n * call throws (so the AI SDK records a tool error) and is audited as `denied`.\n * Tools with no `execute` (client-side / provider-executed tools) pass through\n * unchanged.\n */\nexport function wrapVercelTool(name: string, tool: VercelTool, config: VorimVercelConfig): VercelTool {\n const { vorim, defaultPermission = 'agent:execute', permissionMap = {}, asyncAudit = true } = config;\n if (typeof tool.execute !== 'function') return tool; // nothing to guard\n\n const originalExecute = tool.execute.bind(tool);\n const getReplay = makeReplayGetter(config.replay);\n const scope = permissionMap[name] ?? defaultPermission;\n\n const guarded: VercelTool = {\n ...tool,\n execute: async (args: any, options?: any): Promise<any> => {\n const { allowed, reason, decisionId } = await gate(config, scope, name, args as Record<string, unknown>);\n const replayCtx = await getReplay();\n const resource = truncate(safeJson(args), 500);\n\n if (!allowed) {\n await emitAudit(vorim, {\n agent_id: config.agentId,\n event_type: 'tool_call',\n action: name,\n resource,\n permission: scope,\n result: 'denied',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { reason, framework: 'vercel-ai' },\n ...replayCtx,\n }, asyncAudit);\n throw new Error(`Vorim: permission denied for \"${name}\" — scope \"${scope}\"${reason ? `: ${reason}` : ''}`);\n }\n\n const start = Date.now();\n try {\n const result = await originalExecute(args, options);\n await emitAudit(vorim, {\n agent_id: config.agentId,\n event_type: 'tool_call',\n action: name,\n resource,\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { framework: 'vercel-ai' },\n ...replayCtx,\n }, asyncAudit);\n return result;\n } catch (err) {\n await emitAudit(vorim, {\n agent_id: config.agentId,\n event_type: 'tool_call',\n action: name,\n resource,\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: err instanceof Error ? err.message : String(err), framework: 'vercel-ai' },\n ...replayCtx,\n }, asyncAudit);\n throw err;\n }\n },\n };\n\n return guarded;\n}\n\n/**\n * Wrap the `tools` object you pass to generateText / streamText. Returns a new\n * object with every executable tool guarded. If `replay.tools` was not provided,\n * the tool catalogue is derived from these tools automatically.\n */\nexport function wrapVercelTools(\n tools: Record<string, VercelTool>,\n config: VorimVercelConfig,\n): Record<string, VercelTool> {\n // Auto-derive the replay tool catalogue from the tools when not supplied.\n const cfg: VorimVercelConfig =\n config.replay && !config.replay.tools\n ? { ...config, replay: { ...config.replay, tools: deriveCatalogue(tools) } }\n : config;\n\n const out: Record<string, VercelTool> = {};\n for (const [name, tool] of Object.entries(tools)) {\n out[name] = wrapVercelTool(name, tool, cfg);\n }\n return out;\n}\n\nfunction deriveCatalogue(tools: Record<string, VercelTool>): CatalogueTool[] {\n return Object.entries(tools).map(([name, t]) => ({\n name,\n description: typeof t.description === 'string' ? t.description : '',\n schema: (t.inputSchema ?? t.parameters ?? {}) as Record<string, unknown>,\n }));\n}\n\nfunction safeJson(v: unknown): string {\n try {\n return JSON.stringify(v);\n } catch {\n return String(v);\n }\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\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\nexport interface GateResult {\n allowed: boolean;\n reason?: string;\n decisionId?: string;\n}\n\n/** True for verdicts that permit the action to proceed. `escalate` is handled separately. */\nfunction isAllowVerdict(decision: RuntimeDecision['decision']): boolean {\n return decision === 'allow' || decision === 'modify' || decision === 'fallback';\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 d = await vorim.beforeAction(\n { agentId, actionType: 'tool_call', actionTarget, requiredScope: scope, payload },\n { throwOnDeny: false },\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACuCA,SAAS,eAAe,UAAgD;AACtE,SAAO,aAAa,WAAW,aAAa,YAAY,aAAa;AACvE;AASA,eAAsB,YACpB,OACA,SACA,cACA,OACA,SACA,O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ChD,QAAI,IAAI,IAAI,eAAe,MAAM,MAAM,GAAG;AAAA,EAC5C;AACA,SAAO;AACT;AAEA,SAAS,gBAAgB,OAAoD;AAC3E,SAAO,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,MAAM,CAAC,OAAO;AAAA,IAC/C;AAAA,IACA,aAAa,OAAO,EAAE,gBAAgB,WAAW,EAAE,cAAc;AAAA,IACjE,QAAS,EAAE,eAAe,EAAE,cAAc,CAAC;AAAA,EAC7C,EAAE;AACJ;AAEA,SAAS,SAAS,GAAoB;AACpC,MAAI;AACF,WAAO,KAAK,UAAU,CAAC;AAAA,EACzB,QAAQ;AACN,WAAO,OAAO,CAAC;AAAA,EACjB;AACF;","names":[]}
@@ -37,6 +37,12 @@ function jcsCanonicalise(value) {
37
37
  if (!Number.isFinite(value)) {
38
38
  throw new Error("jcsCanonicalise: NaN and Infinity are not JCS-valid");
39
39
  }
40
+ const abs = Math.abs(value);
41
+ if (value !== 0 && (abs >= 1e21 || abs < 1e-4 || Number.isInteger(value) && abs > 2 ** 53)) {
42
+ throw new Error(
43
+ `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}.`
44
+ );
45
+ }
40
46
  return value.toString();
41
47
  }
42
48
  if (typeof value === "string") {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/integrations/_runtime-gate.ts","../../src/replay.ts","../../src/integrations/vercel-ai.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\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\nexport interface GateResult {\n allowed: boolean;\n reason?: string;\n decisionId?: string;\n}\n\n/** True for verdicts that permit the action to proceed. `escalate` is handled separately. */\nfunction isAllowVerdict(decision: RuntimeDecision['decision']): boolean {\n return decision === 'allow' || decision === 'modify' || decision === 'fallback';\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 d = await vorim.beforeAction(\n { agentId, actionType: 'tool_call', actionTarget, requiredScope: scope, payload },\n { throwOnDeny: false },\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 // For integers in safe range, .toString() matches JCS. For\n // non-integer floats, .toString() also matches in modern JS\n // engines (V8, JavaScriptCore, SpiderMonkey all use the shortest\n // round-trip representation, which is what JCS § 3.2.2.2 requires).\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 — Vercel AI SDK Integration\n// Wraps Vercel AI SDK tools with Vorim permission checks, runtime control,\n// and signed audit trails. Works with the `tool()` helper from the `ai`\n// package (v3/v4): each tool is an object with an async `execute(args, opts)`.\n//\n// Peer dependency: ai >=3.0.0\n//\n// Usage:\n// import { tool } from 'ai';\n// import createVorim from '@vorim/sdk';\n// import { wrapVercelTools } from '@vorim/sdk/integrations/vercel-ai';\n//\n// const vorim = createVorim({ apiKey: 'agid_sk_live_...' });\n//\n// const tools = wrapVercelTools(\n// {\n// searchDocs: tool({ description: '...', parameters: z.object({...}), execute: async ({ query }) => ... }),\n// sendEmail: tool({ description: '...', parameters: z.object({...}), execute: async ({ to }) => ... }),\n// },\n// { vorim, agentId: 'agid_acme_a1b2c3d4', permissionMap: { sendEmail: 'agent:communicate' } },\n// );\n//\n// const result = await generateText({ model, tools, prompt });\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope, AuditEventInput } from '../types.js';\nimport { runtimeGate, type EscalationPolicy } from './_runtime-gate.js';\nimport {\n prepareReplayContext,\n type ReplayInputs,\n type ReplayContext,\n type CatalogueTool,\n} from '../replay.js';\n\n// ─── Re-declared Vercel AI SDK shape (peer dependency — not bundled) ───────\n//\n// A Vercel `tool()` result. We only touch `execute`; everything else\n// (description, parameters/inputSchema) is passed through untouched, so this\n// stays compatible across AI SDK minor versions that rename schema fields.\ninterface VercelTool {\n description?: string;\n parameters?: unknown; // AI SDK v3/early v4\n inputSchema?: unknown; // AI SDK v4+\n execute?: (args: any, options?: any) => Promise<any> | any;\n [k: string]: unknown;\n}\n\n// ─── Configuration ──────────────────────────────────────────────────────────\n\nexport interface VorimVercelConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id (e.g. agid_acme_a1b2c3d4). */\n agentId: string;\n /** Per-tool permission scope override, keyed by tool name. */\n permissionMap?: Record<string, PermissionScope>;\n /** Default scope for tools without an entry in permissionMap. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Emit audit events fire-and-forget. @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. @default false\n *\n * When true, each call is evaluated against your live policy rules and the\n * returned decisionId is linked onto every audit event's decision_id.\n * Requires the runtime_control plan feature (Growth+) and consumes decision\n * quota. When false (default) the fast permission check is used.\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 * Replayable agent decision evidence (VAIP -02). When provided, the hashes\n * are attached to every audit event. If `replay.tools` is not given, the\n * wrapped tools' own catalogue is derived automatically.\n */\n replay?: ReplayInputs;\n}\n\nfunction truncate(s: string, max: number): string {\n return s.length > max ? s.slice(0, max) + '…' : s;\n}\n\nasync function gate(\n cfg: VorimVercelConfig,\n scope: PermissionScope,\n actionTarget: string,\n payload?: Record<string, unknown>,\n): Promise<{ allowed: boolean; reason?: string; decisionId?: string }> {\n if (cfg.useRuntimeControl) {\n return runtimeGate(cfg.vorim, cfg.agentId, actionTarget, scope, payload, {\n onEscalation: cfg.onEscalation,\n escalationTimeoutMs: cfg.escalationTimeoutMs,\n });\n }\n const { allowed, reason } = await cfg.vorim.check(cfg.agentId, scope);\n return { allowed, reason };\n}\n\nfunction emitAudit(vorim: VorimSDK, event: AuditEventInput, asyncAudit: boolean): Promise<void> | void {\n if (asyncAudit) {\n vorim.emit(event).catch(() => {});\n return;\n }\n return vorim.emit(event).then(() => undefined).catch(() => undefined);\n}\n\n/** Lazy replay-context getter — computes hashes once, reuses thereafter. */\nfunction makeReplayGetter(replay: ReplayInputs | undefined): () => Promise<ReplayContext> {\n if (!replay) return async () => ({});\n let cached: Promise<ReplayContext> | null = null;\n return () => {\n if (!cached) cached = prepareReplayContext(replay);\n return cached;\n };\n}\n\n// ─── Wrappers ────────────────────────────────────────────────────────────────\n\n/**\n * Wrap a single Vercel AI SDK tool so every execution is gated by a Vorim\n * permission/runtime check and recorded in the signed audit trail. A denied\n * call throws (so the AI SDK records a tool error) and is audited as `denied`.\n * Tools with no `execute` (client-side / provider-executed tools) pass through\n * unchanged.\n */\nexport function wrapVercelTool(name: string, tool: VercelTool, config: VorimVercelConfig): VercelTool {\n const { vorim, defaultPermission = 'agent:execute', permissionMap = {}, asyncAudit = true } = config;\n if (typeof tool.execute !== 'function') return tool; // nothing to guard\n\n const originalExecute = tool.execute.bind(tool);\n const getReplay = makeReplayGetter(config.replay);\n const scope = permissionMap[name] ?? defaultPermission;\n\n const guarded: VercelTool = {\n ...tool,\n execute: async (args: any, options?: any): Promise<any> => {\n const { allowed, reason, decisionId } = await gate(config, scope, name, args as Record<string, unknown>);\n const replayCtx = await getReplay();\n const resource = truncate(safeJson(args), 500);\n\n if (!allowed) {\n await emitAudit(vorim, {\n agent_id: config.agentId,\n event_type: 'tool_call',\n action: name,\n resource,\n permission: scope,\n result: 'denied',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { reason, framework: 'vercel-ai' },\n ...replayCtx,\n }, asyncAudit);\n throw new Error(`Vorim: permission denied for \"${name}\" — scope \"${scope}\"${reason ? `: ${reason}` : ''}`);\n }\n\n const start = Date.now();\n try {\n const result = await originalExecute(args, options);\n await emitAudit(vorim, {\n agent_id: config.agentId,\n event_type: 'tool_call',\n action: name,\n resource,\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { framework: 'vercel-ai' },\n ...replayCtx,\n }, asyncAudit);\n return result;\n } catch (err) {\n await emitAudit(vorim, {\n agent_id: config.agentId,\n event_type: 'tool_call',\n action: name,\n resource,\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: err instanceof Error ? err.message : String(err), framework: 'vercel-ai' },\n ...replayCtx,\n }, asyncAudit);\n throw err;\n }\n },\n };\n\n return guarded;\n}\n\n/**\n * Wrap the `tools` object you pass to generateText / streamText. Returns a new\n * object with every executable tool guarded. If `replay.tools` was not provided,\n * the tool catalogue is derived from these tools automatically.\n */\nexport function wrapVercelTools(\n tools: Record<string, VercelTool>,\n config: VorimVercelConfig,\n): Record<string, VercelTool> {\n // Auto-derive the replay tool catalogue from the tools when not supplied.\n const cfg: VorimVercelConfig =\n config.replay && !config.replay.tools\n ? { ...config, replay: { ...config.replay, tools: deriveCatalogue(tools) } }\n : config;\n\n const out: Record<string, VercelTool> = {};\n for (const [name, tool] of Object.entries(tools)) {\n out[name] = wrapVercelTool(name, tool, cfg);\n }\n return out;\n}\n\nfunction deriveCatalogue(tools: Record<string, VercelTool>): CatalogueTool[] {\n return Object.entries(tools).map(([name, t]) => ({\n name,\n description: typeof t.description === 'string' ? t.description : '',\n schema: (t.inputSchema ?? t.parameters ?? {}) as Record<string, unknown>,\n }));\n}\n\nfunction safeJson(v: unknown): string {\n try {\n return JSON.stringify(v);\n } catch {\n return String(v);\n }\n}\n"],"mappings":";AAuCA,SAAS,eAAe,UAAgD;AACtE,SAAO,aAAa,WAAW,aAAa,YAAY,aAAa;AACvE;AASA,eAAsB,YACpB,OACA,SACA,cACA,OACA,SACA,OAA2B,CAAC,GACP;AACrB,QAAM,eAAe,KAAK,gBAAgB;AAC1C,QAAM,IAAI,MAAM,MAA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EAAE,cAAc,CAAC;AAAA,EAC7C,EAAE;AACJ;AAEA,SAAS,SAAS,GAAoB;AACpC,MAAI;AACF,WAAO,KAAK,UAAU,CAAC;AAAA,EACzB,QAAQ;AACN,WAAO,OAAO,CAAC;AAAA,EACjB;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/integrations/_runtime-gate.ts","../../src/replay.ts","../../src/integrations/vercel-ai.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\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\nexport interface GateResult {\n allowed: boolean;\n reason?: string;\n decisionId?: string;\n}\n\n/** True for verdicts that permit the action to proceed. `escalate` is handled separately. */\nfunction isAllowVerdict(decision: RuntimeDecision['decision']): boolean {\n return decision === 'allow' || decision === 'modify' || decision === 'fallback';\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 d = await vorim.beforeAction(\n { agentId, actionType: 'tool_call', actionTarget, requiredScope: scope, payload },\n { throwOnDeny: false },\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 — Vercel AI SDK Integration\n// Wraps Vercel AI SDK tools with Vorim permission checks, runtime control,\n// and signed audit trails. Works with the `tool()` helper from the `ai`\n// package (v3/v4): each tool is an object with an async `execute(args, opts)`.\n//\n// Peer dependency: ai >=3.0.0\n//\n// Usage:\n// import { tool } from 'ai';\n// import createVorim from '@vorim/sdk';\n// import { wrapVercelTools } from '@vorim/sdk/integrations/vercel-ai';\n//\n// const vorim = createVorim({ apiKey: 'agid_sk_live_...' });\n//\n// const tools = wrapVercelTools(\n// {\n// searchDocs: tool({ description: '...', parameters: z.object({...}), execute: async ({ query }) => ... }),\n// sendEmail: tool({ description: '...', parameters: z.object({...}), execute: async ({ to }) => ... }),\n// },\n// { vorim, agentId: 'agid_acme_a1b2c3d4', permissionMap: { sendEmail: 'agent:communicate' } },\n// );\n//\n// const result = await generateText({ model, tools, prompt });\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope, AuditEventInput } from '../types.js';\nimport { runtimeGate, type EscalationPolicy } from './_runtime-gate.js';\nimport {\n prepareReplayContext,\n type ReplayInputs,\n type ReplayContext,\n type CatalogueTool,\n} from '../replay.js';\n\n// ─── Re-declared Vercel AI SDK shape (peer dependency — not bundled) ───────\n//\n// A Vercel `tool()` result. We only touch `execute`; everything else\n// (description, parameters/inputSchema) is passed through untouched, so this\n// stays compatible across AI SDK minor versions that rename schema fields.\ninterface VercelTool {\n description?: string;\n parameters?: unknown; // AI SDK v3/early v4\n inputSchema?: unknown; // AI SDK v4+\n execute?: (args: any, options?: any) => Promise<any> | any;\n [k: string]: unknown;\n}\n\n// ─── Configuration ──────────────────────────────────────────────────────────\n\nexport interface VorimVercelConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id (e.g. agid_acme_a1b2c3d4). */\n agentId: string;\n /** Per-tool permission scope override, keyed by tool name. */\n permissionMap?: Record<string, PermissionScope>;\n /** Default scope for tools without an entry in permissionMap. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Emit audit events fire-and-forget. @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. @default false\n *\n * When true, each call is evaluated against your live policy rules and the\n * returned decisionId is linked onto every audit event's decision_id.\n * Requires the runtime_control plan feature (Growth+) and consumes decision\n * quota. When false (default) the fast permission check is used.\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 * Replayable agent decision evidence (VAIP -02). When provided, the hashes\n * are attached to every audit event. If `replay.tools` is not given, the\n * wrapped tools' own catalogue is derived automatically.\n */\n replay?: ReplayInputs;\n}\n\nfunction truncate(s: string, max: number): string {\n return s.length > max ? s.slice(0, max) + '…' : s;\n}\n\nasync function gate(\n cfg: VorimVercelConfig,\n scope: PermissionScope,\n actionTarget: string,\n payload?: Record<string, unknown>,\n): Promise<{ allowed: boolean; reason?: string; decisionId?: string }> {\n if (cfg.useRuntimeControl) {\n return runtimeGate(cfg.vorim, cfg.agentId, actionTarget, scope, payload, {\n onEscalation: cfg.onEscalation,\n escalationTimeoutMs: cfg.escalationTimeoutMs,\n });\n }\n const { allowed, reason } = await cfg.vorim.check(cfg.agentId, scope);\n return { allowed, reason };\n}\n\nfunction emitAudit(vorim: VorimSDK, event: AuditEventInput, asyncAudit: boolean): Promise<void> | void {\n if (asyncAudit) {\n vorim.emit(event).catch(() => {});\n return;\n }\n return vorim.emit(event).then(() => undefined).catch(() => undefined);\n}\n\n/** Lazy replay-context getter — computes hashes once, reuses thereafter. */\nfunction makeReplayGetter(replay: ReplayInputs | undefined): () => Promise<ReplayContext> {\n if (!replay) return async () => ({});\n let cached: Promise<ReplayContext> | null = null;\n return () => {\n if (!cached) cached = prepareReplayContext(replay);\n return cached;\n };\n}\n\n// ─── Wrappers ────────────────────────────────────────────────────────────────\n\n/**\n * Wrap a single Vercel AI SDK tool so every execution is gated by a Vorim\n * permission/runtime check and recorded in the signed audit trail. A denied\n * call throws (so the AI SDK records a tool error) and is audited as `denied`.\n * Tools with no `execute` (client-side / provider-executed tools) pass through\n * unchanged.\n */\nexport function wrapVercelTool(name: string, tool: VercelTool, config: VorimVercelConfig): VercelTool {\n const { vorim, defaultPermission = 'agent:execute', permissionMap = {}, asyncAudit = true } = config;\n if (typeof tool.execute !== 'function') return tool; // nothing to guard\n\n const originalExecute = tool.execute.bind(tool);\n const getReplay = makeReplayGetter(config.replay);\n const scope = permissionMap[name] ?? defaultPermission;\n\n const guarded: VercelTool = {\n ...tool,\n execute: async (args: any, options?: any): Promise<any> => {\n const { allowed, reason, decisionId } = await gate(config, scope, name, args as Record<string, unknown>);\n const replayCtx = await getReplay();\n const resource = truncate(safeJson(args), 500);\n\n if (!allowed) {\n await emitAudit(vorim, {\n agent_id: config.agentId,\n event_type: 'tool_call',\n action: name,\n resource,\n permission: scope,\n result: 'denied',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { reason, framework: 'vercel-ai' },\n ...replayCtx,\n }, asyncAudit);\n throw new Error(`Vorim: permission denied for \"${name}\" — scope \"${scope}\"${reason ? `: ${reason}` : ''}`);\n }\n\n const start = Date.now();\n try {\n const result = await originalExecute(args, options);\n await emitAudit(vorim, {\n agent_id: config.agentId,\n event_type: 'tool_call',\n action: name,\n resource,\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { framework: 'vercel-ai' },\n ...replayCtx,\n }, asyncAudit);\n return result;\n } catch (err) {\n await emitAudit(vorim, {\n agent_id: config.agentId,\n event_type: 'tool_call',\n action: name,\n resource,\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: err instanceof Error ? err.message : String(err), framework: 'vercel-ai' },\n ...replayCtx,\n }, asyncAudit);\n throw err;\n }\n },\n };\n\n return guarded;\n}\n\n/**\n * Wrap the `tools` object you pass to generateText / streamText. Returns a new\n * object with every executable tool guarded. If `replay.tools` was not provided,\n * the tool catalogue is derived from these tools automatically.\n */\nexport function wrapVercelTools(\n tools: Record<string, VercelTool>,\n config: VorimVercelConfig,\n): Record<string, VercelTool> {\n // Auto-derive the replay tool catalogue from the tools when not supplied.\n const cfg: VorimVercelConfig =\n config.replay && !config.replay.tools\n ? { ...config, replay: { ...config.replay, tools: deriveCatalogue(tools) } }\n : config;\n\n const out: Record<string, VercelTool> = {};\n for (const [name, tool] of Object.entries(tools)) {\n out[name] = wrapVercelTool(name, tool, cfg);\n }\n return out;\n}\n\nfunction deriveCatalogue(tools: Record<string, VercelTool>): CatalogueTool[] {\n return Object.entries(tools).map(([name, t]) => ({\n name,\n description: typeof t.description === 'string' ? t.description : '',\n schema: (t.inputSchema ?? t.parameters ?? {}) as Record<string, unknown>,\n }));\n}\n\nfunction safeJson(v: unknown): string {\n try {\n return JSON.stringify(v);\n } catch {\n return String(v);\n }\n}\n"],"mappings":";AAuCA,SAAS,eAAe,UAAgD;AACtE,SAAO,aAAa,WAAW,aAAa,YAAY,aAAa;AACvE;AASA,eAAsB,YACpB,OACA,SACA,cACA,OACA,SACA,OAA2B,CAAC,GACP;AACrB,QAAM,eAAe,KAAK,gBAAgB;AAC1C,QAAM,IAAI,MAAM,MAAM;AAAA,IACpB,EAAE,SAAS,YAAY,aAAa,cAAc,eAAe,OAAO,QAAQ;AAAA,IAChF,EAAE,aAAa,MAAM;AAAA,EACvB;AAEA,MAAI,EAAE,aAAa,YAAY;AAC7B,WAAO,EAAE,SAAS,eAAe,EAAE,QAAQ,GAAG,QAAQ,EAAE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AAE,cAAc,CAAC;AAAA,EAC7C,EAAE;AACJ;AAEA,SAAS,SAAS,GAAoB;AACpC,MAAI;AACF,WAAO,KAAK,UAAU,CAAC;AAAA,EACzB,QAAQ;AACN,WAAO,OAAO,CAAC;AAAA,EACjB;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vorim/sdk",
3
- "version": "3.6.4",
3
+ "version": "3.7.1",
4
4
  "description": "Official TypeScript SDK for Vorim AI — AI Agent Identity, Permissions & Audit",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -97,6 +97,16 @@
97
97
  "default": "./dist/integrations/stripe-acp.cjs"
98
98
  }
99
99
  },
100
+ "./integrations/ucp": {
101
+ "import": {
102
+ "types": "./dist/integrations/ucp.d.ts",
103
+ "default": "./dist/integrations/ucp.js"
104
+ },
105
+ "require": {
106
+ "types": "./dist/integrations/ucp.d.cts",
107
+ "default": "./dist/integrations/ucp.cjs"
108
+ }
109
+ },
100
110
  "./integrations/siem": {
101
111
  "import": {
102
112
  "types": "./dist/integrations/siem.d.ts",