@vorim/sdk 3.8.0 → 3.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -124,7 +124,7 @@ async function prepareReplayContext(inputs) {
124
124
  }
125
125
 
126
126
  // src/index.ts
127
- var SDK_VERSION = true ? "3.8.0" : "0.0.0";
127
+ var SDK_VERSION = true ? "3.8.1" : "0.0.0";
128
128
  var USER_AGENT = `vorim-sdk/${SDK_VERSION}`;
129
129
  function sleep(ms) {
130
130
  return new Promise((resolve) => setTimeout(resolve, ms));
package/dist/index.js CHANGED
@@ -75,7 +75,7 @@ async function prepareReplayContext(inputs) {
75
75
  }
76
76
 
77
77
  // src/index.ts
78
- var SDK_VERSION = true ? "3.8.0" : "0.0.0";
78
+ var SDK_VERSION = true ? "3.8.1" : "0.0.0";
79
79
  var USER_AGENT = `vorim-sdk/${SDK_VERSION}`;
80
80
  function sleep(ms) {
81
81
  return new Promise((resolve) => setTimeout(resolve, ms));
@@ -0,0 +1,280 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/integrations/hermes.ts
31
+ var hermes_exports = {};
32
+ __export(hermes_exports, {
33
+ wrapHermesTool: () => wrapHermesTool,
34
+ wrapHermesTools: () => wrapHermesTools
35
+ });
36
+ module.exports = __toCommonJS(hermes_exports);
37
+
38
+ // src/integrations/_runtime-gate.ts
39
+ function isAllowVerdict(decision) {
40
+ return decision === "allow" || decision === "modify";
41
+ }
42
+ async function runtimeGate(vorim, agentId, actionTarget, scope, payload, opts = {}) {
43
+ const onEscalation = opts.onEscalation ?? "wait";
44
+ const onTransportFailure = opts.onTransportFailure ?? "deny";
45
+ const d = await vorim.beforeAction(
46
+ { agentId, actionType: "tool_call", actionTarget, requiredScope: scope, payload },
47
+ { throwOnDeny: false }
48
+ );
49
+ if (d.isFallback || d.decision === "fallback") {
50
+ if (onTransportFailure === "allow") {
51
+ return { allowed: true, reason: d.reason ?? "control plane unreachable (fail-open)", decisionId: d.decisionId || void 0 };
52
+ }
53
+ return { allowed: false, reason: d.reason ?? "control plane unreachable (failed closed)", decisionId: d.decisionId || void 0 };
54
+ }
55
+ if (d.decision !== "escalate") {
56
+ return { allowed: isAllowVerdict(d.decision), reason: d.reason, decisionId: d.decisionId || void 0 };
57
+ }
58
+ if (onEscalation === "allow") {
59
+ return { allowed: true, reason: d.reason ?? "escalated (auto-allowed)", decisionId: d.decisionId || void 0 };
60
+ }
61
+ if (onEscalation === "deny") {
62
+ return { allowed: false, reason: d.reason ?? "escalated (auto-denied \u2014 awaiting human)", decisionId: d.decisionId || void 0 };
63
+ }
64
+ if (!d.decisionId) {
65
+ return { allowed: false, reason: "escalated but no decisionId to poll", decisionId: void 0 };
66
+ }
67
+ try {
68
+ const resolved = await vorim.waitForDecisionResolution(d.decisionId, { timeoutMs: opts.escalationTimeoutMs });
69
+ return { allowed: isAllowVerdict(resolved.decision), reason: resolved.reason, decisionId: resolved.decisionId || d.decisionId };
70
+ } catch {
71
+ return { allowed: false, reason: "escalation not resolved before timeout", decisionId: d.decisionId };
72
+ }
73
+ }
74
+
75
+ // src/replay.ts
76
+ function jcsCanonicalise(value) {
77
+ if (value === null) return "null";
78
+ if (value === true) return "true";
79
+ if (value === false) return "false";
80
+ if (typeof value === "number") {
81
+ if (!Number.isFinite(value)) {
82
+ throw new Error("jcsCanonicalise: NaN and Infinity are not JCS-valid");
83
+ }
84
+ const abs = Math.abs(value);
85
+ if (value !== 0 && (abs >= 1e21 || abs < 1e-4 || Number.isInteger(value) && abs > 2 ** 53)) {
86
+ throw new Error(
87
+ `jcsCanonicalise: numbers in the ranges where JS and Python formatting diverge (|x| >= 1e21, |x| < 1e-4, or integer |x| > 2^53) are not supported in signed metadata. Use a string instead of ${value}.`
88
+ );
89
+ }
90
+ return value.toString();
91
+ }
92
+ if (typeof value === "string") {
93
+ return JSON.stringify(value);
94
+ }
95
+ if (Array.isArray(value)) {
96
+ return "[" + value.map(jcsCanonicalise).join(",") + "]";
97
+ }
98
+ if (typeof value === "object") {
99
+ const obj = value;
100
+ const keys = Object.keys(obj).filter((k) => obj[k] !== void 0).sort();
101
+ const parts = keys.map((k) => JSON.stringify(k) + ":" + jcsCanonicalise(obj[k]));
102
+ return "{" + parts.join(",") + "}";
103
+ }
104
+ throw new Error(`jcsCanonicalise: unsupported value type: ${typeof value}`);
105
+ }
106
+ async function sha256Hex(input) {
107
+ const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
108
+ const subtle = globalThis.crypto?.subtle;
109
+ if (subtle) {
110
+ const buf = await subtle.digest("SHA-256", bytes);
111
+ return Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, "0")).join("");
112
+ }
113
+ const nodeCrypto = await import("crypto");
114
+ return nodeCrypto.createHash("sha256").update(bytes).digest("hex");
115
+ }
116
+ async function hashTool(tool) {
117
+ const normalised = {
118
+ name: tool.name,
119
+ description: tool.description ?? "",
120
+ schema: tool.schema ?? {}
121
+ };
122
+ const hex = await sha256Hex(jcsCanonicalise(normalised));
123
+ return `sha256:${hex}`;
124
+ }
125
+ async function hashToolCatalogue(tools) {
126
+ if (tools.length === 0) {
127
+ return `sha256:${await sha256Hex("[]")}`;
128
+ }
129
+ const perTool = await Promise.all(tools.map(hashTool));
130
+ perTool.sort();
131
+ const hex = await sha256Hex(perTool.join(""));
132
+ return `sha256:${hex}`;
133
+ }
134
+ async function hashSystemPrompt(prompt) {
135
+ const hex = await sha256Hex(prompt);
136
+ return `sha256:${hex}`;
137
+ }
138
+ async function prepareReplayContext(inputs) {
139
+ const ctx = {};
140
+ if (inputs.modelVersion) ctx.model_version = inputs.modelVersion;
141
+ if (inputs.tools) ctx.tool_catalogue_hash = await hashToolCatalogue(inputs.tools);
142
+ if (inputs.systemPrompt) ctx.system_prompt_hash = await hashSystemPrompt(inputs.systemPrompt);
143
+ return ctx;
144
+ }
145
+
146
+ // src/integrations/hermes.ts
147
+ var FRAMEWORK = "hermes";
148
+ function truncate(s, max) {
149
+ return s.length > max ? s.slice(0, max) + "\u2026" : s;
150
+ }
151
+ function safeJson(v) {
152
+ try {
153
+ return JSON.stringify(v);
154
+ } catch {
155
+ return String(v);
156
+ }
157
+ }
158
+ async function gate(cfg, scope, actionTarget, payload) {
159
+ if (cfg.useRuntimeControl) {
160
+ try {
161
+ return await runtimeGate(cfg.vorim, cfg.agentId, actionTarget, scope, payload, {
162
+ onEscalation: cfg.onEscalation,
163
+ escalationTimeoutMs: cfg.escalationTimeoutMs,
164
+ onTransportFailure: cfg.onTransportFailure
165
+ });
166
+ } catch {
167
+ return { allowed: false, reason: "runtime gate unavailable (failed closed)" };
168
+ }
169
+ }
170
+ try {
171
+ const { allowed, reason } = await cfg.vorim.check(cfg.agentId, scope);
172
+ return { allowed, reason };
173
+ } catch {
174
+ return { allowed: false, reason: "permission check unavailable (failed closed)" };
175
+ }
176
+ }
177
+ function emitAudit(vorim, event, asyncAudit) {
178
+ if (asyncAudit) {
179
+ vorim.emit(event).catch(() => {
180
+ });
181
+ return;
182
+ }
183
+ return vorim.emit(event).then(() => void 0).catch(() => void 0);
184
+ }
185
+ function makeReplayGetter(replay) {
186
+ if (!replay) return async () => ({});
187
+ let cached = null;
188
+ return () => {
189
+ if (!cached) cached = prepareReplayContext(replay);
190
+ return cached;
191
+ };
192
+ }
193
+ function wrapHermesTool(name, tool, config) {
194
+ const { vorim, defaultPermission = "agent:execute", permissionMap = {}, asyncAudit = true } = config;
195
+ if (typeof tool.execute !== "function") return tool;
196
+ const toolName = name || tool.name || "hermes_tool";
197
+ const originalExecute = tool.execute.bind(tool);
198
+ const getReplay = makeReplayGetter(config.replay);
199
+ const scope = permissionMap[toolName] ?? defaultPermission;
200
+ const guarded = {
201
+ ...tool,
202
+ execute: async (args, options) => {
203
+ const { allowed, reason, decisionId } = await gate(config, scope, toolName, args);
204
+ const replayCtx = await getReplay();
205
+ const resource = truncate(safeJson(args), 500);
206
+ if (!allowed) {
207
+ await emitAudit(vorim, {
208
+ agent_id: config.agentId,
209
+ event_type: "tool_call",
210
+ action: toolName,
211
+ resource,
212
+ permission: scope,
213
+ result: "denied",
214
+ ...decisionId ? { decision_id: decisionId } : {},
215
+ metadata: { reason, framework: FRAMEWORK },
216
+ ...replayCtx
217
+ }, asyncAudit);
218
+ throw new Error(`Vorim: permission denied for "${toolName}" \u2014 scope "${scope}"${reason ? `: ${reason}` : ""}`);
219
+ }
220
+ const start = Date.now();
221
+ try {
222
+ const result = await originalExecute(args, options);
223
+ await emitAudit(vorim, {
224
+ agent_id: config.agentId,
225
+ event_type: "tool_call",
226
+ action: toolName,
227
+ resource,
228
+ permission: scope,
229
+ result: "success",
230
+ latency_ms: Date.now() - start,
231
+ ...decisionId ? { decision_id: decisionId } : {},
232
+ metadata: { framework: FRAMEWORK },
233
+ ...replayCtx
234
+ }, asyncAudit);
235
+ return result;
236
+ } catch (err) {
237
+ await emitAudit(vorim, {
238
+ agent_id: config.agentId,
239
+ event_type: "tool_call",
240
+ action: toolName,
241
+ resource,
242
+ permission: scope,
243
+ result: "error",
244
+ latency_ms: Date.now() - start,
245
+ error_code: err instanceof Error ? err.name : "UNKNOWN",
246
+ ...decisionId ? { decision_id: decisionId } : {},
247
+ metadata: { error: err instanceof Error ? err.message : String(err), framework: FRAMEWORK },
248
+ ...replayCtx
249
+ }, asyncAudit);
250
+ throw err;
251
+ }
252
+ }
253
+ };
254
+ return guarded;
255
+ }
256
+ function wrapHermesTools(tools, config) {
257
+ const asRecord = Array.isArray(tools) ? Object.fromEntries(tools.map((t, i) => [t.name || `tool_${i}`, t])) : tools;
258
+ const cfg = config.replay && !config.replay.tools ? { ...config, replay: { ...config.replay, tools: deriveCatalogue(asRecord) } } : config;
259
+ if (Array.isArray(tools)) {
260
+ return tools.map((t) => wrapHermesTool(t.name || "hermes_tool", t, cfg));
261
+ }
262
+ const out = {};
263
+ for (const [name, tool] of Object.entries(tools)) {
264
+ out[name] = wrapHermesTool(name, tool, cfg);
265
+ }
266
+ return out;
267
+ }
268
+ function deriveCatalogue(tools) {
269
+ return Object.entries(tools).map(([name, t]) => ({
270
+ name,
271
+ description: typeof t.description === "string" ? t.description : "",
272
+ schema: t.input_schema ?? t.parameters ?? {}
273
+ }));
274
+ }
275
+ // Annotate the CommonJS export names for ESM import in node:
276
+ 0 && (module.exports = {
277
+ wrapHermesTool,
278
+ wrapHermesTools
279
+ });
280
+ //# sourceMappingURL=hermes.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/integrations/hermes.ts","../../src/integrations/_runtime-gate.ts","../../src/replay.ts"],"sourcesContent":["// ============================================================================\n// VORIM SDK — Hermes Agent (Nous Research) Integration\n//\n// Hermes Agent loads tools two ways: its Python plugin system and external MCP\n// servers. This module secures the *tool execution* path from a TypeScript\n// host: it wraps a Hermes-style function tool ({ name, description, execute })\n// so every call is gated (allow / deny / escalate, fail-closed) and recorded\n// as a signed Vorim audit event.\n//\n// Why this exists alongside the MCP path: pointing Hermes at Vorim's MCP server\n// gives it the Vorim *tool catalog*, but MCP does not gate actions and its\n// audit events are unsigned (the MCP server holds no agent key). This wrapper\n// is the enforcement + signed-audit layer for tools Hermes runs in-process.\n//\n// No peer dependency — a Hermes tool is a plain object with an async `execute`.\n//\n// Usage:\n// import createVorim from '@vorim/sdk';\n// import { wrapHermesTools } from '@vorim/sdk/integrations/hermes';\n//\n// const vorim = createVorim({ apiKey: 'agid_sk_live_...' });\n// const tools = wrapHermesTools(myHermesTools, {\n// vorim, agentId: 'agid_acme_a1b2c3d4',\n// permissionMap: { send_email: 'agent:communicate' },\n// useRuntimeControl: true,\n// });\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope, AuditEventInput } from '../types.js';\nimport { runtimeGate, type EscalationPolicy, type TransportFailurePolicy } from './_runtime-gate.js';\nimport {\n prepareReplayContext,\n type ReplayInputs,\n type ReplayContext,\n type CatalogueTool,\n} from '../replay.js';\n\n// ─── Re-declared Hermes tool shape (no peer dependency — not bundled) ───────\n//\n// A Hermes function tool. We only touch `execute`; name/description/schema pass\n// through untouched so this stays compatible across Hermes tool-shape versions.\nexport interface HermesTool {\n name?: string;\n description?: string;\n /** JSON-schema-ish parameter descriptor (Hermes uses `parameters` / `input_schema`). */\n parameters?: unknown;\n input_schema?: unknown;\n execute?: (args: any, options?: any) => Promise<any> | any;\n [k: string]: unknown;\n}\n\n// ─── Configuration ──────────────────────────────────────────────────────────\n\nexport interface VorimHermesConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id (e.g. agid_acme_a1b2c3d4). */\n agentId: string;\n /** Per-tool permission scope override, keyed by tool name. */\n permissionMap?: Record<string, PermissionScope>;\n /** Default scope for tools without an entry in permissionMap. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Emit audit events fire-and-forget. @default true */\n asyncAudit?: boolean;\n /**\n * Use the full runtime-control decision API (`beforeAction`) instead of the\n * lightweight permission check. When true, every tool call is evaluated\n * against live policy rules (allow/deny/escalate) and the `decisionId` is\n * linked onto each audit event. Requires the runtime_control plan feature.\n * @default false\n */\n useRuntimeControl?: boolean;\n /** What to do on an `escalate` verdict (runtime control only). @default 'wait' */\n onEscalation?: EscalationPolicy;\n /** Timeout (ms) for `onEscalation: 'wait'`. @default 300000 */\n escalationTimeoutMs?: number;\n /** Policy when the runtime gate can't reach the control plane. @default 'deny' */\n onTransportFailure?: TransportFailurePolicy;\n /** Replayable agent-decision evidence (VAIP -02) attached to each audit event. */\n replay?: ReplayInputs;\n}\n\nconst FRAMEWORK = 'hermes';\n\n// ─── Helpers ──────────────────────────────────────────────────────────────\n\nfunction truncate(s: string, max: number): string {\n return s.length > max ? s.slice(0, max) + '…' : s;\n}\n\nfunction safeJson(v: unknown): string {\n try {\n return JSON.stringify(v);\n } catch {\n return String(v);\n }\n}\n\nasync function gate(\n cfg: VorimHermesConfig,\n scope: PermissionScope,\n actionTarget: string,\n payload?: Record<string, unknown>,\n): Promise<{ allowed: boolean; reason?: string; decisionId?: string }> {\n if (cfg.useRuntimeControl) {\n // runtimeGate resolves transport-failure fallbacks internally, but a\n // non-transport VorimError (e.g. 403 missing runtime:decide scope) still\n // throws — wrap so it fails closed instead of crashing Hermes' tool loop.\n try {\n return await runtimeGate(cfg.vorim, cfg.agentId, actionTarget, scope, payload, {\n onEscalation: cfg.onEscalation,\n escalationTimeoutMs: cfg.escalationTimeoutMs,\n onTransportFailure: cfg.onTransportFailure,\n });\n } catch {\n return { allowed: false, reason: 'runtime gate unavailable (failed closed)' };\n }\n }\n try {\n const { allowed, reason } = await cfg.vorim.check(cfg.agentId, scope);\n return { allowed, reason };\n } catch {\n return { allowed: false, reason: 'permission check unavailable (failed closed)' };\n }\n}\n\nfunction emitAudit(vorim: VorimSDK, event: AuditEventInput, asyncAudit: boolean): Promise<void> | void {\n if (asyncAudit) {\n vorim.emit(event).catch(() => {});\n return;\n }\n return vorim.emit(event).then(() => undefined).catch(() => undefined);\n}\n\nfunction makeReplayGetter(replay: ReplayInputs | undefined): () => Promise<ReplayContext> {\n if (!replay) return async () => ({});\n let cached: Promise<ReplayContext> | null = null;\n return () => {\n if (!cached) cached = prepareReplayContext(replay);\n return cached;\n };\n}\n\n// ─── Wrappers ────────────────────────────────────────────────────────────────\n\n/**\n * Wrap a single Hermes function tool so every execution is gated by a Vorim\n * permission/runtime check and recorded in the signed audit trail. A denied\n * call throws (so Hermes records a tool error) and is audited as `denied`.\n * Tools with no `execute` pass through unchanged.\n *\n * @param name Tool name (used for the audit `action` and permissionMap lookup).\n * Falls back to `tool.name` when omitted.\n */\nexport function wrapHermesTool(name: string, tool: HermesTool, config: VorimHermesConfig): HermesTool {\n const { vorim, defaultPermission = 'agent:execute', permissionMap = {}, asyncAudit = true } = config;\n if (typeof tool.execute !== 'function') return tool; // nothing to guard\n\n const toolName = name || tool.name || 'hermes_tool';\n const originalExecute = tool.execute.bind(tool);\n const getReplay = makeReplayGetter(config.replay);\n const scope = permissionMap[toolName] ?? defaultPermission;\n\n const guarded: HermesTool = {\n ...tool,\n execute: async (args: any, options?: any): Promise<any> => {\n const { allowed, reason, decisionId } = await gate(config, scope, toolName, args as Record<string, unknown>);\n const replayCtx = await getReplay();\n const resource = truncate(safeJson(args), 500);\n\n if (!allowed) {\n await emitAudit(vorim, {\n agent_id: config.agentId,\n event_type: 'tool_call',\n action: toolName,\n resource,\n permission: scope,\n result: 'denied',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { reason, framework: FRAMEWORK },\n ...replayCtx,\n }, asyncAudit);\n throw new Error(`Vorim: permission denied for \"${toolName}\" — scope \"${scope}\"${reason ? `: ${reason}` : ''}`);\n }\n\n const start = Date.now();\n try {\n const result = await originalExecute(args, options);\n await emitAudit(vorim, {\n agent_id: config.agentId,\n event_type: 'tool_call',\n action: toolName,\n resource,\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { framework: FRAMEWORK },\n ...replayCtx,\n }, asyncAudit);\n return result;\n } catch (err) {\n await emitAudit(vorim, {\n agent_id: config.agentId,\n event_type: 'tool_call',\n action: toolName,\n resource,\n permission: scope,\n result: 'error',\n latency_ms: Date.now() - start,\n error_code: err instanceof Error ? err.name : 'UNKNOWN',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { error: err instanceof Error ? err.message : String(err), framework: FRAMEWORK },\n ...replayCtx,\n }, asyncAudit);\n throw err;\n }\n },\n };\n\n return guarded;\n}\n\n/**\n * Wrap a collection of Hermes tools. Accepts either an array of tools (each\n * carrying its own `name`) or a name→tool record. Returns the same shape with\n * every executable tool guarded, and auto-derives the replay tool catalogue\n * when `replay.tools` was not supplied.\n */\nexport function wrapHermesTools<T extends HermesTool[] | Record<string, HermesTool>>(\n tools: T,\n config: VorimHermesConfig,\n): T {\n const asRecord: Record<string, HermesTool> = Array.isArray(tools)\n ? Object.fromEntries(tools.map((t, i) => [t.name || `tool_${i}`, t]))\n : tools;\n\n const cfg: VorimHermesConfig =\n config.replay && !config.replay.tools\n ? { ...config, replay: { ...config.replay, tools: deriveCatalogue(asRecord) } }\n : config;\n\n if (Array.isArray(tools)) {\n return tools.map((t) => wrapHermesTool(t.name || 'hermes_tool', t, cfg)) as T;\n }\n const out: Record<string, HermesTool> = {};\n for (const [name, tool] of Object.entries(tools)) {\n out[name] = wrapHermesTool(name, tool, cfg);\n }\n return out as T;\n}\n\nfunction deriveCatalogue(tools: Record<string, HermesTool>): CatalogueTool[] {\n return Object.entries(tools).map(([name, t]) => ({\n name,\n description: typeof t.description === 'string' ? t.description : '',\n schema: (t.input_schema ?? t.parameters ?? {}) as Record<string, unknown>,\n }));\n}\n","// ============================================================================\n// VORIM SDK — Shared runtime-gate helper for framework integrations\n//\n// All tool-wrapping integrations (Vercel, OpenAI, Anthropic, …) turn a\n// `beforeAction` runtime decision into a simple { allowed, reason, decisionId }\n// the wrapper can act on. The subtlety is the `escalate` verdict: it is NOT a\n// denial — it means a human must approve the action. Folding it into\n// `allowed=false` silently breaks every human-in-the-loop flow; folding it into\n// `allowed=true` is a fail-open security hole. So this helper resolves the\n// escalation explicitly, driven by the caller's `onEscalation` preference.\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { RuntimeDecision, PermissionScope } from '../types.js';\n\n/**\n * How a framework integration should treat a runtime `escalate` verdict.\n * - `wait` — block and poll {@link VorimSDK.waitForDecisionResolution} until a\n * human approves/denies (or the timeout elapses → deny). The correct\n * default for human-in-the-loop: an escalation means \"ask a human\".\n * - `deny` — treat escalate as a denial (fail closed without waiting).\n * - `allow` — treat escalate as allowed (fail OPEN — only for trusted/dev use).\n */\nexport type EscalationPolicy = 'wait' | 'deny' | 'allow';\n\n/**\n * How a framework integration should treat a transport-failure `fallback`\n * decision (the control plane was unreachable and the SDK's\n * `runtimeFailOpen` produced a synthetic `decision: 'fallback'`,\n * `isFallback: true`).\n * - `deny` — fail closed: a control-plane outage denies the tool call.\n * The correct default for a SECURITY gate the caller opted into\n * via `useRuntimeControl: true`.\n * - `allow` — fail open: let the action proceed when the policy plane is\n * down (matches the raw SDK `runtimeFailOpen` behaviour).\n */\nexport type TransportFailurePolicy = 'deny' | 'allow';\n\nexport interface RuntimeGateOptions {\n /** What to do on an `escalate` verdict. @default 'wait' */\n onEscalation?: EscalationPolicy;\n /** Timeout (ms) for `onEscalation: 'wait'`. @default 300000 (5 min) */\n escalationTimeoutMs?: number;\n /**\n * What to do when the control plane is unreachable and `beforeAction`\n * returns a synthetic `fallback` decision. @default 'deny'\n *\n * The gate fails CLOSED on a policy-plane outage by default: a user who\n * turned on `useRuntimeControl: true` wants live deny/escalate\n * enforcement, so an outage should not silently auto-allow. Set to\n * `'allow'` to keep the old fail-open behaviour.\n */\n onTransportFailure?: TransportFailurePolicy;\n}\n\nexport interface GateResult {\n allowed: boolean;\n reason?: string;\n decisionId?: string;\n}\n\n/**\n * True for verdicts that permit the action to proceed. `escalate` is handled\n * separately. `fallback` is NOT treated as an allow here — a transport-failure\n * fallback is resolved explicitly via `onTransportFailure` so a control-plane\n * outage can't silently auto-allow inside a security gate.\n */\nfunction isAllowVerdict(decision: RuntimeDecision['decision']): boolean {\n return decision === 'allow' || decision === 'modify';\n}\n\n/**\n * Run a `beforeAction` runtime decision and collapse it to a {@link GateResult},\n * resolving `escalate` per {@link RuntimeGateOptions.onEscalation}.\n *\n * Requires (for `onEscalation: 'wait'`) an API key with the `runtime:decide`\n * scope — the same scope `beforeAction` itself uses.\n */\nexport async function runtimeGate(\n vorim: VorimSDK,\n agentId: string,\n actionTarget: string,\n scope: PermissionScope,\n payload: Record<string, unknown> | undefined,\n opts: RuntimeGateOptions = {},\n): Promise<GateResult> {\n const onEscalation = opts.onEscalation ?? 'wait';\n const onTransportFailure = opts.onTransportFailure ?? 'deny';\n const d = await vorim.beforeAction(\n { agentId, actionType: 'tool_call', actionTarget, requiredScope: scope, payload },\n { throwOnDeny: false },\n );\n\n // Control-plane outage: beforeAction returned a synthetic fallback\n // (isFallback). Govern it by onTransportFailure (default 'deny') rather\n // than auto-allowing — the caller turned on runtime control for live\n // enforcement, so an outage should fail closed unless they opt out.\n if (d.isFallback || d.decision === 'fallback') {\n if (onTransportFailure === 'allow') {\n return { allowed: true, reason: d.reason ?? 'control plane unreachable (fail-open)', decisionId: d.decisionId || undefined };\n }\n return { allowed: false, reason: d.reason ?? 'control plane unreachable (failed closed)', decisionId: d.decisionId || undefined };\n }\n\n if (d.decision !== 'escalate') {\n return { allowed: isAllowVerdict(d.decision), reason: d.reason, decisionId: d.decisionId || undefined };\n }\n\n // escalate ── a human must decide.\n if (onEscalation === 'allow') {\n return { allowed: true, reason: d.reason ?? 'escalated (auto-allowed)', decisionId: d.decisionId || undefined };\n }\n if (onEscalation === 'deny') {\n return { allowed: false, reason: d.reason ?? 'escalated (auto-denied — awaiting human)', decisionId: d.decisionId || undefined };\n }\n // 'wait' — poll for the human decision. On timeout, fail closed (deny).\n if (!d.decisionId) {\n return { allowed: false, reason: 'escalated but no decisionId to poll', decisionId: undefined };\n }\n try {\n const resolved = await vorim.waitForDecisionResolution(d.decisionId, { timeoutMs: opts.escalationTimeoutMs });\n return { allowed: isAllowVerdict(resolved.decision), reason: resolved.reason, decisionId: resolved.decisionId || d.decisionId };\n } catch {\n // ESCALATION_TIMEOUT (or any poll error) → fail closed.\n return { allowed: false, reason: 'escalation not resolved before timeout', decisionId: d.decisionId };\n }\n}\n","/**\n * Replayable agent decision evidence helpers.\n *\n * Canonical-form hashing for the VAIP -02 schema fields that the SDK\n * attaches to audit events. The hashes recorded in audit_events.tool_catalogue_hash\n * and audit_events.system_prompt_hash use these functions, so the bytes\n * an auditor or counterparty reconstructs must match what the SDK produced.\n *\n * These helpers are intentionally separate from the signing path. The\n * v0 canonical signature form (event_type|action|resource|input_hash|\n * output_hash|result) does NOT cover model_version, tool_catalogue_hash,\n * or system_prompt_hash. They will enter the canonical bytes in v1\n * (RFC 8785 JCS) in a follow-up release.\n *\n * Stable across SDK versions: the canonical-form version is documented\n * in CANONICAL_TOOL_CATALOGUE_VERSION. Future changes get a v2 etc;\n * never edit the existing v1 logic, or already-recorded hashes lose\n * their meaning.\n */\n\n// ─── Versioning ───────────────────────────────────────────────────────────\n\n/**\n * Canonical-form version for tool catalogue hashes produced by this SDK.\n * Recorded in tool_catalogue_canon_version on the event metadata (when\n * the metadata field is used) so verifiers know which hash recipe to\n * reproduce. Increment ONLY if the algorithm changes in a way that\n * would change the hash for the same logical catalogue.\n */\nexport const CANONICAL_TOOL_CATALOGUE_VERSION = 'v1' as const;\n\n// ─── Types ────────────────────────────────────────────────────────────────\n\n/**\n * Minimum shape a tool needs for catalogue hashing. The framework\n * integrations adapt their native tool objects to this shape before\n * calling hashToolCatalogue.\n */\nexport interface CatalogueTool {\n /** The name the model sees and calls. Required. */\n name: string;\n /** Human-readable description shown to the model. Optional; absent ↔ empty string. */\n description?: string;\n /**\n * JSON Schema describing the tool's input parameters. Optional;\n * absent ↔ empty object `{}`. The schema gets RFC 8785 JCS-canonicalised\n * before hashing so semantically-equivalent variations (key order,\n * whitespace) produce the same hash.\n */\n schema?: Record<string, unknown> | null;\n}\n\n// ─── RFC 8785 JCS subset ──────────────────────────────────────────────────\n\n/**\n * RFC 8785 JSON Canonicalization Scheme, sufficient subset for tool\n * catalogue values.\n *\n * Rules:\n * - Object keys sorted lexicographically by UTF-16 code units (which\n * is what JS string comparison does naturally).\n * - No whitespace between tokens.\n * - Numbers: integers as integers, finite floats per ECMAScript\n * Number.prototype.toString. JCS forbids NaN and Infinity.\n * - Strings: JSON-escape using minimal set per RFC 8259 § 7.\n * - null, true, false, arrays: as JSON.stringify produces them, since\n * JSON.stringify already produces the canonical form for these.\n *\n * Not vendoring a full library because tool schemas don't carry\n * non-integer numbers in practice and the JS spec for Number.toString\n * happens to coincide with JCS § 3.2.2.2 for the integer case.\n */\nexport function jcsCanonicalise(value: unknown): string {\n if (value === null) return 'null';\n if (value === true) return 'true';\n if (value === false) return 'false';\n\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new Error('jcsCanonicalise: NaN and Infinity are not JCS-valid');\n }\n // Fail closed on magnitudes where JS .toString() and CPython diverge, so TS\n // and Python sign byte-identical bytes (or both reject). JS switches\n // integer-valued floats to exponent form at |x| >= 1e21 (Python expands to\n // full digits); in [1e-7, 1e-4) JS keeps decimals while Python repr() uses\n // exponent form. Keeping both engines in lockstep preserves cross-SDK\n // signature verifiability.\n const abs = Math.abs(value);\n // Reject ranges where JS Number.toString() and CPython diverge: |x| >= 1e21,\n // |x| < 1e-4, and integer-valued |x| > 2^53 (JS shortest-round-trip vs\n // Python exact int expansion — they only coincide for \"round\" values there).\n if (value !== 0 && (abs >= 1e21 || abs < 1e-4 || (Number.isInteger(value) && abs > 2 ** 53))) {\n throw new Error(\n `jcsCanonicalise: numbers in the ranges where JS and Python formatting ` +\n `diverge (|x| >= 1e21, |x| < 1e-4, or integer |x| > 2^53) are not ` +\n `supported in signed metadata. Use a string instead of ${value}.`,\n );\n }\n // For integers in safe range and ordinary decimals, .toString() matches JCS\n // (modern JS engines use the shortest round-trip representation).\n return value.toString();\n }\n\n if (typeof value === 'string') {\n return JSON.stringify(value);\n }\n\n if (Array.isArray(value)) {\n return '[' + value.map(jcsCanonicalise).join(',') + ']';\n }\n\n if (typeof value === 'object') {\n const obj = value as Record<string, unknown>;\n // Filter undefined-valued fields, matching @vorim/verify and\n // @vorim/shared-types. Without this the SDK throws on { a: 1, b: undefined }\n // while the verifier silently drops b — a cross-module canonical-form\n // divergence that would break signature verification on such events.\n const keys = Object.keys(obj).filter(k => obj[k] !== undefined).sort();\n const parts = keys.map(k => JSON.stringify(k) + ':' + jcsCanonicalise(obj[k]));\n return '{' + parts.join(',') + '}';\n }\n\n // undefined, function, symbol, bigint — not JSON-representable\n throw new Error(`jcsCanonicalise: unsupported value type: ${typeof value}`);\n}\n\n// ─── SHA-256 ──────────────────────────────────────────────────────────────\n\nasync function sha256Hex(input: string | Uint8Array): Promise<string> {\n const bytes = typeof input === 'string' ? new TextEncoder().encode(input) : input;\n\n // Node.js Web Crypto (Node 18+) supports digest. Browser Web Crypto does too.\n // Fall back to node:crypto if Web Crypto is unavailable.\n const subtle = (globalThis as any).crypto?.subtle;\n if (subtle) {\n const buf = await subtle.digest('SHA-256', bytes);\n return Array.from(new Uint8Array(buf))\n .map(b => b.toString(16).padStart(2, '0'))\n .join('');\n }\n\n // Node fallback\n const nodeCrypto = await import('node:crypto');\n return nodeCrypto.createHash('sha256').update(bytes).digest('hex');\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────\n\n/**\n * Hash a single tool definition. Returns `sha256:<hex>`.\n *\n * Canonical form (v1):\n * JCS-canonicalised JSON of `{name, description, schema}` where\n * absent fields substitute `description: \"\"` and `schema: {}`.\n */\nexport async function hashTool(tool: CatalogueTool): Promise<string> {\n const normalised = {\n name: tool.name,\n description: tool.description ?? '',\n schema: tool.schema ?? {},\n };\n const hex = await sha256Hex(jcsCanonicalise(normalised));\n return `sha256:${hex}`;\n}\n\n/**\n * Hash an entire tool catalogue. Returns `sha256:<hex>`.\n *\n * Reordering tools does NOT change the hash (tool hashes sorted\n * lexicographically before concatenation). Adding, removing, or\n * modifying a tool DOES change the hash.\n *\n * Per-tool hashing first means a verifier comparing two catalogue\n * hashes that differ can also be given the per-tool hashes to\n * identify which specific tool changed.\n */\nexport async function hashToolCatalogue(tools: CatalogueTool[]): Promise<string> {\n if (tools.length === 0) {\n // Empty catalogue has a deterministic, stable hash distinct from \"no field\"\n return `sha256:${await sha256Hex('[]')}`;\n }\n const perTool = await Promise.all(tools.map(hashTool));\n perTool.sort();\n const hex = await sha256Hex(perTool.join(''));\n return `sha256:${hex}`;\n}\n\n/**\n * Hash a system prompt. Returns `sha256:<hex>`.\n *\n * The prompt is UTF-8 encoded and hashed verbatim — no normalisation.\n * If a caller wants to ignore whitespace or comment differences, they\n * should normalise before calling. The intent here is deterministic\n * reproducibility, not semantic equivalence.\n */\nexport async function hashSystemPrompt(prompt: string): Promise<string> {\n const hex = await sha256Hex(prompt);\n return `sha256:${hex}`;\n}\n\n/**\n * Convenience: hash the previous event's canonical bytes for use in\n * the prev_event_hash field of hash-chained ingest. Caller provides\n * the canonical bytes (use canonicalPayloadV0 from the main module).\n */\nexport async function hashPreviousEvent(canonicalBytes: string): Promise<string> {\n const hex = await sha256Hex(canonicalBytes);\n return `sha256:${hex}`;\n}\n\n// ─── Replay context — framework integration helper ────────────────────────\n\n/**\n * Raw inputs the integration captures from the framework. Set by the\n * integration's config; turned into hashes by {@link prepareReplayContext}.\n */\nexport interface ReplayInputs {\n /** Stable identifier for the model. E.g. `\"anthropic:claude-opus-4-8\"`. */\n modelVersion?: string;\n /** Tools available to the agent at call time. Hashed via {@link hashToolCatalogue}. */\n tools?: CatalogueTool[];\n /** System prompt active at call time. Hashed via {@link hashSystemPrompt}. */\n systemPrompt?: string;\n}\n\n/**\n * Pre-computed hashes ready to attach to audit events. The three keys\n * match the audit_events column names.\n */\nexport interface ReplayContext {\n model_version?: string;\n tool_catalogue_hash?: string;\n system_prompt_hash?: string;\n}\n\n/**\n * Compute replay context once from raw inputs. Use at integration\n * setup time so each emit can attach the hashes without re-hashing.\n *\n * Returns an object suitable for spreading into an AuditEventInput:\n * `await vorim.emit({ ...event, ...replayContext })`\n *\n * If a field is absent in the inputs, it is absent in the result\n * (not the empty string). That keeps the event lean.\n */\nexport async function prepareReplayContext(\n inputs: ReplayInputs,\n): Promise<ReplayContext> {\n const ctx: ReplayContext = {};\n if (inputs.modelVersion) ctx.model_version = inputs.modelVersion;\n if (inputs.tools) ctx.tool_catalogue_hash = await hashToolCatalogue(inputs.tools);\n if (inputs.systemPrompt) ctx.system_prompt_hash = await hashSystemPrompt(inputs.systemPrompt);\n return ctx;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACmEA,SAAS,eAAe,UAAgD;AACtE,SAAO,aAAa,WAAW,aAAa;AAC9C;AASA,eAAsB,YACpB,OACA,SACA,cACA,OACA,SACA,OAA2B,CAAC,GACP;AACrB,QAAM,eAAe,KAAK,gBAAgB;AAC1C,QAAM,qBAAqB,KAAK,sBAAsB;AACtD,QAAM,IAAI,MAAM,MAAM;AAAA,IACpB,EAAE,SAAS,YAAY,aAAa,cAAc,eAAe,OAAO,QAAQ;AAAA,IAChF,EAAE,aAAa,MAAM;AAAA,EACvB;AAMA,MAAI,EAAE,cAAc,EAAE,aAAa,YAAY;AAC7C,QAAI,uBAAuB,SAAS;AAClC,aAAO,EAAE,SAAS,MAAM,QAAQ,EAAE,UAAU,yCAAyC,YAAY,EAAE,cAAc,OAAU;AAAA,IAC7H;AACA,WAAO,EAAE,SAAS,OAAO,QAAQ,EA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AQO,SAAS,gBACd,OACA,QACG;AACH,QAAM,WAAuC,MAAM,QAAQ,KAAK,IAC5D,OAAO,YAAY,MAAM,IAAI,CAAC,GAAG,MAAM,CAAC,EAAE,QAAQ,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,IAClE;AAEJ,QAAM,MACJ,OAAO,UAAU,CAAC,OAAO,OAAO,QAC5B,EAAE,GAAG,QAAQ,QAAQ,EAAE,GAAG,OAAO,QAAQ,OAAO,gBAAgB,QAAQ,EAAE,EAAE,IAC5E;AAEN,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,MAAM,IAAI,CAAC,MAAM,eAAe,EAAE,QAAQ,eAAe,GAAG,GAAG,CAAC;AAAA,EACzE;AACA,QAAM,MAAkC,CAAC;AACzC,aAAW,CAAC,MAAM,IAAI,KAAK,OAAO,QAAQ,KAAK,GAAG;AAChD,QAAI,IAAI,IAAI,eAAe,MAAM,MAAM,GAAG;AAAA,EAC5C;AACA,SAAO;AACT;AAEA,SAAS,gBAAgB,OAAoD;AAC3E,SAAO,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,MAAM,CAAC,OAAO;AAAA,IAC/C;AAAA,IACA,aAAa,OAAO,EAAE,gBAAgB,WAAW,EAAE,cAAc;AAAA,IACjE,QAAS,EAAE,gBAAgB,EAAE,cAAc,CAAC;AAAA,EAC9C,EAAE;AACJ;","names":[]}
@@ -0,0 +1,60 @@
1
+ import { VorimSDK, ReplayInputs } from '../index.cjs';
2
+ import { P as PermissionScope } from '../types-Cb6V-boJ.cjs';
3
+ import { E as EscalationPolicy, T as TransportFailurePolicy } from '../_runtime-gate-DOJUKJBu.cjs';
4
+
5
+ interface HermesTool {
6
+ name?: string;
7
+ description?: string;
8
+ /** JSON-schema-ish parameter descriptor (Hermes uses `parameters` / `input_schema`). */
9
+ parameters?: unknown;
10
+ input_schema?: unknown;
11
+ execute?: (args: any, options?: any) => Promise<any> | any;
12
+ [k: string]: unknown;
13
+ }
14
+ interface VorimHermesConfig {
15
+ /** Vorim SDK instance. */
16
+ vorim: VorimSDK;
17
+ /** The Vorim agent_id (e.g. agid_acme_a1b2c3d4). */
18
+ agentId: string;
19
+ /** Per-tool permission scope override, keyed by tool name. */
20
+ permissionMap?: Record<string, PermissionScope>;
21
+ /** Default scope for tools without an entry in permissionMap. @default 'agent:execute' */
22
+ defaultPermission?: PermissionScope;
23
+ /** Emit audit events fire-and-forget. @default true */
24
+ asyncAudit?: boolean;
25
+ /**
26
+ * Use the full runtime-control decision API (`beforeAction`) instead of the
27
+ * lightweight permission check. When true, every tool call is evaluated
28
+ * against live policy rules (allow/deny/escalate) and the `decisionId` is
29
+ * linked onto each audit event. Requires the runtime_control plan feature.
30
+ * @default false
31
+ */
32
+ useRuntimeControl?: boolean;
33
+ /** What to do on an `escalate` verdict (runtime control only). @default 'wait' */
34
+ onEscalation?: EscalationPolicy;
35
+ /** Timeout (ms) for `onEscalation: 'wait'`. @default 300000 */
36
+ escalationTimeoutMs?: number;
37
+ /** Policy when the runtime gate can't reach the control plane. @default 'deny' */
38
+ onTransportFailure?: TransportFailurePolicy;
39
+ /** Replayable agent-decision evidence (VAIP -02) attached to each audit event. */
40
+ replay?: ReplayInputs;
41
+ }
42
+ /**
43
+ * Wrap a single Hermes function tool so every execution is gated by a Vorim
44
+ * permission/runtime check and recorded in the signed audit trail. A denied
45
+ * call throws (so Hermes records a tool error) and is audited as `denied`.
46
+ * Tools with no `execute` pass through unchanged.
47
+ *
48
+ * @param name Tool name (used for the audit `action` and permissionMap lookup).
49
+ * Falls back to `tool.name` when omitted.
50
+ */
51
+ declare function wrapHermesTool(name: string, tool: HermesTool, config: VorimHermesConfig): HermesTool;
52
+ /**
53
+ * Wrap a collection of Hermes tools. Accepts either an array of tools (each
54
+ * carrying its own `name`) or a name→tool record. Returns the same shape with
55
+ * every executable tool guarded, and auto-derives the replay tool catalogue
56
+ * when `replay.tools` was not supplied.
57
+ */
58
+ declare function wrapHermesTools<T extends HermesTool[] | Record<string, HermesTool>>(tools: T, config: VorimHermesConfig): T;
59
+
60
+ export { type HermesTool, type VorimHermesConfig, wrapHermesTool, wrapHermesTools };
@@ -0,0 +1,60 @@
1
+ import { VorimSDK, ReplayInputs } from '../index.js';
2
+ import { P as PermissionScope } from '../types-Cb6V-boJ.js';
3
+ import { E as EscalationPolicy, T as TransportFailurePolicy } from '../_runtime-gate-DOJUKJBu.js';
4
+
5
+ interface HermesTool {
6
+ name?: string;
7
+ description?: string;
8
+ /** JSON-schema-ish parameter descriptor (Hermes uses `parameters` / `input_schema`). */
9
+ parameters?: unknown;
10
+ input_schema?: unknown;
11
+ execute?: (args: any, options?: any) => Promise<any> | any;
12
+ [k: string]: unknown;
13
+ }
14
+ interface VorimHermesConfig {
15
+ /** Vorim SDK instance. */
16
+ vorim: VorimSDK;
17
+ /** The Vorim agent_id (e.g. agid_acme_a1b2c3d4). */
18
+ agentId: string;
19
+ /** Per-tool permission scope override, keyed by tool name. */
20
+ permissionMap?: Record<string, PermissionScope>;
21
+ /** Default scope for tools without an entry in permissionMap. @default 'agent:execute' */
22
+ defaultPermission?: PermissionScope;
23
+ /** Emit audit events fire-and-forget. @default true */
24
+ asyncAudit?: boolean;
25
+ /**
26
+ * Use the full runtime-control decision API (`beforeAction`) instead of the
27
+ * lightweight permission check. When true, every tool call is evaluated
28
+ * against live policy rules (allow/deny/escalate) and the `decisionId` is
29
+ * linked onto each audit event. Requires the runtime_control plan feature.
30
+ * @default false
31
+ */
32
+ useRuntimeControl?: boolean;
33
+ /** What to do on an `escalate` verdict (runtime control only). @default 'wait' */
34
+ onEscalation?: EscalationPolicy;
35
+ /** Timeout (ms) for `onEscalation: 'wait'`. @default 300000 */
36
+ escalationTimeoutMs?: number;
37
+ /** Policy when the runtime gate can't reach the control plane. @default 'deny' */
38
+ onTransportFailure?: TransportFailurePolicy;
39
+ /** Replayable agent-decision evidence (VAIP -02) attached to each audit event. */
40
+ replay?: ReplayInputs;
41
+ }
42
+ /**
43
+ * Wrap a single Hermes function tool so every execution is gated by a Vorim
44
+ * permission/runtime check and recorded in the signed audit trail. A denied
45
+ * call throws (so Hermes records a tool error) and is audited as `denied`.
46
+ * Tools with no `execute` pass through unchanged.
47
+ *
48
+ * @param name Tool name (used for the audit `action` and permissionMap lookup).
49
+ * Falls back to `tool.name` when omitted.
50
+ */
51
+ declare function wrapHermesTool(name: string, tool: HermesTool, config: VorimHermesConfig): HermesTool;
52
+ /**
53
+ * Wrap a collection of Hermes tools. Accepts either an array of tools (each
54
+ * carrying its own `name`) or a name→tool record. Returns the same shape with
55
+ * every executable tool guarded, and auto-derives the replay tool catalogue
56
+ * when `replay.tools` was not supplied.
57
+ */
58
+ declare function wrapHermesTools<T extends HermesTool[] | Record<string, HermesTool>>(tools: T, config: VorimHermesConfig): T;
59
+
60
+ export { type HermesTool, type VorimHermesConfig, wrapHermesTool, wrapHermesTools };
@@ -0,0 +1,242 @@
1
+ // src/integrations/_runtime-gate.ts
2
+ function isAllowVerdict(decision) {
3
+ return decision === "allow" || decision === "modify";
4
+ }
5
+ async function runtimeGate(vorim, agentId, actionTarget, scope, payload, opts = {}) {
6
+ const onEscalation = opts.onEscalation ?? "wait";
7
+ const onTransportFailure = opts.onTransportFailure ?? "deny";
8
+ const d = await vorim.beforeAction(
9
+ { agentId, actionType: "tool_call", actionTarget, requiredScope: scope, payload },
10
+ { throwOnDeny: false }
11
+ );
12
+ if (d.isFallback || d.decision === "fallback") {
13
+ if (onTransportFailure === "allow") {
14
+ return { allowed: true, reason: d.reason ?? "control plane unreachable (fail-open)", decisionId: d.decisionId || void 0 };
15
+ }
16
+ return { allowed: false, reason: d.reason ?? "control plane unreachable (failed closed)", decisionId: d.decisionId || void 0 };
17
+ }
18
+ if (d.decision !== "escalate") {
19
+ return { allowed: isAllowVerdict(d.decision), reason: d.reason, decisionId: d.decisionId || void 0 };
20
+ }
21
+ if (onEscalation === "allow") {
22
+ return { allowed: true, reason: d.reason ?? "escalated (auto-allowed)", decisionId: d.decisionId || void 0 };
23
+ }
24
+ if (onEscalation === "deny") {
25
+ return { allowed: false, reason: d.reason ?? "escalated (auto-denied \u2014 awaiting human)", decisionId: d.decisionId || void 0 };
26
+ }
27
+ if (!d.decisionId) {
28
+ return { allowed: false, reason: "escalated but no decisionId to poll", decisionId: void 0 };
29
+ }
30
+ try {
31
+ const resolved = await vorim.waitForDecisionResolution(d.decisionId, { timeoutMs: opts.escalationTimeoutMs });
32
+ return { allowed: isAllowVerdict(resolved.decision), reason: resolved.reason, decisionId: resolved.decisionId || d.decisionId };
33
+ } catch {
34
+ return { allowed: false, reason: "escalation not resolved before timeout", decisionId: d.decisionId };
35
+ }
36
+ }
37
+
38
+ // src/replay.ts
39
+ function jcsCanonicalise(value) {
40
+ if (value === null) return "null";
41
+ if (value === true) return "true";
42
+ if (value === false) return "false";
43
+ if (typeof value === "number") {
44
+ if (!Number.isFinite(value)) {
45
+ throw new Error("jcsCanonicalise: NaN and Infinity are not JCS-valid");
46
+ }
47
+ const abs = Math.abs(value);
48
+ if (value !== 0 && (abs >= 1e21 || abs < 1e-4 || Number.isInteger(value) && abs > 2 ** 53)) {
49
+ throw new Error(
50
+ `jcsCanonicalise: numbers in the ranges where JS and Python formatting diverge (|x| >= 1e21, |x| < 1e-4, or integer |x| > 2^53) are not supported in signed metadata. Use a string instead of ${value}.`
51
+ );
52
+ }
53
+ return value.toString();
54
+ }
55
+ if (typeof value === "string") {
56
+ return JSON.stringify(value);
57
+ }
58
+ if (Array.isArray(value)) {
59
+ return "[" + value.map(jcsCanonicalise).join(",") + "]";
60
+ }
61
+ if (typeof value === "object") {
62
+ const obj = value;
63
+ const keys = Object.keys(obj).filter((k) => obj[k] !== void 0).sort();
64
+ const parts = keys.map((k) => JSON.stringify(k) + ":" + jcsCanonicalise(obj[k]));
65
+ return "{" + parts.join(",") + "}";
66
+ }
67
+ throw new Error(`jcsCanonicalise: unsupported value type: ${typeof value}`);
68
+ }
69
+ async function sha256Hex(input) {
70
+ const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
71
+ const subtle = globalThis.crypto?.subtle;
72
+ if (subtle) {
73
+ const buf = await subtle.digest("SHA-256", bytes);
74
+ return Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, "0")).join("");
75
+ }
76
+ const nodeCrypto = await import("crypto");
77
+ return nodeCrypto.createHash("sha256").update(bytes).digest("hex");
78
+ }
79
+ async function hashTool(tool) {
80
+ const normalised = {
81
+ name: tool.name,
82
+ description: tool.description ?? "",
83
+ schema: tool.schema ?? {}
84
+ };
85
+ const hex = await sha256Hex(jcsCanonicalise(normalised));
86
+ return `sha256:${hex}`;
87
+ }
88
+ async function hashToolCatalogue(tools) {
89
+ if (tools.length === 0) {
90
+ return `sha256:${await sha256Hex("[]")}`;
91
+ }
92
+ const perTool = await Promise.all(tools.map(hashTool));
93
+ perTool.sort();
94
+ const hex = await sha256Hex(perTool.join(""));
95
+ return `sha256:${hex}`;
96
+ }
97
+ async function hashSystemPrompt(prompt) {
98
+ const hex = await sha256Hex(prompt);
99
+ return `sha256:${hex}`;
100
+ }
101
+ async function prepareReplayContext(inputs) {
102
+ const ctx = {};
103
+ if (inputs.modelVersion) ctx.model_version = inputs.modelVersion;
104
+ if (inputs.tools) ctx.tool_catalogue_hash = await hashToolCatalogue(inputs.tools);
105
+ if (inputs.systemPrompt) ctx.system_prompt_hash = await hashSystemPrompt(inputs.systemPrompt);
106
+ return ctx;
107
+ }
108
+
109
+ // src/integrations/hermes.ts
110
+ var FRAMEWORK = "hermes";
111
+ function truncate(s, max) {
112
+ return s.length > max ? s.slice(0, max) + "\u2026" : s;
113
+ }
114
+ function safeJson(v) {
115
+ try {
116
+ return JSON.stringify(v);
117
+ } catch {
118
+ return String(v);
119
+ }
120
+ }
121
+ async function gate(cfg, scope, actionTarget, payload) {
122
+ if (cfg.useRuntimeControl) {
123
+ try {
124
+ return await runtimeGate(cfg.vorim, cfg.agentId, actionTarget, scope, payload, {
125
+ onEscalation: cfg.onEscalation,
126
+ escalationTimeoutMs: cfg.escalationTimeoutMs,
127
+ onTransportFailure: cfg.onTransportFailure
128
+ });
129
+ } catch {
130
+ return { allowed: false, reason: "runtime gate unavailable (failed closed)" };
131
+ }
132
+ }
133
+ try {
134
+ const { allowed, reason } = await cfg.vorim.check(cfg.agentId, scope);
135
+ return { allowed, reason };
136
+ } catch {
137
+ return { allowed: false, reason: "permission check unavailable (failed closed)" };
138
+ }
139
+ }
140
+ function emitAudit(vorim, event, asyncAudit) {
141
+ if (asyncAudit) {
142
+ vorim.emit(event).catch(() => {
143
+ });
144
+ return;
145
+ }
146
+ return vorim.emit(event).then(() => void 0).catch(() => void 0);
147
+ }
148
+ function makeReplayGetter(replay) {
149
+ if (!replay) return async () => ({});
150
+ let cached = null;
151
+ return () => {
152
+ if (!cached) cached = prepareReplayContext(replay);
153
+ return cached;
154
+ };
155
+ }
156
+ function wrapHermesTool(name, tool, config) {
157
+ const { vorim, defaultPermission = "agent:execute", permissionMap = {}, asyncAudit = true } = config;
158
+ if (typeof tool.execute !== "function") return tool;
159
+ const toolName = name || tool.name || "hermes_tool";
160
+ const originalExecute = tool.execute.bind(tool);
161
+ const getReplay = makeReplayGetter(config.replay);
162
+ const scope = permissionMap[toolName] ?? defaultPermission;
163
+ const guarded = {
164
+ ...tool,
165
+ execute: async (args, options) => {
166
+ const { allowed, reason, decisionId } = await gate(config, scope, toolName, args);
167
+ const replayCtx = await getReplay();
168
+ const resource = truncate(safeJson(args), 500);
169
+ if (!allowed) {
170
+ await emitAudit(vorim, {
171
+ agent_id: config.agentId,
172
+ event_type: "tool_call",
173
+ action: toolName,
174
+ resource,
175
+ permission: scope,
176
+ result: "denied",
177
+ ...decisionId ? { decision_id: decisionId } : {},
178
+ metadata: { reason, framework: FRAMEWORK },
179
+ ...replayCtx
180
+ }, asyncAudit);
181
+ throw new Error(`Vorim: permission denied for "${toolName}" \u2014 scope "${scope}"${reason ? `: ${reason}` : ""}`);
182
+ }
183
+ const start = Date.now();
184
+ try {
185
+ const result = await originalExecute(args, options);
186
+ await emitAudit(vorim, {
187
+ agent_id: config.agentId,
188
+ event_type: "tool_call",
189
+ action: toolName,
190
+ resource,
191
+ permission: scope,
192
+ result: "success",
193
+ latency_ms: Date.now() - start,
194
+ ...decisionId ? { decision_id: decisionId } : {},
195
+ metadata: { framework: FRAMEWORK },
196
+ ...replayCtx
197
+ }, asyncAudit);
198
+ return result;
199
+ } catch (err) {
200
+ await emitAudit(vorim, {
201
+ agent_id: config.agentId,
202
+ event_type: "tool_call",
203
+ action: toolName,
204
+ resource,
205
+ permission: scope,
206
+ result: "error",
207
+ latency_ms: Date.now() - start,
208
+ error_code: err instanceof Error ? err.name : "UNKNOWN",
209
+ ...decisionId ? { decision_id: decisionId } : {},
210
+ metadata: { error: err instanceof Error ? err.message : String(err), framework: FRAMEWORK },
211
+ ...replayCtx
212
+ }, asyncAudit);
213
+ throw err;
214
+ }
215
+ }
216
+ };
217
+ return guarded;
218
+ }
219
+ function wrapHermesTools(tools, config) {
220
+ const asRecord = Array.isArray(tools) ? Object.fromEntries(tools.map((t, i) => [t.name || `tool_${i}`, t])) : tools;
221
+ const cfg = config.replay && !config.replay.tools ? { ...config, replay: { ...config.replay, tools: deriveCatalogue(asRecord) } } : config;
222
+ if (Array.isArray(tools)) {
223
+ return tools.map((t) => wrapHermesTool(t.name || "hermes_tool", t, cfg));
224
+ }
225
+ const out = {};
226
+ for (const [name, tool] of Object.entries(tools)) {
227
+ out[name] = wrapHermesTool(name, tool, cfg);
228
+ }
229
+ return out;
230
+ }
231
+ function deriveCatalogue(tools) {
232
+ return Object.entries(tools).map(([name, t]) => ({
233
+ name,
234
+ description: typeof t.description === "string" ? t.description : "",
235
+ schema: t.input_schema ?? t.parameters ?? {}
236
+ }));
237
+ }
238
+ export {
239
+ wrapHermesTool,
240
+ wrapHermesTools
241
+ };
242
+ //# sourceMappingURL=hermes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/integrations/_runtime-gate.ts","../../src/replay.ts","../../src/integrations/hermes.ts"],"sourcesContent":["// ============================================================================\n// VORIM SDK — Shared runtime-gate helper for framework integrations\n//\n// All tool-wrapping integrations (Vercel, OpenAI, Anthropic, …) turn a\n// `beforeAction` runtime decision into a simple { allowed, reason, decisionId }\n// the wrapper can act on. The subtlety is the `escalate` verdict: it is NOT a\n// denial — it means a human must approve the action. Folding it into\n// `allowed=false` silently breaks every human-in-the-loop flow; folding it into\n// `allowed=true` is a fail-open security hole. So this helper resolves the\n// escalation explicitly, driven by the caller's `onEscalation` preference.\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { RuntimeDecision, PermissionScope } from '../types.js';\n\n/**\n * How a framework integration should treat a runtime `escalate` verdict.\n * - `wait` — block and poll {@link VorimSDK.waitForDecisionResolution} until a\n * human approves/denies (or the timeout elapses → deny). The correct\n * default for human-in-the-loop: an escalation means \"ask a human\".\n * - `deny` — treat escalate as a denial (fail closed without waiting).\n * - `allow` — treat escalate as allowed (fail OPEN — only for trusted/dev use).\n */\nexport type EscalationPolicy = 'wait' | 'deny' | 'allow';\n\n/**\n * How a framework integration should treat a transport-failure `fallback`\n * decision (the control plane was unreachable and the SDK's\n * `runtimeFailOpen` produced a synthetic `decision: 'fallback'`,\n * `isFallback: true`).\n * - `deny` — fail closed: a control-plane outage denies the tool call.\n * The correct default for a SECURITY gate the caller opted into\n * via `useRuntimeControl: true`.\n * - `allow` — fail open: let the action proceed when the policy plane is\n * down (matches the raw SDK `runtimeFailOpen` behaviour).\n */\nexport type TransportFailurePolicy = 'deny' | 'allow';\n\nexport interface RuntimeGateOptions {\n /** What to do on an `escalate` verdict. @default 'wait' */\n onEscalation?: EscalationPolicy;\n /** Timeout (ms) for `onEscalation: 'wait'`. @default 300000 (5 min) */\n escalationTimeoutMs?: number;\n /**\n * What to do when the control plane is unreachable and `beforeAction`\n * returns a synthetic `fallback` decision. @default 'deny'\n *\n * The gate fails CLOSED on a policy-plane outage by default: a user who\n * turned on `useRuntimeControl: true` wants live deny/escalate\n * enforcement, so an outage should not silently auto-allow. Set to\n * `'allow'` to keep the old fail-open behaviour.\n */\n onTransportFailure?: TransportFailurePolicy;\n}\n\nexport interface GateResult {\n allowed: boolean;\n reason?: string;\n decisionId?: string;\n}\n\n/**\n * True for verdicts that permit the action to proceed. `escalate` is handled\n * separately. `fallback` is NOT treated as an allow here — a transport-failure\n * fallback is resolved explicitly via `onTransportFailure` so a control-plane\n * outage can't silently auto-allow inside a security gate.\n */\nfunction isAllowVerdict(decision: RuntimeDecision['decision']): boolean {\n return decision === 'allow' || decision === 'modify';\n}\n\n/**\n * Run a `beforeAction` runtime decision and collapse it to a {@link GateResult},\n * resolving `escalate` per {@link RuntimeGateOptions.onEscalation}.\n *\n * Requires (for `onEscalation: 'wait'`) an API key with the `runtime:decide`\n * scope — the same scope `beforeAction` itself uses.\n */\nexport async function runtimeGate(\n vorim: VorimSDK,\n agentId: string,\n actionTarget: string,\n scope: PermissionScope,\n payload: Record<string, unknown> | undefined,\n opts: RuntimeGateOptions = {},\n): Promise<GateResult> {\n const onEscalation = opts.onEscalation ?? 'wait';\n const onTransportFailure = opts.onTransportFailure ?? 'deny';\n const d = await vorim.beforeAction(\n { agentId, actionType: 'tool_call', actionTarget, requiredScope: scope, payload },\n { throwOnDeny: false },\n );\n\n // Control-plane outage: beforeAction returned a synthetic fallback\n // (isFallback). Govern it by onTransportFailure (default 'deny') rather\n // than auto-allowing — the caller turned on runtime control for live\n // enforcement, so an outage should fail closed unless they opt out.\n if (d.isFallback || d.decision === 'fallback') {\n if (onTransportFailure === 'allow') {\n return { allowed: true, reason: d.reason ?? 'control plane unreachable (fail-open)', decisionId: d.decisionId || undefined };\n }\n return { allowed: false, reason: d.reason ?? 'control plane unreachable (failed closed)', decisionId: d.decisionId || undefined };\n }\n\n if (d.decision !== 'escalate') {\n return { allowed: isAllowVerdict(d.decision), reason: d.reason, decisionId: d.decisionId || undefined };\n }\n\n // escalate ── a human must decide.\n if (onEscalation === 'allow') {\n return { allowed: true, reason: d.reason ?? 'escalated (auto-allowed)', decisionId: d.decisionId || undefined };\n }\n if (onEscalation === 'deny') {\n return { allowed: false, reason: d.reason ?? 'escalated (auto-denied — awaiting human)', decisionId: d.decisionId || undefined };\n }\n // 'wait' — poll for the human decision. On timeout, fail closed (deny).\n if (!d.decisionId) {\n return { allowed: false, reason: 'escalated but no decisionId to poll', decisionId: undefined };\n }\n try {\n const resolved = await vorim.waitForDecisionResolution(d.decisionId, { timeoutMs: opts.escalationTimeoutMs });\n return { allowed: isAllowVerdict(resolved.decision), reason: resolved.reason, decisionId: resolved.decisionId || d.decisionId };\n } catch {\n // ESCALATION_TIMEOUT (or any poll error) → fail closed.\n return { allowed: false, reason: 'escalation not resolved before timeout', decisionId: d.decisionId };\n }\n}\n","/**\n * Replayable agent decision evidence helpers.\n *\n * Canonical-form hashing for the VAIP -02 schema fields that the SDK\n * attaches to audit events. The hashes recorded in audit_events.tool_catalogue_hash\n * and audit_events.system_prompt_hash use these functions, so the bytes\n * an auditor or counterparty reconstructs must match what the SDK produced.\n *\n * These helpers are intentionally separate from the signing path. The\n * v0 canonical signature form (event_type|action|resource|input_hash|\n * output_hash|result) does NOT cover model_version, tool_catalogue_hash,\n * or system_prompt_hash. They will enter the canonical bytes in v1\n * (RFC 8785 JCS) in a follow-up release.\n *\n * Stable across SDK versions: the canonical-form version is documented\n * in CANONICAL_TOOL_CATALOGUE_VERSION. Future changes get a v2 etc;\n * never edit the existing v1 logic, or already-recorded hashes lose\n * their meaning.\n */\n\n// ─── Versioning ───────────────────────────────────────────────────────────\n\n/**\n * Canonical-form version for tool catalogue hashes produced by this SDK.\n * Recorded in tool_catalogue_canon_version on the event metadata (when\n * the metadata field is used) so verifiers know which hash recipe to\n * reproduce. Increment ONLY if the algorithm changes in a way that\n * would change the hash for the same logical catalogue.\n */\nexport const CANONICAL_TOOL_CATALOGUE_VERSION = 'v1' as const;\n\n// ─── Types ────────────────────────────────────────────────────────────────\n\n/**\n * Minimum shape a tool needs for catalogue hashing. The framework\n * integrations adapt their native tool objects to this shape before\n * calling hashToolCatalogue.\n */\nexport interface CatalogueTool {\n /** The name the model sees and calls. Required. */\n name: string;\n /** Human-readable description shown to the model. Optional; absent ↔ empty string. */\n description?: string;\n /**\n * JSON Schema describing the tool's input parameters. Optional;\n * absent ↔ empty object `{}`. The schema gets RFC 8785 JCS-canonicalised\n * before hashing so semantically-equivalent variations (key order,\n * whitespace) produce the same hash.\n */\n schema?: Record<string, unknown> | null;\n}\n\n// ─── RFC 8785 JCS subset ──────────────────────────────────────────────────\n\n/**\n * RFC 8785 JSON Canonicalization Scheme, sufficient subset for tool\n * catalogue values.\n *\n * Rules:\n * - Object keys sorted lexicographically by UTF-16 code units (which\n * is what JS string comparison does naturally).\n * - No whitespace between tokens.\n * - Numbers: integers as integers, finite floats per ECMAScript\n * Number.prototype.toString. JCS forbids NaN and Infinity.\n * - Strings: JSON-escape using minimal set per RFC 8259 § 7.\n * - null, true, false, arrays: as JSON.stringify produces them, since\n * JSON.stringify already produces the canonical form for these.\n *\n * Not vendoring a full library because tool schemas don't carry\n * non-integer numbers in practice and the JS spec for Number.toString\n * happens to coincide with JCS § 3.2.2.2 for the integer case.\n */\nexport function jcsCanonicalise(value: unknown): string {\n if (value === null) return 'null';\n if (value === true) return 'true';\n if (value === false) return 'false';\n\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new Error('jcsCanonicalise: NaN and Infinity are not JCS-valid');\n }\n // Fail closed on magnitudes where JS .toString() and CPython diverge, so TS\n // and Python sign byte-identical bytes (or both reject). JS switches\n // integer-valued floats to exponent form at |x| >= 1e21 (Python expands to\n // full digits); in [1e-7, 1e-4) JS keeps decimals while Python repr() uses\n // exponent form. Keeping both engines in lockstep preserves cross-SDK\n // signature verifiability.\n const abs = Math.abs(value);\n // Reject ranges where JS Number.toString() and CPython diverge: |x| >= 1e21,\n // |x| < 1e-4, and integer-valued |x| > 2^53 (JS shortest-round-trip vs\n // Python exact int expansion — they only coincide for \"round\" values there).\n if (value !== 0 && (abs >= 1e21 || abs < 1e-4 || (Number.isInteger(value) && abs > 2 ** 53))) {\n throw new Error(\n `jcsCanonicalise: numbers in the ranges where JS and Python formatting ` +\n `diverge (|x| >= 1e21, |x| < 1e-4, or integer |x| > 2^53) are not ` +\n `supported in signed metadata. Use a string instead of ${value}.`,\n );\n }\n // For integers in safe range and ordinary decimals, .toString() matches JCS\n // (modern JS engines use the shortest round-trip representation).\n return value.toString();\n }\n\n if (typeof value === 'string') {\n return JSON.stringify(value);\n }\n\n if (Array.isArray(value)) {\n return '[' + value.map(jcsCanonicalise).join(',') + ']';\n }\n\n if (typeof value === 'object') {\n const obj = value as Record<string, unknown>;\n // Filter undefined-valued fields, matching @vorim/verify and\n // @vorim/shared-types. Without this the SDK throws on { a: 1, b: undefined }\n // while the verifier silently drops b — a cross-module canonical-form\n // divergence that would break signature verification on such events.\n const keys = Object.keys(obj).filter(k => obj[k] !== undefined).sort();\n const parts = keys.map(k => JSON.stringify(k) + ':' + jcsCanonicalise(obj[k]));\n return '{' + parts.join(',') + '}';\n }\n\n // undefined, function, symbol, bigint — not JSON-representable\n throw new Error(`jcsCanonicalise: unsupported value type: ${typeof value}`);\n}\n\n// ─── SHA-256 ──────────────────────────────────────────────────────────────\n\nasync function sha256Hex(input: string | Uint8Array): Promise<string> {\n const bytes = typeof input === 'string' ? new TextEncoder().encode(input) : input;\n\n // Node.js Web Crypto (Node 18+) supports digest. Browser Web Crypto does too.\n // Fall back to node:crypto if Web Crypto is unavailable.\n const subtle = (globalThis as any).crypto?.subtle;\n if (subtle) {\n const buf = await subtle.digest('SHA-256', bytes);\n return Array.from(new Uint8Array(buf))\n .map(b => b.toString(16).padStart(2, '0'))\n .join('');\n }\n\n // Node fallback\n const nodeCrypto = await import('node:crypto');\n return nodeCrypto.createHash('sha256').update(bytes).digest('hex');\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────\n\n/**\n * Hash a single tool definition. Returns `sha256:<hex>`.\n *\n * Canonical form (v1):\n * JCS-canonicalised JSON of `{name, description, schema}` where\n * absent fields substitute `description: \"\"` and `schema: {}`.\n */\nexport async function hashTool(tool: CatalogueTool): Promise<string> {\n const normalised = {\n name: tool.name,\n description: tool.description ?? '',\n schema: tool.schema ?? {},\n };\n const hex = await sha256Hex(jcsCanonicalise(normalised));\n return `sha256:${hex}`;\n}\n\n/**\n * Hash an entire tool catalogue. Returns `sha256:<hex>`.\n *\n * Reordering tools does NOT change the hash (tool hashes sorted\n * lexicographically before concatenation). Adding, removing, or\n * modifying a tool DOES change the hash.\n *\n * Per-tool hashing first means a verifier comparing two catalogue\n * hashes that differ can also be given the per-tool hashes to\n * identify which specific tool changed.\n */\nexport async function hashToolCatalogue(tools: CatalogueTool[]): Promise<string> {\n if (tools.length === 0) {\n // Empty catalogue has a deterministic, stable hash distinct from \"no field\"\n return `sha256:${await sha256Hex('[]')}`;\n }\n const perTool = await Promise.all(tools.map(hashTool));\n perTool.sort();\n const hex = await sha256Hex(perTool.join(''));\n return `sha256:${hex}`;\n}\n\n/**\n * Hash a system prompt. Returns `sha256:<hex>`.\n *\n * The prompt is UTF-8 encoded and hashed verbatim — no normalisation.\n * If a caller wants to ignore whitespace or comment differences, they\n * should normalise before calling. The intent here is deterministic\n * reproducibility, not semantic equivalence.\n */\nexport async function hashSystemPrompt(prompt: string): Promise<string> {\n const hex = await sha256Hex(prompt);\n return `sha256:${hex}`;\n}\n\n/**\n * Convenience: hash the previous event's canonical bytes for use in\n * the prev_event_hash field of hash-chained ingest. Caller provides\n * the canonical bytes (use canonicalPayloadV0 from the main module).\n */\nexport async function hashPreviousEvent(canonicalBytes: string): Promise<string> {\n const hex = await sha256Hex(canonicalBytes);\n return `sha256:${hex}`;\n}\n\n// ─── Replay context — framework integration helper ────────────────────────\n\n/**\n * Raw inputs the integration captures from the framework. Set by the\n * integration's config; turned into hashes by {@link prepareReplayContext}.\n */\nexport interface ReplayInputs {\n /** Stable identifier for the model. E.g. `\"anthropic:claude-opus-4-8\"`. */\n modelVersion?: string;\n /** Tools available to the agent at call time. Hashed via {@link hashToolCatalogue}. */\n tools?: CatalogueTool[];\n /** System prompt active at call time. Hashed via {@link hashSystemPrompt}. */\n systemPrompt?: string;\n}\n\n/**\n * Pre-computed hashes ready to attach to audit events. The three keys\n * match the audit_events column names.\n */\nexport interface ReplayContext {\n model_version?: string;\n tool_catalogue_hash?: string;\n system_prompt_hash?: string;\n}\n\n/**\n * Compute replay context once from raw inputs. Use at integration\n * setup time so each emit can attach the hashes without re-hashing.\n *\n * Returns an object suitable for spreading into an AuditEventInput:\n * `await vorim.emit({ ...event, ...replayContext })`\n *\n * If a field is absent in the inputs, it is absent in the result\n * (not the empty string). That keeps the event lean.\n */\nexport async function prepareReplayContext(\n inputs: ReplayInputs,\n): Promise<ReplayContext> {\n const ctx: ReplayContext = {};\n if (inputs.modelVersion) ctx.model_version = inputs.modelVersion;\n if (inputs.tools) ctx.tool_catalogue_hash = await hashToolCatalogue(inputs.tools);\n if (inputs.systemPrompt) ctx.system_prompt_hash = await hashSystemPrompt(inputs.systemPrompt);\n return ctx;\n}\n","// ============================================================================\n// VORIM SDK — Hermes Agent (Nous Research) Integration\n//\n// Hermes Agent loads tools two ways: its Python plugin system and external MCP\n// servers. This module secures the *tool execution* path from a TypeScript\n// host: it wraps a Hermes-style function tool ({ name, description, execute })\n// so every call is gated (allow / deny / escalate, fail-closed) and recorded\n// as a signed Vorim audit event.\n//\n// Why this exists alongside the MCP path: pointing Hermes at Vorim's MCP server\n// gives it the Vorim *tool catalog*, but MCP does not gate actions and its\n// audit events are unsigned (the MCP server holds no agent key). This wrapper\n// is the enforcement + signed-audit layer for tools Hermes runs in-process.\n//\n// No peer dependency — a Hermes tool is a plain object with an async `execute`.\n//\n// Usage:\n// import createVorim from '@vorim/sdk';\n// import { wrapHermesTools } from '@vorim/sdk/integrations/hermes';\n//\n// const vorim = createVorim({ apiKey: 'agid_sk_live_...' });\n// const tools = wrapHermesTools(myHermesTools, {\n// vorim, agentId: 'agid_acme_a1b2c3d4',\n// permissionMap: { send_email: 'agent:communicate' },\n// useRuntimeControl: true,\n// });\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope, AuditEventInput } from '../types.js';\nimport { runtimeGate, type EscalationPolicy, type TransportFailurePolicy } from './_runtime-gate.js';\nimport {\n prepareReplayContext,\n type ReplayInputs,\n type ReplayContext,\n type CatalogueTool,\n} from '../replay.js';\n\n// ─── Re-declared Hermes tool shape (no peer dependency — not bundled) ───────\n//\n// A Hermes function tool. We only touch `execute`; name/description/schema pass\n// through untouched so this stays compatible across Hermes tool-shape versions.\nexport interface HermesTool {\n name?: string;\n description?: string;\n /** JSON-schema-ish parameter descriptor (Hermes uses `parameters` / `input_schema`). */\n parameters?: unknown;\n input_schema?: unknown;\n execute?: (args: any, options?: any) => Promise<any> | any;\n [k: string]: unknown;\n}\n\n// ─── Configuration ──────────────────────────────────────────────────────────\n\nexport interface VorimHermesConfig {\n /** Vorim SDK instance. */\n vorim: VorimSDK;\n /** The Vorim agent_id (e.g. agid_acme_a1b2c3d4). */\n agentId: string;\n /** Per-tool permission scope override, keyed by tool name. */\n permissionMap?: Record<string, PermissionScope>;\n /** Default scope for tools without an entry in permissionMap. @default 'agent:execute' */\n defaultPermission?: PermissionScope;\n /** Emit audit events fire-and-forget. @default true */\n asyncAudit?: boolean;\n /**\n * Use the full runtime-control decision API (`beforeAction`) instead of the\n * lightweight permission check. When true, every tool call is evaluated\n * against live policy rules (allow/deny/escalate) and the `decisionId` is\n * linked onto each audit event. Requires the runtime_control plan feature.\n * @default false\n */\n useRuntimeControl?: boolean;\n /** What to do on an `escalate` verdict (runtime control only). @default 'wait' */\n onEscalation?: EscalationPolicy;\n /** Timeout (ms) for `onEscalation: 'wait'`. @default 300000 */\n escalationTimeoutMs?: number;\n /** Policy when the runtime gate can't reach the control plane. @default 'deny' */\n onTransportFailure?: TransportFailurePolicy;\n /** Replayable agent-decision evidence (VAIP -02) attached to each audit event. */\n replay?: ReplayInputs;\n}\n\nconst FRAMEWORK = 'hermes';\n\n// ─── Helpers ──────────────────────────────────────────────────────────────\n\nfunction truncate(s: string, max: number): string {\n return s.length > max ? s.slice(0, max) + '…' : s;\n}\n\nfunction safeJson(v: unknown): string {\n try {\n return JSON.stringify(v);\n } catch {\n return String(v);\n }\n}\n\nasync function gate(\n cfg: VorimHermesConfig,\n scope: PermissionScope,\n actionTarget: string,\n payload?: Record<string, unknown>,\n): Promise<{ allowed: boolean; reason?: string; decisionId?: string }> {\n if (cfg.useRuntimeControl) {\n // runtimeGate resolves transport-failure fallbacks internally, but a\n // non-transport VorimError (e.g. 403 missing runtime:decide scope) still\n // throws — wrap so it fails closed instead of crashing Hermes' tool loop.\n try {\n return await runtimeGate(cfg.vorim, cfg.agentId, actionTarget, scope, payload, {\n onEscalation: cfg.onEscalation,\n escalationTimeoutMs: cfg.escalationTimeoutMs,\n onTransportFailure: cfg.onTransportFailure,\n });\n } catch {\n return { allowed: false, reason: 'runtime gate unavailable (failed closed)' };\n }\n }\n try {\n const { allowed, reason } = await cfg.vorim.check(cfg.agentId, scope);\n return { allowed, reason };\n } catch {\n return { allowed: false, reason: 'permission check unavailable (failed closed)' };\n }\n}\n\nfunction emitAudit(vorim: VorimSDK, event: AuditEventInput, asyncAudit: boolean): Promise<void> | void {\n if (asyncAudit) {\n vorim.emit(event).catch(() => {});\n return;\n }\n return vorim.emit(event).then(() => undefined).catch(() => undefined);\n}\n\nfunction makeReplayGetter(replay: ReplayInputs | undefined): () => Promise<ReplayContext> {\n if (!replay) return async () => ({});\n let cached: Promise<ReplayContext> | null = null;\n return () => {\n if (!cached) cached = prepareReplayContext(replay);\n return cached;\n };\n}\n\n// ─── Wrappers ────────────────────────────────────────────────────────────────\n\n/**\n * Wrap a single Hermes function tool so every execution is gated by a Vorim\n * permission/runtime check and recorded in the signed audit trail. A denied\n * call throws (so Hermes records a tool error) and is audited as `denied`.\n * Tools with no `execute` pass through unchanged.\n *\n * @param name Tool name (used for the audit `action` and permissionMap lookup).\n * Falls back to `tool.name` when omitted.\n */\nexport function wrapHermesTool(name: string, tool: HermesTool, config: VorimHermesConfig): HermesTool {\n const { vorim, defaultPermission = 'agent:execute', permissionMap = {}, asyncAudit = true } = config;\n if (typeof tool.execute !== 'function') return tool; // nothing to guard\n\n const toolName = name || tool.name || 'hermes_tool';\n const originalExecute = tool.execute.bind(tool);\n const getReplay = makeReplayGetter(config.replay);\n const scope = permissionMap[toolName] ?? defaultPermission;\n\n const guarded: HermesTool = {\n ...tool,\n execute: async (args: any, options?: any): Promise<any> => {\n const { allowed, reason, decisionId } = await gate(config, scope, toolName, args as Record<string, unknown>);\n const replayCtx = await getReplay();\n const resource = truncate(safeJson(args), 500);\n\n if (!allowed) {\n await emitAudit(vorim, {\n agent_id: config.agentId,\n event_type: 'tool_call',\n action: toolName,\n resource,\n permission: scope,\n result: 'denied',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { reason, framework: FRAMEWORK },\n ...replayCtx,\n }, asyncAudit);\n throw new Error(`Vorim: permission denied for \"${toolName}\" — scope \"${scope}\"${reason ? `: ${reason}` : ''}`);\n }\n\n const start = Date.now();\n try {\n const result = await originalExecute(args, options);\n await emitAudit(vorim, {\n agent_id: config.agentId,\n event_type: 'tool_call',\n action: toolName,\n resource,\n permission: scope,\n result: 'success',\n latency_ms: Date.now() - start,\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { framework: FRAMEWORK },\n ...replayCtx,\n }, asyncAudit);\n return result;\n } catch (err) {\n await emitAudit(vorim, {\n agent_id: config.agentId,\n event_type: 'tool_call',\n action: toolName,\n resource,\n permission: scope,\n result: 'error',\n latency_ms: Date.now() - start,\n error_code: err instanceof Error ? err.name : 'UNKNOWN',\n ...(decisionId ? { decision_id: decisionId } : {}),\n metadata: { error: err instanceof Error ? err.message : String(err), framework: FRAMEWORK },\n ...replayCtx,\n }, asyncAudit);\n throw err;\n }\n },\n };\n\n return guarded;\n}\n\n/**\n * Wrap a collection of Hermes tools. Accepts either an array of tools (each\n * carrying its own `name`) or a name→tool record. Returns the same shape with\n * every executable tool guarded, and auto-derives the replay tool catalogue\n * when `replay.tools` was not supplied.\n */\nexport function wrapHermesTools<T extends HermesTool[] | Record<string, HermesTool>>(\n tools: T,\n config: VorimHermesConfig,\n): T {\n const asRecord: Record<string, HermesTool> = Array.isArray(tools)\n ? Object.fromEntries(tools.map((t, i) => [t.name || `tool_${i}`, t]))\n : tools;\n\n const cfg: VorimHermesConfig =\n config.replay && !config.replay.tools\n ? { ...config, replay: { ...config.replay, tools: deriveCatalogue(asRecord) } }\n : config;\n\n if (Array.isArray(tools)) {\n return tools.map((t) => wrapHermesTool(t.name || 'hermes_tool', t, cfg)) as T;\n }\n const out: Record<string, HermesTool> = {};\n for (const [name, tool] of Object.entries(tools)) {\n out[name] = wrapHermesTool(name, tool, cfg);\n }\n return out as T;\n}\n\nfunction deriveCatalogue(tools: Record<string, HermesTool>): CatalogueTool[] {\n return Object.entries(tools).map(([name, t]) => ({\n name,\n description: typeof t.description === 'string' ? t.description : '',\n schema: (t.input_schema ?? t.parameters ?? {}) as Record<string, unknown>,\n }));\n}\n"],"mappings":";AAmEA,SAAS,eAAe,UAAgD;AACtE,SAAO,aAAa,WAAW,aAAa;AAC9C;AASA,eAAsB,YACpB,OACA,SACA,cACA,OACA,SACA,OAA2B,CAAC,GACP;AACrB,QAAM,eAAe,KAAK,gBAAgB;AAC1C,QAAM,qBAAqB,KAAK,sBAAsB;AACtD,QAAM,IAAI,MAAM,MAAM;AAAA,IACpB,EAAE,SAAS,YAAY,aAAa,cAAc,eAAe,OAAO,QAAQ;AAAA,IAChF,EAAE,aAAa,MAAM;AAAA,EACvB;AAMA,MAAI,EAAE,cAAc,EAAE,aAAa,YAAY;AAC7C,QAAI,uBAAuB,SAAS;AAClC,aAAO,EAAE,SAAS,MAAM,QAAQ,EAAE,UAAU,yCAAyC,YAAY,EAAE,cAAc,OAAU;AAAA,IAC7H;AACA,WAAO,E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AA,EACF;AAEA,SAAO;AACT;AAQO,SAAS,gBACd,OACA,QACG;AACH,QAAM,WAAuC,MAAM,QAAQ,KAAK,IAC5D,OAAO,YAAY,MAAM,IAAI,CAAC,GAAG,MAAM,CAAC,EAAE,QAAQ,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,IAClE;AAEJ,QAAM,MACJ,OAAO,UAAU,CAAC,OAAO,OAAO,QAC5B,EAAE,GAAG,QAAQ,QAAQ,EAAE,GAAG,OAAO,QAAQ,OAAO,gBAAgB,QAAQ,EAAE,EAAE,IAC5E;AAEN,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,MAAM,IAAI,CAAC,MAAM,eAAe,EAAE,QAAQ,eAAe,GAAG,GAAG,CAAC;AAAA,EACzE;AACA,QAAM,MAAkC,CAAC;AACzC,aAAW,CAAC,MAAM,IAAI,KAAK,OAAO,QAAQ,KAAK,GAAG;AAChD,QAAI,IAAI,IAAI,eAAe,MAAM,MAAM,GAAG;AAAA,EAC5C;AACA,SAAO;AACT;AAEA,SAAS,gBAAgB,OAAoD;AAC3E,SAAO,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,MAAM,CAAC,OAAO;AAAA,IAC/C;AAAA,IACA,aAAa,OAAO,EAAE,gBAAgB,WAAW,EAAE,cAAc;AAAA,IACjE,QAAS,EAAE,gBAAgB,EAAE,cAAc,CAAC;AAAA,EAC9C,EAAE;AACJ;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vorim/sdk",
3
- "version": "3.8.0",
3
+ "version": "3.8.1",
4
4
  "description": "Official TypeScript SDK for Vorim AI — AI Agent Identity, Permissions & Audit",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -87,6 +87,16 @@
87
87
  "default": "./dist/integrations/vercel-ai.cjs"
88
88
  }
89
89
  },
90
+ "./integrations/hermes": {
91
+ "import": {
92
+ "types": "./dist/integrations/hermes.d.ts",
93
+ "default": "./dist/integrations/hermes.js"
94
+ },
95
+ "require": {
96
+ "types": "./dist/integrations/hermes.d.cts",
97
+ "default": "./dist/integrations/hermes.cjs"
98
+ }
99
+ },
90
100
  "./integrations/stripe-acp": {
91
101
  "import": {
92
102
  "types": "./dist/integrations/stripe-acp.d.ts",
@@ -150,7 +160,8 @@
150
160
  "langgraph",
151
161
  "openai",
152
162
  "crewai",
153
- "llamaindex"
163
+ "llamaindex",
164
+ "hermes"
154
165
  ],
155
166
  "repository": {
156
167
  "type": "git",