@belticlabs/agent-risk-sdk 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- import { b as JsonValue, E as EvidenceSourceAll } from '../verdict-CDAsxktI.js';
2
- export { A as ALL_SOURCES, c as ANOMALY_TYPES, d as Amount, e as AmountSchema, f as ApiError, g as ApiErrorSchema, C as ChainHead, h as ChainHeadSchema, i as CreatePolicyInput, j as CreatePolicyInputSchema, k as CreatePolicyOutput, l as CreatePolicyOutputSchema, m as CreateSessionInput, n as CreateSessionInputSchema, o as CreateSessionOutput, p as CreateSessionOutputSchema, D as Decision, q as DecisionSchema, r as DeclaredIntent, s as DeclaredIntentSchema, t as DigestedEnvelope, u as EvaluateInput, v as EvaluateInputSchema, w as EvaluateOutput, x as EvaluateOutputSchema, y as EventResult, z as EventResultSchema, B as EventResultStatus, F as EventResultStatusSchema, G as EvidenceAck, H as EvidenceAckSchema, I as EvidenceBatchInput, K as EvidenceBatchInputSchema, L as EvidenceEnvelope, M as EvidenceEvent, N as EvidenceEventSchema, O as EvidenceKind, Q as EvidenceKindSchema, R as EvidenceSource, S as EvidenceSourceAllSchema, T as EvidenceSourceSchema, U as GatewayDecisionPayload, V as GatewayDecisionPayloadSchema, W as Hex64, X as Hex64Schema, Y as IntentDeclaredPayload, Z as IntentDeclaredPayloadSchema, J as JsonObject, _ as JsonValueSchema, $ as LlmCallEndPayload, a0 as LlmCallEndPayloadSchema, a1 as LlmCallStartPayload, a2 as LlmCallStartPayloadSchema, a3 as MAX_BATCH_EVENTS, a4 as OnReview, a5 as PAYMENT_ARTIFACTS, a6 as PLATFORM_KINDS, a7 as PayloadByKind, P as PaymentMomentPayload, a8 as PaymentMomentPayloadSchema, a as PaymentSummary, a9 as PaymentSummarySchema, aa as PlatformAnomalyPayload, ab as PlatformAnomalyPayloadSchema, ac as PlatformEvidenceKind, ad as PlatformEvidenceKindSchema, ae as PlatformObservationPayload, af as PlatformObservationPayloadSchema, ag as SESSION_CLOSE_REASONS, ah as SOURCE_ORDER, ai as SeqSchema, aj as SessionClosePayload, ak as SessionClosePayloadSchema, al as SessionIdSchema, am as SessionOpenPayload, an as SessionOpenPayloadSchema, ao as Sig, ap as SigSchema, aq as TimestampSchema, ar as ToolCallEndPayload, as as ToolCallEndPayloadSchema, at as ToolCallStartPayload, au as ToolCallStartPayloadSchema, av as TransportGapPayload, aw as TransportGapPayloadSchema, ax as Verdict, ay as WIRE_KINDS, az as WIRE_SOURCES, aA as WireEvidenceKind, aB as WireEvidenceKindSchema, aC as compareBySessionSource, aD as compareBySourceSeq, aE as isPlatformKind, aF as isWireKind, aG as payloadSchemaFor } from '../verdict-CDAsxktI.js';
1
+ import { J as JsonValue, E as EvidenceSourceAll, D as Decision } from '../index-IfY4XCvJ.js';
2
+ export { A as ALL_SOURCES, a as ANOMALY_TYPES, b as Amount, c as AmountSchema, d as ApiError, e as ApiErrorSchema, C as ChainHead, f as ChainHeadSchema, g as CreatePolicyInput, h as CreatePolicyInputSchema, i as CreatePolicyOutput, j as CreatePolicyOutputSchema, k as CreateSessionInput, l as CreateSessionInputSchema, m as CreateSessionOutput, n as CreateSessionOutputSchema, o as DecisionSchema, p as DeclaredIntent, q as DeclaredIntentSchema, r as DigestedEnvelope, s as EvaluateInput, t as EvaluateInputSchema, u as EvaluateOutput, v as EvaluateOutputSchema, w as EventResult, x as EventResultSchema, y as EventResultStatus, z as EventResultStatusSchema, B as EvidenceAck, F as EvidenceAckSchema, G as EvidenceBatchInput, H as EvidenceBatchInputSchema, I as EvidenceEnvelope, K as EvidenceEvent, L as EvidenceEventSchema, M as EvidenceKind, N as EvidenceKindSchema, O as EvidenceSource, P as EvidenceSourceAllSchema, Q as EvidenceSourceSchema, R as GatewayDecisionPayload, S as GatewayDecisionPayloadSchema, T as Hex64, U as Hex64Schema, V as IntentDeclaredPayload, W as IntentDeclaredPayloadSchema, X as JsonObject, Y as JsonValueSchema, Z as LlmCallEndPayload, _ as LlmCallEndPayloadSchema, $ as LlmCallStartPayload, a0 as LlmCallStartPayloadSchema, a1 as MAX_BATCH_EVENTS, a2 as PAYMENT_ARTIFACTS, a3 as PLATFORM_KINDS, a4 as PayloadByKind, a5 as PaymentMomentPayload, a6 as PaymentMomentPayloadSchema, a7 as PaymentSummary, a8 as PaymentSummarySchema, a9 as PlatformAnomalyPayload, aa as PlatformAnomalyPayloadSchema, ab as PlatformEvidenceKind, ac as PlatformEvidenceKindSchema, ad as PlatformObservationPayload, ae as PlatformObservationPayloadSchema, af as SESSION_CLOSE_REASONS, ag as SOURCE_ORDER, ah as SeqSchema, ai as SessionClosePayload, aj as SessionClosePayloadSchema, ak as SessionIdSchema, al as SessionOpenPayload, am as SessionOpenPayloadSchema, an as Sig, ao as SigSchema, ap as TimestampSchema, aq as ToolCallEndPayload, ar as ToolCallEndPayloadSchema, as as ToolCallStartPayload, at as ToolCallStartPayloadSchema, au as TransportGapPayload, av as TransportGapPayloadSchema, aw as WIRE_KINDS, ax as WIRE_SOURCES, ay as WireEvidenceKind, az as WireEvidenceKindSchema, aA as compareBySessionSource, aB as compareBySourceSeq, aC as isPlatformKind, aD as isWireKind, aE as payloadSchemaFor } from '../index-IfY4XCvJ.js';
3
3
  import { z } from 'zod';
