@vorim/sdk 3.20.0 → 3.22.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/CHANGELOG.md +7 -0
- package/README.md +12 -6
- package/dist/index.cjs +117 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +43 -2
- package/dist/index.d.ts +43 -2
- package/dist/index.js +116 -3
- package/dist/index.js.map +1 -1
- package/dist/integrations/anthropic.d.cts +2 -1
- package/dist/integrations/anthropic.d.ts +2 -1
- package/dist/integrations/ap2.d.cts +2 -1
- package/dist/integrations/ap2.d.ts +2 -1
- package/dist/integrations/aws-iam.d.cts +2 -1
- package/dist/integrations/aws-iam.d.ts +2 -1
- package/dist/integrations/bank-rails.d.cts +2 -1
- package/dist/integrations/bank-rails.d.ts +2 -1
- package/dist/integrations/circle.d.cts +2 -1
- package/dist/integrations/circle.d.ts +2 -1
- package/dist/integrations/cloudflare.d.cts +2 -1
- package/dist/integrations/cloudflare.d.ts +2 -1
- package/dist/integrations/coinbase-cdp.d.cts +2 -1
- package/dist/integrations/coinbase-cdp.d.ts +2 -1
- package/dist/integrations/commerce-agents.d.cts +2 -1
- package/dist/integrations/commerce-agents.d.ts +2 -1
- package/dist/integrations/crewai.d.cts +2 -1
- package/dist/integrations/crewai.d.ts +2 -1
- package/dist/integrations/entra.d.cts +2 -1
- package/dist/integrations/entra.d.ts +2 -1
- package/dist/integrations/fhir.d.cts +2 -1
- package/dist/integrations/fhir.d.ts +2 -1
- package/dist/integrations/grok.d.cts +2 -1
- package/dist/integrations/grok.d.ts +2 -1
- package/dist/integrations/guidewire.d.cts +2 -1
- package/dist/integrations/guidewire.d.ts +2 -1
- package/dist/integrations/hermes.d.cts +2 -1
- package/dist/integrations/hermes.d.ts +2 -1
- package/dist/integrations/jira.d.cts +2 -1
- package/dist/integrations/jira.d.ts +2 -1
- package/dist/integrations/langchain.d.cts +2 -1
- package/dist/integrations/langchain.d.ts +2 -1
- package/dist/integrations/langgraph.d.cts +2 -1
- package/dist/integrations/langgraph.d.ts +2 -1
- package/dist/integrations/legal.d.cts +2 -1
- package/dist/integrations/legal.d.ts +2 -1
- package/dist/integrations/life-sciences.d.cts +2 -1
- package/dist/integrations/life-sciences.d.ts +2 -1
- package/dist/integrations/linear.d.cts +2 -1
- package/dist/integrations/linear.d.ts +2 -1
- package/dist/integrations/lithic.d.cts +2 -1
- package/dist/integrations/lithic.d.ts +2 -1
- package/dist/integrations/llamaindex.d.cts +2 -1
- package/dist/integrations/llamaindex.d.ts +2 -1
- package/dist/integrations/marqeta.d.cts +2 -1
- package/dist/integrations/marqeta.d.ts +2 -1
- package/dist/integrations/modern-treasury.d.cts +2 -1
- package/dist/integrations/modern-treasury.d.ts +2 -1
- package/dist/integrations/muse.cjs +437 -0
- package/dist/integrations/muse.cjs.map +1 -0
- package/dist/integrations/muse.d.cts +72 -0
- package/dist/integrations/muse.d.ts +72 -0
- package/dist/integrations/muse.js +394 -0
- package/dist/integrations/muse.js.map +1 -0
- package/dist/integrations/nekuda.d.cts +2 -1
- package/dist/integrations/nekuda.d.ts +2 -1
- package/dist/integrations/okta.d.cts +2 -1
- package/dist/integrations/okta.d.ts +2 -1
- package/dist/integrations/openai.d.cts +2 -1
- package/dist/integrations/openai.d.ts +2 -1
- package/dist/integrations/openrouter.d.cts +2 -1
- package/dist/integrations/openrouter.d.ts +2 -1
- package/dist/integrations/paypal-agent.d.cts +2 -1
- package/dist/integrations/paypal-agent.d.ts +2 -1
- package/dist/integrations/perplexity.d.cts +2 -1
- package/dist/integrations/perplexity.d.ts +2 -1
- package/dist/integrations/plaid.d.cts +2 -1
- package/dist/integrations/plaid.d.ts +2 -1
- package/dist/integrations/ramp.d.cts +2 -1
- package/dist/integrations/ramp.d.ts +2 -1
- package/dist/integrations/shopify.d.cts +2 -1
- package/dist/integrations/shopify.d.ts +2 -1
- package/dist/integrations/siem.d.cts +1 -1
- package/dist/integrations/siem.d.ts +1 -1
- package/dist/integrations/skyfire.d.cts +2 -1
- package/dist/integrations/skyfire.d.ts +2 -1
- package/dist/integrations/stripe-acp.d.cts +2 -1
- package/dist/integrations/stripe-acp.d.ts +2 -1
- package/dist/integrations/stripe-issuing.d.cts +2 -1
- package/dist/integrations/stripe-issuing.d.ts +2 -1
- package/dist/integrations/truanon.d.cts +2 -1
- package/dist/integrations/truanon.d.ts +2 -1
- package/dist/integrations/typesafe.cjs +268 -0
- package/dist/integrations/typesafe.cjs.map +1 -0
- package/dist/integrations/typesafe.d.cts +145 -0
- package/dist/integrations/typesafe.d.ts +145 -0
- package/dist/integrations/typesafe.js +221 -0
- package/dist/integrations/typesafe.js.map +1 -0
- package/dist/integrations/ucp.d.cts +2 -1
- package/dist/integrations/ucp.d.ts +2 -1
- package/dist/integrations/vercel-ai.d.cts +2 -1
- package/dist/integrations/vercel-ai.d.ts +2 -1
- package/dist/integrations/x402.d.cts +2 -1
- package/dist/integrations/x402.d.ts +2 -1
- package/dist/{types-BmeluKHI.d.cts → types-BrDQAJdl.d.cts} +36 -1
- package/dist/{types-BmeluKHI.d.ts → types-BrDQAJdl.d.ts} +36 -1
- package/package.json +21 -1
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { VorimSDK } from '../index.js';
|
|
2
2
|
import { VorimToolRegistry } from './openai.js';
|
|
3
3
|
export { VorimAgentLoopConfig, VorimOpenAIConfig as VorimOpenRouterConfig, VorimToolDefinition, createVorimOpenAIAgent as createVorimOpenRouterAgent, runAgentLoop } from './openai.js';
|
|
4
|
-
import '../types-
|
|
4
|
+
import '../types-BrDQAJdl.js';
|
|
5
|
+
import '@vorim/shared-types';
|
|
5
6
|
import '../_runtime-gate-DOJUKJBu.js';
|
|
6
7
|
|
|
7
8
|
/** OpenRouter API base URL (OpenAI-SDK compatible). */
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { VorimSDK } from '../index.cjs';
|
|
2
2
|
import { VorimToolRegistry } from './openai.cjs';
|
|
3
3
|
export { VorimAgentLoopConfig, VorimOpenAIConfig as VorimPerplexityConfig, VorimToolDefinition, createVorimOpenAIAgent as createVorimPerplexityAgent, runAgentLoop } from './openai.cjs';
|
|
4
|
-
import '../types-
|
|
4
|
+
import '../types-BrDQAJdl.cjs';
|
|
5
|
+
import '@vorim/shared-types';
|
|
5
6
|
import '../_runtime-gate-DOJUKJBu.cjs';
|
|
6
7
|
|
|
7
8
|
/** Perplexity Sonar API base URL (OpenAI-SDK compatible). */
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { VorimSDK } from '../index.js';
|
|
2
2
|
import { VorimToolRegistry } from './openai.js';
|
|
3
3
|
export { VorimAgentLoopConfig, VorimOpenAIConfig as VorimPerplexityConfig, VorimToolDefinition, createVorimOpenAIAgent as createVorimPerplexityAgent, runAgentLoop } from './openai.js';
|
|
4
|
-
import '../types-
|
|
4
|
+
import '../types-BrDQAJdl.js';
|
|
5
|
+
import '@vorim/shared-types';
|
|
5
6
|
import '../_runtime-gate-DOJUKJBu.js';
|
|
6
7
|
|
|
7
8
|
/** Perplexity Sonar API base URL (OpenAI-SDK compatible). */
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { VorimSDK } from '../index.cjs';
|
|
2
|
-
import { P as PermissionScope } from '../types-
|
|
2
|
+
import { P as PermissionScope } from '../types-BrDQAJdl.cjs';
|
|
3
|
+
import '@vorim/shared-types';
|
|
3
4
|
|
|
4
5
|
type RampOperation = 'createLimit' | 'updateRestriction' | 'terminateCard';
|
|
5
6
|
interface RampConfig {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { VorimSDK } from '../index.js';
|
|
2
|
-
import { P as PermissionScope } from '../types-
|
|
2
|
+
import { P as PermissionScope } from '../types-BrDQAJdl.js';
|
|
3
|
+
import '@vorim/shared-types';
|
|
3
4
|
|
|
4
5
|
type RampOperation = 'createLimit' | 'updateRestriction' | 'terminateCard';
|
|
5
6
|
interface RampConfig {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { VorimSDK } from '../index.cjs';
|
|
2
|
-
import { P as PermissionScope } from '../types-
|
|
2
|
+
import { P as PermissionScope } from '../types-BrDQAJdl.cjs';
|
|
3
|
+
import '@vorim/shared-types';
|
|
3
4
|
|
|
4
5
|
/** The Admin GraphQL mutations this guard knows how to classify. Any other
|
|
5
6
|
* label is accepted too; it just defaults to the 'write' risk tier. */
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { VorimSDK } from '../index.js';
|
|
2
|
-
import { P as PermissionScope } from '../types-
|
|
2
|
+
import { P as PermissionScope } from '../types-BrDQAJdl.js';
|
|
3
|
+
import '@vorim/shared-types';
|
|
3
4
|
|
|
4
5
|
/** The Admin GraphQL mutations this guard knows how to classify. Any other
|
|
5
6
|
* label is accepted too; it just defaults to the 'write' risk tier. */
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { VorimSDK } from '../index.cjs';
|
|
2
|
-
import { P as PermissionScope } from '../types-
|
|
2
|
+
import { P as PermissionScope } from '../types-BrDQAJdl.cjs';
|
|
3
|
+
import '@vorim/shared-types';
|
|
3
4
|
|
|
4
5
|
/** The Stripe Issuing operations this guard classifies. */
|
|
5
6
|
type StripeIssuingOperation = 'issueCard' | 'updateCard' | 'authorize' | 'dispute';
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { VorimSDK } from '../index.js';
|
|
2
|
-
import { P as PermissionScope } from '../types-
|
|
2
|
+
import { P as PermissionScope } from '../types-BrDQAJdl.js';
|
|
3
|
+
import '@vorim/shared-types';
|
|
3
4
|
|
|
4
5
|
/** The Stripe Issuing operations this guard classifies. */
|
|
5
6
|
type StripeIssuingOperation = 'issueCard' | 'updateCard' | 'authorize' | 'dispute';
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { VorimSDK } from '../index.cjs';
|
|
2
|
-
import '../types-
|
|
2
|
+
import '../types-BrDQAJdl.cjs';
|
|
3
|
+
import '@vorim/shared-types';
|
|
3
4
|
|
|
4
5
|
/** TruAnon rank tiers, weakest to strongest. `Unknown` never meets a minimum. */
|
|
5
6
|
type TruAnonRank = 'Unknown' | 'Dangerous' | 'Cautioned' | 'Credible' | 'Reliable' | 'Genuine';
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { VorimSDK } from '../index.js';
|
|
2
|
-
import '../types-
|
|
2
|
+
import '../types-BrDQAJdl.js';
|
|
3
|
+
import '@vorim/shared-types';
|
|
3
4
|
|
|
4
5
|
/** TruAnon rank tiers, weakest to strongest. `Unknown` never meets a minimum. */
|
|
5
6
|
type TruAnonRank = 'Unknown' | 'Dangerous' | 'Cautioned' | 'Credible' | 'Reliable' | 'Genuine';
|
|
@@ -0,0 +1,268 @@
|
|
|
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/typesafe.ts
|
|
31
|
+
var typesafe_exports = {};
|
|
32
|
+
__export(typesafe_exports, {
|
|
33
|
+
DEFAULT_TYPESAFE_MODEL: () => DEFAULT_TYPESAFE_MODEL,
|
|
34
|
+
TYPESAFE_API_KEY_ENV: () => TYPESAFE_API_KEY_ENV,
|
|
35
|
+
TYPESAFE_BASE_URL: () => TYPESAFE_BASE_URL,
|
|
36
|
+
VorimTypeSafe: () => VorimTypeSafe,
|
|
37
|
+
answerMeetsConfidence: () => answerMeetsConfidence,
|
|
38
|
+
choiceQuestion: () => choiceQuestion,
|
|
39
|
+
createTypeSafeFetchClient: () => createTypeSafeFetchClient,
|
|
40
|
+
createVorimTypeSafe: () => createVorimTypeSafe,
|
|
41
|
+
normaliseAnswers: () => normaliseAnswers,
|
|
42
|
+
noulQuestion: () => noulQuestion,
|
|
43
|
+
scoreQuestion: () => scoreQuestion
|
|
44
|
+
});
|
|
45
|
+
module.exports = __toCommonJS(typesafe_exports);
|
|
46
|
+
|
|
47
|
+
// src/commit.ts
|
|
48
|
+
var SHA256_PREFIX = "sha256:";
|
|
49
|
+
function toBytes(v) {
|
|
50
|
+
return typeof v === "string" ? new TextEncoder().encode(v) : v;
|
|
51
|
+
}
|
|
52
|
+
function toHex(buf) {
|
|
53
|
+
return Array.from(buf instanceof Uint8Array ? buf : new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
54
|
+
}
|
|
55
|
+
async function hashPayload(content) {
|
|
56
|
+
const bytes = toBytes(content);
|
|
57
|
+
const subtle = globalThis.crypto?.subtle;
|
|
58
|
+
if (subtle) {
|
|
59
|
+
return SHA256_PREFIX + toHex(await subtle.digest("SHA-256", bytes));
|
|
60
|
+
}
|
|
61
|
+
const nodeCrypto = await import("crypto");
|
|
62
|
+
return SHA256_PREFIX + nodeCrypto.createHash("sha256").update(bytes).digest("hex");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// src/integrations/typesafe.ts
|
|
66
|
+
var TYPESAFE_BASE_URL = "https://api.typesafe.ai/v1";
|
|
67
|
+
var DEFAULT_TYPESAFE_MODEL = "jev-latest";
|
|
68
|
+
var TYPESAFE_API_KEY_ENV = "TYPESAFE_API_KEY";
|
|
69
|
+
function noulQuestion(instructions, criteria) {
|
|
70
|
+
return criteria ? { type: "noul", instructions, criteria } : { type: "noul", instructions };
|
|
71
|
+
}
|
|
72
|
+
function choiceQuestion(instructions, criteria) {
|
|
73
|
+
return { type: "choice", instructions, criteria };
|
|
74
|
+
}
|
|
75
|
+
function scoreQuestion(instructions, levels) {
|
|
76
|
+
return { type: "score", instructions, criteria: levels };
|
|
77
|
+
}
|
|
78
|
+
function answerMeetsConfidence(answer, minConfidence) {
|
|
79
|
+
if (minConfidence <= 0) return true;
|
|
80
|
+
if (answer.type === "noul") {
|
|
81
|
+
const p = typeof answer.noul === "number" ? answer.noul : 0.5;
|
|
82
|
+
return Math.max(p, 1 - p) >= minConfidence;
|
|
83
|
+
}
|
|
84
|
+
const c = typeof answer.confidence === "number" ? answer.confidence : 0;
|
|
85
|
+
return c >= minConfidence;
|
|
86
|
+
}
|
|
87
|
+
function stableStringify(value) {
|
|
88
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
89
|
+
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
|
|
90
|
+
const keys = Object.keys(value).sort();
|
|
91
|
+
return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;
|
|
92
|
+
}
|
|
93
|
+
function createTypeSafeFetchClient(opts) {
|
|
94
|
+
const baseUrl = (opts.baseUrl ?? TYPESAFE_BASE_URL).replace(/\/$/, "");
|
|
95
|
+
const timeoutMs = opts.timeoutMs ?? 3e4;
|
|
96
|
+
const doFetch = opts.fetchImpl ?? fetch;
|
|
97
|
+
return {
|
|
98
|
+
async systemOne(req) {
|
|
99
|
+
const apiKey = opts.apiKey ?? (typeof process !== "undefined" ? process.env?.[TYPESAFE_API_KEY_ENV] : void 0);
|
|
100
|
+
if (!apiKey) throw new Error(`[vorim] TypeSafe: no API key. Pass apiKey or set ${TYPESAFE_API_KEY_ENV}.`);
|
|
101
|
+
const controller = new AbortController();
|
|
102
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
103
|
+
try {
|
|
104
|
+
const res = await doFetch(`${baseUrl}/systemone`, {
|
|
105
|
+
method: "POST",
|
|
106
|
+
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", Accept: "application/json" },
|
|
107
|
+
body: JSON.stringify({ model: req.model ?? DEFAULT_TYPESAFE_MODEL, state: req.state, questions: req.questions }),
|
|
108
|
+
redirect: "error",
|
|
109
|
+
signal: controller.signal
|
|
110
|
+
});
|
|
111
|
+
if (!res.ok) throw new Error(`[vorim] TypeSafe: HTTP ${res.status}`);
|
|
112
|
+
return await res.json();
|
|
113
|
+
} finally {
|
|
114
|
+
clearTimeout(timer);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
var VorimTypeSafe = class {
|
|
120
|
+
sdk;
|
|
121
|
+
agentId;
|
|
122
|
+
client;
|
|
123
|
+
model;
|
|
124
|
+
minConfidence;
|
|
125
|
+
minTrustScore;
|
|
126
|
+
requiredScope;
|
|
127
|
+
constructor(sdk, config) {
|
|
128
|
+
if (!config?.agentId) throw new Error("[vorim] TypeSafe integration requires an agentId.");
|
|
129
|
+
this.sdk = sdk;
|
|
130
|
+
this.agentId = config.agentId;
|
|
131
|
+
this.client = config.client ?? createTypeSafeFetchClient({
|
|
132
|
+
apiKey: config.apiKey,
|
|
133
|
+
baseUrl: config.baseUrl,
|
|
134
|
+
timeoutMs: config.timeoutMs,
|
|
135
|
+
fetchImpl: config.fetchImpl
|
|
136
|
+
});
|
|
137
|
+
this.model = config.model ?? DEFAULT_TYPESAFE_MODEL;
|
|
138
|
+
this.minConfidence = config.minConfidence ?? 0;
|
|
139
|
+
this.minTrustScore = config.minTrustScore;
|
|
140
|
+
this.requiredScope = config.requiredScope ?? "agent:execute";
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Ask Jev for a typed decision, under Vorim's authority check, and sign the
|
|
144
|
+
* result. Never throws for a denial or a Jev error: read `authorized`,
|
|
145
|
+
* `actionable` and `reason`.
|
|
146
|
+
*/
|
|
147
|
+
async decide(input) {
|
|
148
|
+
const started = Date.now();
|
|
149
|
+
const model = input.model ?? this.model;
|
|
150
|
+
const minConfidence = input.minConfidence ?? this.minConfidence;
|
|
151
|
+
const questionIds = Object.keys(input.questions ?? {});
|
|
152
|
+
const stateHash = await hashPayload(stableStringify(input.state));
|
|
153
|
+
const base = { answers: {}, lowConfidence: [], model, stateHash };
|
|
154
|
+
const finish = async (partial, result, meta) => {
|
|
155
|
+
const latencyMs = Date.now() - started;
|
|
156
|
+
const recorded = await this.record(input, result, latencyMs, {
|
|
157
|
+
model,
|
|
158
|
+
question_ids: questionIds,
|
|
159
|
+
min_confidence: minConfidence,
|
|
160
|
+
...meta
|
|
161
|
+
}, stateHash, partial.answersHash);
|
|
162
|
+
return { ...base, ...partial, recorded, latencyMs };
|
|
163
|
+
};
|
|
164
|
+
try {
|
|
165
|
+
const perm = await this.sdk.check(this.agentId, this.requiredScope);
|
|
166
|
+
if (!perm.allowed) {
|
|
167
|
+
return finish({ authorized: false, actionable: false, reason: perm.reason ?? `Agent lacks ${this.requiredScope}` }, "denied", { denial: "scope" });
|
|
168
|
+
}
|
|
169
|
+
} catch (e) {
|
|
170
|
+
return finish({ authorized: false, actionable: false, reason: `Permission check failed: ${e?.message ?? e}` }, "error", { denial: "check_error" });
|
|
171
|
+
}
|
|
172
|
+
if (this.minTrustScore !== void 0) {
|
|
173
|
+
let score = 0;
|
|
174
|
+
try {
|
|
175
|
+
score = (await this.sdk.verify(this.agentId)).trust_score ?? 0;
|
|
176
|
+
} catch {
|
|
177
|
+
}
|
|
178
|
+
if (score < this.minTrustScore) {
|
|
179
|
+
return finish({ authorized: false, actionable: false, reason: `Agent trust score ${score} below ${this.minTrustScore}` }, "denied", { denial: "trust", trust_score: score });
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
let res;
|
|
183
|
+
try {
|
|
184
|
+
res = await this.client.systemOne({ state: input.state, questions: input.questions, model });
|
|
185
|
+
} catch (e) {
|
|
186
|
+
return finish({ authorized: true, actionable: false, reason: `TypeSafe call failed: ${e?.message ?? e}` }, "error", { error: String(e?.message ?? e) });
|
|
187
|
+
}
|
|
188
|
+
const answers = normaliseAnswers(res);
|
|
189
|
+
const answersHash = await hashPayload(stableStringify(answers));
|
|
190
|
+
const lowConfidence = Object.entries(answers).filter(([, a]) => !answerMeetsConfidence(a, minConfidence)).map(([id]) => id);
|
|
191
|
+
const actionable = lowConfidence.length === 0;
|
|
192
|
+
return finish({
|
|
193
|
+
authorized: true,
|
|
194
|
+
actionable,
|
|
195
|
+
answers,
|
|
196
|
+
lowConfidence,
|
|
197
|
+
model: res?.model ?? model,
|
|
198
|
+
usage: res?.usage,
|
|
199
|
+
answersHash,
|
|
200
|
+
reason: actionable ? void 0 : `Confidence below ${minConfidence} for: ${lowConfidence.join(", ")}`
|
|
201
|
+
}, "success", {
|
|
202
|
+
model_version: res?.model ?? model,
|
|
203
|
+
actionable,
|
|
204
|
+
low_confidence: lowConfidence,
|
|
205
|
+
answers: summariseAnswers(answers),
|
|
206
|
+
usage: res?.usage
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
async record(input, result, latencyMs, metadata, stateHash, answersHash) {
|
|
210
|
+
try {
|
|
211
|
+
const r = await this.sdk.emit({
|
|
212
|
+
agent_id: this.agentId,
|
|
213
|
+
event_type: "api_request",
|
|
214
|
+
action: `typesafe:systemone:${input.purpose}`,
|
|
215
|
+
resource: input.resource ?? input.purpose,
|
|
216
|
+
result,
|
|
217
|
+
latency_ms: latencyMs,
|
|
218
|
+
input_hash: stateHash,
|
|
219
|
+
...answersHash ? { output_hash: answersHash } : {},
|
|
220
|
+
permission: this.requiredScope,
|
|
221
|
+
metadata: { integration: "typesafe", provider: "typesafe", purpose: input.purpose, ...metadata }
|
|
222
|
+
}, { sign: true });
|
|
223
|
+
return (r?.ingested ?? 0) > 0;
|
|
224
|
+
} catch {
|
|
225
|
+
return false;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
function normaliseAnswers(res) {
|
|
230
|
+
if (!res) return {};
|
|
231
|
+
if (res.answers && typeof res.answers === "object") return res.answers;
|
|
232
|
+
const out = {};
|
|
233
|
+
for (const [bucket, type] of [["nouls", "noul"], ["choices", "choice"], ["scores", "score"]]) {
|
|
234
|
+
const m = res[bucket];
|
|
235
|
+
if (m && typeof m === "object") for (const [id, a] of Object.entries(m)) out[id] = { type, ...a ?? {} };
|
|
236
|
+
}
|
|
237
|
+
return out;
|
|
238
|
+
}
|
|
239
|
+
function summariseAnswers(answers) {
|
|
240
|
+
const out = {};
|
|
241
|
+
for (const [id, a] of Object.entries(answers)) {
|
|
242
|
+
out[id] = {
|
|
243
|
+
type: a.type,
|
|
244
|
+
...a.type === "noul" ? { noul: a.noul } : {},
|
|
245
|
+
...a.type === "choice" ? { choice: a.choice, confidence: a.confidence } : {},
|
|
246
|
+
...a.type === "score" ? { score: a.score, confidence: a.confidence } : {}
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
return out;
|
|
250
|
+
}
|
|
251
|
+
function createVorimTypeSafe(sdk, config) {
|
|
252
|
+
return new VorimTypeSafe(sdk, config);
|
|
253
|
+
}
|
|
254
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
255
|
+
0 && (module.exports = {
|
|
256
|
+
DEFAULT_TYPESAFE_MODEL,
|
|
257
|
+
TYPESAFE_API_KEY_ENV,
|
|
258
|
+
TYPESAFE_BASE_URL,
|
|
259
|
+
VorimTypeSafe,
|
|
260
|
+
answerMeetsConfidence,
|
|
261
|
+
choiceQuestion,
|
|
262
|
+
createTypeSafeFetchClient,
|
|
263
|
+
createVorimTypeSafe,
|
|
264
|
+
normaliseAnswers,
|
|
265
|
+
noulQuestion,
|
|
266
|
+
scoreQuestion
|
|
267
|
+
});
|
|
268
|
+
//# sourceMappingURL=typesafe.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/integrations/typesafe.ts","../../src/commit.ts"],"sourcesContent":["// ============================================================================\n// VORIM SDK — TypeSafe AI (Jev) Integration\n//\n// TypeSafe AI (https://typesafe.ai) ships Jev, a \"System One\" model: it does not\n// generate text. You hand it a `state` (a ticket, a transaction, a record) and a\n// map of typed questions, and it returns typed answers with calibrated\n// probabilities in roughly 100ms:\n//\n// noul -> { noul: 0..1 } is this true?\n// choice -> { choice, probabilities, confidence } pick an option\n// score -> { score, legend, probabilities, confidence } rate on a rubric\n//\n// Teams put Jev INSIDE agent control flow: route the payout, flag the claim,\n// decide whether a step needs a human. That makes each Jev call an agent\n// decision with consequences, and in a regulated setting three things have to\n// be true of such a decision: the agent that asked was allowed to, the decision\n// is attributable to that agent, and the confidence behind it is on the record.\n//\n// This module wraps a Jev call so that all three hold. Before the call it checks\n// the acting agent's Vorim scope (and, optionally, its trust floor). After the\n// call it turns Jev's calibrated confidence into a policy input: answers below\n// `minConfidence` are marked NOT actionable so your code escalates instead of\n// branching on a coin flip. Then it signs one audit event carrying the model\n// version, the question ids, every typed answer, its confidence, and SHA-256\n// digests of the state and the answers (never the raw state).\n//\n// It never holds your TypeSafe key unless you ask it to make the HTTP call for\n// you: pass the official `@typesafe-ai/sdk` client and it uses that.\n//\n// Usage:\n// import createVorim from '@vorim/sdk';\n// import { TypeSafeClient, choice, noul } from '@typesafe-ai/sdk';\n// import { createVorimTypeSafe } from '@vorim/sdk/integrations/typesafe';\n//\n// const vorim = createVorim({ apiKey: 'agid_sk_...' });\n// const jev = createVorimTypeSafe(vorim, {\n// agentId: 'agid_abc123',\n// client: new TypeSafeClient(), // reads TYPESAFE_API_KEY\n// minConfidence: 0.8, // below this, actionable = false\n// });\n//\n// const d = await jev.decide({\n// purpose: 'route-refund',\n// state: { ticket: 'I was charged twice. Please fix this ASAP.' },\n// questions: {\n// category: choice('What is this ticket about?', { billing: null, technical: null, other: null }),\n// urgent: noul('Does this convey urgency?'),\n// },\n// });\n// if (d.authorized && d.actionable) route(d.answers.category.choice);\n// else escalate(d.reason ?? d.lowConfidence);\n//\n// Peer dependency: @typesafe-ai/sdk (optional; a fetch-based fallback is built in).\n//\n// MODEL IDS ARE CONFIG. `jev-latest` is the stable alias TypeSafe documents; pin\n// a version (e.g. `jev-1.13.0`) when you need reproducible decisions.\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport { hashPayload } from '../commit.js';\n\n/** TypeSafe System One REST endpoint base. */\nexport const TYPESAFE_BASE_URL = 'https://api.typesafe.ai/v1';\n/** Stable model alias TypeSafe documents. Override or pin a version freely. */\nexport const DEFAULT_TYPESAFE_MODEL = 'jev-latest';\n/** The environment variable the official TypeSafe SDK reads. */\nexport const TYPESAFE_API_KEY_ENV = 'TYPESAFE_API_KEY';\n\nexport type TypeSafeQuestionType = 'noul' | 'choice' | 'score';\n\n/** A question in TypeSafe's REST shape. The official SDK helpers produce these too. */\nexport interface TypeSafeQuestion {\n type: TypeSafeQuestionType;\n instructions: string;\n /** choice: option -> description (or null); score: ordered level descriptions; noul: optional true/false criteria. */\n criteria?: Record<string, unknown> | unknown[];\n}\n\n/** One typed answer from Jev. Fields present depend on `type`. */\nexport interface TypeSafeAnswer {\n type: TypeSafeQuestionType;\n noul?: number;\n choice?: string;\n score?: number;\n probabilities?: Record<string, number>;\n confidence?: number;\n legend?: Record<string, unknown>;\n}\n\nexport interface TypeSafeSystemOneRequest {\n state: unknown;\n questions: Record<string, TypeSafeQuestion | unknown>;\n model?: string;\n}\n\nexport interface TypeSafeSystemOneResponse {\n model?: string;\n answers: Record<string, TypeSafeAnswer>;\n usage?: { input_tokens?: number; output_tokens?: number };\n}\n\n/**\n * Minimal shape of the official `@typesafe-ai/sdk` client (we only call\n * `systemOne`). Declared here so the SDK stays a peer dependency.\n */\nexport interface TypeSafeSystemOneClient {\n systemOne: (req: TypeSafeSystemOneRequest) => Promise<TypeSafeSystemOneResponse | any>;\n}\n\n/* Plain-object question builders for the fetch-based path (or when you do not\n want to import the TypeSafe SDK just to build questions). */\nexport function noulQuestion(instructions: string, criteria?: Record<string, unknown>): TypeSafeQuestion {\n return criteria ? { type: 'noul', instructions, criteria } : { type: 'noul', instructions };\n}\nexport function choiceQuestion(instructions: string, criteria: Record<string, unknown>): TypeSafeQuestion {\n return { type: 'choice', instructions, criteria };\n}\nexport function scoreQuestion(instructions: string, levels: string[]): TypeSafeQuestion {\n return { type: 'score', instructions, criteria: levels };\n}\n\nexport interface TypeSafeGuardConfig {\n /** The acting agent (the one asking Jev for a decision). */\n agentId: string;\n /** Official TypeSafe client. If omitted, a fetch-based client is built from `apiKey`. */\n client?: TypeSafeSystemOneClient;\n /** TypeSafe API key for the built-in client. Falls back to TYPESAFE_API_KEY. */\n apiKey?: string;\n /** REST base for the built-in client. @default TYPESAFE_BASE_URL */\n baseUrl?: string;\n /** Default model id. @default DEFAULT_TYPESAFE_MODEL */\n model?: string;\n /**\n * Confidence floor, 0..1. choice/score answers below it, and noul answers\n * whose max(p, 1-p) is below it, are reported as NOT actionable. Default 0\n * (everything actionable; you still get every confidence on the record).\n */\n minConfidence?: number;\n /** Optional agent trust floor (0..100). Unset = not checked. */\n minTrustScore?: number;\n /** Vorim scope the agent must hold to ask for a decision. @default 'agent:execute' */\n requiredScope?: string;\n /** Per-request timeout for the built-in client, ms. @default 30000 */\n timeoutMs?: number;\n /** Injectable fetch (tests). Defaults to global fetch. */\n fetchImpl?: typeof fetch;\n}\n\nexport interface TypeSafeDecideInput {\n /** What this decision is for, e.g. 'route-refund'. Goes on the audit record. */\n purpose: string;\n state: unknown;\n questions: Record<string, TypeSafeQuestion | unknown>;\n model?: string;\n minConfidence?: number;\n /** Optional resource label for the audit event (e.g. a ticket or claim id). */\n resource?: string;\n}\n\nexport interface TypeSafeDecision {\n /** The agent held the scope (and cleared the trust floor); Jev was called. */\n authorized: boolean;\n /** Every answer met the confidence floor. Branch on this, not on `authorized` alone. */\n actionable: boolean;\n /** Question ids whose answer fell below the confidence floor. */\n lowConfidence: string[];\n answers: Record<string, TypeSafeAnswer>;\n model?: string;\n usage?: { input_tokens?: number; output_tokens?: number };\n /** Set when not authorized, when Jev errored, or when confidence fell short. */\n reason?: string;\n /** The signed audit event was accepted. */\n recorded: boolean;\n /** sha256:<hex> of the canonical state JSON, as written to the audit record. */\n stateHash?: string;\n /** sha256:<hex> of the canonical answers JSON. */\n answersHash?: string;\n latencyMs: number;\n}\n\n/** Is a single answer confident enough to act on? */\nexport function answerMeetsConfidence(answer: TypeSafeAnswer, minConfidence: number): boolean {\n if (minConfidence <= 0) return true;\n if (answer.type === 'noul') {\n const p = typeof answer.noul === 'number' ? answer.noul : 0.5;\n return Math.max(p, 1 - p) >= minConfidence;\n }\n const c = typeof answer.confidence === 'number' ? answer.confidence : 0;\n return c >= minConfidence;\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;\n const keys = Object.keys(value as Record<string, unknown>).sort();\n return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify((value as any)[k])}`).join(',')}}`;\n}\n\n/** Build a minimal System One client over fetch, for when the official SDK is not installed. */\nexport function createTypeSafeFetchClient(opts: {\n apiKey?: string;\n baseUrl?: string;\n timeoutMs?: number;\n fetchImpl?: typeof fetch;\n}): TypeSafeSystemOneClient {\n const baseUrl = (opts.baseUrl ?? TYPESAFE_BASE_URL).replace(/\\/$/, '');\n const timeoutMs = opts.timeoutMs ?? 30_000;\n const doFetch = opts.fetchImpl ?? fetch;\n return {\n async systemOne(req) {\n const apiKey = opts.apiKey\n ?? (typeof process !== 'undefined' ? process.env?.[TYPESAFE_API_KEY_ENV] : undefined);\n if (!apiKey) throw new Error(`[vorim] TypeSafe: no API key. Pass apiKey or set ${TYPESAFE_API_KEY_ENV}.`);\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const res = await doFetch(`${baseUrl}/systemone`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', Accept: 'application/json' },\n body: JSON.stringify({ model: req.model ?? DEFAULT_TYPESAFE_MODEL, state: req.state, questions: req.questions }),\n redirect: 'error',\n signal: controller.signal,\n });\n if (!res.ok) throw new Error(`[vorim] TypeSafe: HTTP ${res.status}`);\n return await res.json();\n } finally {\n clearTimeout(timer);\n }\n },\n };\n}\n\nexport class VorimTypeSafe {\n private sdk: VorimSDK;\n private agentId: string;\n private client: TypeSafeSystemOneClient;\n private model: string;\n private minConfidence: number;\n private minTrustScore?: number;\n private requiredScope: string;\n\n constructor(sdk: VorimSDK, config: TypeSafeGuardConfig) {\n if (!config?.agentId) throw new Error('[vorim] TypeSafe integration requires an agentId.');\n this.sdk = sdk;\n this.agentId = config.agentId;\n this.client = config.client ?? createTypeSafeFetchClient({\n apiKey: config.apiKey, baseUrl: config.baseUrl, timeoutMs: config.timeoutMs, fetchImpl: config.fetchImpl,\n });\n this.model = config.model ?? DEFAULT_TYPESAFE_MODEL;\n this.minConfidence = config.minConfidence ?? 0;\n this.minTrustScore = config.minTrustScore;\n this.requiredScope = config.requiredScope ?? 'agent:execute';\n }\n\n /**\n * Ask Jev for a typed decision, under Vorim's authority check, and sign the\n * result. Never throws for a denial or a Jev error: read `authorized`,\n * `actionable` and `reason`.\n */\n async decide(input: TypeSafeDecideInput): Promise<TypeSafeDecision> {\n const started = Date.now();\n const model = input.model ?? this.model;\n const minConfidence = input.minConfidence ?? this.minConfidence;\n const questionIds = Object.keys(input.questions ?? {});\n const stateHash = await hashPayload(stableStringify(input.state));\n\n const base = { answers: {} as Record<string, TypeSafeAnswer>, lowConfidence: [] as string[], model, stateHash };\n const finish = async (\n partial: Omit<TypeSafeDecision, 'recorded' | 'latencyMs' | 'stateHash' | 'answers' | 'lowConfidence' | 'model'> & Partial<TypeSafeDecision>,\n result: 'success' | 'denied' | 'error',\n meta: Record<string, unknown>,\n ): Promise<TypeSafeDecision> => {\n const latencyMs = Date.now() - started;\n const recorded = await this.record(input, result, latencyMs, {\n model, question_ids: questionIds, min_confidence: minConfidence, ...meta,\n }, stateHash, partial.answersHash);\n return { ...base, ...partial, recorded, latencyMs };\n };\n\n // 1. Authority: the agent may ask for this decision.\n try {\n const perm = await this.sdk.check(this.agentId, this.requiredScope as any);\n if (!(perm as any).allowed) {\n return finish({ authorized: false, actionable: false, reason: (perm as any).reason ?? `Agent lacks ${this.requiredScope}` }, 'denied', { denial: 'scope' });\n }\n } catch (e: any) {\n return finish({ authorized: false, actionable: false, reason: `Permission check failed: ${e?.message ?? e}` }, 'error', { denial: 'check_error' });\n }\n if (this.minTrustScore !== undefined) {\n let score = 0;\n try { score = (await this.sdk.verify(this.agentId) as any).trust_score ?? 0; } catch { /* treated as 0 */ }\n if (score < this.minTrustScore) {\n return finish({ authorized: false, actionable: false, reason: `Agent trust score ${score} below ${this.minTrustScore}` }, 'denied', { denial: 'trust', trust_score: score });\n }\n }\n\n // 2. The decision itself.\n let res: TypeSafeSystemOneResponse;\n try {\n res = await this.client.systemOne({ state: input.state, questions: input.questions, model });\n } catch (e: any) {\n return finish({ authorized: true, actionable: false, reason: `TypeSafe call failed: ${e?.message ?? e}` }, 'error', { error: String(e?.message ?? e) });\n }\n const answers = normaliseAnswers(res);\n const answersHash = await hashPayload(stableStringify(answers));\n\n // 3. Calibrated confidence becomes policy.\n const lowConfidence = Object.entries(answers)\n .filter(([, a]) => !answerMeetsConfidence(a, minConfidence))\n .map(([id]) => id);\n const actionable = lowConfidence.length === 0;\n\n return finish({\n authorized: true,\n actionable,\n answers,\n lowConfidence,\n model: res?.model ?? model,\n usage: res?.usage,\n answersHash,\n reason: actionable ? undefined : `Confidence below ${minConfidence} for: ${lowConfidence.join(', ')}`,\n }, 'success', {\n model_version: res?.model ?? model,\n actionable,\n low_confidence: lowConfidence,\n answers: summariseAnswers(answers),\n usage: res?.usage,\n });\n }\n\n private async record(\n input: TypeSafeDecideInput,\n result: 'success' | 'denied' | 'error',\n latencyMs: number,\n metadata: Record<string, unknown>,\n stateHash: string,\n answersHash?: string,\n ): Promise<boolean> {\n try {\n const r = await this.sdk.emit({\n agent_id: this.agentId,\n event_type: 'api_request',\n action: `typesafe:systemone:${input.purpose}`,\n resource: input.resource ?? input.purpose,\n result,\n latency_ms: latencyMs,\n input_hash: stateHash,\n ...(answersHash ? { output_hash: answersHash } : {}),\n permission: this.requiredScope as any,\n metadata: { integration: 'typesafe', provider: 'typesafe', purpose: input.purpose, ...metadata },\n }, { sign: true });\n return (r?.ingested ?? 0) > 0;\n } catch {\n return false; // never block the decision on an audit hiccup\n }\n }\n}\n\n/** Accept the REST shape or an official-SDK response object and return `answers`. */\nexport function normaliseAnswers(res: any): Record<string, TypeSafeAnswer> {\n if (!res) return {};\n if (res.answers && typeof res.answers === 'object') return res.answers as Record<string, TypeSafeAnswer>;\n // Typed containers (Python-SDK style): merge nouls / choices / scores.\n const out: Record<string, TypeSafeAnswer> = {};\n for (const [bucket, type] of [['nouls', 'noul'], ['choices', 'choice'], ['scores', 'score']] as const) {\n const m = res[bucket];\n if (m && typeof m === 'object') for (const [id, a] of Object.entries(m as Record<string, any>)) out[id] = { type, ...(a ?? {}) };\n }\n return out;\n}\n\n/** Compact per-answer summary for the audit record: type, decision, confidence. */\nfunction summariseAnswers(answers: Record<string, TypeSafeAnswer>): Record<string, Record<string, unknown>> {\n const out: Record<string, Record<string, unknown>> = {};\n for (const [id, a] of Object.entries(answers)) {\n out[id] = {\n type: a.type,\n ...(a.type === 'noul' ? { noul: a.noul } : {}),\n ...(a.type === 'choice' ? { choice: a.choice, confidence: a.confidence } : {}),\n ...(a.type === 'score' ? { score: a.score, confidence: a.confidence } : {}),\n };\n }\n return out;\n}\n\n/**\n * Create a VorimTypeSafe guard: Jev decisions under Vorim authority, with\n * confidence as a policy input and a signed record of each decision.\n */\nexport function createVorimTypeSafe(sdk: VorimSDK, config: TypeSafeGuardConfig): VorimTypeSafe {\n return new VorimTypeSafe(sdk, config);\n}\n","// ============================================================================\n// VORIM — Payload commitments\n//\n// WHY THIS EXISTS. `input_hash` and `output_hash` have always let a caller\n// send a digest instead of a prompt, so agent content never had to reach\n// Vorim. The digest format was a bare `sha256:<hex>`, and a bare SHA-256 of a\n// prompt is not a commitment — it is a lookup key. Prompts are low-entropy\n// and usually templated: given the digest and the template, an attacker (or\n// Vorim, or anyone who obtains an export) recovers the content by trying\n// candidates until a hash matches. Nothing about that is exotic; it is the\n// same reason unsalted password hashes fail.\n//\n// So \"we never see your prompts\" was true of the wire and false of the maths.\n// These helpers close that gap.\n//\n// WHAT TO USE. `commitPayload(content, key)` produces `hmac-sha256:<hex>`\n// under a key you hold and never send us. Without the key the digest is\n// unlinkable to any candidate content, so an exported bundle discloses that\n// an action happened and nothing about what was in it. You can still prove\n// the link later, to an auditor or a counterparty, by revealing the content\n// and the key and letting them recompute.\n//\n// `hashPayload` remains available and remains a bare SHA-256. It is correct\n// for content that is already high-entropy (a file digest, a random id) and\n// wrong for anything a person wrote. It is not deprecated, it is narrower\n// than it looks.\n//\n// FORMAT. Digests are `<alg>:<hex>` and the algorithm label travels with the\n// value, so a verifier reading a bundle years from now can tell a keyed\n// commitment from a bare hash without being told out of band, and a future\n// algorithm can be added without a migration.\n// ============================================================================\n\n/** Prefix used for keyed commitments. */\nexport const HMAC_SHA256_PREFIX = 'hmac-sha256:';\n/** Prefix used for bare digests. */\nexport const SHA256_PREFIX = 'sha256:';\n\n/**\n * Key material for a payload commitment. Never transmitted by the SDK.\n *\n * A string is UTF-8 encoded. Prefer at least 32 bytes from a CSPRNG, held\n * wherever you already hold secrets. One key per org is fine; one per agent\n * or per tenant narrows what a single leaked key exposes.\n */\nexport type CommitmentKey = string | Uint8Array;\n\nfunction toBytes(v: string | Uint8Array): Uint8Array {\n return typeof v === 'string' ? new TextEncoder().encode(v) : v;\n}\n\nfunction toHex(buf: ArrayBuffer | Uint8Array): string {\n return Array.from(buf instanceof Uint8Array ? buf : new Uint8Array(buf))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * Bare SHA-256 digest of `content`, as `sha256:<hex>`.\n *\n * Correct only when `content` has enough entropy that guessing it is\n * infeasible. For prompts, responses, tool arguments or anything else a\n * human or a model wrote, use {@link commitPayload} instead.\n */\nexport async function hashPayload(content: string | Uint8Array): Promise<string> {\n const bytes = toBytes(content);\n const subtle = (globalThis as any).crypto?.subtle;\n if (subtle) {\n return SHA256_PREFIX + toHex(await subtle.digest('SHA-256', bytes));\n }\n const nodeCrypto = await import('node:crypto');\n return SHA256_PREFIX + nodeCrypto.createHash('sha256').update(bytes).digest('hex');\n}\n\n/**\n * Keyed commitment to `content`, as `hmac-sha256:<hex>`.\n *\n * `key` never leaves this process. Vorim stores and signs over the digest\n * with no way to test a candidate plaintext against it.\n *\n * To disclose later, hand the verifier the content and the key; they\n * recompute and compare. Disclosure is per-key, so a key scoped to one agent\n * or one tenant lets you open that subset without opening the rest.\n *\n * Rotating the key does not invalidate past events. Old digests stay\n * verifiable under the old key, which is why the key you used has to be\n * retained for as long as you might need to prove the events it covers.\n */\nexport async function commitPayload(\n content: string | Uint8Array,\n key: CommitmentKey,\n): Promise<string> {\n const keyBytes = toBytes(key);\n if (keyBytes.length === 0) {\n // An empty key is an HMAC with a known key, which is a bare hash wearing\n // a different prefix. Fail rather than emit something that looks keyed.\n throw new Error(\n 'commitPayload: key must not be empty. An empty key makes the commitment ' +\n 'no stronger than hashPayload while labelling it as keyed.',\n );\n }\n const bytes = toBytes(content);\n\n const subtle = (globalThis as any).crypto?.subtle;\n if (subtle) {\n const cryptoKey = await subtle.importKey(\n 'raw',\n keyBytes,\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n const sig = await subtle.sign('HMAC', cryptoKey, bytes);\n return HMAC_SHA256_PREFIX + toHex(sig);\n }\n\n const nodeCrypto = await import('node:crypto');\n return HMAC_SHA256_PREFIX + nodeCrypto.createHmac('sha256', keyBytes).update(bytes).digest('hex');\n}\n\n/**\n * True when `digest` is a keyed commitment rather than a bare hash.\n *\n * Useful in a review or an export check: a bundle whose `input_hash` values\n * are all `sha256:` carries content that a determined reader may be able to\n * recover, and that is worth knowing before the bundle leaves the building.\n */\nexport function isKeyedCommitment(digest: unknown): boolean {\n return typeof digest === 'string' && digest.startsWith(HMAC_SHA256_PREFIX);\n}\n\n/** Shape of any digest this SDK will put in a hash field. */\nconst DIGEST_RE = /^(?:sha256|hmac-sha256):[0-9a-f]{64}$/;\n\n/**\n * True when `digest` is a well-formed `<alg>:<64 hex>` value in a form the\n * server and `@vorim/verify` both understand.\n */\nexport function isDigest(digest: unknown): boolean {\n return typeof digest === 'string' && DIGEST_RE.test(digest);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoCO,IAAM,gBAAgB;AAW7B,SAAS,QAAQ,GAAoC;AACnD,SAAO,OAAO,MAAM,WAAW,IAAI,YAAY,EAAE,OAAO,CAAC,IAAI;AAC/D;AAEA,SAAS,MAAM,KAAuC;AACpD,SAAO,MAAM,KAAK,eAAe,aAAa,MAAM,IAAI,WAAW,GAAG,CAAC,EACpE,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GA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