@vorim/sdk 3.6.2 → 3.6.3
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.
- package/CHANGELOG.md +13 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/integrations/anthropic.cjs +13 -6
- package/dist/integrations/anthropic.cjs.map +1 -1
- package/dist/integrations/anthropic.js +13 -6
- package/dist/integrations/anthropic.js.map +1 -1
- package/dist/integrations/llamaindex.cjs +5 -6
- package/dist/integrations/llamaindex.cjs.map +1 -1
- package/dist/integrations/llamaindex.js +5 -6
- package/dist/integrations/llamaindex.js.map +1 -1
- package/dist/integrations/stripe-acp.cjs.map +1 -1
- package/dist/integrations/stripe-acp.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# Changelog — @vorim/sdk
|
|
2
2
|
|
|
3
|
+
## 3.6.2
|
|
4
|
+
|
|
5
|
+
### Changed
|
|
6
|
+
|
|
7
|
+
- Republish with repository references updated from the `Kzino` account to the
|
|
8
|
+
`Vorim-AI-Labs` organisation. No runtime behaviour changes.
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
|
|
12
|
+
- Corrected the `stripe-acp` integration usage example in the file header: it
|
|
13
|
+
now shows the real `createVorimACP(vorim, config?)` signature (an SDK instance
|
|
14
|
+
first, then optional config), matching the function and its JSDoc.
|
|
15
|
+
|
|
3
16
|
## 3.6.1
|
|
4
17
|
|
|
5
18
|
### Fixed
|
package/dist/index.cjs
CHANGED
|
@@ -117,7 +117,7 @@ async function prepareReplayContext(inputs) {
|
|
|
117
117
|
}
|
|
118
118
|
|
|
119
119
|
// src/index.ts
|
|
120
|
-
var SDK_VERSION = true ? "3.6.
|
|
120
|
+
var SDK_VERSION = true ? "3.6.3" : "0.0.0";
|
|
121
121
|
var USER_AGENT = `vorim-sdk/${SDK_VERSION}`;
|
|
122
122
|
function sleep(ms) {
|
|
123
123
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
package/dist/index.js
CHANGED
|
@@ -69,7 +69,7 @@ async function prepareReplayContext(inputs) {
|
|
|
69
69
|
}
|
|
70
70
|
|
|
71
71
|
// src/index.ts
|
|
72
|
-
var SDK_VERSION = true ? "3.6.
|
|
72
|
+
var SDK_VERSION = true ? "3.6.3" : "0.0.0";
|
|
73
73
|
var USER_AGENT = `vorim-sdk/${SDK_VERSION}`;
|
|
74
74
|
function sleep(ms) {
|
|
75
75
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -236,7 +236,7 @@ var VorimToolRegistry = class {
|
|
|
236
236
|
metadata: { reason, framework: "anthropic" },
|
|
237
237
|
...replayCtx
|
|
238
238
|
};
|
|
239
|
-
this.emitAudit(event);
|
|
239
|
+
await this.emitAudit(event);
|
|
240
240
|
return {
|
|
241
241
|
type: "tool_result",
|
|
242
242
|
tool_use_id: block.id,
|
|
@@ -260,7 +260,7 @@ var VorimToolRegistry = class {
|
|
|
260
260
|
metadata: { framework: "anthropic" },
|
|
261
261
|
...replayCtx
|
|
262
262
|
};
|
|
263
|
-
this.emitAudit(event);
|
|
263
|
+
await this.emitAudit(event);
|
|
264
264
|
return { type: "tool_result", tool_use_id: block.id, content };
|
|
265
265
|
} catch (err) {
|
|
266
266
|
const errMsg = err instanceof Error ? err.message : String(err);
|
|
@@ -277,7 +277,7 @@ var VorimToolRegistry = class {
|
|
|
277
277
|
metadata: { error: errMsg, framework: "anthropic" },
|
|
278
278
|
...replayCtx
|
|
279
279
|
};
|
|
280
|
-
this.emitAudit(event);
|
|
280
|
+
await this.emitAudit(event);
|
|
281
281
|
return {
|
|
282
282
|
type: "tool_result",
|
|
283
283
|
tool_use_id: block.id,
|
|
@@ -286,9 +286,16 @@ var VorimToolRegistry = class {
|
|
|
286
286
|
};
|
|
287
287
|
}
|
|
288
288
|
}
|
|
289
|
-
emitAudit(event) {
|
|
290
|
-
this.
|
|
291
|
-
|
|
289
|
+
async emitAudit(event) {
|
|
290
|
+
if (this.asyncAudit) {
|
|
291
|
+
this.vorim.emit(event).catch(() => {
|
|
292
|
+
});
|
|
293
|
+
} else {
|
|
294
|
+
try {
|
|
295
|
+
await this.vorim.emit(event);
|
|
296
|
+
} catch {
|
|
297
|
+
}
|
|
298
|
+
}
|
|
292
299
|
}
|
|
293
300
|
};
|
|
294
301
|
async function runAgentLoop(config) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/integrations/anthropic.ts","../../src/integrations/_runtime-gate.ts","../../src/replay.ts"],"sourcesContent":["// ============================================================================\n// VORIM SDK — Anthropic/Claude Integration\n// Wraps Anthropic tool use with Vorim permission checks, audit trails,\n// and agent identity. Works with the Anthropic Node.js SDK (messages API\n// with tool use).\n//\n// Peer dependency: @anthropic-ai/sdk >=0.30.0\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 Anthropic types (peer dependency — not bundled) ──────────\n\ninterface AnthropicTool {\n name: string;\n description: string;\n input_schema: Record<string, unknown>;\n}\n\ninterface ToolUseBlock {\n type: 'tool_use';\n id: string;\n name: string;\n input: Record<string, unknown>;\n}\n\ninterface ToolResultBlock {\n type: 'tool_result';\n tool_use_id: string;\n content: string;\n is_error?: boolean;\n}\n\n// ─── Configuration ────────────────────────────────────────────────────────\n\nexport interface VorimToolDefinition<TArgs = Record<string, unknown>, TResult = unknown> {\n /** Tool name (must match the tool name sent to Claude). */\n name: string;\n /** Description shown to Claude. */\n description: string;\n /** JSON Schema for the tool's input. */\n input_schema: Record<string, unknown>;\n /** The function to execute when the tool is called. */\n execute: (args: TArgs) => Promise<TResult>;\n /** Vorim permission scope required. @default 'agent:execute' */\n permission?: PermissionScope;\n}\n\nexport interface VorimAnthropicConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id. */\n agentId: string;\n /** Default permission scope for tools without an explicit one. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Whether to emit audit events asynchronously (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, tool calls are evaluated against live policy rules and the\n * returned decisionId is linked onto each 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). Hashes attached to\n * every audit event. If `replay.tools` is omitted, the registry's\n * own tool list is used automatically. Not covered by v0 canonical\n * signature form.\n */\n replay?: ReplayInputs;\n}\n\n// ─── Tool Registry ────────────────────────────────────────────────────────\n\n/**\n * Manages a set of tools with Vorim permission checks and audit logging.\n * Converts tools to Anthropic's tool format and handles execution of\n * tool_use blocks from Claude's response.\n *\n * @example\n * ```ts\n * import Anthropic from \"@anthropic-ai/sdk\";\n * import createVorim from \"@vorim/sdk\";\n * import { VorimToolRegistry } from \"@vorim/sdk/integrations/anthropic\";\n *\n * const vorim = createVorim({ apiKey: \"agid_sk_live_...\" });\n * const anthropic = new Anthropic();\n *\n * const registry = new VorimToolRegistry({\n * vorim,\n * agentId: \"agid_acme_a1b2c3d4\",\n * });\n *\n * registry.add({\n * name: \"search_docs\",\n * description: \"Search internal documents\",\n * input_schema: {\n * type: \"object\",\n * properties: { query: { type: \"string\" } },\n * required: [\"query\"],\n * },\n * execute: async ({ query }) => searchDocs(query),\n * permission: \"agent:read\",\n * });\n *\n * const response = await anthropic.messages.create({\n * model: \"claude-sonnet-4-20250514\",\n * max_tokens: 1024,\n * messages,\n * tools: registry.toAnthropicTools(),\n * });\n *\n * // Execute tool_use blocks from response\n * const toolResults = await registry.executeToolUseBlocks(\n * response.content.filter(b => b.type === \"tool_use\")\n * );\n * ```\n */\nexport class VorimToolRegistry {\n private vorim: VorimSDK;\n private agentId: string;\n private defaultPermission: PermissionScope;\n private asyncAudit: boolean;\n private useRuntimeControl: boolean;\n private onEscalation?: EscalationPolicy;\n private escalationTimeoutMs?: number;\n private tools = new Map<string, VorimToolDefinition>();\n private replayInputs: ReplayInputs | undefined;\n private replayCache: Promise<ReplayContext> | null = null;\n\n constructor(config: VorimAnthropicConfig) {\n this.vorim = config.vorim;\n this.agentId = config.agentId;\n this.defaultPermission = config.defaultPermission ?? 'agent:execute';\n this.asyncAudit = config.asyncAudit ?? true;\n this.useRuntimeControl = config.useRuntimeControl ?? false;\n this.onEscalation = config.onEscalation;\n this.escalationTimeoutMs = config.escalationTimeoutMs;\n this.replayInputs = config.replay;\n }\n\n /** Gate a tool call: runtime decision (with decisionId) or permission check. */\n private async gate(\n scope: PermissionScope,\n actionTarget: string,\n payload?: Record<string, unknown>,\n ): Promise<{ allowed: boolean; reason?: string; decisionId?: string }> {\n if (this.useRuntimeControl) {\n return runtimeGate(this.vorim, this.agentId, actionTarget, scope, payload, {\n onEscalation: this.onEscalation,\n escalationTimeoutMs: this.escalationTimeoutMs,\n });\n }\n const { allowed, reason } = await this.vorim.check(this.agentId, scope);\n return { allowed, reason };\n }\n\n private async getReplayContext(): Promise<ReplayContext> {\n if (!this.replayInputs) return {};\n if (!this.replayCache) {\n const inputs: ReplayInputs = {\n ...this.replayInputs,\n tools: this.replayInputs.tools ?? this.deriveCatalogue(),\n };\n this.replayCache = prepareReplayContext(inputs);\n }\n return this.replayCache;\n }\n\n private deriveCatalogue(): CatalogueTool[] {\n return [...this.tools.values()].map(t => ({\n name: t.name,\n description: t.description,\n schema: t.input_schema,\n }));\n }\n\n /** Register a tool. Invalidates the cached tool-catalogue hash. */\n add<TArgs, TResult>(definition: VorimToolDefinition<TArgs, TResult>): this {\n this.tools.set(definition.name, definition as VorimToolDefinition);\n this.replayCache = null;\n return this;\n }\n\n /** Register multiple tools. */\n addAll(definitions: VorimToolDefinition[]): this {\n for (const def of definitions) this.add(def);\n return this;\n }\n\n /** Convert registered tools to Anthropic's tool format. */\n toAnthropicTools(): AnthropicTool[] {\n return [...this.tools.values()].map(t => ({\n name: t.name,\n description: t.description,\n input_schema: t.input_schema,\n }));\n }\n\n /**\n * Execute tool_use blocks from a Claude message response.\n * Each call is checked against Vorim permissions and audited.\n * Returns an array of tool_result blocks ready to send back to Claude.\n */\n async executeToolUseBlocks(toolUseBlocks: ToolUseBlock[]): Promise<ToolResultBlock[]> {\n return Promise.all(\n toolUseBlocks.map(block => this.executeSingleBlock(block)),\n );\n }\n\n private async executeSingleBlock(block: ToolUseBlock): Promise<ToolResultBlock> {\n const definition = this.tools.get(block.name);\n\n if (!definition) {\n return {\n type: 'tool_result',\n tool_use_id: block.id,\n content: JSON.stringify({ error: `Unknown tool: ${block.name}` }),\n is_error: true,\n };\n }\n\n const scope = definition.permission ?? this.defaultPermission;\n\n // 1. Gate: runtime decision (with decisionId linkage) or permission check.\n const { allowed, reason, decisionId } = await this.gate(scope, block.name, block.input as Record<string, unknown>);\n const replayCtx = await this.getReplayContext();\n\n if (!allowed) {\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: block.name,\n resource: truncate(JSON.stringify(block.input), 500),\n permission: scope,\n result: 'denied',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { reason, framework: 'anthropic' },\n ...replayCtx,\n };\n this.emitAudit(event);\n\n return {\n type: 'tool_result',\n tool_use_id: block.id,\n content: JSON.stringify({ error: `Permission denied: ${scope}${reason ? ` — ${reason}` : ''}` }),\n is_error: true,\n };\n }\n\n // 2. Execute\n const start = Date.now();\n try {\n const result = await definition.execute(block.input as any);\n const content = typeof result === 'string' ? result : JSON.stringify(result);\n\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: block.name,\n resource: truncate(JSON.stringify(block.input), 500),\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { framework: 'anthropic' },\n ...replayCtx,\n };\n this.emitAudit(event);\n\n return { type: 'tool_result', tool_use_id: block.id, content };\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: block.name,\n resource: truncate(JSON.stringify(block.input), 500),\n permission: scope,\n result: 'error',\n latency_ms: Date.now() - start,\n error_code: err instanceof Error ? err.name : 'UNKNOWN',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { error: errMsg, framework: 'anthropic' },\n ...replayCtx,\n };\n this.emitAudit(event);\n\n return {\n type: 'tool_result',\n tool_use_id: block.id,\n content: JSON.stringify({ error: errMsg }),\n is_error: true,\n };\n }\n }\n\n private emitAudit(event: AuditEventInput): void {\n this.vorim.emit(event).catch(() => {});\n }\n}\n\n// ─── Agent Loop ───────────────────────────────────────────────────────────\n\n/** Minimal Anthropic client interface (avoids importing the full SDK). */\ninterface AnthropicClient {\n messages: {\n create(params: any): Promise<any>;\n };\n}\n\nexport interface VorimAgentLoopConfig extends VorimAnthropicConfig {\n /** Anthropic client instance. */\n anthropic: AnthropicClient;\n /** Model to use. @default 'claude-sonnet-4-20250514' */\n model?: string;\n /** System prompt for the agent. */\n systemPrompt?: string;\n /** Maximum tool-use iterations before stopping. @default 10 */\n maxIterations?: number;\n /** Max tokens per response. @default 1024 */\n maxTokens?: number;\n}\n\n/**\n * Runs a complete agent loop with Claude tool use, Vorim\n * permission enforcement, and audit logging.\n *\n * @example\n * ```ts\n * import Anthropic from \"@anthropic-ai/sdk\";\n * import createVorim from \"@vorim/sdk\";\n * import { runAgentLoop, VorimToolRegistry } from \"@vorim/sdk/integrations/anthropic\";\n *\n * const registry = new VorimToolRegistry({ vorim, agentId });\n * registry.add({ name: \"search\", ... });\n *\n * const response = await runAgentLoop({\n * vorim,\n * agentId,\n * anthropic: new Anthropic(),\n * model: \"claude-sonnet-4-20250514\",\n * systemPrompt: \"You are a helpful assistant.\",\n * registry,\n * userMessage: \"Find docs about onboarding\",\n * });\n * ```\n */\nexport async function runAgentLoop(\n config: VorimAgentLoopConfig & {\n registry: VorimToolRegistry;\n userMessage: string;\n },\n): Promise<string> {\n const {\n anthropic,\n model = 'claude-sonnet-4-20250514',\n systemPrompt,\n maxIterations = 10,\n maxTokens = 1024,\n registry,\n userMessage,\n } = config;\n\n const tools = registry.toAnthropicTools();\n const messages: any[] = [{ role: 'user', content: userMessage }];\n\n for (let i = 0; i < maxIterations; i++) {\n const response = await anthropic.messages.create({\n model,\n max_tokens: maxTokens,\n ...(systemPrompt ? { system: systemPrompt } : {}),\n messages,\n ...(tools.length > 0 ? { tools } : {}),\n });\n\n // If stop_reason is \"end_turn\" — Claude is done\n if (response.stop_reason === 'end_turn' || response.stop_reason !== 'tool_use') {\n const textBlocks = response.content.filter((b: any) => b.type === 'text');\n return textBlocks.map((b: any) => b.text).join('') || '';\n }\n\n // Extract tool_use blocks and execute\n const toolUseBlocks = response.content.filter((b: any) => b.type === 'tool_use');\n const toolResults = await registry.executeToolUseBlocks(toolUseBlocks);\n\n // Append assistant response and tool results to conversation\n messages.push({ role: 'assistant', content: response.content });\n messages.push({ role: 'user', content: toolResults });\n }\n\n return '';\n}\n\n// ─── Agent Registration Helper ───────────────────────────────────────────\n\n/**\n * Registers a new agent with Vorim and returns a ready-to-use tool registry\n * configured for Anthropic/Claude.\n *\n * @example\n * ```ts\n * const { agentId, registry } = await createVorimClaudeAgent({\n * vorim,\n * name: \"claude-assistant\",\n * capabilities: [\"search\", \"calculate\"],\n * scopes: [\"agent:read\", \"agent:execute\"],\n * tools: [searchTool, calcTool],\n * });\n * ```\n */\nexport async function createVorimClaudeAgent(config: {\n vorim: VorimSDK;\n name: string;\n description?: string;\n capabilities: string[];\n scopes: PermissionScope[];\n tools: VorimToolDefinition[];\n}) {\n const { vorim, name, description, capabilities, scopes, tools } = config;\n\n const registration = await vorim.register({\n name,\n description,\n capabilities,\n scopes,\n });\n\n const agentId = registration.agent.agent_id;\n const registry = new VorimToolRegistry({ vorim, agentId });\n registry.addAll(tools);\n\n return {\n agentId,\n registration,\n registry,\n privateKey: registration.private_key,\n };\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────────\n\nfunction truncate(str: string, max: number): string {\n return str.length > max ? str.slice(0, max) + '…' : str;\n}\n","// ============================================================================\n// VORIM SDK — 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;AAAA;AAAA;;;ACuCA,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,QAA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WAAM;AACtD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/integrations/anthropic.ts","../../src/integrations/_runtime-gate.ts","../../src/replay.ts"],"sourcesContent":["// ============================================================================\n// VORIM SDK — Anthropic/Claude Integration\n// Wraps Anthropic tool use with Vorim permission checks, audit trails,\n// and agent identity. Works with the Anthropic Node.js SDK (messages API\n// with tool use).\n//\n// Peer dependency: @anthropic-ai/sdk >=0.30.0\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 Anthropic types (peer dependency — not bundled) ──────────\n\ninterface AnthropicTool {\n name: string;\n description: string;\n input_schema: Record<string, unknown>;\n}\n\ninterface ToolUseBlock {\n type: 'tool_use';\n id: string;\n name: string;\n input: Record<string, unknown>;\n}\n\ninterface ToolResultBlock {\n type: 'tool_result';\n tool_use_id: string;\n content: string;\n is_error?: boolean;\n}\n\n// ─── Configuration ────────────────────────────────────────────────────────\n\nexport interface VorimToolDefinition<TArgs = Record<string, unknown>, TResult = unknown> {\n /** Tool name (must match the tool name sent to Claude). */\n name: string;\n /** Description shown to Claude. */\n description: string;\n /** JSON Schema for the tool's input. */\n input_schema: Record<string, unknown>;\n /** The function to execute when the tool is called. */\n execute: (args: TArgs) => Promise<TResult>;\n /** Vorim permission scope required. @default 'agent:execute' */\n permission?: PermissionScope;\n}\n\nexport interface VorimAnthropicConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id. */\n agentId: string;\n /** Default permission scope for tools without an explicit one. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Whether to emit audit events asynchronously (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, tool calls are evaluated against live policy rules and the\n * returned decisionId is linked onto each 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). Hashes attached to\n * every audit event. If `replay.tools` is omitted, the registry's\n * own tool list is used automatically. Not covered by v0 canonical\n * signature form.\n */\n replay?: ReplayInputs;\n}\n\n// ─── Tool Registry ────────────────────────────────────────────────────────\n\n/**\n * Manages a set of tools with Vorim permission checks and audit logging.\n * Converts tools to Anthropic's tool format and handles execution of\n * tool_use blocks from Claude's response.\n *\n * @example\n * ```ts\n * import Anthropic from \"@anthropic-ai/sdk\";\n * import createVorim from \"@vorim/sdk\";\n * import { VorimToolRegistry } from \"@vorim/sdk/integrations/anthropic\";\n *\n * const vorim = createVorim({ apiKey: \"agid_sk_live_...\" });\n * const anthropic = new Anthropic();\n *\n * const registry = new VorimToolRegistry({\n * vorim,\n * agentId: \"agid_acme_a1b2c3d4\",\n * });\n *\n * registry.add({\n * name: \"search_docs\",\n * description: \"Search internal documents\",\n * input_schema: {\n * type: \"object\",\n * properties: { query: { type: \"string\" } },\n * required: [\"query\"],\n * },\n * execute: async ({ query }) => searchDocs(query),\n * permission: \"agent:read\",\n * });\n *\n * const response = await anthropic.messages.create({\n * model: \"claude-sonnet-4-20250514\",\n * max_tokens: 1024,\n * messages,\n * tools: registry.toAnthropicTools(),\n * });\n *\n * // Execute tool_use blocks from response\n * const toolResults = await registry.executeToolUseBlocks(\n * response.content.filter(b => b.type === \"tool_use\")\n * );\n * ```\n */\nexport class VorimToolRegistry {\n private vorim: VorimSDK;\n private agentId: string;\n private defaultPermission: PermissionScope;\n private asyncAudit: boolean;\n private useRuntimeControl: boolean;\n private onEscalation?: EscalationPolicy;\n private escalationTimeoutMs?: number;\n private tools = new Map<string, VorimToolDefinition>();\n private replayInputs: ReplayInputs | undefined;\n private replayCache: Promise<ReplayContext> | null = null;\n\n constructor(config: VorimAnthropicConfig) {\n this.vorim = config.vorim;\n this.agentId = config.agentId;\n this.defaultPermission = config.defaultPermission ?? 'agent:execute';\n this.asyncAudit = config.asyncAudit ?? true;\n this.useRuntimeControl = config.useRuntimeControl ?? false;\n this.onEscalation = config.onEscalation;\n this.escalationTimeoutMs = config.escalationTimeoutMs;\n this.replayInputs = config.replay;\n }\n\n /** Gate a tool call: runtime decision (with decisionId) or permission check. */\n private async gate(\n scope: PermissionScope,\n actionTarget: string,\n payload?: Record<string, unknown>,\n ): Promise<{ allowed: boolean; reason?: string; decisionId?: string }> {\n if (this.useRuntimeControl) {\n return runtimeGate(this.vorim, this.agentId, actionTarget, scope, payload, {\n onEscalation: this.onEscalation,\n escalationTimeoutMs: this.escalationTimeoutMs,\n });\n }\n const { allowed, reason } = await this.vorim.check(this.agentId, scope);\n return { allowed, reason };\n }\n\n private async getReplayContext(): Promise<ReplayContext> {\n if (!this.replayInputs) return {};\n if (!this.replayCache) {\n const inputs: ReplayInputs = {\n ...this.replayInputs,\n tools: this.replayInputs.tools ?? this.deriveCatalogue(),\n };\n this.replayCache = prepareReplayContext(inputs);\n }\n return this.replayCache;\n }\n\n private deriveCatalogue(): CatalogueTool[] {\n return [...this.tools.values()].map(t => ({\n name: t.name,\n description: t.description,\n schema: t.input_schema,\n }));\n }\n\n /** Register a tool. Invalidates the cached tool-catalogue hash. */\n add<TArgs, TResult>(definition: VorimToolDefinition<TArgs, TResult>): this {\n this.tools.set(definition.name, definition as VorimToolDefinition);\n this.replayCache = null;\n return this;\n }\n\n /** Register multiple tools. */\n addAll(definitions: VorimToolDefinition[]): this {\n for (const def of definitions) this.add(def);\n return this;\n }\n\n /** Convert registered tools to Anthropic's tool format. */\n toAnthropicTools(): AnthropicTool[] {\n return [...this.tools.values()].map(t => ({\n name: t.name,\n description: t.description,\n input_schema: t.input_schema,\n }));\n }\n\n /**\n * Execute tool_use blocks from a Claude message response.\n * Each call is checked against Vorim permissions and audited.\n * Returns an array of tool_result blocks ready to send back to Claude.\n */\n async executeToolUseBlocks(toolUseBlocks: ToolUseBlock[]): Promise<ToolResultBlock[]> {\n return Promise.all(\n toolUseBlocks.map(block => this.executeSingleBlock(block)),\n );\n }\n\n private async executeSingleBlock(block: ToolUseBlock): Promise<ToolResultBlock> {\n const definition = this.tools.get(block.name);\n\n if (!definition) {\n return {\n type: 'tool_result',\n tool_use_id: block.id,\n content: JSON.stringify({ error: `Unknown tool: ${block.name}` }),\n is_error: true,\n };\n }\n\n const scope = definition.permission ?? this.defaultPermission;\n\n // 1. Gate: runtime decision (with decisionId linkage) or permission check.\n const { allowed, reason, decisionId } = await this.gate(scope, block.name, block.input as Record<string, unknown>);\n const replayCtx = await this.getReplayContext();\n\n if (!allowed) {\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: block.name,\n resource: truncate(JSON.stringify(block.input), 500),\n permission: scope,\n result: 'denied',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { reason, framework: 'anthropic' },\n ...replayCtx,\n };\n await this.emitAudit(event);\n\n return {\n type: 'tool_result',\n tool_use_id: block.id,\n content: JSON.stringify({ error: `Permission denied: ${scope}${reason ? ` — ${reason}` : ''}` }),\n is_error: true,\n };\n }\n\n // 2. Execute\n const start = Date.now();\n try {\n const result = await definition.execute(block.input as any);\n const content = typeof result === 'string' ? result : JSON.stringify(result);\n\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: block.name,\n resource: truncate(JSON.stringify(block.input), 500),\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { framework: 'anthropic' },\n ...replayCtx,\n };\n await this.emitAudit(event);\n\n return { type: 'tool_result', tool_use_id: block.id, content };\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: block.name,\n resource: truncate(JSON.stringify(block.input), 500),\n permission: scope,\n result: 'error',\n latency_ms: Date.now() - start,\n error_code: err instanceof Error ? err.name : 'UNKNOWN',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { error: errMsg, framework: 'anthropic' },\n ...replayCtx,\n };\n await this.emitAudit(event);\n\n return {\n type: 'tool_result',\n tool_use_id: block.id,\n content: JSON.stringify({ error: errMsg }),\n is_error: true,\n };\n }\n }\n\n private async emitAudit(event: AuditEventInput): Promise<void> {\n if (this.asyncAudit) {\n // Fire-and-forget: don't block the tool pipeline on the audit write.\n this.vorim.emit(event).catch(() => {});\n } else {\n // Synchronous mode: actually await so the audit is flushed before the\n // caller continues.\n try { await this.vorim.emit(event); } catch { /* best-effort */ }\n }\n }\n}\n\n// ─── Agent Loop ───────────────────────────────────────────────────────────\n\n/** Minimal Anthropic client interface (avoids importing the full SDK). */\ninterface AnthropicClient {\n messages: {\n create(params: any): Promise<any>;\n };\n}\n\nexport interface VorimAgentLoopConfig extends VorimAnthropicConfig {\n /** Anthropic client instance. */\n anthropic: AnthropicClient;\n /** Model to use. @default 'claude-sonnet-4-20250514' */\n model?: string;\n /** System prompt for the agent. */\n systemPrompt?: string;\n /** Maximum tool-use iterations before stopping. @default 10 */\n maxIterations?: number;\n /** Max tokens per response. @default 1024 */\n maxTokens?: number;\n}\n\n/**\n * Runs a complete agent loop with Claude tool use, Vorim\n * permission enforcement, and audit logging.\n *\n * @example\n * ```ts\n * import Anthropic from \"@anthropic-ai/sdk\";\n * import createVorim from \"@vorim/sdk\";\n * import { runAgentLoop, VorimToolRegistry } from \"@vorim/sdk/integrations/anthropic\";\n *\n * const registry = new VorimToolRegistry({ vorim, agentId });\n * registry.add({ name: \"search\", ... });\n *\n * const response = await runAgentLoop({\n * vorim,\n * agentId,\n * anthropic: new Anthropic(),\n * model: \"claude-sonnet-4-20250514\",\n * systemPrompt: \"You are a helpful assistant.\",\n * registry,\n * userMessage: \"Find docs about onboarding\",\n * });\n * ```\n */\nexport async function runAgentLoop(\n config: VorimAgentLoopConfig & {\n registry: VorimToolRegistry;\n userMessage: string;\n },\n): Promise<string> {\n const {\n anthropic,\n model = 'claude-sonnet-4-20250514',\n systemPrompt,\n maxIterations = 10,\n maxTokens = 1024,\n registry,\n userMessage,\n } = config;\n\n const tools = registry.toAnthropicTools();\n const messages: any[] = [{ role: 'user', content: userMessage }];\n\n for (let i = 0; i < maxIterations; i++) {\n const response = await anthropic.messages.create({\n model,\n max_tokens: maxTokens,\n ...(systemPrompt ? { system: systemPrompt } : {}),\n messages,\n ...(tools.length > 0 ? { tools } : {}),\n });\n\n // If stop_reason is \"end_turn\" — Claude is done\n if (response.stop_reason === 'end_turn' || response.stop_reason !== 'tool_use') {\n const textBlocks = response.content.filter((b: any) => b.type === 'text');\n return textBlocks.map((b: any) => b.text).join('') || '';\n }\n\n // Extract tool_use blocks and execute\n const toolUseBlocks = response.content.filter((b: any) => b.type === 'tool_use');\n const toolResults = await registry.executeToolUseBlocks(toolUseBlocks);\n\n // Append assistant response and tool results to conversation\n messages.push({ role: 'assistant', content: response.content });\n messages.push({ role: 'user', content: toolResults });\n }\n\n return '';\n}\n\n// ─── Agent Registration Helper ───────────────────────────────────────────\n\n/**\n * Registers a new agent with Vorim and returns a ready-to-use tool registry\n * configured for Anthropic/Claude.\n *\n * @example\n * ```ts\n * const { agentId, registry } = await createVorimClaudeAgent({\n * vorim,\n * name: \"claude-assistant\",\n * capabilities: [\"search\", \"calculate\"],\n * scopes: [\"agent:read\", \"agent:execute\"],\n * tools: [searchTool, calcTool],\n * });\n * ```\n */\nexport async function createVorimClaudeAgent(config: {\n vorim: VorimSDK;\n name: string;\n description?: string;\n capabilities: string[];\n scopes: PermissionScope[];\n tools: VorimToolDefinition[];\n}) {\n const { vorim, name, description, capabilities, scopes, tools } = config;\n\n const registration = await vorim.register({\n name,\n description,\n capabilities,\n scopes,\n });\n\n const agentId = registration.agent.agent_id;\n const registry = new VorimToolRegistry({ vorim, agentId });\n registry.addAll(tools);\n\n return {\n agentId,\n registration,\n registry,\n privateKey: registration.private_key,\n };\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────────\n\nfunction truncate(str: string, max: number): string {\n return str.length > max ? str.slice(0, max) + '…' : str;\n}\n","// ============================================================================\n// VORIM SDK — 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;AAAA;AAAA;;;ACuCA,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,MAA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IAAI,SAAS,MAAM,IAAI,MAAM,GAAG,GAAG,IAAI,WAAM;AACtD;","names":[]}
|
|
@@ -198,7 +198,7 @@ var VorimToolRegistry = class {
|
|
|
198
198
|
metadata: { reason, framework: "anthropic" },
|
|
199
199
|
...replayCtx
|
|
200
200
|
};
|
|
201
|
-
this.emitAudit(event);
|
|
201
|
+
await this.emitAudit(event);
|
|
202
202
|
return {
|
|
203
203
|
type: "tool_result",
|
|
204
204
|
tool_use_id: block.id,
|
|
@@ -222,7 +222,7 @@ var VorimToolRegistry = class {
|
|
|
222
222
|
metadata: { framework: "anthropic" },
|
|
223
223
|
...replayCtx
|
|
224
224
|
};
|
|
225
|
-
this.emitAudit(event);
|
|
225
|
+
await this.emitAudit(event);
|
|
226
226
|
return { type: "tool_result", tool_use_id: block.id, content };
|
|
227
227
|
} catch (err) {
|
|
228
228
|
const errMsg = err instanceof Error ? err.message : String(err);
|
|
@@ -239,7 +239,7 @@ var VorimToolRegistry = class {
|
|
|
239
239
|
metadata: { error: errMsg, framework: "anthropic" },
|
|
240
240
|
...replayCtx
|
|
241
241
|
};
|
|
242
|
-
this.emitAudit(event);
|
|
242
|
+
await this.emitAudit(event);
|
|
243
243
|
return {
|
|
244
244
|
type: "tool_result",
|
|
245
245
|
tool_use_id: block.id,
|
|
@@ -248,9 +248,16 @@ var VorimToolRegistry = class {
|
|
|
248
248
|
};
|
|
249
249
|
}
|
|
250
250
|
}
|
|
251
|
-
emitAudit(event) {
|
|
252
|
-
this.
|
|
253
|
-
|
|
251
|
+
async emitAudit(event) {
|
|
252
|
+
if (this.asyncAudit) {
|
|
253
|
+
this.vorim.emit(event).catch(() => {
|
|
254
|
+
});
|
|
255
|
+
} else {
|
|
256
|
+
try {
|
|
257
|
+
await this.vorim.emit(event);
|
|
258
|
+
} catch {
|
|
259
|
+
}
|
|
260
|
+
}
|
|
254
261
|
}
|
|
255
262
|
};
|
|
256
263
|
async function runAgentLoop(config) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/integrations/_runtime-gate.ts","../../src/replay.ts","../../src/integrations/anthropic.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 — Anthropic/Claude Integration\n// Wraps Anthropic tool use with Vorim permission checks, audit trails,\n// and agent identity. Works with the Anthropic Node.js SDK (messages API\n// with tool use).\n//\n// Peer dependency: @anthropic-ai/sdk >=0.30.0\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 Anthropic types (peer dependency — not bundled) ──────────\n\ninterface AnthropicTool {\n name: string;\n description: string;\n input_schema: Record<string, unknown>;\n}\n\ninterface ToolUseBlock {\n type: 'tool_use';\n id: string;\n name: string;\n input: Record<string, unknown>;\n}\n\ninterface ToolResultBlock {\n type: 'tool_result';\n tool_use_id: string;\n content: string;\n is_error?: boolean;\n}\n\n// ─── Configuration ────────────────────────────────────────────────────────\n\nexport interface VorimToolDefinition<TArgs = Record<string, unknown>, TResult = unknown> {\n /** Tool name (must match the tool name sent to Claude). */\n name: string;\n /** Description shown to Claude. */\n description: string;\n /** JSON Schema for the tool's input. */\n input_schema: Record<string, unknown>;\n /** The function to execute when the tool is called. */\n execute: (args: TArgs) => Promise<TResult>;\n /** Vorim permission scope required. @default 'agent:execute' */\n permission?: PermissionScope;\n}\n\nexport interface VorimAnthropicConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id. */\n agentId: string;\n /** Default permission scope for tools without an explicit one. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Whether to emit audit events asynchronously (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, tool calls are evaluated against live policy rules and the\n * returned decisionId is linked onto each 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). Hashes attached to\n * every audit event. If `replay.tools` is omitted, the registry's\n * own tool list is used automatically. Not covered by v0 canonical\n * signature form.\n */\n replay?: ReplayInputs;\n}\n\n// ─── Tool Registry ────────────────────────────────────────────────────────\n\n/**\n * Manages a set of tools with Vorim permission checks and audit logging.\n * Converts tools to Anthropic's tool format and handles execution of\n * tool_use blocks from Claude's response.\n *\n * @example\n * ```ts\n * import Anthropic from \"@anthropic-ai/sdk\";\n * import createVorim from \"@vorim/sdk\";\n * import { VorimToolRegistry } from \"@vorim/sdk/integrations/anthropic\";\n *\n * const vorim = createVorim({ apiKey: \"agid_sk_live_...\" });\n * const anthropic = new Anthropic();\n *\n * const registry = new VorimToolRegistry({\n * vorim,\n * agentId: \"agid_acme_a1b2c3d4\",\n * });\n *\n * registry.add({\n * name: \"search_docs\",\n * description: \"Search internal documents\",\n * input_schema: {\n * type: \"object\",\n * properties: { query: { type: \"string\" } },\n * required: [\"query\"],\n * },\n * execute: async ({ query }) => searchDocs(query),\n * permission: \"agent:read\",\n * });\n *\n * const response = await anthropic.messages.create({\n * model: \"claude-sonnet-4-20250514\",\n * max_tokens: 1024,\n * messages,\n * tools: registry.toAnthropicTools(),\n * });\n *\n * // Execute tool_use blocks from response\n * const toolResults = await registry.executeToolUseBlocks(\n * response.content.filter(b => b.type === \"tool_use\")\n * );\n * ```\n */\nexport class VorimToolRegistry {\n private vorim: VorimSDK;\n private agentId: string;\n private defaultPermission: PermissionScope;\n private asyncAudit: boolean;\n private useRuntimeControl: boolean;\n private onEscalation?: EscalationPolicy;\n private escalationTimeoutMs?: number;\n private tools = new Map<string, VorimToolDefinition>();\n private replayInputs: ReplayInputs | undefined;\n private replayCache: Promise<ReplayContext> | null = null;\n\n constructor(config: VorimAnthropicConfig) {\n this.vorim = config.vorim;\n this.agentId = config.agentId;\n this.defaultPermission = config.defaultPermission ?? 'agent:execute';\n this.asyncAudit = config.asyncAudit ?? true;\n this.useRuntimeControl = config.useRuntimeControl ?? false;\n this.onEscalation = config.onEscalation;\n this.escalationTimeoutMs = config.escalationTimeoutMs;\n this.replayInputs = config.replay;\n }\n\n /** Gate a tool call: runtime decision (with decisionId) or permission check. */\n private async gate(\n scope: PermissionScope,\n actionTarget: string,\n payload?: Record<string, unknown>,\n ): Promise<{ allowed: boolean; reason?: string; decisionId?: string }> {\n if (this.useRuntimeControl) {\n return runtimeGate(this.vorim, this.agentId, actionTarget, scope, payload, {\n onEscalation: this.onEscalation,\n escalationTimeoutMs: this.escalationTimeoutMs,\n });\n }\n const { allowed, reason } = await this.vorim.check(this.agentId, scope);\n return { allowed, reason };\n }\n\n private async getReplayContext(): Promise<ReplayContext> {\n if (!this.replayInputs) return {};\n if (!this.replayCache) {\n const inputs: ReplayInputs = {\n ...this.replayInputs,\n tools: this.replayInputs.tools ?? this.deriveCatalogue(),\n };\n this.replayCache = prepareReplayContext(inputs);\n }\n return this.replayCache;\n }\n\n private deriveCatalogue(): CatalogueTool[] {\n return [...this.tools.values()].map(t => ({\n name: t.name,\n description: t.description,\n schema: t.input_schema,\n }));\n }\n\n /** Register a tool. Invalidates the cached tool-catalogue hash. */\n add<TArgs, TResult>(definition: VorimToolDefinition<TArgs, TResult>): this {\n this.tools.set(definition.name, definition as VorimToolDefinition);\n this.replayCache = null;\n return this;\n }\n\n /** Register multiple tools. */\n addAll(definitions: VorimToolDefinition[]): this {\n for (const def of definitions) this.add(def);\n return this;\n }\n\n /** Convert registered tools to Anthropic's tool format. */\n toAnthropicTools(): AnthropicTool[] {\n return [...this.tools.values()].map(t => ({\n name: t.name,\n description: t.description,\n input_schema: t.input_schema,\n }));\n }\n\n /**\n * Execute tool_use blocks from a Claude message response.\n * Each call is checked against Vorim permissions and audited.\n * Returns an array of tool_result blocks ready to send back to Claude.\n */\n async executeToolUseBlocks(toolUseBlocks: ToolUseBlock[]): Promise<ToolResultBlock[]> {\n return Promise.all(\n toolUseBlocks.map(block => this.executeSingleBlock(block)),\n );\n }\n\n private async executeSingleBlock(block: ToolUseBlock): Promise<ToolResultBlock> {\n const definition = this.tools.get(block.name);\n\n if (!definition) {\n return {\n type: 'tool_result',\n tool_use_id: block.id,\n content: JSON.stringify({ error: `Unknown tool: ${block.name}` }),\n is_error: true,\n };\n }\n\n const scope = definition.permission ?? this.defaultPermission;\n\n // 1. Gate: runtime decision (with decisionId linkage) or permission check.\n const { allowed, reason, decisionId } = await this.gate(scope, block.name, block.input as Record<string, unknown>);\n const replayCtx = await this.getReplayContext();\n\n if (!allowed) {\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: block.name,\n resource: truncate(JSON.stringify(block.input), 500),\n permission: scope,\n result: 'denied',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { reason, framework: 'anthropic' },\n ...replayCtx,\n };\n this.emitAudit(event);\n\n return {\n type: 'tool_result',\n tool_use_id: block.id,\n content: JSON.stringify({ error: `Permission denied: ${scope}${reason ? ` — ${reason}` : ''}` }),\n is_error: true,\n };\n }\n\n // 2. Execute\n const start = Date.now();\n try {\n const result = await definition.execute(block.input as any);\n const content = typeof result === 'string' ? result : JSON.stringify(result);\n\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: block.name,\n resource: truncate(JSON.stringify(block.input), 500),\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { framework: 'anthropic' },\n ...replayCtx,\n };\n this.emitAudit(event);\n\n return { type: 'tool_result', tool_use_id: block.id, content };\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: block.name,\n resource: truncate(JSON.stringify(block.input), 500),\n permission: scope,\n result: 'error',\n latency_ms: Date.now() - start,\n error_code: err instanceof Error ? err.name : 'UNKNOWN',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { error: errMsg, framework: 'anthropic' },\n ...replayCtx,\n };\n this.emitAudit(event);\n\n return {\n type: 'tool_result',\n tool_use_id: block.id,\n content: JSON.stringify({ error: errMsg }),\n is_error: true,\n };\n }\n }\n\n private emitAudit(event: AuditEventInput): void {\n this.vorim.emit(event).catch(() => {});\n }\n}\n\n// ─── Agent Loop ───────────────────────────────────────────────────────────\n\n/** Minimal Anthropic client interface (avoids importing the full SDK). */\ninterface AnthropicClient {\n messages: {\n create(params: any): Promise<any>;\n };\n}\n\nexport interface VorimAgentLoopConfig extends VorimAnthropicConfig {\n /** Anthropic client instance. */\n anthropic: AnthropicClient;\n /** Model to use. @default 'claude-sonnet-4-20250514' */\n model?: string;\n /** System prompt for the agent. */\n systemPrompt?: string;\n /** Maximum tool-use iterations before stopping. @default 10 */\n maxIterations?: number;\n /** Max tokens per response. @default 1024 */\n maxTokens?: number;\n}\n\n/**\n * Runs a complete agent loop with Claude tool use, Vorim\n * permission enforcement, and audit logging.\n *\n * @example\n * ```ts\n * import Anthropic from \"@anthropic-ai/sdk\";\n * import createVorim from \"@vorim/sdk\";\n * import { runAgentLoop, VorimToolRegistry } from \"@vorim/sdk/integrations/anthropic\";\n *\n * const registry = new VorimToolRegistry({ vorim, agentId });\n * registry.add({ name: \"search\", ... });\n *\n * const response = await runAgentLoop({\n * vorim,\n * agentId,\n * anthropic: new Anthropic(),\n * model: \"claude-sonnet-4-20250514\",\n * systemPrompt: \"You are a helpful assistant.\",\n * registry,\n * userMessage: \"Find docs about onboarding\",\n * });\n * ```\n */\nexport async function runAgentLoop(\n config: VorimAgentLoopConfig & {\n registry: VorimToolRegistry;\n userMessage: string;\n },\n): Promise<string> {\n const {\n anthropic,\n model = 'claude-sonnet-4-20250514',\n systemPrompt,\n maxIterations = 10,\n maxTokens = 1024,\n registry,\n userMessage,\n } = config;\n\n const tools = registry.toAnthropicTools();\n const messages: any[] = [{ role: 'user', content: userMessage }];\n\n for (let i = 0; i < maxIterations; i++) {\n const response = await anthropic.messages.create({\n model,\n max_tokens: maxTokens,\n ...(systemPrompt ? { system: systemPrompt } : {}),\n messages,\n ...(tools.length > 0 ? { tools } : {}),\n });\n\n // If stop_reason is \"end_turn\" — Claude is done\n if (response.stop_reason === 'end_turn' || response.stop_reason !== 'tool_use') {\n const textBlocks = response.content.filter((b: any) => b.type === 'text');\n return textBlocks.map((b: any) => b.text).join('') || '';\n }\n\n // Extract tool_use blocks and execute\n const toolUseBlocks = response.content.filter((b: any) => b.type === 'tool_use');\n const toolResults = await registry.executeToolUseBlocks(toolUseBlocks);\n\n // Append assistant response and tool results to conversation\n messages.push({ role: 'assistant', content: response.content });\n messages.push({ role: 'user', content: toolResults });\n }\n\n return '';\n}\n\n// ─── Agent Registration Helper ───────────────────────────────────────────\n\n/**\n * Registers a new agent with Vorim and returns a ready-to-use tool registry\n * configured for Anthropic/Claude.\n *\n * @example\n * ```ts\n * const { agentId, registry } = await createVorimClaudeAgent({\n * vorim,\n * name: \"claude-assistant\",\n * capabilities: [\"search\", \"calculate\"],\n * scopes: [\"agent:read\", \"agent:execute\"],\n * tools: [searchTool, calcTool],\n * });\n * ```\n */\nexport async function createVorimClaudeAgent(config: {\n vorim: VorimSDK;\n name: string;\n description?: string;\n capabilities: string[];\n scopes: PermissionScope[];\n tools: VorimToolDefinition[];\n}) {\n const { vorim, name, description, capabilities, scopes, tools } = config;\n\n const registration = await vorim.register({\n name,\n description,\n capabilities,\n scopes,\n });\n\n const agentId = registration.agent.agent_id;\n const registry = new VorimToolRegistry({ vorim, agentId });\n registry.addAll(tools);\n\n return {\n agentId,\n registration,\n registry,\n privateKey: registration.private_key,\n };\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────────\n\nfunction truncate(str: string, max: number): string {\n return str.length > max ? str.slice(0, max) + '…' : str;\n}\n"],"mappings":";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,QAAQ,YAAY,EAAE,cAAc,OAAU;AAAA,EACxG;AAGA,MAAI,iBAAiB,SAAS;AAC5B,WAAO,EAAE,SAAS,MAAM,QAAQ,EAAE,UAAU,4BAA4B,YAAY,EAAE,cAA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S,QAAQ,OAAO,CAAC,MAAW,EAAE,SAAS,MAAM;AACxE,aAAO,WAAW,IAAI,CAAC,MAAW,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK;AAAA,IACxD;AAGA,UAAM,gBAAgB,SAAS,QAAQ,OAAO,CAAC,MAAW,EAAE,SAAS,UAAU;AAC/E,UAAM,cAAc,MAAM,SAAS,qBAAqB,aAAa;AAGrE,aAAS,KAAK,EAAE,MAAM,aAAa,SAAS,SAAS,QAAQ,CAAC;AAC9D,aAAS,KAAK,EAAE,MAAM,QAAQ,SAAS,YAAY,CAAC;AAAA,EACtD;AAEA,SAAO;AACT;AAmBA,eAAsB,uBAAuB,QAO1C;AACD,QAAM,EAAE,OAAO,MAAM,aAAa,cAAc,QAAQ,MAAM,IAAI;AAElE,QAAM,eAAe,MAAM,MAAM,SAAS;AAAA,IACxC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AAED,QAAM,UAAU,aAAa,MAAM;AACnC,QAAM,WAAW,IAAI,kBAAkB,EAAE,OAAO,QAAQ,CAAC;AACzD,WAAS,OAAO,KAAK;AAErB,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,YAAY,aAAa;AAAA,EAC3B;AACF;AAIA,SAAS,SAAS,KAAa,KAAqB;AAClD,SAAO,IAAI,SAAS,MAAM,IAAI,MAAM,GAAG,GAAG,IAAI,WAAM;AACtD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/integrations/_runtime-gate.ts","../../src/replay.ts","../../src/integrations/anthropic.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 — Anthropic/Claude Integration\n// Wraps Anthropic tool use with Vorim permission checks, audit trails,\n// and agent identity. Works with the Anthropic Node.js SDK (messages API\n// with tool use).\n//\n// Peer dependency: @anthropic-ai/sdk >=0.30.0\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 Anthropic types (peer dependency — not bundled) ──────────\n\ninterface AnthropicTool {\n name: string;\n description: string;\n input_schema: Record<string, unknown>;\n}\n\ninterface ToolUseBlock {\n type: 'tool_use';\n id: string;\n name: string;\n input: Record<string, unknown>;\n}\n\ninterface ToolResultBlock {\n type: 'tool_result';\n tool_use_id: string;\n content: string;\n is_error?: boolean;\n}\n\n// ─── Configuration ────────────────────────────────────────────────────────\n\nexport interface VorimToolDefinition<TArgs = Record<string, unknown>, TResult = unknown> {\n /** Tool name (must match the tool name sent to Claude). */\n name: string;\n /** Description shown to Claude. */\n description: string;\n /** JSON Schema for the tool's input. */\n input_schema: Record<string, unknown>;\n /** The function to execute when the tool is called. */\n execute: (args: TArgs) => Promise<TResult>;\n /** Vorim permission scope required. @default 'agent:execute' */\n permission?: PermissionScope;\n}\n\nexport interface VorimAnthropicConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id. */\n agentId: string;\n /** Default permission scope for tools without an explicit one. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Whether to emit audit events asynchronously (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, tool calls are evaluated against live policy rules and the\n * returned decisionId is linked onto each 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). Hashes attached to\n * every audit event. If `replay.tools` is omitted, the registry's\n * own tool list is used automatically. Not covered by v0 canonical\n * signature form.\n */\n replay?: ReplayInputs;\n}\n\n// ─── Tool Registry ────────────────────────────────────────────────────────\n\n/**\n * Manages a set of tools with Vorim permission checks and audit logging.\n * Converts tools to Anthropic's tool format and handles execution of\n * tool_use blocks from Claude's response.\n *\n * @example\n * ```ts\n * import Anthropic from \"@anthropic-ai/sdk\";\n * import createVorim from \"@vorim/sdk\";\n * import { VorimToolRegistry } from \"@vorim/sdk/integrations/anthropic\";\n *\n * const vorim = createVorim({ apiKey: \"agid_sk_live_...\" });\n * const anthropic = new Anthropic();\n *\n * const registry = new VorimToolRegistry({\n * vorim,\n * agentId: \"agid_acme_a1b2c3d4\",\n * });\n *\n * registry.add({\n * name: \"search_docs\",\n * description: \"Search internal documents\",\n * input_schema: {\n * type: \"object\",\n * properties: { query: { type: \"string\" } },\n * required: [\"query\"],\n * },\n * execute: async ({ query }) => searchDocs(query),\n * permission: \"agent:read\",\n * });\n *\n * const response = await anthropic.messages.create({\n * model: \"claude-sonnet-4-20250514\",\n * max_tokens: 1024,\n * messages,\n * tools: registry.toAnthropicTools(),\n * });\n *\n * // Execute tool_use blocks from response\n * const toolResults = await registry.executeToolUseBlocks(\n * response.content.filter(b => b.type === \"tool_use\")\n * );\n * ```\n */\nexport class VorimToolRegistry {\n private vorim: VorimSDK;\n private agentId: string;\n private defaultPermission: PermissionScope;\n private asyncAudit: boolean;\n private useRuntimeControl: boolean;\n private onEscalation?: EscalationPolicy;\n private escalationTimeoutMs?: number;\n private tools = new Map<string, VorimToolDefinition>();\n private replayInputs: ReplayInputs | undefined;\n private replayCache: Promise<ReplayContext> | null = null;\n\n constructor(config: VorimAnthropicConfig) {\n this.vorim = config.vorim;\n this.agentId = config.agentId;\n this.defaultPermission = config.defaultPermission ?? 'agent:execute';\n this.asyncAudit = config.asyncAudit ?? true;\n this.useRuntimeControl = config.useRuntimeControl ?? false;\n this.onEscalation = config.onEscalation;\n this.escalationTimeoutMs = config.escalationTimeoutMs;\n this.replayInputs = config.replay;\n }\n\n /** Gate a tool call: runtime decision (with decisionId) or permission check. */\n private async gate(\n scope: PermissionScope,\n actionTarget: string,\n payload?: Record<string, unknown>,\n ): Promise<{ allowed: boolean; reason?: string; decisionId?: string }> {\n if (this.useRuntimeControl) {\n return runtimeGate(this.vorim, this.agentId, actionTarget, scope, payload, {\n onEscalation: this.onEscalation,\n escalationTimeoutMs: this.escalationTimeoutMs,\n });\n }\n const { allowed, reason } = await this.vorim.check(this.agentId, scope);\n return { allowed, reason };\n }\n\n private async getReplayContext(): Promise<ReplayContext> {\n if (!this.replayInputs) return {};\n if (!this.replayCache) {\n const inputs: ReplayInputs = {\n ...this.replayInputs,\n tools: this.replayInputs.tools ?? this.deriveCatalogue(),\n };\n this.replayCache = prepareReplayContext(inputs);\n }\n return this.replayCache;\n }\n\n private deriveCatalogue(): CatalogueTool[] {\n return [...this.tools.values()].map(t => ({\n name: t.name,\n description: t.description,\n schema: t.input_schema,\n }));\n }\n\n /** Register a tool. Invalidates the cached tool-catalogue hash. */\n add<TArgs, TResult>(definition: VorimToolDefinition<TArgs, TResult>): this {\n this.tools.set(definition.name, definition as VorimToolDefinition);\n this.replayCache = null;\n return this;\n }\n\n /** Register multiple tools. */\n addAll(definitions: VorimToolDefinition[]): this {\n for (const def of definitions) this.add(def);\n return this;\n }\n\n /** Convert registered tools to Anthropic's tool format. */\n toAnthropicTools(): AnthropicTool[] {\n return [...this.tools.values()].map(t => ({\n name: t.name,\n description: t.description,\n input_schema: t.input_schema,\n }));\n }\n\n /**\n * Execute tool_use blocks from a Claude message response.\n * Each call is checked against Vorim permissions and audited.\n * Returns an array of tool_result blocks ready to send back to Claude.\n */\n async executeToolUseBlocks(toolUseBlocks: ToolUseBlock[]): Promise<ToolResultBlock[]> {\n return Promise.all(\n toolUseBlocks.map(block => this.executeSingleBlock(block)),\n );\n }\n\n private async executeSingleBlock(block: ToolUseBlock): Promise<ToolResultBlock> {\n const definition = this.tools.get(block.name);\n\n if (!definition) {\n return {\n type: 'tool_result',\n tool_use_id: block.id,\n content: JSON.stringify({ error: `Unknown tool: ${block.name}` }),\n is_error: true,\n };\n }\n\n const scope = definition.permission ?? this.defaultPermission;\n\n // 1. Gate: runtime decision (with decisionId linkage) or permission check.\n const { allowed, reason, decisionId } = await this.gate(scope, block.name, block.input as Record<string, unknown>);\n const replayCtx = await this.getReplayContext();\n\n if (!allowed) {\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: block.name,\n resource: truncate(JSON.stringify(block.input), 500),\n permission: scope,\n result: 'denied',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { reason, framework: 'anthropic' },\n ...replayCtx,\n };\n await this.emitAudit(event);\n\n return {\n type: 'tool_result',\n tool_use_id: block.id,\n content: JSON.stringify({ error: `Permission denied: ${scope}${reason ? ` — ${reason}` : ''}` }),\n is_error: true,\n };\n }\n\n // 2. Execute\n const start = Date.now();\n try {\n const result = await definition.execute(block.input as any);\n const content = typeof result === 'string' ? result : JSON.stringify(result);\n\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: block.name,\n resource: truncate(JSON.stringify(block.input), 500),\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { framework: 'anthropic' },\n ...replayCtx,\n };\n await this.emitAudit(event);\n\n return { type: 'tool_result', tool_use_id: block.id, content };\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n\n const event: AuditEventInput = {\n agent_id: this.agentId,\n event_type: 'tool_call',\n action: block.name,\n resource: truncate(JSON.stringify(block.input), 500),\n permission: scope,\n result: 'error',\n latency_ms: Date.now() - start,\n error_code: err instanceof Error ? err.name : 'UNKNOWN',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { error: errMsg, framework: 'anthropic' },\n ...replayCtx,\n };\n await this.emitAudit(event);\n\n return {\n type: 'tool_result',\n tool_use_id: block.id,\n content: JSON.stringify({ error: errMsg }),\n is_error: true,\n };\n }\n }\n\n private async emitAudit(event: AuditEventInput): Promise<void> {\n if (this.asyncAudit) {\n // Fire-and-forget: don't block the tool pipeline on the audit write.\n this.vorim.emit(event).catch(() => {});\n } else {\n // Synchronous mode: actually await so the audit is flushed before the\n // caller continues.\n try { await this.vorim.emit(event); } catch { /* best-effort */ }\n }\n }\n}\n\n// ─── Agent Loop ───────────────────────────────────────────────────────────\n\n/** Minimal Anthropic client interface (avoids importing the full SDK). */\ninterface AnthropicClient {\n messages: {\n create(params: any): Promise<any>;\n };\n}\n\nexport interface VorimAgentLoopConfig extends VorimAnthropicConfig {\n /** Anthropic client instance. */\n anthropic: AnthropicClient;\n /** Model to use. @default 'claude-sonnet-4-20250514' */\n model?: string;\n /** System prompt for the agent. */\n systemPrompt?: string;\n /** Maximum tool-use iterations before stopping. @default 10 */\n maxIterations?: number;\n /** Max tokens per response. @default 1024 */\n maxTokens?: number;\n}\n\n/**\n * Runs a complete agent loop with Claude tool use, Vorim\n * permission enforcement, and audit logging.\n *\n * @example\n * ```ts\n * import Anthropic from \"@anthropic-ai/sdk\";\n * import createVorim from \"@vorim/sdk\";\n * import { runAgentLoop, VorimToolRegistry } from \"@vorim/sdk/integrations/anthropic\";\n *\n * const registry = new VorimToolRegistry({ vorim, agentId });\n * registry.add({ name: \"search\", ... });\n *\n * const response = await runAgentLoop({\n * vorim,\n * agentId,\n * anthropic: new Anthropic(),\n * model: \"claude-sonnet-4-20250514\",\n * systemPrompt: \"You are a helpful assistant.\",\n * registry,\n * userMessage: \"Find docs about onboarding\",\n * });\n * ```\n */\nexport async function runAgentLoop(\n config: VorimAgentLoopConfig & {\n registry: VorimToolRegistry;\n userMessage: string;\n },\n): Promise<string> {\n const {\n anthropic,\n model = 'claude-sonnet-4-20250514',\n systemPrompt,\n maxIterations = 10,\n maxTokens = 1024,\n registry,\n userMessage,\n } = config;\n\n const tools = registry.toAnthropicTools();\n const messages: any[] = [{ role: 'user', content: userMessage }];\n\n for (let i = 0; i < maxIterations; i++) {\n const response = await anthropic.messages.create({\n model,\n max_tokens: maxTokens,\n ...(systemPrompt ? { system: systemPrompt } : {}),\n messages,\n ...(tools.length > 0 ? { tools } : {}),\n });\n\n // If stop_reason is \"end_turn\" — Claude is done\n if (response.stop_reason === 'end_turn' || response.stop_reason !== 'tool_use') {\n const textBlocks = response.content.filter((b: any) => b.type === 'text');\n return textBlocks.map((b: any) => b.text).join('') || '';\n }\n\n // Extract tool_use blocks and execute\n const toolUseBlocks = response.content.filter((b: any) => b.type === 'tool_use');\n const toolResults = await registry.executeToolUseBlocks(toolUseBlocks);\n\n // Append assistant response and tool results to conversation\n messages.push({ role: 'assistant', content: response.content });\n messages.push({ role: 'user', content: toolResults });\n }\n\n return '';\n}\n\n// ─── Agent Registration Helper ───────────────────────────────────────────\n\n/**\n * Registers a new agent with Vorim and returns a ready-to-use tool registry\n * configured for Anthropic/Claude.\n *\n * @example\n * ```ts\n * const { agentId, registry } = await createVorimClaudeAgent({\n * vorim,\n * name: \"claude-assistant\",\n * capabilities: [\"search\", \"calculate\"],\n * scopes: [\"agent:read\", \"agent:execute\"],\n * tools: [searchTool, calcTool],\n * });\n * ```\n */\nexport async function createVorimClaudeAgent(config: {\n vorim: VorimSDK;\n name: string;\n description?: string;\n capabilities: string[];\n scopes: PermissionScope[];\n tools: VorimToolDefinition[];\n}) {\n const { vorim, name, description, capabilities, scopes, tools } = config;\n\n const registration = await vorim.register({\n name,\n description,\n capabilities,\n scopes,\n });\n\n const agentId = registration.agent.agent_id;\n const registry = new VorimToolRegistry({ vorim, agentId });\n registry.addAll(tools);\n\n return {\n agentId,\n registration,\n registry,\n privateKey: registration.private_key,\n };\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────────\n\nfunction truncate(str: string, max: number): string {\n return str.length > max ? str.slice(0, max) + '…' : str;\n}\n"],"mappings":";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,QAAQ,YAAY,EAAE,cAAc,OAAU;AAAA,EACxG;AAGA,MAAI,iBAAiB,SAAS;AAC5B,WAAO,EAAE,SAAS,MAAM,QAAQ,EAAE,UAAU,4BAA4B,YAAY,EAAE,cAAc,OAAU;AAAA,EAChH;AACA,MAAI,iBAAiB,QAAQ;AAC3B,WAAO,EAAE,SAAS,OAAO,QAAQ,EAAE,UAAU,iDAA4C,YAAY,EAAE,cAAc,OAAU;AAAA,EACjI;AAEA,MAAI,CAAC,EAAE,YAAY;AACjB,WAAO,EAAE,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,SAAS,MAAM;AACxE,aAAO,WAAW,IAAI,CAAC,MAAW,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK;AAAA,IACxD;AAGA,UAAM,gBAAgB,SAAS,QAAQ,OAAO,CAAC,MAAW,EAAE,SAAS,UAAU;AAC/E,UAAM,cAAc,MAAM,SAAS,qBAAqB,aAAa;AAGrE,aAAS,KAAK,EAAE,MAAM,aAAa,SAAS,SAAS,QAAQ,CAAC;AAC9D,aAAS,KAAK,EAAE,MAAM,QAAQ,SAAS,YAAY,CAAC;AAAA,EACtD;AAEA,SAAO;AACT;AAmBA,eAAsB,uBAAuB,QAO1C;AACD,QAAM,EAAE,OAAO,MAAM,aAAa,cAAc,QAAQ,MAAM,IAAI;AAElE,QAAM,eAAe,MAAM,MAAM,SAAS;AAAA,IACxC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AAED,QAAM,UAAU,aAAa,MAAM;AACnC,QAAM,WAAW,IAAI,kBAAkB,EAAE,OAAO,QAAQ,CAAC;AACzD,WAAS,OAAO,KAAK;AAErB,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,YAAY,aAAa;AAAA,EAC3B;AACF;AAIA,SAAS,SAAS,KAAa,KAAqB;AAClD,SAAO,IAAI,SAAS,MAAM,IAAI,MAAM,GAAG,GAAG,IAAI,WAAM;AACtD;","names":[]}
|
|
@@ -133,7 +133,7 @@ function wrapTool(tool, config) {
|
|
|
133
133
|
metadata: { reason, framework: "llamaindex" },
|
|
134
134
|
...replayCtx
|
|
135
135
|
};
|
|
136
|
-
emitAudit(vorim, event2, asyncAudit);
|
|
136
|
+
await emitAudit(vorim, event2, asyncAudit);
|
|
137
137
|
throw new Error(
|
|
138
138
|
`Vorim: permission denied for "${toolName}" \u2014 scope "${scope}"${reason ? `: ${reason}` : ""}`
|
|
139
139
|
);
|
|
@@ -158,7 +158,7 @@ function wrapTool(tool, config) {
|
|
|
158
158
|
},
|
|
159
159
|
...replayCtx
|
|
160
160
|
};
|
|
161
|
-
emitAudit(vorim, event2, asyncAudit);
|
|
161
|
+
await emitAudit(vorim, event2, asyncAudit);
|
|
162
162
|
throw err;
|
|
163
163
|
}
|
|
164
164
|
const event = {
|
|
@@ -172,7 +172,7 @@ function wrapTool(tool, config) {
|
|
|
172
172
|
metadata: { framework: "llamaindex" },
|
|
173
173
|
...replayCtx
|
|
174
174
|
};
|
|
175
|
-
emitAudit(vorim, event, asyncAudit);
|
|
175
|
+
await emitAudit(vorim, event, asyncAudit);
|
|
176
176
|
return result;
|
|
177
177
|
},
|
|
178
178
|
writable: true,
|
|
@@ -230,10 +230,9 @@ function emitAudit(vorim, event, async) {
|
|
|
230
230
|
if (async) {
|
|
231
231
|
vorim.emit(event).catch(() => {
|
|
232
232
|
});
|
|
233
|
-
|
|
234
|
-
vorim.emit(event).catch(() => {
|
|
235
|
-
});
|
|
233
|
+
return;
|
|
236
234
|
}
|
|
235
|
+
return vorim.emit(event).then(() => void 0).catch(() => void 0);
|
|
237
236
|
}
|
|
238
237
|
function makeReplayContextGetter(replay) {
|
|
239
238
|
if (!replay) return async () => ({});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/integrations/llamaindex.ts","../../src/replay.ts"],"sourcesContent":["// ============================================================================\n// VORIM SDK — LlamaIndex TS Integration\n// Wraps LlamaIndex tools with Vorim permission checks + audit trails.\n// Provides a tool wrapper and agent registration factory.\n//\n// Peer dependency: llamaindex >=0.4.0 (or @llamaindex/core)\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope, AuditEventInput } from '../types.js';\nimport {\n prepareReplayContext,\n type ReplayInputs,\n type ReplayContext,\n type CatalogueTool,\n} from '../replay.js';\n\n// ─── Re-declared LlamaIndex types (peer dependency — not bundled) ─────────\n// These mirror the actual interfaces from @llamaindex/core/llms and\n// @llamaindex/core/tools so consumers don't need to wrangle imports.\n\n/** Matches @llamaindex/core ToolMetadata */\ninterface ToolMetadata<P extends Record<string, unknown> = Record<string, unknown>> {\n name: string;\n description: string;\n parameters?: P;\n}\n\n/**\n * Matches @llamaindex/core BaseTool.\n * In LlamaIndex, `call` is optional on BaseTool but required on BaseToolWithCall.\n */\ninterface LlamaIndexTool<Input = any> {\n metadata: ToolMetadata;\n call: (input: Input) => any | Promise<any>;\n}\n\n// ─── Configuration ────────────────────────────────────────────────────────\n\nexport interface VorimLlamaIndexConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id to associate. */\n agentId: string;\n /** Map tool names → Vorim permission scopes. */\n permissionMap?: Record<string, PermissionScope>;\n /** Default permission scope for unmapped tools. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Whether to emit audit events asynchronously (fire-and-forget). @default true */\n asyncAudit?: boolean;\n /**\n * Replayable agent decision evidence (VAIP -02). Hashes attached to\n * every audit event the wrapper emits. Not covered by v0 canonical\n * signature form.\n */\n replay?: ReplayInputs;\n}\n\n// ─── Tool Wrapper ─────────────────────────────────────────────────────────\n\n/**\n * Wraps a LlamaIndex tool (`BaseTool` / `BaseToolWithCall` / `FunctionTool`)\n * with Vorim permission checks before execution and audit event emission after.\n *\n * The wrapper implements the same `BaseTool` interface so it's a drop-in\n * replacement anywhere LlamaIndex expects a tool.\n *\n * @example\n * ```ts\n * import { FunctionTool } from \"llamaindex\";\n * import createVorim from \"@vorim/sdk\";\n * import { wrapTool } from \"@vorim/sdk/integrations/llamaindex\";\n *\n * const vorim = createVorim({ apiKey: \"agid_sk_live_...\" });\n *\n * const searchTool = FunctionTool.from(\n * async ({ query }: { query: string }) => `Results for: ${query}`,\n * { name: \"search\", description: \"Search documents\", parameters: { ... } }\n * );\n *\n * const guarded = wrapTool(searchTool, {\n * vorim,\n * agentId: \"agid_acme_a1b2c3d4\",\n * permissionMap: { search: \"agent:read\" },\n * });\n *\n * // Use with any LlamaIndex agent\n * const agent = new OpenAIAgent({ tools: [guarded] });\n * ```\n */\nexport function wrapTool<T extends LlamaIndexTool>(\n tool: T,\n config: VorimLlamaIndexConfig,\n): T {\n const {\n vorim, agentId,\n permissionMap = {},\n defaultPermission = 'agent:execute',\n asyncAudit = true,\n replay,\n } = config;\n\n const originalCall = tool.call.bind(tool);\n const toolName = tool.metadata.name;\n const scope = permissionMap[toolName] ?? defaultPermission;\n const getReplayCtx = makeReplayContextGetter(replay);\n\n // Create a new object that preserves the tool's prototype chain\n // and all properties, but overrides `call`\n const wrapped = Object.create(Object.getPrototypeOf(tool), {\n ...Object.getOwnPropertyDescriptors(tool),\n call: {\n value: async function vorimGuardedCall(input: any): Promise<any> {\n // 1. Permission check\n const { allowed, reason } = await vorim.check(agentId, scope);\n const replayCtx = await getReplayCtx();\n\n if (!allowed) {\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: toolName,\n resource: truncate(JSON.stringify(input), 500),\n permission: scope,\n result: 'denied',\n metadata: { reason, framework: 'llamaindex' },\n ...replayCtx,\n };\n emitAudit(vorim, event, asyncAudit);\n throw new Error(\n `Vorim: permission denied for \"${toolName}\" — scope \"${scope}\"${reason ? `: ${reason}` : ''}`,\n );\n }\n\n // 2. Execute the original tool\n const start = Date.now();\n let result: any;\n try {\n result = await originalCall(input);\n } catch (err) {\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: toolName,\n resource: truncate(JSON.stringify(input), 500),\n permission: scope,\n result: 'error',\n latency_ms: Date.now() - start,\n error_code: err instanceof Error ? err.name : 'UNKNOWN',\n metadata: {\n error: err instanceof Error ? err.message : String(err),\n framework: 'llamaindex',\n },\n ...replayCtx,\n };\n emitAudit(vorim, event, asyncAudit);\n throw err;\n }\n\n // 3. Audit success\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: toolName,\n resource: truncate(JSON.stringify(input), 500),\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n metadata: { framework: 'llamaindex' },\n ...replayCtx,\n };\n emitAudit(vorim, event, asyncAudit);\n\n return result;\n },\n writable: true,\n configurable: true,\n enumerable: true,\n },\n }) as T;\n\n return wrapped;\n}\n\n/**\n * Wraps an array of LlamaIndex tools with Vorim permission + audit.\n */\nexport function wrapTools<T extends LlamaIndexTool>(\n tools: T[],\n config: VorimLlamaIndexConfig,\n): T[] {\n return tools.map(t => wrapTool(t, config));\n}\n\n// ─── Agent Factory ────────────────────────────────────────────────────────\n\nexport interface CreateVorimLlamaIndexAgentConfig extends VorimLlamaIndexConfig {\n /** Display name for the agent. */\n name: string;\n /** Agent capabilities. */\n capabilities: string[];\n /** Initial permission scopes. */\n scopes: PermissionScope[];\n /** Optional description. */\n description?: string;\n}\n\n/**\n * Registers a new agent with Vorim and returns wrapped tools ready for\n * use with any LlamaIndex agent (OpenAIAgent, ReActAgent, etc.).\n *\n * @example\n * ```ts\n * import { OpenAIAgent, FunctionTool } from \"llamaindex\";\n * import createVorim from \"@vorim/sdk\";\n * import { createVorimAgent } from \"@vorim/sdk/integrations/llamaindex\";\n *\n * const vorim = createVorim({ apiKey: \"agid_sk_live_...\" });\n *\n * const searchTool = FunctionTool.from(...);\n * const writeTool = FunctionTool.from(...);\n *\n * const { agentId, tools } = await createVorimAgent({\n * vorim,\n * name: \"research-agent\",\n * capabilities: [\"search\", \"write\"],\n * scopes: [\"agent:read\", \"agent:write\", \"agent:execute\"],\n * tools: [searchTool, writeTool],\n * permissionMap: {\n * search: \"agent:read\",\n * write: \"agent:write\",\n * },\n * });\n *\n * // Create LlamaIndex agent with Vorim-wrapped tools\n * const agent = new OpenAIAgent({ tools });\n * const response = await agent.chat({ message: \"Research AI trends\" });\n * ```\n */\nexport async function createVorimAgent<T extends LlamaIndexTool>(\n config: CreateVorimLlamaIndexAgentConfig & { tools: T[] },\n) {\n const { vorim, name, capabilities, scopes, description, tools: rawTools, permissionMap, defaultPermission, asyncAudit } = config;\n\n // Register agent with Vorim\n const registration = await vorim.register({\n name,\n description,\n capabilities,\n scopes,\n });\n\n const agentId = registration.agent.agent_id;\n const toolConfig: VorimLlamaIndexConfig = { vorim, agentId, permissionMap, defaultPermission, asyncAudit };\n\n // Wrap tools with permission checks\n const tools = wrapTools(rawTools, toolConfig);\n\n return {\n /** The Vorim agent_id. */\n agentId,\n /** Full registration result. */\n registration,\n /** Tools wrapped with Vorim permission checks + audit. */\n tools,\n /** The private key (store securely — shown once). */\n privateKey: registration.private_key,\n };\n}\n\n// ─── Audit Helpers ────────────────────────────────────────────────────────\n\n/**\n * Emit a manual audit event for a LlamaIndex agent action that isn't\n * captured by the tool wrapper (e.g. RAG retrieval, chat responses).\n */\nexport async function emitLlamaIndexEvent(\n vorim: VorimSDK,\n agentId: string,\n event: {\n action: string;\n resource?: string;\n result: 'success' | 'denied' | 'error';\n latencyMs?: number;\n error?: string;\n metadata?: Record<string, unknown>;\n },\n): Promise<void> {\n await vorim.emit({\n agent_id: agentId,\n event_type: 'api_request',\n action: event.action,\n resource: event.resource,\n result: event.result,\n latency_ms: event.latencyMs,\n error_code: event.error ? 'LLAMAINDEX_ERROR' : undefined,\n metadata: {\n framework: 'llamaindex',\n ...(event.error ? { error: event.error } : {}),\n ...event.metadata,\n },\n });\n}\n\n// ─── Internal helpers ─────────────────────────────────────────────────────\n\nfunction truncate(str: string, max: number): string {\n return str.length > max ? str.slice(0, max) + '…' : str;\n}\n\nfunction emitAudit(vorim: VorimSDK, event: AuditEventInput, async: boolean): void {\n if (async) {\n vorim.emit(event).catch(() => {});\n } else {\n vorim.emit(event).catch(() => {});\n }\n}\n\n/**\n * Lazy-cached replay context getter. Hashes computed once on first\n * call, reused thereafter. Returns empty object when no replay config\n * was given, so the spread is a no-op.\n */\nfunction makeReplayContextGetter(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 * 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;AAAA;AAAA;AAAA;;;ACwEO,SAAS,gBAAgB,OAAwB;AACtD,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,UAAU,MAAO,QAAO;AAE5B,MAAI,OAAO,UAAU,UAAU;AAC7B,QAAI,CAAC,OAAO,SAAS,KAAK,GAAG;AAC3B,YAAM,IAAI,MAAM,qDAAqD;AAAA,IACvE;AAKA,WAAO,MAAM,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;AAAA,EAClC,OAAO;AACL,UAAM,KAAK,KAAK,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAAA,EAClC;AACF;AAOA,SAAS,wBAAwB,QAAgE;AAC/F,MAAI,CAAC,OAAQ,QAAO,aAAa,CAAC;AAClC,MAAI,SAAwC;AAC5C,SAAO,MAAM;AACX,QAAI,CAAC,OAAQ,UAAS,qBAAqB,MAAM;AACjD,WAAO;AAAA,EACT;AACF;","names":["event"]}
|
|
1
|
+
{"version":3,"sources":["../../src/integrations/llamaindex.ts","../../src/replay.ts"],"sourcesContent":["// ============================================================================\n// VORIM SDK — LlamaIndex TS Integration\n// Wraps LlamaIndex tools with Vorim permission checks + audit trails.\n// Provides a tool wrapper and agent registration factory.\n//\n// Peer dependency: llamaindex >=0.4.0 (or @llamaindex/core)\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope, AuditEventInput } from '../types.js';\nimport {\n prepareReplayContext,\n type ReplayInputs,\n type ReplayContext,\n type CatalogueTool,\n} from '../replay.js';\n\n// ─── Re-declared LlamaIndex types (peer dependency — not bundled) ─────────\n// These mirror the actual interfaces from @llamaindex/core/llms and\n// @llamaindex/core/tools so consumers don't need to wrangle imports.\n\n/** Matches @llamaindex/core ToolMetadata */\ninterface ToolMetadata<P extends Record<string, unknown> = Record<string, unknown>> {\n name: string;\n description: string;\n parameters?: P;\n}\n\n/**\n * Matches @llamaindex/core BaseTool.\n * In LlamaIndex, `call` is optional on BaseTool but required on BaseToolWithCall.\n */\ninterface LlamaIndexTool<Input = any> {\n metadata: ToolMetadata;\n call: (input: Input) => any | Promise<any>;\n}\n\n// ─── Configuration ────────────────────────────────────────────────────────\n\nexport interface VorimLlamaIndexConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id to associate. */\n agentId: string;\n /** Map tool names → Vorim permission scopes. */\n permissionMap?: Record<string, PermissionScope>;\n /** Default permission scope for unmapped tools. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Whether to emit audit events asynchronously (fire-and-forget). @default true */\n asyncAudit?: boolean;\n /**\n * Replayable agent decision evidence (VAIP -02). Hashes attached to\n * every audit event the wrapper emits. Not covered by v0 canonical\n * signature form.\n */\n replay?: ReplayInputs;\n}\n\n// ─── Tool Wrapper ─────────────────────────────────────────────────────────\n\n/**\n * Wraps a LlamaIndex tool (`BaseTool` / `BaseToolWithCall` / `FunctionTool`)\n * with Vorim permission checks before execution and audit event emission after.\n *\n * The wrapper implements the same `BaseTool` interface so it's a drop-in\n * replacement anywhere LlamaIndex expects a tool.\n *\n * @example\n * ```ts\n * import { FunctionTool } from \"llamaindex\";\n * import createVorim from \"@vorim/sdk\";\n * import { wrapTool } from \"@vorim/sdk/integrations/llamaindex\";\n *\n * const vorim = createVorim({ apiKey: \"agid_sk_live_...\" });\n *\n * const searchTool = FunctionTool.from(\n * async ({ query }: { query: string }) => `Results for: ${query}`,\n * { name: \"search\", description: \"Search documents\", parameters: { ... } }\n * );\n *\n * const guarded = wrapTool(searchTool, {\n * vorim,\n * agentId: \"agid_acme_a1b2c3d4\",\n * permissionMap: { search: \"agent:read\" },\n * });\n *\n * // Use with any LlamaIndex agent\n * const agent = new OpenAIAgent({ tools: [guarded] });\n * ```\n */\nexport function wrapTool<T extends LlamaIndexTool>(\n tool: T,\n config: VorimLlamaIndexConfig,\n): T {\n const {\n vorim, agentId,\n permissionMap = {},\n defaultPermission = 'agent:execute',\n asyncAudit = true,\n replay,\n } = config;\n\n const originalCall = tool.call.bind(tool);\n const toolName = tool.metadata.name;\n const scope = permissionMap[toolName] ?? defaultPermission;\n const getReplayCtx = makeReplayContextGetter(replay);\n\n // Create a new object that preserves the tool's prototype chain\n // and all properties, but overrides `call`\n const wrapped = Object.create(Object.getPrototypeOf(tool), {\n ...Object.getOwnPropertyDescriptors(tool),\n call: {\n value: async function vorimGuardedCall(input: any): Promise<any> {\n // 1. Permission check\n const { allowed, reason } = await vorim.check(agentId, scope);\n const replayCtx = await getReplayCtx();\n\n if (!allowed) {\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: toolName,\n resource: truncate(JSON.stringify(input), 500),\n permission: scope,\n result: 'denied',\n metadata: { reason, framework: 'llamaindex' },\n ...replayCtx,\n };\n await emitAudit(vorim, event, asyncAudit);\n throw new Error(\n `Vorim: permission denied for \"${toolName}\" — scope \"${scope}\"${reason ? `: ${reason}` : ''}`,\n );\n }\n\n // 2. Execute the original tool\n const start = Date.now();\n let result: any;\n try {\n result = await originalCall(input);\n } catch (err) {\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: toolName,\n resource: truncate(JSON.stringify(input), 500),\n permission: scope,\n result: 'error',\n latency_ms: Date.now() - start,\n error_code: err instanceof Error ? err.name : 'UNKNOWN',\n metadata: {\n error: err instanceof Error ? err.message : String(err),\n framework: 'llamaindex',\n },\n ...replayCtx,\n };\n await emitAudit(vorim, event, asyncAudit);\n throw err;\n }\n\n // 3. Audit success\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: toolName,\n resource: truncate(JSON.stringify(input), 500),\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n metadata: { framework: 'llamaindex' },\n ...replayCtx,\n };\n await emitAudit(vorim, event, asyncAudit);\n\n return result;\n },\n writable: true,\n configurable: true,\n enumerable: true,\n },\n }) as T;\n\n return wrapped;\n}\n\n/**\n * Wraps an array of LlamaIndex tools with Vorim permission + audit.\n */\nexport function wrapTools<T extends LlamaIndexTool>(\n tools: T[],\n config: VorimLlamaIndexConfig,\n): T[] {\n return tools.map(t => wrapTool(t, config));\n}\n\n// ─── Agent Factory ────────────────────────────────────────────────────────\n\nexport interface CreateVorimLlamaIndexAgentConfig extends VorimLlamaIndexConfig {\n /** Display name for the agent. */\n name: string;\n /** Agent capabilities. */\n capabilities: string[];\n /** Initial permission scopes. */\n scopes: PermissionScope[];\n /** Optional description. */\n description?: string;\n}\n\n/**\n * Registers a new agent with Vorim and returns wrapped tools ready for\n * use with any LlamaIndex agent (OpenAIAgent, ReActAgent, etc.).\n *\n * @example\n * ```ts\n * import { OpenAIAgent, FunctionTool } from \"llamaindex\";\n * import createVorim from \"@vorim/sdk\";\n * import { createVorimAgent } from \"@vorim/sdk/integrations/llamaindex\";\n *\n * const vorim = createVorim({ apiKey: \"agid_sk_live_...\" });\n *\n * const searchTool = FunctionTool.from(...);\n * const writeTool = FunctionTool.from(...);\n *\n * const { agentId, tools } = await createVorimAgent({\n * vorim,\n * name: \"research-agent\",\n * capabilities: [\"search\", \"write\"],\n * scopes: [\"agent:read\", \"agent:write\", \"agent:execute\"],\n * tools: [searchTool, writeTool],\n * permissionMap: {\n * search: \"agent:read\",\n * write: \"agent:write\",\n * },\n * });\n *\n * // Create LlamaIndex agent with Vorim-wrapped tools\n * const agent = new OpenAIAgent({ tools });\n * const response = await agent.chat({ message: \"Research AI trends\" });\n * ```\n */\nexport async function createVorimAgent<T extends LlamaIndexTool>(\n config: CreateVorimLlamaIndexAgentConfig & { tools: T[] },\n) {\n const { vorim, name, capabilities, scopes, description, tools: rawTools, permissionMap, defaultPermission, asyncAudit } = config;\n\n // Register agent with Vorim\n const registration = await vorim.register({\n name,\n description,\n capabilities,\n scopes,\n });\n\n const agentId = registration.agent.agent_id;\n const toolConfig: VorimLlamaIndexConfig = { vorim, agentId, permissionMap, defaultPermission, asyncAudit };\n\n // Wrap tools with permission checks\n const tools = wrapTools(rawTools, toolConfig);\n\n return {\n /** The Vorim agent_id. */\n agentId,\n /** Full registration result. */\n registration,\n /** Tools wrapped with Vorim permission checks + audit. */\n tools,\n /** The private key (store securely — shown once). */\n privateKey: registration.private_key,\n };\n}\n\n// ─── Audit Helpers ────────────────────────────────────────────────────────\n\n/**\n * Emit a manual audit event for a LlamaIndex agent action that isn't\n * captured by the tool wrapper (e.g. RAG retrieval, chat responses).\n */\nexport async function emitLlamaIndexEvent(\n vorim: VorimSDK,\n agentId: string,\n event: {\n action: string;\n resource?: string;\n result: 'success' | 'denied' | 'error';\n latencyMs?: number;\n error?: string;\n metadata?: Record<string, unknown>;\n },\n): Promise<void> {\n await vorim.emit({\n agent_id: agentId,\n event_type: 'api_request',\n action: event.action,\n resource: event.resource,\n result: event.result,\n latency_ms: event.latencyMs,\n error_code: event.error ? 'LLAMAINDEX_ERROR' : undefined,\n metadata: {\n framework: 'llamaindex',\n ...(event.error ? { error: event.error } : {}),\n ...event.metadata,\n },\n });\n}\n\n// ─── Internal helpers ─────────────────────────────────────────────────────\n\nfunction truncate(str: string, max: number): string {\n return str.length > max ? str.slice(0, max) + '…' : str;\n}\n\nfunction emitAudit(vorim: VorimSDK, event: AuditEventInput, async: boolean): Promise<void> | void {\n if (async) {\n vorim.emit(event).catch(() => {});\n return;\n }\n // asyncAudit=false: return the awaitable so callers can ensure the audit\n // event is persisted before the process exits.\n return vorim.emit(event).then(() => undefined).catch(() => undefined);\n}\n\n/**\n * Lazy-cached replay context getter. Hashes computed once on first\n * call, reused thereafter. Returns empty object when no replay config\n * was given, so the spread is a no-op.\n */\nfunction makeReplayContextGetter(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 * 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;AAAA;AAAA;AAAA;;;ACwEO,SAAS,gBAAgB,OAAwB;AACtD,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,UAAU,MAAO,QAAO;AAE5B,MAAI,OAAO,UAAU,UAAU;AAC7B,QAAI,CAAC,OAAO,SAAS,KAAK,GAAG;AAC3B,YAAM,IAAI,MAAM,qDAAqD;AAAA,IACvE;AAKA,WAAO,MAAM,SAAS;AAAA,EACxB;AAEA,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO,KAAK,UAAU,KAAK;AAAA,EAC7B;AAEA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,MAAM,MAAM,IAAI,eAAe,EAAE,KAAK,GAAG,IAAI;AAAA,EACtD;AAEA,MAAI,OAAO,UAAU,UAAU;AAC7B,UAAM,MAAM;AAKZ,UAAM,OAAO,OAAO,KAAK,GAAG,EAAE,OAAO,OAAK,IAAI,CAAC,MAAM,MAAS,EAAE,KAAK;AACrE,UAAM,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
|
|
94
94
|
metadata: { reason, framework: "llamaindex" },
|
|
95
95
|
...replayCtx
|
|
96
96
|
};
|
|
97
|
-
emitAudit(vorim, event2, asyncAudit);
|
|
97
|
+
await emitAudit(vorim, event2, asyncAudit);
|
|
98
98
|
throw new Error(
|
|
99
99
|
`Vorim: permission denied for "${toolName}" \u2014 scope "${scope}"${reason ? `: ${reason}` : ""}`
|
|
100
100
|
);
|
|
@@ -119,7 +119,7 @@ function wrapTool(tool, config) {
|
|
|
119
119
|
},
|
|
120
120
|
...replayCtx
|
|
121
121
|
};
|
|
122
|
-
emitAudit(vorim, event2, asyncAudit);
|
|
122
|
+
await emitAudit(vorim, event2, asyncAudit);
|
|
123
123
|
throw err;
|
|
124
124
|
}
|
|
125
125
|
const event = {
|
|
@@ -133,7 +133,7 @@ function wrapTool(tool, config) {
|
|
|
133
133
|
metadata: { framework: "llamaindex" },
|
|
134
134
|
...replayCtx
|
|
135
135
|
};
|
|
136
|
-
emitAudit(vorim, event, asyncAudit);
|
|
136
|
+
await emitAudit(vorim, event, asyncAudit);
|
|
137
137
|
return result;
|
|
138
138
|
},
|
|
139
139
|
writable: true,
|
|
@@ -191,10 +191,9 @@ function emitAudit(vorim, event, async) {
|
|
|
191
191
|
if (async) {
|
|
192
192
|
vorim.emit(event).catch(() => {
|
|
193
193
|
});
|
|
194
|
-
|
|
195
|
-
vorim.emit(event).catch(() => {
|
|
196
|
-
});
|
|
194
|
+
return;
|
|
197
195
|
}
|
|
196
|
+
return vorim.emit(event).then(() => void 0).catch(() => void 0);
|
|
198
197
|
}
|
|
199
198
|
function makeReplayContextGetter(replay) {
|
|
200
199
|
if (!replay) return async () => ({});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/replay.ts","../../src/integrations/llamaindex.ts"],"sourcesContent":["/**\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 — LlamaIndex TS Integration\n// Wraps LlamaIndex tools with Vorim permission checks + audit trails.\n// Provides a tool wrapper and agent registration factory.\n//\n// Peer dependency: llamaindex >=0.4.0 (or @llamaindex/core)\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope, AuditEventInput } from '../types.js';\nimport {\n prepareReplayContext,\n type ReplayInputs,\n type ReplayContext,\n type CatalogueTool,\n} from '../replay.js';\n\n// ─── Re-declared LlamaIndex types (peer dependency — not bundled) ─────────\n// These mirror the actual interfaces from @llamaindex/core/llms and\n// @llamaindex/core/tools so consumers don't need to wrangle imports.\n\n/** Matches @llamaindex/core ToolMetadata */\ninterface ToolMetadata<P extends Record<string, unknown> = Record<string, unknown>> {\n name: string;\n description: string;\n parameters?: P;\n}\n\n/**\n * Matches @llamaindex/core BaseTool.\n * In LlamaIndex, `call` is optional on BaseTool but required on BaseToolWithCall.\n */\ninterface LlamaIndexTool<Input = any> {\n metadata: ToolMetadata;\n call: (input: Input) => any | Promise<any>;\n}\n\n// ─── Configuration ────────────────────────────────────────────────────────\n\nexport interface VorimLlamaIndexConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id to associate. */\n agentId: string;\n /** Map tool names → Vorim permission scopes. */\n permissionMap?: Record<string, PermissionScope>;\n /** Default permission scope for unmapped tools. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Whether to emit audit events asynchronously (fire-and-forget). @default true */\n asyncAudit?: boolean;\n /**\n * Replayable agent decision evidence (VAIP -02). Hashes attached to\n * every audit event the wrapper emits. Not covered by v0 canonical\n * signature form.\n */\n replay?: ReplayInputs;\n}\n\n// ─── Tool Wrapper ─────────────────────────────────────────────────────────\n\n/**\n * Wraps a LlamaIndex tool (`BaseTool` / `BaseToolWithCall` / `FunctionTool`)\n * with Vorim permission checks before execution and audit event emission after.\n *\n * The wrapper implements the same `BaseTool` interface so it's a drop-in\n * replacement anywhere LlamaIndex expects a tool.\n *\n * @example\n * ```ts\n * import { FunctionTool } from \"llamaindex\";\n * import createVorim from \"@vorim/sdk\";\n * import { wrapTool } from \"@vorim/sdk/integrations/llamaindex\";\n *\n * const vorim = createVorim({ apiKey: \"agid_sk_live_...\" });\n *\n * const searchTool = FunctionTool.from(\n * async ({ query }: { query: string }) => `Results for: ${query}`,\n * { name: \"search\", description: \"Search documents\", parameters: { ... } }\n * );\n *\n * const guarded = wrapTool(searchTool, {\n * vorim,\n * agentId: \"agid_acme_a1b2c3d4\",\n * permissionMap: { search: \"agent:read\" },\n * });\n *\n * // Use with any LlamaIndex agent\n * const agent = new OpenAIAgent({ tools: [guarded] });\n * ```\n */\nexport function wrapTool<T extends LlamaIndexTool>(\n tool: T,\n config: VorimLlamaIndexConfig,\n): T {\n const {\n vorim, agentId,\n permissionMap = {},\n defaultPermission = 'agent:execute',\n asyncAudit = true,\n replay,\n } = config;\n\n const originalCall = tool.call.bind(tool);\n const toolName = tool.metadata.name;\n const scope = permissionMap[toolName] ?? defaultPermission;\n const getReplayCtx = makeReplayContextGetter(replay);\n\n // Create a new object that preserves the tool's prototype chain\n // and all properties, but overrides `call`\n const wrapped = Object.create(Object.getPrototypeOf(tool), {\n ...Object.getOwnPropertyDescriptors(tool),\n call: {\n value: async function vorimGuardedCall(input: any): Promise<any> {\n // 1. Permission check\n const { allowed, reason } = await vorim.check(agentId, scope);\n const replayCtx = await getReplayCtx();\n\n if (!allowed) {\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: toolName,\n resource: truncate(JSON.stringify(input), 500),\n permission: scope,\n result: 'denied',\n metadata: { reason, framework: 'llamaindex' },\n ...replayCtx,\n };\n emitAudit(vorim, event, asyncAudit);\n throw new Error(\n `Vorim: permission denied for \"${toolName}\" — scope \"${scope}\"${reason ? `: ${reason}` : ''}`,\n );\n }\n\n // 2. Execute the original tool\n const start = Date.now();\n let result: any;\n try {\n result = await originalCall(input);\n } catch (err) {\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: toolName,\n resource: truncate(JSON.stringify(input), 500),\n permission: scope,\n result: 'error',\n latency_ms: Date.now() - start,\n error_code: err instanceof Error ? err.name : 'UNKNOWN',\n metadata: {\n error: err instanceof Error ? err.message : String(err),\n framework: 'llamaindex',\n },\n ...replayCtx,\n };\n emitAudit(vorim, event, asyncAudit);\n throw err;\n }\n\n // 3. Audit success\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: toolName,\n resource: truncate(JSON.stringify(input), 500),\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n metadata: { framework: 'llamaindex' },\n ...replayCtx,\n };\n emitAudit(vorim, event, asyncAudit);\n\n return result;\n },\n writable: true,\n configurable: true,\n enumerable: true,\n },\n }) as T;\n\n return wrapped;\n}\n\n/**\n * Wraps an array of LlamaIndex tools with Vorim permission + audit.\n */\nexport function wrapTools<T extends LlamaIndexTool>(\n tools: T[],\n config: VorimLlamaIndexConfig,\n): T[] {\n return tools.map(t => wrapTool(t, config));\n}\n\n// ─── Agent Factory ────────────────────────────────────────────────────────\n\nexport interface CreateVorimLlamaIndexAgentConfig extends VorimLlamaIndexConfig {\n /** Display name for the agent. */\n name: string;\n /** Agent capabilities. */\n capabilities: string[];\n /** Initial permission scopes. */\n scopes: PermissionScope[];\n /** Optional description. */\n description?: string;\n}\n\n/**\n * Registers a new agent with Vorim and returns wrapped tools ready for\n * use with any LlamaIndex agent (OpenAIAgent, ReActAgent, etc.).\n *\n * @example\n * ```ts\n * import { OpenAIAgent, FunctionTool } from \"llamaindex\";\n * import createVorim from \"@vorim/sdk\";\n * import { createVorimAgent } from \"@vorim/sdk/integrations/llamaindex\";\n *\n * const vorim = createVorim({ apiKey: \"agid_sk_live_...\" });\n *\n * const searchTool = FunctionTool.from(...);\n * const writeTool = FunctionTool.from(...);\n *\n * const { agentId, tools } = await createVorimAgent({\n * vorim,\n * name: \"research-agent\",\n * capabilities: [\"search\", \"write\"],\n * scopes: [\"agent:read\", \"agent:write\", \"agent:execute\"],\n * tools: [searchTool, writeTool],\n * permissionMap: {\n * search: \"agent:read\",\n * write: \"agent:write\",\n * },\n * });\n *\n * // Create LlamaIndex agent with Vorim-wrapped tools\n * const agent = new OpenAIAgent({ tools });\n * const response = await agent.chat({ message: \"Research AI trends\" });\n * ```\n */\nexport async function createVorimAgent<T extends LlamaIndexTool>(\n config: CreateVorimLlamaIndexAgentConfig & { tools: T[] },\n) {\n const { vorim, name, capabilities, scopes, description, tools: rawTools, permissionMap, defaultPermission, asyncAudit } = config;\n\n // Register agent with Vorim\n const registration = await vorim.register({\n name,\n description,\n capabilities,\n scopes,\n });\n\n const agentId = registration.agent.agent_id;\n const toolConfig: VorimLlamaIndexConfig = { vorim, agentId, permissionMap, defaultPermission, asyncAudit };\n\n // Wrap tools with permission checks\n const tools = wrapTools(rawTools, toolConfig);\n\n return {\n /** The Vorim agent_id. */\n agentId,\n /** Full registration result. */\n registration,\n /** Tools wrapped with Vorim permission checks + audit. */\n tools,\n /** The private key (store securely — shown once). */\n privateKey: registration.private_key,\n };\n}\n\n// ─── Audit Helpers ────────────────────────────────────────────────────────\n\n/**\n * Emit a manual audit event for a LlamaIndex agent action that isn't\n * captured by the tool wrapper (e.g. RAG retrieval, chat responses).\n */\nexport async function emitLlamaIndexEvent(\n vorim: VorimSDK,\n agentId: string,\n event: {\n action: string;\n resource?: string;\n result: 'success' | 'denied' | 'error';\n latencyMs?: number;\n error?: string;\n metadata?: Record<string, unknown>;\n },\n): Promise<void> {\n await vorim.emit({\n agent_id: agentId,\n event_type: 'api_request',\n action: event.action,\n resource: event.resource,\n result: event.result,\n latency_ms: event.latencyMs,\n error_code: event.error ? 'LLAMAINDEX_ERROR' : undefined,\n metadata: {\n framework: 'llamaindex',\n ...(event.error ? { error: event.error } : {}),\n ...event.metadata,\n },\n });\n}\n\n// ─── Internal helpers ─────────────────────────────────────────────────────\n\nfunction truncate(str: string, max: number): string {\n return str.length > max ? str.slice(0, max) + '…' : str;\n}\n\nfunction emitAudit(vorim: VorimSDK, event: AuditEventInput, async: boolean): void {\n if (async) {\n vorim.emit(event).catch(() => {});\n } else {\n vorim.emit(event).catch(() => {});\n }\n}\n\n/**\n * Lazy-cached replay context getter. Hashes computed once on first\n * call, reused thereafter. Returns empty object when no replay config\n * was given, so the spread is a no-op.\n */\nfunction makeReplayContextGetter(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"],"mappings":";AAwEO,SAAS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A,IACX;AAAA,EACF,CAAC;AACH;AAIA,SAAS,SAAS,KAAa,KAAqB;AAClD,SAAO,IAAI,SAAS,MAAM,IAAI,MAAM,GAAG,GAAG,IAAI,WAAM;AACtD;AAEA,SAAS,UAAU,OAAiB,OAAwB,OAAsB;AAChF,MAAI,OAAO;AACT,UAAM,KAAK,KAAK,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAAA,EAClC,OAAO;AACL,UAAM,KAAK,KAAK,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAAA,EAClC;AACF;AAOA,SAAS,wBAAwB,QAAgE;AAC/F,MAAI,CAAC,OAAQ,QAAO,aAAa,CAAC;AAClC,MAAI,SAAwC;AAC5C,SAAO,MAAM;AACX,QAAI,CAAC,OAAQ,UAAS,qBAAqB,MAAM;AACjD,WAAO;AAAA,EACT;AACF;","names":["event"]}
|
|
1
|
+
{"version":3,"sources":["../../src/replay.ts","../../src/integrations/llamaindex.ts"],"sourcesContent":["/**\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 — LlamaIndex TS Integration\n// Wraps LlamaIndex tools with Vorim permission checks + audit trails.\n// Provides a tool wrapper and agent registration factory.\n//\n// Peer dependency: llamaindex >=0.4.0 (or @llamaindex/core)\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope, AuditEventInput } from '../types.js';\nimport {\n prepareReplayContext,\n type ReplayInputs,\n type ReplayContext,\n type CatalogueTool,\n} from '../replay.js';\n\n// ─── Re-declared LlamaIndex types (peer dependency — not bundled) ─────────\n// These mirror the actual interfaces from @llamaindex/core/llms and\n// @llamaindex/core/tools so consumers don't need to wrangle imports.\n\n/** Matches @llamaindex/core ToolMetadata */\ninterface ToolMetadata<P extends Record<string, unknown> = Record<string, unknown>> {\n name: string;\n description: string;\n parameters?: P;\n}\n\n/**\n * Matches @llamaindex/core BaseTool.\n * In LlamaIndex, `call` is optional on BaseTool but required on BaseToolWithCall.\n */\ninterface LlamaIndexTool<Input = any> {\n metadata: ToolMetadata;\n call: (input: Input) => any | Promise<any>;\n}\n\n// ─── Configuration ────────────────────────────────────────────────────────\n\nexport interface VorimLlamaIndexConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id to associate. */\n agentId: string;\n /** Map tool names → Vorim permission scopes. */\n permissionMap?: Record<string, PermissionScope>;\n /** Default permission scope for unmapped tools. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Whether to emit audit events asynchronously (fire-and-forget). @default true */\n asyncAudit?: boolean;\n /**\n * Replayable agent decision evidence (VAIP -02). Hashes attached to\n * every audit event the wrapper emits. Not covered by v0 canonical\n * signature form.\n */\n replay?: ReplayInputs;\n}\n\n// ─── Tool Wrapper ─────────────────────────────────────────────────────────\n\n/**\n * Wraps a LlamaIndex tool (`BaseTool` / `BaseToolWithCall` / `FunctionTool`)\n * with Vorim permission checks before execution and audit event emission after.\n *\n * The wrapper implements the same `BaseTool` interface so it's a drop-in\n * replacement anywhere LlamaIndex expects a tool.\n *\n * @example\n * ```ts\n * import { FunctionTool } from \"llamaindex\";\n * import createVorim from \"@vorim/sdk\";\n * import { wrapTool } from \"@vorim/sdk/integrations/llamaindex\";\n *\n * const vorim = createVorim({ apiKey: \"agid_sk_live_...\" });\n *\n * const searchTool = FunctionTool.from(\n * async ({ query }: { query: string }) => `Results for: ${query}`,\n * { name: \"search\", description: \"Search documents\", parameters: { ... } }\n * );\n *\n * const guarded = wrapTool(searchTool, {\n * vorim,\n * agentId: \"agid_acme_a1b2c3d4\",\n * permissionMap: { search: \"agent:read\" },\n * });\n *\n * // Use with any LlamaIndex agent\n * const agent = new OpenAIAgent({ tools: [guarded] });\n * ```\n */\nexport function wrapTool<T extends LlamaIndexTool>(\n tool: T,\n config: VorimLlamaIndexConfig,\n): T {\n const {\n vorim, agentId,\n permissionMap = {},\n defaultPermission = 'agent:execute',\n asyncAudit = true,\n replay,\n } = config;\n\n const originalCall = tool.call.bind(tool);\n const toolName = tool.metadata.name;\n const scope = permissionMap[toolName] ?? defaultPermission;\n const getReplayCtx = makeReplayContextGetter(replay);\n\n // Create a new object that preserves the tool's prototype chain\n // and all properties, but overrides `call`\n const wrapped = Object.create(Object.getPrototypeOf(tool), {\n ...Object.getOwnPropertyDescriptors(tool),\n call: {\n value: async function vorimGuardedCall(input: any): Promise<any> {\n // 1. Permission check\n const { allowed, reason } = await vorim.check(agentId, scope);\n const replayCtx = await getReplayCtx();\n\n if (!allowed) {\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: toolName,\n resource: truncate(JSON.stringify(input), 500),\n permission: scope,\n result: 'denied',\n metadata: { reason, framework: 'llamaindex' },\n ...replayCtx,\n };\n await emitAudit(vorim, event, asyncAudit);\n throw new Error(\n `Vorim: permission denied for \"${toolName}\" — scope \"${scope}\"${reason ? `: ${reason}` : ''}`,\n );\n }\n\n // 2. Execute the original tool\n const start = Date.now();\n let result: any;\n try {\n result = await originalCall(input);\n } catch (err) {\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: toolName,\n resource: truncate(JSON.stringify(input), 500),\n permission: scope,\n result: 'error',\n latency_ms: Date.now() - start,\n error_code: err instanceof Error ? err.name : 'UNKNOWN',\n metadata: {\n error: err instanceof Error ? err.message : String(err),\n framework: 'llamaindex',\n },\n ...replayCtx,\n };\n await emitAudit(vorim, event, asyncAudit);\n throw err;\n }\n\n // 3. Audit success\n const event: AuditEventInput = {\n agent_id: agentId,\n event_type: 'tool_call',\n action: toolName,\n resource: truncate(JSON.stringify(input), 500),\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n metadata: { framework: 'llamaindex' },\n ...replayCtx,\n };\n await emitAudit(vorim, event, asyncAudit);\n\n return result;\n },\n writable: true,\n configurable: true,\n enumerable: true,\n },\n }) as T;\n\n return wrapped;\n}\n\n/**\n * Wraps an array of LlamaIndex tools with Vorim permission + audit.\n */\nexport function wrapTools<T extends LlamaIndexTool>(\n tools: T[],\n config: VorimLlamaIndexConfig,\n): T[] {\n return tools.map(t => wrapTool(t, config));\n}\n\n// ─── Agent Factory ────────────────────────────────────────────────────────\n\nexport interface CreateVorimLlamaIndexAgentConfig extends VorimLlamaIndexConfig {\n /** Display name for the agent. */\n name: string;\n /** Agent capabilities. */\n capabilities: string[];\n /** Initial permission scopes. */\n scopes: PermissionScope[];\n /** Optional description. */\n description?: string;\n}\n\n/**\n * Registers a new agent with Vorim and returns wrapped tools ready for\n * use with any LlamaIndex agent (OpenAIAgent, ReActAgent, etc.).\n *\n * @example\n * ```ts\n * import { OpenAIAgent, FunctionTool } from \"llamaindex\";\n * import createVorim from \"@vorim/sdk\";\n * import { createVorimAgent } from \"@vorim/sdk/integrations/llamaindex\";\n *\n * const vorim = createVorim({ apiKey: \"agid_sk_live_...\" });\n *\n * const searchTool = FunctionTool.from(...);\n * const writeTool = FunctionTool.from(...);\n *\n * const { agentId, tools } = await createVorimAgent({\n * vorim,\n * name: \"research-agent\",\n * capabilities: [\"search\", \"write\"],\n * scopes: [\"agent:read\", \"agent:write\", \"agent:execute\"],\n * tools: [searchTool, writeTool],\n * permissionMap: {\n * search: \"agent:read\",\n * write: \"agent:write\",\n * },\n * });\n *\n * // Create LlamaIndex agent with Vorim-wrapped tools\n * const agent = new OpenAIAgent({ tools });\n * const response = await agent.chat({ message: \"Research AI trends\" });\n * ```\n */\nexport async function createVorimAgent<T extends LlamaIndexTool>(\n config: CreateVorimLlamaIndexAgentConfig & { tools: T[] },\n) {\n const { vorim, name, capabilities, scopes, description, tools: rawTools, permissionMap, defaultPermission, asyncAudit } = config;\n\n // Register agent with Vorim\n const registration = await vorim.register({\n name,\n description,\n capabilities,\n scopes,\n });\n\n const agentId = registration.agent.agent_id;\n const toolConfig: VorimLlamaIndexConfig = { vorim, agentId, permissionMap, defaultPermission, asyncAudit };\n\n // Wrap tools with permission checks\n const tools = wrapTools(rawTools, toolConfig);\n\n return {\n /** The Vorim agent_id. */\n agentId,\n /** Full registration result. */\n registration,\n /** Tools wrapped with Vorim permission checks + audit. */\n tools,\n /** The private key (store securely — shown once). */\n privateKey: registration.private_key,\n };\n}\n\n// ─── Audit Helpers ────────────────────────────────────────────────────────\n\n/**\n * Emit a manual audit event for a LlamaIndex agent action that isn't\n * captured by the tool wrapper (e.g. RAG retrieval, chat responses).\n */\nexport async function emitLlamaIndexEvent(\n vorim: VorimSDK,\n agentId: string,\n event: {\n action: string;\n resource?: string;\n result: 'success' | 'denied' | 'error';\n latencyMs?: number;\n error?: string;\n metadata?: Record<string, unknown>;\n },\n): Promise<void> {\n await vorim.emit({\n agent_id: agentId,\n event_type: 'api_request',\n action: event.action,\n resource: event.resource,\n result: event.result,\n latency_ms: event.latencyMs,\n error_code: event.error ? 'LLAMAINDEX_ERROR' : undefined,\n metadata: {\n framework: 'llamaindex',\n ...(event.error ? { error: event.error } : {}),\n ...event.metadata,\n },\n });\n}\n\n// ─── Internal helpers ─────────────────────────────────────────────────────\n\nfunction truncate(str: string, max: number): string {\n return str.length > max ? str.slice(0, max) + '…' : str;\n}\n\nfunction emitAudit(vorim: VorimSDK, event: AuditEventInput, async: boolean): Promise<void> | void {\n if (async) {\n vorim.emit(event).catch(() => {});\n return;\n }\n // asyncAudit=false: return the awaitable so callers can ensure the audit\n // event is persisted before the process exits.\n return vorim.emit(event).then(() => undefined).catch(() => undefined);\n}\n\n/**\n * Lazy-cached replay context getter. Hashes computed once on first\n * call, reused thereafter. Returns empty object when no replay config\n * was given, so the spread is a no-op.\n */\nfunction makeReplayContextGetter(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"],"mappings":";AAwEO,SAAS,gBAAgB,OAAwB;AACtD,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,UAAU,MAAO,QAAO;AAE5B,MAAI,OAAO,UAAU,UAAU;AAC7B,QAAI,CAAC,OAAO,SAAS,KAAK,GAAG;AAC3B,YAAM,IAAI,MAAM,qDAAqD;AAAA,IACvE;AAKA,WAAO,MAAM,SAAS;AAAA,EACxB;AAEA,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO,KAAK,UAAU,KAAK;AAAA,EAC7B;AAEA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,MAAM,MAAM,IAAI,eAAe,EAAE,KAAK,GAAG,IAAI;AA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AClC,MAAI,SAAwC;AAC5C,SAAO,MAAM;AACX,QAAI,CAAC,OAAQ,UAAS,qBAAqB,MAAM;AACjD,WAAO;AAAA,EACT;AACF;","names":["event"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/integrations/stripe-acp.ts"],"sourcesContent":["// ============================================================================\n// Vorim AI — Stripe Agentic Commerce Protocol (ACP) Integration\n//\n// Adds agent identity verification and permission checking before agents can\n// initiate payments via Stripe ACP. Ensures only authorized agents with the\n// 'transact' permission scope can create checkouts and complete purchases.\n//\n// Usage:\n// import { createVorimACP } from '@vorim/sdk/integrations/stripe-acp';\n//\n// const acp = createVorimACP({ apiKey: 'agid_sk_...', minTrustScore: 60 });\n//\n// // Before creating a Stripe ACP checkout\n// const auth = await acp.authorizeCheckout({\n// agentId: 'agid_abc123',\n// seller: 'acme-store',\n// amount: 9999,\n// currency: 'usd',\n// });\n//\n// if (auth.authorized) {\n// // Proceed with Stripe checkout\n// }\n//\n// // Express middleware\n// app.post('/checkouts', acp.middleware(), (req, res) => {\n// // Only reached if agent has transact permission + trust score passes\n// });\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\n\nexport interface ACPConfig {\n apiKey: string;\n baseUrl?: string;\n minTrustScore?: number;\n requiredScope?: string;\n}\n\nexport interface CheckoutAuthorizationRequest {\n agentId: string;\n seller?: string;\n amount?: number;\n currency?: string;\n minTrustScore?: number;\n}\n\nexport interface CheckoutAuthorization {\n authorized: boolean;\n agentId: string;\n trustScore: number;\n status: string;\n reason?: string;\n scopeVerified: boolean;\n}\n\nexport class VorimACP {\n private sdk: VorimSDK;\n private minTrustScore: number;\n private requiredScope: string;\n\n constructor(sdk: VorimSDK, config?: Partial<ACPConfig>) {\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 checkout.\n */\n async authorizeCheckout(req: CheckoutAuthorizationRequest): Promise<CheckoutAuthorization> {\n const threshold = req.minTrustScore ?? this.minTrustScore;\n\n // Check transact permission\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, 'checkout.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, 'checkout.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 // Verify trust score\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\n }\n\n if (status !== 'active') {\n await this.logEvent(req.agentId, 'checkout.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, 'checkout.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, 'checkout.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 * Log a checkout lifecycle event.\n */\n async logCheckoutCreated(agentId: string, checkoutId: string, seller?: string, amount?: number): Promise<void> {\n await this.logEvent(agentId, 'checkout.created', 'success', { agentId, seller, amount }, { checkout_id: checkoutId });\n }\n\n async logCheckoutCompleted(agentId: string, checkoutId: string, seller?: string, amount?: number): Promise<void> {\n await this.logEvent(agentId, 'checkout.completed', 'success', { agentId, seller, amount }, { checkout_id: checkoutId });\n }\n\n async logCheckoutCanceled(agentId: string, checkoutId: string, reason?: string): Promise<void> {\n await this.logEvent(agentId, 'checkout.canceled', 'success', { agentId }, { checkout_id: checkoutId, cancel_reason: reason });\n }\n\n /**\n * Express/Connect middleware that requires transact permission.\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.authorizeCheckout({\n agentId,\n seller: 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 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 // Use the canonical audit-event contract: event_type from the\n // AuditEventType enum ('api_request' for a payment authorization) and\n // `result` (not the non-existent `outcome`) 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?.seller || '',\n metadata: {\n seller: req?.seller || '',\n amount: req?.amount || 0,\n currency: req?.currency || '',\n ...metadata,\n },\n });\n } catch {\n // Don't block commerce flow\n }\n }\n}\n\n/**\n * Create a VorimACP instance.\n *\n * @example\n * ```typescript\n * import createVorim from '@vorim/sdk';\n * import { createVorimACP } from '@vorim/sdk/integrations/stripe-acp';\n *\n * const vorim = createVorim({ apiKey: 'agid_sk_...' });\n * const acp = createVorimACP(vorim, { minTrustScore: 70 });\n *\n * // Verify before checkout\n * const auth = await acp.authorizeCheckout({ agentId: 'agid_abc123', seller: 'shop', amount: 4999 });\n *\n * // Express middleware\n * app.post('/checkouts', acp.middleware(), createCheckoutHandler);\n * ```\n */\nexport function createVorimACP(sdk: VorimSDK, config?: Partial<ACPConfig>): VorimACP {\n return new VorimACP(sdk, config);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAwDO,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,EAKA,MAAM,kBAAkB,KAAmE;AACzF,UAAM,YAAY,IAAI,iBAAiB,KAAK;AAG5C,QAAI;AACF,YAAM,OAAO,MAAM,KAAK,IAAI,MAAM,IAAI,SAAS,KAAK,aAAoB;AACxE,UAAI,CAAE,KAAa,SAAS;AAC1B,cAAM,KAAK,SAAS,IAAI,SAAS,sBAAsB,UAAU,KAAK,EAAE,QAAQ,WAAW,KAAK,aAAa,GAAG,CAAC;AACjH,eAAO;AAAA,UACL,YAAY;AAAA,UACZ,SAAS,IAAI;AAAA,UACb,YAAY;AAAA,UACZ,QAAQ;AAAA,UACR,QAAQ,uBAAuB,KAAK,aAAa;AAAA,UACjD,eAAe;AAAA,QACjB;AAAA,MACF;AAAA,IACF,SAAS,GAAQ;AACf,YAAM,KAAK,SAAS,IAAI,SAAS,sBAAsB,UAAU,KAAK,EAAE,QAAQ,EAAE,QAAQ,CAAC;AAC3F,aAAO;AAAA,QACL,YAAY;AAAA,QACZ,SAAS,IAAI;AAAA,QAC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,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,UAAU;AAAA,QACzB,UAAU;AAAA,UACR,QAAQ,KAAK,UAAU;AAAA,UACvB,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":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/integrations/stripe-acp.ts"],"sourcesContent":["// ============================================================================\n// Vorim AI — Stripe Agentic Commerce Protocol (ACP) Integration\n//\n// Adds agent identity verification and permission checking before agents can\n// initiate payments via Stripe ACP. Ensures only authorized agents with the\n// 'transact' permission scope can create checkouts and complete purchases.\n//\n// Usage:\n// import createVorim from '@vorim/sdk';\n// import { createVorimACP } from '@vorim/sdk/integrations/stripe-acp';\n//\n// const vorim = createVorim({ apiKey: 'agid_sk_...' });\n// const acp = createVorimACP(vorim, { minTrustScore: 60 });\n//\n// // Before creating a Stripe ACP checkout\n// const auth = await acp.authorizeCheckout({\n// agentId: 'agid_abc123',\n// seller: 'acme-store',\n// amount: 9999,\n// currency: 'usd',\n// });\n//\n// if (auth.authorized) {\n// // Proceed with Stripe checkout\n// }\n//\n// // Express middleware\n// app.post('/checkouts', acp.middleware(), (req, res) => {\n// // Only reached if agent has transact permission + trust score passes\n// });\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\n\nexport interface ACPConfig {\n apiKey: string;\n baseUrl?: string;\n minTrustScore?: number;\n requiredScope?: string;\n}\n\nexport interface CheckoutAuthorizationRequest {\n agentId: string;\n seller?: string;\n amount?: number;\n currency?: string;\n minTrustScore?: number;\n}\n\nexport interface CheckoutAuthorization {\n authorized: boolean;\n agentId: string;\n trustScore: number;\n status: string;\n reason?: string;\n scopeVerified: boolean;\n}\n\nexport class VorimACP {\n private sdk: VorimSDK;\n private minTrustScore: number;\n private requiredScope: string;\n\n constructor(sdk: VorimSDK, config?: Partial<ACPConfig>) {\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 checkout.\n */\n async authorizeCheckout(req: CheckoutAuthorizationRequest): Promise<CheckoutAuthorization> {\n const threshold = req.minTrustScore ?? this.minTrustScore;\n\n // Check transact permission\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, 'checkout.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, 'checkout.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 // Verify trust score\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\n }\n\n if (status !== 'active') {\n await this.logEvent(req.agentId, 'checkout.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, 'checkout.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, 'checkout.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 * Log a checkout lifecycle event.\n */\n async logCheckoutCreated(agentId: string, checkoutId: string, seller?: string, amount?: number): Promise<void> {\n await this.logEvent(agentId, 'checkout.created', 'success', { agentId, seller, amount }, { checkout_id: checkoutId });\n }\n\n async logCheckoutCompleted(agentId: string, checkoutId: string, seller?: string, amount?: number): Promise<void> {\n await this.logEvent(agentId, 'checkout.completed', 'success', { agentId, seller, amount }, { checkout_id: checkoutId });\n }\n\n async logCheckoutCanceled(agentId: string, checkoutId: string, reason?: string): Promise<void> {\n await this.logEvent(agentId, 'checkout.canceled', 'success', { agentId }, { checkout_id: checkoutId, cancel_reason: reason });\n }\n\n /**\n * Express/Connect middleware that requires transact permission.\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.authorizeCheckout({\n agentId,\n seller: 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 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 // Use the canonical audit-event contract: event_type from the\n // AuditEventType enum ('api_request' for a payment authorization) and\n // `result` (not the non-existent `outcome`) 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?.seller || '',\n metadata: {\n seller: req?.seller || '',\n amount: req?.amount || 0,\n currency: req?.currency || '',\n ...metadata,\n },\n });\n } catch {\n // Don't block commerce flow\n }\n }\n}\n\n/**\n * Create a VorimACP instance.\n *\n * @example\n * ```typescript\n * import createVorim from '@vorim/sdk';\n * import { createVorimACP } from '@vorim/sdk/integrations/stripe-acp';\n *\n * const vorim = createVorim({ apiKey: 'agid_sk_...' });\n * const acp = createVorimACP(vorim, { minTrustScore: 70 });\n *\n * // Verify before checkout\n * const auth = await acp.authorizeCheckout({ agentId: 'agid_abc123', seller: 'shop', amount: 4999 });\n *\n * // Express middleware\n * app.post('/checkouts', acp.middleware(), createCheckoutHandler);\n * ```\n */\nexport function createVorimACP(sdk: VorimSDK, config?: Partial<ACPConfig>): VorimACP {\n return new VorimACP(sdk, config);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA0DO,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,EAKA,MAAM,kBAAkB,KAAmE;AACzF,UAAM,YAAY,IAAI,iBAAiB,KAAK;AAG5C,QAAI;AACF,YAAM,OAAO,MAAM,KAAK,IAAI,MAAM,IAAI,SAAS,KAAK,aAAoB;AACxE,UAAI,CAAE,KAAa,SAAS;AAC1B,cAAM,KAAK,SAAS,IAAI,SAAS,sBAAsB,UAAU,KAAK,EAAE,QAAQ,WAAW,KAAK,aAAa,GAAG,CA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IAAI,MAAM,YAAY;AAAA,QAChC,eAAe;AAAA,MACjB,CAAC;AAED,UAAI,CAAC,KAAK,YAAY;AACpB,YAAI,OAAO,GAAG,EAAE,KAAK;AAAA,UACnB,OAAO;AAAA,YACL,MAAM;AAAA,YACN,SAAS,KAAK,UAAU;AAAA,YACxB,aAAa,KAAK;AAAA,YAClB,QAAQ,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,UAAU;AAAA,QACzB,UAAU;AAAA,UACR,QAAQ,KAAK,UAAU;AAAA,UACvB,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":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/integrations/stripe-acp.ts"],"sourcesContent":["// ============================================================================\n// Vorim AI — Stripe Agentic Commerce Protocol (ACP) Integration\n//\n// Adds agent identity verification and permission checking before agents can\n// initiate payments via Stripe ACP. Ensures only authorized agents with the\n// 'transact' permission scope can create checkouts and complete purchases.\n//\n// Usage:\n// import { createVorimACP } from '@vorim/sdk/integrations/stripe-acp';\n//\n// const acp = createVorimACP({ apiKey: 'agid_sk_...', minTrustScore: 60 });\n//\n// // Before creating a Stripe ACP checkout\n// const auth = await acp.authorizeCheckout({\n// agentId: 'agid_abc123',\n// seller: 'acme-store',\n// amount: 9999,\n// currency: 'usd',\n// });\n//\n// if (auth.authorized) {\n// // Proceed with Stripe checkout\n// }\n//\n// // Express middleware\n// app.post('/checkouts', acp.middleware(), (req, res) => {\n// // Only reached if agent has transact permission + trust score passes\n// });\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\n\nexport interface ACPConfig {\n apiKey: string;\n baseUrl?: string;\n minTrustScore?: number;\n requiredScope?: string;\n}\n\nexport interface CheckoutAuthorizationRequest {\n agentId: string;\n seller?: string;\n amount?: number;\n currency?: string;\n minTrustScore?: number;\n}\n\nexport interface CheckoutAuthorization {\n authorized: boolean;\n agentId: string;\n trustScore: number;\n status: string;\n reason?: string;\n scopeVerified: boolean;\n}\n\nexport class VorimACP {\n private sdk: VorimSDK;\n private minTrustScore: number;\n private requiredScope: string;\n\n constructor(sdk: VorimSDK, config?: Partial<ACPConfig>) {\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 checkout.\n */\n async authorizeCheckout(req: CheckoutAuthorizationRequest): Promise<CheckoutAuthorization> {\n const threshold = req.minTrustScore ?? this.minTrustScore;\n\n // Check transact permission\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, 'checkout.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, 'checkout.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 // Verify trust score\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\n }\n\n if (status !== 'active') {\n await this.logEvent(req.agentId, 'checkout.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, 'checkout.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, 'checkout.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 * Log a checkout lifecycle event.\n */\n async logCheckoutCreated(agentId: string, checkoutId: string, seller?: string, amount?: number): Promise<void> {\n await this.logEvent(agentId, 'checkout.created', 'success', { agentId, seller, amount }, { checkout_id: checkoutId });\n }\n\n async logCheckoutCompleted(agentId: string, checkoutId: string, seller?: string, amount?: number): Promise<void> {\n await this.logEvent(agentId, 'checkout.completed', 'success', { agentId, seller, amount }, { checkout_id: checkoutId });\n }\n\n async logCheckoutCanceled(agentId: string, checkoutId: string, reason?: string): Promise<void> {\n await this.logEvent(agentId, 'checkout.canceled', 'success', { agentId }, { checkout_id: checkoutId, cancel_reason: reason });\n }\n\n /**\n * Express/Connect middleware that requires transact permission.\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.authorizeCheckout({\n agentId,\n seller: 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 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 // Use the canonical audit-event contract: event_type from the\n // AuditEventType enum ('api_request' for a payment authorization) and\n // `result` (not the non-existent `outcome`) 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?.seller || '',\n metadata: {\n seller: req?.seller || '',\n amount: req?.amount || 0,\n currency: req?.currency || '',\n ...metadata,\n },\n });\n } catch {\n // Don't block commerce flow\n }\n }\n}\n\n/**\n * Create a VorimACP instance.\n *\n * @example\n * ```typescript\n * import createVorim from '@vorim/sdk';\n * import { createVorimACP } from '@vorim/sdk/integrations/stripe-acp';\n *\n * const vorim = createVorim({ apiKey: 'agid_sk_...' });\n * const acp = createVorimACP(vorim, { minTrustScore: 70 });\n *\n * // Verify before checkout\n * const auth = await acp.authorizeCheckout({ agentId: 'agid_abc123', seller: 'shop', amount: 4999 });\n *\n * // Express middleware\n * app.post('/checkouts', acp.middleware(), createCheckoutHandler);\n * ```\n */\nexport function createVorimACP(sdk: VorimSDK, config?: Partial<ACPConfig>): VorimACP {\n return new VorimACP(sdk, config);\n}\n"],"mappings":";AAwDO,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,EAKA,MAA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O,GAAG,EAAE,KAAK;AAAA,UACnB,OAAO,EAAE,MAAM,oBAAoB,SAAS,wBAAwB,MAAM,UAAU;AAAA,QACtF,CAAC;AACD;AAAA,MACF;AAEA,YAAM,OAAO,MAAM,KAAK,kBAAkB;AAAA,QACxC;AAAA,QACA,QAAQ,IAAI,MAAM,UAAU;AAAA,QAC5B,QAAQ,IAAI,MAAM,UAAU;AAAA,QAC5B,UAAU,IAAI,MAAM,YAAY;AAAA,QAChC,eAAe;AAAA,MACjB,CAAC;AAED,UAAI,CAAC,KAAK,YAAY;AACpB,YAAI,OAAO,GAAG,EAAE,KAAK;AAAA,UACnB,OAAO;AAAA,YACL,MAAM;AAAA,YACN,SAAS,KAAK,UAAU;AAAA,YACxB,aAAa,KAAK;AAAA,YAClB,QAAQ,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,UAAU;AAAA,QACzB,UAAU;AAAA,UACR,QAAQ,KAAK,UAAU;AAAA,UACvB,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":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/integrations/stripe-acp.ts"],"sourcesContent":["// ============================================================================\n// Vorim AI — Stripe Agentic Commerce Protocol (ACP) Integration\n//\n// Adds agent identity verification and permission checking before agents can\n// initiate payments via Stripe ACP. Ensures only authorized agents with the\n// 'transact' permission scope can create checkouts and complete purchases.\n//\n// Usage:\n// import createVorim from '@vorim/sdk';\n// import { createVorimACP } from '@vorim/sdk/integrations/stripe-acp';\n//\n// const vorim = createVorim({ apiKey: 'agid_sk_...' });\n// const acp = createVorimACP(vorim, { minTrustScore: 60 });\n//\n// // Before creating a Stripe ACP checkout\n// const auth = await acp.authorizeCheckout({\n// agentId: 'agid_abc123',\n// seller: 'acme-store',\n// amount: 9999,\n// currency: 'usd',\n// });\n//\n// if (auth.authorized) {\n// // Proceed with Stripe checkout\n// }\n//\n// // Express middleware\n// app.post('/checkouts', acp.middleware(), (req, res) => {\n// // Only reached if agent has transact permission + trust score passes\n// });\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\n\nexport interface ACPConfig {\n apiKey: string;\n baseUrl?: string;\n minTrustScore?: number;\n requiredScope?: string;\n}\n\nexport interface CheckoutAuthorizationRequest {\n agentId: string;\n seller?: string;\n amount?: number;\n currency?: string;\n minTrustScore?: number;\n}\n\nexport interface CheckoutAuthorization {\n authorized: boolean;\n agentId: string;\n trustScore: number;\n status: string;\n reason?: string;\n scopeVerified: boolean;\n}\n\nexport class VorimACP {\n private sdk: VorimSDK;\n private minTrustScore: number;\n private requiredScope: string;\n\n constructor(sdk: VorimSDK, config?: Partial<ACPConfig>) {\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 checkout.\n */\n async authorizeCheckout(req: CheckoutAuthorizationRequest): Promise<CheckoutAuthorization> {\n const threshold = req.minTrustScore ?? this.minTrustScore;\n\n // Check transact permission\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, 'checkout.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, 'checkout.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 // Verify trust score\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\n }\n\n if (status !== 'active') {\n await this.logEvent(req.agentId, 'checkout.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, 'checkout.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, 'checkout.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 * Log a checkout lifecycle event.\n */\n async logCheckoutCreated(agentId: string, checkoutId: string, seller?: string, amount?: number): Promise<void> {\n await this.logEvent(agentId, 'checkout.created', 'success', { agentId, seller, amount }, { checkout_id: checkoutId });\n }\n\n async logCheckoutCompleted(agentId: string, checkoutId: string, seller?: string, amount?: number): Promise<void> {\n await this.logEvent(agentId, 'checkout.completed', 'success', { agentId, seller, amount }, { checkout_id: checkoutId });\n }\n\n async logCheckoutCanceled(agentId: string, checkoutId: string, reason?: string): Promise<void> {\n await this.logEvent(agentId, 'checkout.canceled', 'success', { agentId }, { checkout_id: checkoutId, cancel_reason: reason });\n }\n\n /**\n * Express/Connect middleware that requires transact permission.\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.authorizeCheckout({\n agentId,\n seller: 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 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 // Use the canonical audit-event contract: event_type from the\n // AuditEventType enum ('api_request' for a payment authorization) and\n // `result` (not the non-existent `outcome`) 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?.seller || '',\n metadata: {\n seller: req?.seller || '',\n amount: req?.amount || 0,\n currency: req?.currency || '',\n ...metadata,\n },\n });\n } catch {\n // Don't block commerce flow\n }\n }\n}\n\n/**\n * Create a VorimACP instance.\n *\n * @example\n * ```typescript\n * import createVorim from '@vorim/sdk';\n * import { createVorimACP } from '@vorim/sdk/integrations/stripe-acp';\n *\n * const vorim = createVorim({ apiKey: 'agid_sk_...' });\n * const acp = createVorimACP(vorim, { minTrustScore: 70 });\n *\n * // Verify before checkout\n * const auth = await acp.authorizeCheckout({ agentId: 'agid_abc123', seller: 'shop', amount: 4999 });\n *\n * // Express middleware\n * app.post('/checkouts', acp.middleware(), createCheckoutHandler);\n * ```\n */\nexport function createVorimACP(sdk: VorimSD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