4
4
 
5
5
  declare const PRIMITIVES: readonly ["THRESHOLD", "MEMBERSHIP", "MATCH", "PRESENCE", "FRESHNESS"];
@@ -154,4 +154,27 @@ declare function parseSelectorRef(ref: string): Selector;
154
154
  declare function walkPath(value: unknown, path: readonly PathSegment[]): unknown;
155
155
  declare const SelectorStringSchema: z.ZodString;
156
156
 
157
- export { ANNOTATION_CODES, type AnnotationCode, COLLECTOR_CODES, type CollectorCode, DEFAULT_RULE_CODES, type DefaultRuleCode, EvidenceSourceAll, INDICATOR_CODES, type IndicatorCode, JsonValue, PRIMITIVES, type PathSegment, type PolicyRules, PolicyRulesSchema, type Primitive, PrimitiveSchema, REASON_CODE_PATTERN, type ReasonCode, type Rule, RuleSchema, type RuleVerdict, RuleVerdictSchema, type Selector, SelectorStringSchema, SelectorSyntaxError, formatSelector, isSelectorRef, parseSelector, parseSelectorRef, walkPath };
157
+ /**
158
+ * The verdict as a value (Fraud Engine RFC › API: ALLOW | DENY | REVIEW).
159
+ * Layers combine by severity (GAP-45); a synchronous seller hook turns
160
+ * REVIEW into a stop or a pass according to its `onReview` (GAP-52). Both
161
+ * halves of the SDK and the engine share this one rule.
162
+ */
163
+
164
+ type OnReview = 'abort' | 'allow';
165
+ declare class Verdict {
166
+ readonly value: Decision;
167
+ private constructor();
168
+ static readonly ALLOW: Verdict;
169
+ static readonly REVIEW: Verdict;
170
+ static readonly DENY: Verdict;
171
+ static of(value: Decision): Verdict;
172
+ /** The more severe of the two. */
173
+ atLeast(other: Verdict | Decision): Verdict;
174
+ /** Whether a synchronous gate must stop the call (GAP-52). */
175
+ blocks(onReview: OnReview): boolean;
176
+ /** What the gate effectively did: DENY when it blocked, else the verdict itself. */
177
+ effective(onReview: OnReview): Decision;
178
+ }
179
+
180
+ export { ANNOTATION_CODES, type AnnotationCode, COLLECTOR_CODES, type CollectorCode, DEFAULT_RULE_CODES, Decision, type DefaultRuleCode, EvidenceSourceAll, INDICATOR_CODES, type IndicatorCode, JsonValue, type OnReview, PRIMITIVES, type PathSegment, type PolicyRules, PolicyRulesSchema, type Primitive, PrimitiveSchema, REASON_CODE_PATTERN, type ReasonCode, type Rule, RuleSchema, type RuleVerdict, RuleVerdictSchema, type Selector, SelectorStringSchema, SelectorSyntaxError, Verdict, formatSelector, isSelectorRef, parseSelector, parseSelectorRef, walkPath };
@@ -1,77 +1,490 @@
1
- import {
2
- ALL_SOURCES,
3
- ANNOTATION_CODES,
4
- ANOMALY_TYPES,
5
- AmountSchema,
6
- ApiErrorSchema,
7
- COLLECTOR_CODES,
8
- ChainHeadSchema,
9
- CreatePolicyInputSchema,
10
- CreatePolicyOutputSchema,
11
- CreateSessionInputSchema,
12
- CreateSessionOutputSchema,
13
- DEFAULT_RULE_CODES,
14
- DecisionSchema,
15
- DeclaredIntentSchema,
16
- EvaluateInputSchema,
17
- EvaluateOutputSchema,
18
- EventResultSchema,
19
- EventResultStatusSchema,
20
- EvidenceAckSchema,
21
- EvidenceBatchInputSchema,
22
- EvidenceEventSchema,
23
- EvidenceKindSchema,
24
- EvidenceSourceAllSchema,
25
- EvidenceSourceSchema,
26
- GatewayDecisionPayloadSchema,
27
- Hex64Schema,
28
- INDICATOR_CODES,
29
- IntentDeclaredPayloadSchema,
30
- JsonValueSchema,
31
- LlmCallEndPayloadSchema,
32
- LlmCallStartPayloadSchema,
33
- MAX_BATCH_EVENTS,
34
- PAYMENT_ARTIFACTS,
35
- PLATFORM_KINDS,
36
- PRIMITIVES,
37
- PaymentMomentPayloadSchema,
38
- PaymentSummarySchema,
39
- PlatformAnomalyPayloadSchema,
40
- PlatformEvidenceKindSchema,
41
- PlatformObservationPayloadSchema,
42
- PolicyRulesSchema,
43
- PrimitiveSchema,
44
- REASON_CODE_PATTERN,
45
- RuleSchema,
46
- RuleVerdictSchema,
47
- SESSION_CLOSE_REASONS,
48
- SOURCE_ORDER,
49
- SelectorStringSchema,
50
- SelectorSyntaxError,
51
- SeqSchema,
52
- SessionClosePayloadSchema,
53
- SessionIdSchema,
54
- SessionOpenPayloadSchema,
55
- SigSchema,
56
- TimestampSchema,
57
- ToolCallEndPayloadSchema,
58
- ToolCallStartPayloadSchema,
59
- TransportGapPayloadSchema,
60
- Verdict,
61
- WIRE_KINDS,
62
- WIRE_SOURCES,
63
- WireEvidenceKindSchema,
64
- compareBySessionSource,
65
- compareBySourceSeq,
66
- formatSelector,
67
- isPlatformKind,
68
- isSelectorRef,
69
- isWireKind,
70
- parseSelector,
71
- parseSelectorRef,
72
- payloadSchemaFor,
73
- walkPath
74
- } from "../chunk-4BUUPU3O.js";
1
+ // ../protocol/src/api.ts
2
+ import { z as z4 } from "zod";
3
+
4
+ // ../protocol/src/evidence.ts
5
+ import { z } from "zod";
6
+ var WIRE_SOURCES = ["AGENT_TRACE", "INTERNAL_NETWORK"];
7
+ var ALL_SOURCES = ["AGENT_TRACE", "INTERNAL_NETWORK", "PLATFORM"];
8
+ var EvidenceSourceSchema = z.enum(WIRE_SOURCES);
9
+ var EvidenceSourceAllSchema = z.enum(ALL_SOURCES);
10
+ var SOURCE_ORDER = {
11
+ AGENT_TRACE: 0,
12
+ INTERNAL_NETWORK: 1,
13
+ PLATFORM: 2
14
+ };
15
+ function compareBySourceSeq(a, b) {
16
+ return SOURCE_ORDER[a.source] - SOURCE_ORDER[b.source] || a.seq - b.seq;
17
+ }
18
+ function compareBySessionSource(a, b) {
19
+ return a.sessionId < b.sessionId ? -1 : a.sessionId > b.sessionId ? 1 : SOURCE_ORDER[a.source] - SOURCE_ORDER[b.source];
20
+ }
21
+ var WIRE_KINDS = [
22
+ "session.open",
23
+ "session.close",
24
+ "intent.declared",
25
+ "llm_call.start",
26
+ "llm_call.end",
27
+ "tool_call.start",
28
+ "tool_call.end",
29
+ "payment.requested",
30
+ "payment.presented",
31
+ "gateway.decision",
32
+ "transport.gap"
33
+ ];
34
+ var PLATFORM_KINDS = ["platform.observation", "platform.anomaly"];
35
+ var WireEvidenceKindSchema = z.enum(WIRE_KINDS);
36
+ var PlatformEvidenceKindSchema = z.enum(PLATFORM_KINDS);
37
+ var EvidenceKindSchema = z.enum([...WIRE_KINDS, ...PLATFORM_KINDS]);
38
+ var Hex64Schema = z.string().regex(/^[0-9a-f]{64}$/, "expected 64 lowercase hex chars");
39
+ var SigSchema = z.string().regex(/^ed25519:[A-Za-z0-9_-]{86}$/, "expected ed25519:<base64url>");
40
+ var SessionIdSchema = z.uuid();
41
+ var SeqSchema = z.number().int().min(0);
42
+ var TimestampSchema = z.iso.datetime({ offset: false });
43
+ var JsonValueSchema = z.lazy(
44
+ () => z.union([
45
+ z.null(),
46
+ z.boolean(),
47
+ z.number().finite(),
48
+ z.string(),
49
+ z.array(JsonValueSchema),
50
+ z.record(z.string(), JsonValueSchema)
51
+ ])
52
+ );
53
+ var EvidenceEventSchema = z.strictObject({
54
+ sessionId: SessionIdSchema,
55
+ source: EvidenceSourceSchema,
56
+ seq: SeqSchema,
57
+ ts: TimestampSchema,
58
+ kind: WireEvidenceKindSchema,
59
+ payload: z.record(z.string(), JsonValueSchema),
60
+ prevHash: Hex64Schema,
61
+ sig: SigSchema.optional()
62
+ });
63
+ function isWireKind(kind) {
64
+ return WIRE_KINDS.includes(kind);
65
+ }
66
+ function isPlatformKind(kind) {
67
+ return PLATFORM_KINDS.includes(kind);
68
+ }
69
+
70
+ // ../protocol/src/policy.ts
71
+ import { z as z3 } from "zod";
72
+
73
+ // ../protocol/src/reason-codes.ts
74
+ var INDICATOR_CODES = [
75
+ "CHAIN_BROKEN",
76
+ "EVIDENCE_MISMATCH",
77
+ "CREDENTIAL_REVOKED",
78
+ "SESSION_INVALID",
79
+ "PRINCIPAL_FLAGGED"
80
+ ];
81
+ var ANNOTATION_CODES = ["NO_AGENT_TRACE", "NO_POLICY"];
82
+ var COLLECTOR_CODES = [
83
+ "SCHEMA_INVALID",
84
+ "SESSION_UNKNOWN",
85
+ "SESSION_CLOSED",
86
+ "SESSION_EXPIRED",
87
+ "SOURCE_FORBIDDEN",
88
+ "KIND_FORBIDDEN",
89
+ "SEQ_GAP",
90
+ "PREV_HASH_MISMATCH",
91
+ "SIG_MISSING",
92
+ "SIG_INVALID",
93
+ "PAYLOAD_INVALID",
94
+ "EVENT_TOO_LARGE"
95
+ ];
96
+ var DEFAULT_RULE_CODES = [
97
+ "CAP_EXCEEDED",
98
+ "PAYEE_NOT_ALLOWED",
99
+ "NO_INTENT",
100
+ "INTENT_EXPIRED"
101
+ ];
102
+ var REASON_CODE_PATTERN = /^[A-Z][A-Z0-9_]{1,63}$/;
103
+
104
+ // ../protocol/src/selector.ts
105
+ import { z as z2 } from "zod";
106
+ var SelectorSyntaxError = class extends Error {
107
+ constructor(input, at, detail) {
108
+ super(`invalid selector "${input}" at ${at}: ${detail}`);
109
+ this.input = input;
110
+ this.at = at;
111
+ this.name = "SelectorSyntaxError";
112
+ }
113
+ code = "SELECTOR_SYNTAX";
114
+ };
115
+ var IDENT = /^[A-Za-z_][A-Za-z0-9_-]*/;
116
+ var NAME = /^[A-Za-z_][A-Za-z0-9_.-]*/;
117
+ function parsePath(input, from) {
118
+ const path = [];
119
+ let i = from;
120
+ while (i < input.length) {
121
+ const ch = input[i];
122
+ if (ch === ".") {
123
+ const m = IDENT.exec(input.slice(i + 1));
124
+ if (!m) throw new SelectorSyntaxError(input, i + 1, 'expected identifier after "."');
125
+ path.push({ key: m[0] });
126
+ i += 1 + m[0].length;
127
+ } else if (ch === "[") {
128
+ const close = input.indexOf("]", i);
129
+ if (close < 0) throw new SelectorSyntaxError(input, i, 'unterminated "["');
130
+ const body = input.slice(i + 1, close);
131
+ if (!/^\d+$/.test(body))
132
+ throw new SelectorSyntaxError(input, i + 1, "expected integer index");
133
+ path.push({ index: Number(body) });
134
+ i = close + 1;
135
+ } else {
136
+ throw new SelectorSyntaxError(input, i, `unexpected "${ch}"`);
137
+ }
138
+ }
139
+ return { path, end: i };
140
+ }
141
+ function parseSelector(input) {
142
+ if (typeof input !== "string" || input.length === 0) {
143
+ throw new SelectorSyntaxError(String(input), 0, "empty selector");
144
+ }
145
+ if (input.length > 512)
146
+ throw new SelectorSyntaxError(input.slice(0, 32), 512, "selector too long");
147
+ for (const root of ["payment", "intent", "session"]) {
148
+ if (input === root || input.startsWith(`${root}.`) || input.startsWith(`${root}[`)) {
149
+ return { root, path: parsePath(input, root.length).path };
150
+ }
151
+ }
152
+ if (input.startsWith("signal[name=")) {
153
+ const rest = input.slice("signal[name=".length);
154
+ const m = NAME.exec(rest);
155
+ if (!m) throw new SelectorSyntaxError(input, "signal[name=".length, "expected signal name");
156
+ const after = "signal[name=".length + m[0].length;
157
+ if (input[after] !== "]") throw new SelectorSyntaxError(input, after, 'expected "]"');
158
+ return { root: "signal", name: m[0], path: parsePath(input, after + 1).path };
159
+ }
160
+ if (input === "evidence[*]" || input.startsWith("evidence[*]")) {
161
+ return {
162
+ root: "evidence",
163
+ kind: "*",
164
+ all: true,
165
+ path: parsePath(input, "evidence[*]".length).path
166
+ };
167
+ }
168
+ if (input.startsWith("evidence[kind=")) {
169
+ let i = "evidence[kind=".length;
170
+ const km = NAME.exec(input.slice(i));
171
+ if (!km) throw new SelectorSyntaxError(input, i, "expected evidence kind");
172
+ const kind = km[0];
173
+ i += kind.length;
174
+ let source;
175
+ if (input.startsWith(",source=", i)) {
176
+ i += ",source=".length;
177
+ const sm = /^[A-Z_]+/.exec(input.slice(i));
178
+ if (!sm || !ALL_SOURCES.includes(sm[0])) {
179
+ throw new SelectorSyntaxError(input, i, `expected one of ${ALL_SOURCES.join("|")}`);
180
+ }
181
+ source = sm[0];
182
+ i += sm[0].length;
183
+ }
184
+ if (input[i] !== "]") throw new SelectorSyntaxError(input, i, 'expected "]"');
185
+ i += 1;
186
+ let all = false;
187
+ if (input.startsWith("[*]", i)) {
188
+ all = true;
189
+ i += 3;
190
+ }
191
+ const sel = { root: "evidence", kind, all, path: parsePath(input, i).path };
192
+ if (source) sel.source = source;
193
+ return sel;
194
+ }
195
+ throw new SelectorSyntaxError(
196
+ input,
197
+ 0,
198
+ "unknown root (payment | intent | session | signal[name=\u2026] | evidence[\u2026])"
199
+ );
200
+ }
201
+ function formatSelector(sel) {
202
+ const path = sel.path.map((p) => "key" in p ? `.${p.key}` : `[${p.index}]`).join("");
203
+ switch (sel.root) {
204
+ case "payment":
205
+ case "intent":
206
+ case "session":
207
+ return `${sel.root}${path}`;
208
+ case "signal":
209
+ return `signal[name=${sel.name}]${path}`;
210
+ case "evidence":
211
+ if (sel.kind === "*") return `evidence[*]${path}`;
212
+ return `evidence[kind=${sel.kind}${sel.source ? `,source=${sel.source}` : ""}]${sel.all ? "[*]" : ""}${path}`;
213
+ }
214
+ }
215
+ function isSelectorRef(value) {
216
+ return typeof value === "string" && value.startsWith("@") && value.length > 1;
217
+ }
218
+ function parseSelectorRef(ref) {
219
+ return parseSelector(ref.slice(1));
220
+ }
221
+ function walkPath(value, path) {
222
+ let cur = value;
223
+ for (const seg of path) {
224
+ if (cur === null || cur === void 0) return void 0;
225
+ if ("key" in seg) {
226
+ if (typeof cur !== "object" || Array.isArray(cur)) return void 0;
227
+ cur = cur[seg.key];
228
+ } else {
229
+ if (!Array.isArray(cur)) return void 0;
230
+ cur = cur[seg.index];
231
+ }
232
+ }
233
+ return cur;
234
+ }
235
+ var SelectorStringSchema = z2.string().refine(
236
+ (s) => {
237
+ try {
238
+ parseSelector(s);
239
+ return true;
240
+ } catch {
241
+ return false;
242
+ }
243
+ },
244
+ { message: "invalid selector" }
245
+ );
246
+
247
+ // ../protocol/src/policy.ts
248
+ var PRIMITIVES = ["THRESHOLD", "MEMBERSHIP", "MATCH", "PRESENCE", "FRESHNESS"];
249
+ var PrimitiveSchema = z3.enum(PRIMITIVES);
250
+ var RuleVerdictSchema = z3.enum(["DENY", "REVIEW"]);
251
+ var RuleSchema = z3.strictObject({
252
+ id: z3.string().min(1).max(64),
253
+ primitive: PrimitiveSchema,
254
+ selector: SelectorStringSchema,
255
+ params: z3.record(z3.string(), JsonValueSchema),
256
+ onFail: RuleVerdictSchema,
257
+ /** What to do when the selector (or a `@ref`) resolves to nothing. Default: skip (GAP-44). */
258
+ onMissing: z3.enum(["skip", "DENY", "REVIEW"]).optional(),
259
+ /** Reason code surfaced to the caller when the rule fails (GAP-44). */
260
+ code: z3.string().regex(REASON_CODE_PATTERN)
261
+ });
262
+ var PolicyRulesSchema = z3.strictObject({
263
+ rules: z3.array(RuleSchema).max(200).refine((rules) => new Set(rules.map((r) => r.id)).size === rules.length, {
264
+ message: "rule ids must be unique"
265
+ }),
266
+ /** Domain-score thresholds — the only configurable part of the scores layer. */
267
+ scoreThresholds: z3.record(z3.string(), z3.number().min(0).max(1)).optional()
268
+ });
269
+
270
+ // ../protocol/src/api.ts
271
+ var AmountSchema = z4.strictObject({
272
+ /** Decimal string — never a float. For x402 this is the atomic amount (GAP-49). */
273
+ value: z4.string().regex(/^\d+(\.\d+)?$/, "expected a decimal string"),
274
+ /** ISO code, or `<network>/<asset>` for on-chain rails (GAP-49). */
275
+ currency: z4.string().min(1).max(128)
276
+ });
277
+ var DeclaredIntentSchema = z4.strictObject({
278
+ mandate: z4.string().min(1).max(4e3),
279
+ maxAmount: AmountSchema.optional(),
280
+ merchantAllowlist: z4.array(z4.string().min(1)).optional(),
281
+ validUntil: TimestampSchema
282
+ });
283
+ var CreateSessionInputSchema = z4.strictObject({
284
+ source: EvidenceSourceSchema,
285
+ /** Buyer-born sessions. `credential` is opaque this phase (GAP-11). */
286
+ agent: z4.strictObject({ did: z4.string().min(1), credential: z4.string().min(1) }).optional(),
287
+ intent: DeclaredIntentSchema.optional()
288
+ });
289
+ var CreateSessionOutputSchema = z4.strictObject({
290
+ sessionId: SessionIdSchema,
291
+ expiresAt: TimestampSchema
292
+ });
293
+ var MAX_BATCH_EVENTS = 500;
294
+ var EvidenceBatchInputSchema = z4.array(EvidenceEventSchema).min(1).max(MAX_BATCH_EVENTS);
295
+ var EventResultStatusSchema = z4.enum(["ok", "duplicate", "fork", "rejected"]);
296
+ var EventResultSchema = z4.strictObject({
297
+ index: z4.number().int().min(0),
298
+ sessionId: SessionIdSchema.nullable(),
299
+ source: EvidenceSourceSchema.nullable(),
300
+ seq: z4.number().int().min(0).nullable(),
301
+ status: EventResultStatusSchema,
302
+ code: z4.string().optional(),
303
+ eventDigest: Hex64Schema.optional()
304
+ });
305
+ var ChainHeadSchema = z4.strictObject({
306
+ seq: z4.number().int().min(0),
307
+ digest: Hex64Schema
308
+ });
309
+ var EvidenceAckSchema = z4.strictObject({
310
+ results: z4.array(EventResultSchema),
311
+ /** Head of every chain touched by the batch, after the batch. Keyed `sessionId:source`. */
312
+ heads: z4.record(z4.string(), ChainHeadSchema)
313
+ });
314
+ var PaymentSummarySchema = z4.strictObject({
315
+ protocol: z4.string().min(1),
316
+ payee: z4.string().min(1),
317
+ amount: AmountSchema,
318
+ /** Not in the RFC; needed by `principal-links` and `EVIDENCE_MISMATCH` (GAP-06). */
319
+ payer: z4.string().min(1).optional()
320
+ });
321
+ var EvaluateInputSchema = z4.strictObject({
322
+ sessionId: SessionIdSchema,
323
+ payment: PaymentSummarySchema
324
+ });
325
+ var DecisionSchema = z4.enum(["ALLOW", "DENY", "REVIEW"]);
326
+ var EvaluateOutputSchema = z4.strictObject({
327
+ decision: DecisionSchema,
328
+ reasonCodes: z4.array(z4.string().regex(REASON_CODE_PATTERN)),
329
+ sessionId: SessionIdSchema,
330
+ /** Additive (GAP-21). */
331
+ decisionId: z4.uuid()
332
+ });
333
+ var CreatePolicyInputSchema = z4.strictObject({ rules: PolicyRulesSchema });
334
+ var CreatePolicyOutputSchema = z4.strictObject({
335
+ policyId: z4.uuid(),
336
+ version: z4.number().int().min(1),
337
+ status: z4.enum(["ACTIVE", "SUPERSEDED", "DRAFT"])
338
+ });
339
+ var ApiErrorSchema = z4.strictObject({
340
+ error: z4.strictObject({
341
+ code: z4.string().min(1),
342
+ message: z4.string().min(1),
343
+ details: JsonValueSchema.optional(),
344
+ request_id: z4.string().optional()
345
+ })
346
+ });
347
+
348
+ // ../protocol/src/payloads/index.ts
349
+ import { z as z5 } from "zod";
350
+ var Json = JsonValueSchema;
351
+ var JsonRecord = z5.record(z5.string(), Json);
352
+ var SessionOpenPayloadSchema = z5.looseObject({
353
+ runtime: z5.looseObject({
354
+ sdk: z5.string().min(1),
355
+ version: z5.string().min(1),
356
+ framework: z5.string().optional(),
357
+ model: z5.string().optional()
358
+ }),
359
+ /** Runtime / repo attestations read by the (staged) Attestation Assurance score. */
360
+ attestations: JsonRecord.optional()
361
+ });
362
+ var SESSION_CLOSE_REASONS = ["completed", "settled", "aborted", "expired"];
363
+ var SessionClosePayloadSchema = z5.looseObject({
364
+ reason: z5.enum(SESSION_CLOSE_REASONS),
365
+ transaction: z5.string().optional()
366
+ });
367
+ var IntentDeclaredPayloadSchema = DeclaredIntentSchema.loose();
368
+ var LlmCallStartPayloadSchema = z5.looseObject({
369
+ callId: z5.string().min(1),
370
+ // GAP-07
371
+ provider: z5.string().min(1),
372
+ modelId: z5.string().min(1),
373
+ params: JsonRecord
374
+ });
375
+ var LlmCallEndPayloadSchema = z5.looseObject({
376
+ callId: z5.string().min(1),
377
+ content: Json.optional(),
378
+ finishReason: z5.string().optional(),
379
+ usage: JsonRecord.optional(),
380
+ durationMs: z5.number().int().min(0),
381
+ error: z5.looseObject({ name: z5.string(), message: z5.string() }).optional()
382
+ });
383
+ var ToolCallStartPayloadSchema = z5.looseObject({
384
+ callId: z5.string().min(1),
385
+ // GAP-07
386
+ toolName: z5.string().min(1),
387
+ input: Json,
388
+ transport: z5.enum(["local", "mcp"]).optional(),
389
+ server: z5.string().optional()
390
+ });
391
+ var ToolCallEndPayloadSchema = z5.looseObject({
392
+ callId: z5.string().min(1),
393
+ output: Json.optional(),
394
+ error: z5.looseObject({ name: z5.string(), message: z5.string() }).optional(),
395
+ durationMs: z5.number().int().min(0)
396
+ });
397
+ var PAYMENT_ARTIFACTS = [
398
+ "http-402",
399
+ "mrtr-input-required",
400
+ "payment-signature",
401
+ "checkout-url"
402
+ ];
403
+ var PaymentMomentPayloadSchema = z5.looseObject({
404
+ protocol: z5.string().min(1),
405
+ payee: z5.string().min(1),
406
+ amount: z5.looseObject({ value: z5.string().min(1), currency: z5.string().min(1) }),
407
+ payer: z5.string().optional(),
408
+ artifact: z5.enum(PAYMENT_ARTIFACTS),
409
+ raw: JsonRecord
410
+ });
411
+ var GatewayDecisionPayloadSchema = z5.looseObject({
412
+ gateway: z5.string().min(1),
413
+ call: z5.looseObject({ tool: z5.string().min(1), args: Json.optional() }),
414
+ decision: z5.enum(["ALLOW", "DENY", "REVIEW", "CHALLENGE"]),
415
+ reasonCodes: z5.array(z5.string()),
416
+ /** The gateway's own record of what it decided on — a black box to the platform. */
417
+ record: JsonRecord
418
+ });
419
+ var TransportGapPayloadSchema = z5.looseObject({
420
+ dropped: z5.number().int().min(1),
421
+ firstTs: z5.string(),
422
+ lastTs: z5.string()
423
+ });
424
+ var PlatformObservationPayloadSchema = z5.strictObject({
425
+ origin: z5.string().min(1),
426
+ params: Json,
427
+ response: Json
428
+ });
429
+ var ANOMALY_TYPES = [
430
+ "fork",
431
+ "seq_gap",
432
+ "prev_hash_mismatch",
433
+ "bad_sig",
434
+ "clock_skew",
435
+ "source_conflict"
436
+ ];
437
+ var PlatformAnomalyPayloadSchema = z5.looseObject({
438
+ type: z5.enum(ANOMALY_TYPES),
439
+ source: EvidenceSourceAllSchema,
440
+ seq: z5.number().int().min(0).nullable(),
441
+ detail: JsonRecord
442
+ });
443
+ var REGISTRY = {
444
+ "session.open": SessionOpenPayloadSchema,
445
+ "session.close": SessionClosePayloadSchema,
446
+ "intent.declared": IntentDeclaredPayloadSchema,
447
+ "llm_call.start": LlmCallStartPayloadSchema,
448
+ "llm_call.end": LlmCallEndPayloadSchema,
449
+ "tool_call.start": ToolCallStartPayloadSchema,
450
+ "tool_call.end": ToolCallEndPayloadSchema,
451
+ "payment.requested": PaymentMomentPayloadSchema,
452
+ "payment.presented": PaymentMomentPayloadSchema,
453
+ "gateway.decision": GatewayDecisionPayloadSchema,
454
+ "transport.gap": TransportGapPayloadSchema,
455
+ "platform.observation": PlatformObservationPayloadSchema,
456
+ "platform.anomaly": PlatformAnomalyPayloadSchema
457
+ };
458
+ function payloadSchemaFor(kind) {
459
+ return REGISTRY[kind];
460
+ }
461
+
462
+ // ../protocol/src/verdict.ts
463
+ var SEVERITY = { ALLOW: 0, REVIEW: 1, DENY: 2 };
464
+ var Verdict = class _Verdict {
465
+ constructor(value) {
466
+ this.value = value;
467
+ }
468
+ static ALLOW = new _Verdict("ALLOW");
469
+ static REVIEW = new _Verdict("REVIEW");
470
+ static DENY = new _Verdict("DENY");
471
+ static of(value) {
472
+ return value === "DENY" ? _Verdict.DENY : value === "REVIEW" ? _Verdict.REVIEW : _Verdict.ALLOW;
473
+ }
474
+ /** The more severe of the two. */
475
+ atLeast(other) {
476
+ const o = typeof other === "string" ? _Verdict.of(other) : other;
477
+ return SEVERITY[o.value] > SEVERITY[this.value] ? o : this;
478
+ }
479
+ /** Whether a synchronous gate must stop the call (GAP-52). */
480
+ blocks(onReview) {
481
+ return this.value === "DENY" || this.value === "REVIEW" && onReview === "abort";
482
+ }
483
+ /** What the gate effectively did: DENY when it blocked, else the verdict itself. */
484
+ effective(onReview) {
485
+ return this.blocks(onReview) ? "DENY" : this.value;
486
+ }
487
+ };
75
488
  export {
76
489
  ALL_SOURCES,
77
490
  ANNOTATION_CODES,