@belticlabs/agent-risk-sdk 0.2.0 → 0.4.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.
@@ -3,8 +3,6 @@ import {
3
3
  ANNOTATION_CODES,
4
4
  ANOMALY_TYPES,
5
5
  AmountSchema,
6
- AnchorEntrySchema,
7
- AnchorsOutputSchema,
8
6
  ApiErrorSchema,
9
7
  COLLECTOR_CODES,
10
8
  ChainHeadSchema,
@@ -73,14 +71,12 @@ import {
73
71
  parseSelectorRef,
74
72
  payloadSchemaFor,
75
73
  walkPath
76
- } from "../chunk-46QN2KEZ.js";
74
+ } from "../chunk-4BUUPU3O.js";
77
75
  export {
78
76
  ALL_SOURCES,
79
77
  ANNOTATION_CODES,
80
78
  ANOMALY_TYPES,
81
79
  AmountSchema,
82
- AnchorEntrySchema,
83
- AnchorsOutputSchema,
84
80
  ApiErrorSchema,
85
81
  COLLECTOR_CODES,
86
82
  ChainHeadSchema,
@@ -0,0 +1,484 @@
1
+ import { G as EvidenceAck, y as EventResult, M as EvidenceEvent, w as EvaluateOutput, ax as Verdict, a4 as OnReview, a as PaymentSummary, P as PaymentMomentPayload, D as Decision$1, r as DeclaredIntent, at as ToolCallStartPayload, b as JsonValue, J as JsonObject, aj as SessionClosePayload, R as EvidenceSource, aA as WireEvidenceKind, C as ChainHead, a7 as PayloadByKind } from './verdict-CDAsxktI.js';
2
+
3
+ /**
4
+ * The edge signs event digests (Fraud SDK RFC › Modules › Identity Module);
5
+ * the platform signs its own PLATFORM chain. Both are the same operation
6
+ * over different keys, so one interface.
7
+ */
8
+ interface Signer {
9
+ /** Raw 32-byte Ed25519 public key. */
10
+ readonly publicKey: Uint8Array;
11
+ /** Stable identifier for logs and key rotation; `did:key` for agents. */
12
+ readonly keyId: string;
13
+ sign(message: Uint8Array): Promise<Uint8Array>;
14
+ }
15
+
16
+ interface ApiClientOptions {
17
+ baseUrl: string;
18
+ apiKey: string;
19
+ fetch?: typeof globalThis.fetch;
20
+ timeoutMs?: number;
21
+ userAgent?: string;
22
+ }
23
+ declare class BelticApiError extends Error {
24
+ readonly status: number;
25
+ readonly code: string;
26
+ readonly details?: unknown | undefined;
27
+ readonly requestId?: string | undefined;
28
+ constructor(status: number, code: string, message: string, details?: unknown | undefined, requestId?: string | undefined);
29
+ /** 5xx and network failures are retried by the transport; 4xx are not. */
30
+ get retryable(): boolean;
31
+ }
32
+ declare class ApiClient {
33
+ private readonly baseUrl;
34
+ private readonly fetchImpl;
35
+ private readonly timeoutMs;
36
+ private readonly headers;
37
+ constructor(opts: ApiClientOptions);
38
+ post<T>(path: string, body: unknown, headers?: Record<string, string>): Promise<T>;
39
+ get<T>(path: string, query?: Record<string, string | undefined>): Promise<T>;
40
+ private request;
41
+ }
42
+
43
+ interface AgentIdentity {
44
+ did: string;
45
+ signer: Signer;
46
+ /** Opaque credential presented at session start (stored, not verified this phase). */
47
+ credential?: string;
48
+ }
49
+ declare function identityFromSeed(seed: Uint8Array, credential?: string): AgentIdentity;
50
+ declare function ephemeralIdentity(credential?: string): AgentIdentity;
51
+ /** A JSON keystore on disk: `{ "seed": "<64 hex>" }`, created 0600 when missing. */
52
+ declare function fileIdentity(path: string, credential?: string): AgentIdentity;
53
+
54
+ /**
55
+ * Correlation without binding (Fraud SDK RFC › Protocol Adapter — x402:
56
+ * "binding travels on the call that initiates the purchase, not
57
+ * necessarily on the payment artifact"). The merchant binds a key it will
58
+ * see again (a checkout session id, a challenge nonce) to the buyer's
59
+ * session; the adapter resolves it when the settlement arrives (GAP-31).
60
+ */
61
+ interface CorrelationStore {
62
+ bind(key: string, sessionId: string, ttlMs?: number): Promise<void>;
63
+ resolve(key: string): Promise<string | null>;
64
+ }
65
+ declare class MemoryCorrelationStore implements CorrelationStore {
66
+ private readonly defaultTtlMs;
67
+ private readonly entries;
68
+ constructor(defaultTtlMs?: number);
69
+ bind(key: string, sessionId: string, ttlMs?: number): Promise<void>;
70
+ resolve(key: string): Promise<string | null>;
71
+ }
72
+
73
+ /**
74
+ * Transport (Fraud SDK RFC › Modules: "buffering, batching, chained delivery
75
+ * to the Collector"). Contract as assumed in GAP-18/38: one FIFO per
76
+ * chain; at most one batch in flight per chain, so order is preserved;
77
+ * exponential backoff on network / 5xx; a `fork` or `rejected` ack halts
78
+ * the chain and surfaces `ChainRejectedError` — an SDK must not silently
79
+ * keep chaining onto a head the platform never accepted.
80
+ */
81
+
82
+ interface TransportOptions {
83
+ maxBatch: number;
84
+ flushMs: number;
85
+ /** Total buffered events across chains; beyond this new events are dropped (GAP-38). */
86
+ maxBuffered: number;
87
+ backoff: {
88
+ baseMs: number;
89
+ maxMs: number;
90
+ maxAttempts: number;
91
+ };
92
+ onAck?: (ack: EvidenceAck) => void;
93
+ onError?: (err: Error) => void;
94
+ onChainHalted?: (err: ChainRejectedError) => void;
95
+ setTimeout?: typeof globalThis.setTimeout;
96
+ clearTimeout?: typeof globalThis.clearTimeout;
97
+ }
98
+ declare const DEFAULT_TRANSPORT: TransportOptions;
99
+ declare class ChainRejectedError extends Error {
100
+ readonly sessionId: string;
101
+ readonly source: string;
102
+ readonly result: EventResult;
103
+ constructor(sessionId: string, source: string, result: EventResult);
104
+ }
105
+ declare class TransportClosedError extends Error {
106
+ constructor();
107
+ }
108
+ declare class Transport {
109
+ private readonly api;
110
+ private readonly opts;
111
+ private readonly chains;
112
+ private buffered;
113
+ private timer;
114
+ private closed;
115
+ private inFlightCount;
116
+ private drainWaiters;
117
+ constructor(api: ApiClient, opts?: Partial<TransportOptions>);
118
+ get size(): number;
119
+ hasRoom(): boolean;
120
+ haltedError(sessionId: string, source: string): ChainRejectedError | null;
121
+ /** Callers check `hasRoom()` first and assign `seq` only then (GAP-38). */
122
+ enqueue(ev: EvidenceEvent): void;
123
+ /** Send everything pending and wait for every in-flight batch to settle (ack or halt). */
124
+ flush(): Promise<void>;
125
+ close(): Promise<void>;
126
+ private schedule;
127
+ private unschedule;
128
+ private drained;
129
+ private settleWaiters;
130
+ private flushChain;
131
+ private send;
132
+ }
133
+
134
+ /**
135
+ * One SDK, two halves (Fraud SDK RFC › Summary). `Beltic` is the single
136
+ * client: sessions and evidence for both halves, `evaluate` for whichever
137
+ * half is about to let a payment through. Protocol integrations are plain
138
+ * functions behind subpath exports, each pulling exactly one optional peer:
139
+ *
140
+ * @belticlabs/agent-risk-sdk/ai → middleware(session), wrapTools(session, …)
141
+ * @belticlabs/agent-risk-sdk/x402 → belticFetch(session), x402Summary(…), attachX402(beltic, …)
142
+ * @belticlabs/agent-risk-sdk/hono → belticPaymentMiddleware(beltic, …)
143
+ *
144
+ * Neither half decides risk locally: verdicts are platform-side.
145
+ *
146
+ * A host that runs its own agent loop takes `beltic.run(key)` — a `Run`
147
+ * keyed by its own session id that owns spans, verdicts and the mandate
148
+ * (GAP-79); every integration above accepts a `Run` where it accepts a
149
+ * `Session`. `Beltic.fromEnv()` reads `BELTIC_*` and, when none is set,
150
+ * answers a disabled client that records nothing and never throws into
151
+ * the work (GAP-78), so a host wires Beltic unconditionally.
152
+ *
153
+ * Evidence is a side channel of the work it observes. With `failOpen`
154
+ * nothing the SDK does throws into that work: `Session.emit` reports and
155
+ * answers `false`, `sessions.open` answers `null`, `evaluate` answers
156
+ * `null` — never an invented verdict; the host decides what to do without
157
+ * one (GAP-70). `sessions.start` and `sessions.ensure` throw either way:
158
+ * they are the primitives the fail-open entries are built on.
159
+ */
160
+
161
+ declare const SDK_VERSION = "0.4.0";
162
+ type Env = Record<string, string | undefined>;
163
+ interface BelticOptions extends Omit<ApiClientOptions, 'userAgent'> {
164
+ /** Buyer half. Without it, `sessions.start` is unavailable; the seller half works. */
165
+ identity?: AgentIdentity | undefined;
166
+ transport?: Partial<TransportOptions> | undefined;
167
+ /** What a synchronous seller hook does with REVIEW (GAP-52). */
168
+ onReview?: OnReview | undefined;
169
+ correlation?: CorrelationStore | undefined;
170
+ redact?: RedactFn | undefined;
171
+ now?: (() => Date) | undefined;
172
+ /** Evidence never fails the work it observes; see the module note (GAP-70). */
173
+ failOpen?: boolean | undefined;
174
+ /** Where fail-open failures go (and transport delivery failures unless `transport` names its own). Default: `console.error`. */
175
+ onError?: ((err: Error) => void) | undefined;
176
+ /** Fail-open only: how long `sessions.open` answers null after the platform refused to open a session (GAP-71). */
177
+ openRetryMs?: number | undefined;
178
+ /** `false` is what `Beltic.disabled()` sets: no platform is ever called (GAP-78). */
179
+ enabled?: boolean | undefined;
180
+ }
181
+ /** The platform's answer, with the verdict as a value the caller can ask `blocks(onReview)`. */
182
+ type Evaluation = EvaluateOutput & {
183
+ verdict: Verdict;
184
+ };
185
+ declare class Beltic {
186
+ readonly api: ApiClient;
187
+ readonly transport: Transport;
188
+ readonly sessions: Sessions;
189
+ readonly identity: AgentIdentity | undefined;
190
+ readonly correlation: CorrelationStore;
191
+ readonly onReview: OnReview;
192
+ readonly failOpen: boolean;
193
+ /** `false` for a disabled client (GAP-78): nothing is posted, `run`/`sessions.open` answer without a session. */
194
+ readonly enabled: boolean;
195
+ private readonly onError;
196
+ private readonly runs;
197
+ /**
198
+ * The client the environment describes: `BELTIC_API_KEY`,
199
+ * `BELTIC_BASE_URL`, `BELTIC_AGENT_SEED` (64 hex) and optionally
200
+ * `BELTIC_AGENT_CREDENTIAL`, fail-open by default. None set → a disabled
201
+ * client; some set → a configuration error, thrown (GAP-78).
202
+ */
203
+ static fromEnv(env?: Env, opts?: Partial<BelticOptions>): Beltic;
204
+ /** A client that records nothing and never throws into the work: the null object for "no evidence stream" (GAP-78). */
205
+ static disabled(opts?: Partial<BelticOptions>): Beltic;
206
+ constructor(opts: BelticOptions);
207
+ /**
208
+ * The platform's verdict on a payment — the seller's before it verifies,
209
+ * the buyer's before it presents. Read-your-writes: the buffered evidence
210
+ * is flushed first so the platform judges what the caller already saw
211
+ * (GAP-16). A recorded moment is accepted as is: only its comparable core
212
+ * (payee, amount, payer) is sent. `null` only under `failOpen`, when the
213
+ * platform could not be asked.
214
+ */
215
+ evaluate(sessionId: string, payment: PaymentSummary | PaymentMomentPayload): Promise<Evaluation | null>;
216
+ private decide;
217
+ /**
218
+ * The run for a key of the host's own — one object per key until it
219
+ * closes (the options count on the first call only). See `Run`.
220
+ */
221
+ run(key: string, opts?: RunOptions): Run;
222
+ flush(): Promise<void>;
223
+ shutdown(): Promise<void>;
224
+ /** `process.env` where there is a `process` (Node); `{}` on workerd, where the shell passes its `env`. */
225
+ private static processEnv;
226
+ }
227
+ declare function createBeltic(opts: BelticOptions): Beltic;
228
+
229
+ /**
230
+ * The platform's verdict on one payment as a value the host can ask
231
+ * questions of (Fraud Engine RFC › API: ALLOW | DENY | REVIEW). `absent`
232
+ * is the fail-open case: the platform could not be asked (GAP-70), and no
233
+ * verdict was invented — the host decides what to do without one. A
234
+ * `Run` memoizes decisions by the host's call id, so a re-run approval
235
+ * reads the verdict already given (GAP-79).
236
+ */
237
+
238
+ declare class Decision {
239
+ readonly evaluation: Evaluation | null;
240
+ private static readonly ABSENT;
241
+ private constructor();
242
+ static of(evaluation: Evaluation): Decision;
243
+ static absent(): Decision;
244
+ get value(): Decision$1 | null;
245
+ get reasonCodes(): readonly string[];
246
+ get decisionId(): string | null;
247
+ get allowed(): boolean;
248
+ get denied(): boolean;
249
+ get review(): boolean;
250
+ get absent(): boolean;
251
+ /** Whether a gate must stop the payment (GAP-52); an absent verdict never blocks. */
252
+ blocks(onReview: OnReview): boolean;
253
+ /** One sentence for the agent or the person: what Beltic said and why. */
254
+ explain(): string;
255
+ }
256
+
257
+ interface RunOptions {
258
+ /** What `sessions.open` sends when this run actually opens a session. */
259
+ open?: OpenSessionInput | undefined;
260
+ /** Close the session (`expired`) after this long without evidence; unset = only the host closes. */
261
+ idleMs?: number | undefined;
262
+ }
263
+ interface HumanDecisionInput {
264
+ /** Whether the person let the call proceed. */
265
+ allowed: boolean;
266
+ /** The host's own word for what happened: `approved`, `answered`, `rejected`, `cancelled`… */
267
+ outcome: string;
268
+ responder?: string | undefined;
269
+ /** The host's record of what was asked and chosen — a black box to the platform (GAP-75). */
270
+ record?: JsonObject | undefined;
271
+ }
272
+ interface DecideOptions {
273
+ /** The host's id for the call the verdict applies to: memoizes the decision and links it to the span. */
274
+ callId?: string | undefined;
275
+ /** The mandate as of now; declared first when it differs from the last one. */
276
+ intent?: DeclaredIntent | undefined;
277
+ }
278
+ interface RunDeps {
279
+ sessions: Sessions;
280
+ evaluate: (sessionId: string, payment: PaymentSummary | PaymentMomentPayload) => Promise<Evaluation | null>;
281
+ /** Called once the run closed, so the registry forgets it. */
282
+ onClosed: (run: Run) => void;
283
+ }
284
+ declare class Run {
285
+ private readonly deps;
286
+ readonly key: string;
287
+ private readonly opts;
288
+ private opened;
289
+ private current;
290
+ /** JCS hash of the mandate on the chain, and of the one the open input carried. */
291
+ private declared;
292
+ private openedWith;
293
+ private closed;
294
+ private timer;
295
+ private readonly calls;
296
+ private readonly decisions;
297
+ private readonly byPayment;
298
+ constructor(deps: RunDeps, key: string, opts?: RunOptions);
299
+ /** The session this run records into — opened on first use, `null` when there is none. */
300
+ session(): Promise<Session | null>;
301
+ private readonly opener;
302
+ /** `intent.declared`, unless the mandate is the one already on the chain. */
303
+ declare(intent: DeclaredIntent): Promise<boolean>;
304
+ /**
305
+ * The platform's verdict on a payment about to be presented. Asked once
306
+ * per call id: a host that re-runs its approval step reads the same
307
+ * `Decision`. An absent verdict is not memoized, so the next attempt
308
+ * asks again.
309
+ */
310
+ decide(payment: PaymentSummary | PaymentMomentPayload, opts?: DecideOptions): Promise<Decision>;
311
+ /** The decision given for a call id, or absent. */
312
+ decision(callId: string): Decision;
313
+ /**
314
+ * The decision given for a payment with the same comparable core (payee,
315
+ * amount, payer — or payee and amount when one side names no payer), or
316
+ * absent.
317
+ */
318
+ decisionFor(payment: PaymentSummary | PaymentMomentPayload): Decision;
319
+ /** A tool call the host runs itself, reported as two events by its own call id. */
320
+ readonly tools: {
321
+ start: (call: ToolCallStartPayload) => Promise<boolean>;
322
+ end: (callId: string, outcome?: {
323
+ output?: JsonValue;
324
+ }) => Promise<boolean>;
325
+ fail: (callId: string, error: unknown, outcome?: {
326
+ output?: JsonValue;
327
+ }) => Promise<boolean>;
328
+ };
329
+ /** A person's answer about a call, as the decision it was (GAP-75). */
330
+ humanDecided(callId: string, input: HumanDecisionInput): Promise<boolean>;
331
+ close(reason?: SessionClosePayload['reason']): Promise<void>;
332
+ private take;
333
+ private touch;
334
+ private static hash;
335
+ /** With the payer first, then without it. */
336
+ private static paymentKeys;
337
+ private static callOf;
338
+ }
339
+
340
+ /**
341
+ * A risk session as the SDK sees it: one chain per (sessionId, source),
342
+ * built at the edge (Fraud SDK RFC › Wire contract). The buyer half opens
343
+ * AGENT_TRACE sessions and announces them with `session.open` (seq 0) and
344
+ * `intent.declared` (seq 1; GAP-23/60); the seller half attaches to a bound
345
+ * session or opens its own INTERNAL_NETWORK session (GAP-13).
346
+ *
347
+ * `seq` is handed out only when the transport has room for the event
348
+ * (GAP-38): a dropped event never leaves a hole — the next accepted event
349
+ * is preceded by a `transport.gap` that counts the drops. `redact` is off
350
+ * by default (GAP-33).
351
+ *
352
+ * Evidence is a side channel of the agent's work: with `failOpen` an emit
353
+ * that cannot be chained (halted chain, closed transport) is reported and
354
+ * returns `false` instead of throwing into the model or tool call it
355
+ * observes (GAP-70).
356
+ */
357
+
358
+ type RedactFn = (kind: WireEvidenceKind, payload: JsonObject) => JsonObject;
359
+ /** Who created the session — the seller half treats a bound session as buyer-born. */
360
+ type SessionBorn = 'buyer' | 'seller';
361
+ interface SessionDeps {
362
+ transport: Transport;
363
+ signer?: Signer | undefined;
364
+ redact?: RedactFn | undefined;
365
+ now?: (() => Date) | undefined;
366
+ /** Called once the session closed, so the registry can forget it. */
367
+ onClosed?: ((session: Session) => void) | undefined;
368
+ /** Report instead of throw when an event cannot be chained (GAP-70). */
369
+ failOpen?: boolean | undefined;
370
+ onError?: ((err: Error) => void) | undefined;
371
+ }
372
+ /**
373
+ * One tool call as a span: `tool_call.start` now, `tool_call.end` with the
374
+ * outcome and the elapsed time when the host reports it. For hosts that run
375
+ * their own tool loop and cannot hand the SDK an `execute` to wrap.
376
+ */
377
+ interface ToolCallSpan {
378
+ readonly callId: string;
379
+ /** Resolves once `tool_call.start` is sequenced; `end` and `fail` wait for it. */
380
+ readonly opened: Promise<boolean>;
381
+ end(outcome?: {
382
+ output?: JsonValue;
383
+ }): Promise<boolean>;
384
+ fail(error: unknown, outcome?: {
385
+ output?: JsonValue;
386
+ }): Promise<boolean>;
387
+ }
388
+ declare class Session {
389
+ private readonly deps;
390
+ readonly id: string;
391
+ readonly source: EvidenceSource;
392
+ readonly expiresAt: string | null;
393
+ readonly born: SessionBorn;
394
+ private chain;
395
+ private building;
396
+ private dropped;
397
+ private droppedFirstTs;
398
+ private droppedLastTs;
399
+ private closed;
400
+ private readonly now;
401
+ constructor(deps: SessionDeps, id: string, source: EvidenceSource, expiresAt: string | null, born: SessionBorn);
402
+ get head(): ChainHead | null;
403
+ get droppedCount(): number;
404
+ get isClosed(): boolean;
405
+ /**
406
+ * Resolves once the event is sequenced and buffered — not once it is
407
+ * acknowledged. `false` when the event was dropped, or (fail-open) when
408
+ * the chain can no longer take it.
409
+ */
410
+ emit<K extends WireEvidenceKind>(kind: K, payload: PayloadByKind[K]): Promise<boolean>;
411
+ /** The tool call whose `execute` the host runs itself; see `ToolCallSpan`. */
412
+ toolCall(call: ToolCallStartPayload): ToolCallSpan;
413
+ private chainEvent;
414
+ close(reason?: SessionClosePayload['reason'], extra?: JsonObject): Promise<void>;
415
+ /** Read-your-writes: the platform must hold the evidence before anyone judges it (GAP-16/66). */
416
+ flush(): Promise<void>;
417
+ /** Serialized: two concurrent emits get consecutive seqs, never the same one. */
418
+ private next;
419
+ }
420
+ interface StartSessionInput {
421
+ intent?: DeclaredIntent;
422
+ runtime?: {
423
+ framework?: string;
424
+ model?: string;
425
+ };
426
+ attestations?: JsonObject;
427
+ }
428
+ /** What `open` sends when it actually opens: a value, or a resolver run only then. */
429
+ type OpenSessionInput = StartSessionInput | (() => StartSessionInput | Promise<StartSessionInput>);
430
+ /** What an integration takes: a session, or the run that owns one — resolved by `Sessions.resolve`. */
431
+ type SessionSource = Session | Run | null | undefined;
432
+ interface SessionsDeps {
433
+ api: ApiClient;
434
+ transport: Transport;
435
+ /** A disabled client (GAP-78): `open` answers null, `start`/`ensure` throw, nothing is posted. */
436
+ enabled?: boolean | undefined;
437
+ identity?: AgentIdentity | undefined;
438
+ redact?: RedactFn | undefined;
439
+ now?: (() => Date) | undefined;
440
+ sdkVersion: string;
441
+ failOpen?: boolean | undefined;
442
+ onError?: ((err: Error) => void) | undefined;
443
+ /** Fail-open only: after the platform refused to open a session, `open` resolves null for this long (GAP-71). */
444
+ openRetryMs?: number | undefined;
445
+ }
446
+ declare const DEFAULT_OPEN_RETRY_MS = 60000;
447
+ declare class Sessions {
448
+ private readonly deps;
449
+ /**
450
+ * One session object per (session, source) per process: a chain's head
451
+ * lives in it, so two objects for the same chain would both start at
452
+ * seq 0 and fork it. Closed sessions are forgotten; a process restart
453
+ * mid-session still loses the head (GAP-67).
454
+ */
455
+ private readonly attached;
456
+ /** Buyer sessions by the host's own key (GAP-71). */
457
+ private readonly opened;
458
+ private retryAt;
459
+ constructor(deps: SessionsDeps);
460
+ /** The session behind a source: itself, or the one the run opens (null when there is none). */
461
+ static resolve(source: SessionSource): Promise<Session | null>;
462
+ /**
463
+ * Buyer half: the evidence session for a key of the host's own (its
464
+ * session, run or conversation id), opened on first use and reused
465
+ * after. A halted chain is reopened as a fresh session that continues
466
+ * the same key; a closed key is forgotten. When the platform refuses to
467
+ * open one, a fail-open client resolves null — the host runs without
468
+ * evidence — until `openRetryMs` has passed (GAP-71); otherwise the
469
+ * refusal is thrown and the next call tries again. The identity is
470
+ * required either way: that is configuration.
471
+ */
472
+ open(key: string, input?: OpenSessionInput): Promise<Session | null>;
473
+ private forget;
474
+ private openFresh;
475
+ /** Buyer half: create an AGENT_TRACE session bound to the agent identity, then announce it on the chain. */
476
+ start(input?: StartSessionInput): Promise<Session>;
477
+ private identityFor;
478
+ private create;
479
+ /** Seller half: emit INTERNAL_NETWORK evidence into a session the buyer bound, or open a seller-born one. */
480
+ ensure(sessionId?: string | null): Promise<Session>;
481
+ private attach;
482
+ }
483
+
484
+ export { type AgentIdentity as A, Beltic as B, ChainRejectedError as C, DEFAULT_OPEN_RETRY_MS as D, type Env as E, type HumanDecisionInput as H, MemoryCorrelationStore as M, type OpenSessionInput as O, type RedactFn as R, type SessionSource as S, type ToolCallSpan as T, Session as a, ApiClient as b, type ApiClientOptions as c, BelticApiError as d, type BelticOptions as e, type CorrelationStore as f, DEFAULT_TRANSPORT as g, type DecideOptions as h, Decision as i, type Evaluation as j, Run as k, type RunOptions as l, SDK_VERSION as m, type SessionBorn as n, Sessions as o, type StartSessionInput as p, Transport as q, TransportClosedError as r, type TransportOptions as s, createBeltic as t, ephemeralIdentity as u, fileIdentity as v, identityFromSeed as w };
@@ -318,22 +318,6 @@ declare const EvaluateOutputSchema: z.ZodObject<{
318
318
  decisionId: z.ZodUUID;
319
319
  }, z.core.$strict>;
320
320
  type EvaluateOutput = z.infer<typeof EvaluateOutputSchema>;
321
- declare const AnchorEntrySchema: z.ZodObject<{
322
- epoch: z.ZodString;
323
- root: z.ZodString;
324
- sig: z.ZodString;
325
- chainRef: z.ZodOptional<z.ZodString>;
326
- }, z.core.$strict>;
327
- type AnchorEntry = z.infer<typeof AnchorEntrySchema>;
328
- declare const AnchorsOutputSchema: z.ZodObject<{
329
- entries: z.ZodArray<z.ZodObject<{
330
- epoch: z.ZodString;
331
- root: z.ZodString;
332
- sig: z.ZodString;
333
- chainRef: z.ZodOptional<z.ZodString>;
334
- }, z.core.$strict>>;
335
- }, z.core.$strict>;
336
- type AnchorsOutput = z.infer<typeof AnchorsOutputSchema>;
337
321
  /** Non-RFC admin surface (GAP-53). */
338
322
  declare const CreatePolicyInputSchema: z.ZodObject<{
339
323
  rules: z.ZodObject<{
@@ -470,6 +454,7 @@ declare const PaymentMomentPayloadSchema: z.ZodObject<{
470
454
  }>;
471
455
  raw: z.ZodRecord<z.ZodString, z.ZodType<JsonValue, unknown, z.core.$ZodTypeInternals<JsonValue, unknown>>>;
472
456
  }, z.core.$loose>;
457
+ /** Also the host's own decisions — its spend policy, a person's answer to an approval card or a question (GAP-75). */
473
458
  declare const GatewayDecisionPayloadSchema: z.ZodObject<{
474
459
  gateway: z.ZodString;
475
460
  call: z.ZodObject<{
@@ -544,4 +529,27 @@ interface PayloadByKind {
544
529
  'platform.anomaly': PlatformAnomalyPayload;
545
530
  }
546
531
 
547
- export { Hex64Schema as $, ALL_SOURCES as A, type EvaluateOutput as B, type ChainHead as C, type Decision as D, type EvidenceSourceAll as E, EvaluateOutputSchema as F, type EventResult as G, EventResultSchema as H, type EventResultStatus as I, type JsonObject as J, EventResultStatusSchema as K, type EvidenceAck as L, EvidenceAckSchema as M, type EvidenceBatchInput as N, EvidenceBatchInputSchema as O, type PaymentMomentPayload as P, type EvidenceEnvelope as Q, type EvidenceEvent as R, EvidenceEventSchema as S, type EvidenceKind as T, EvidenceKindSchema as U, type EvidenceSource as V, EvidenceSourceAllSchema as W, EvidenceSourceSchema as X, type GatewayDecisionPayload as Y, GatewayDecisionPayloadSchema as Z, type Hex64 as _, type PaymentSummary as a, type IntentDeclaredPayload as a0, IntentDeclaredPayloadSchema as a1, JsonValueSchema as a2, type LlmCallEndPayload as a3, LlmCallEndPayloadSchema as a4, type LlmCallStartPayload as a5, LlmCallStartPayloadSchema as a6, MAX_BATCH_EVENTS as a7, PAYMENT_ARTIFACTS as a8, PLATFORM_KINDS as a9, WIRE_KINDS as aA, WIRE_SOURCES as aB, type WireEvidenceKind as aC, WireEvidenceKindSchema as aD, compareBySessionSource as aE, compareBySourceSeq as aF, isPlatformKind as aG, isWireKind as aH, payloadSchemaFor as aI, type PayloadByKind as aa, PaymentMomentPayloadSchema as ab, PaymentSummarySchema as ac, type PlatformAnomalyPayload as ad, PlatformAnomalyPayloadSchema as ae, type PlatformEvidenceKind as af, PlatformEvidenceKindSchema as ag, type PlatformObservationPayload as ah, PlatformObservationPayloadSchema as ai, SESSION_CLOSE_REASONS as aj, SOURCE_ORDER as ak, SeqSchema as al, type SessionClosePayload as am, SessionClosePayloadSchema as an, SessionIdSchema as ao, type SessionOpenPayload as ap, SessionOpenPayloadSchema as aq, type Sig as ar, SigSchema as as, TimestampSchema as at, type ToolCallEndPayload as au, ToolCallEndPayloadSchema as av, type ToolCallStartPayload as aw, ToolCallStartPayloadSchema as ax, type TransportGapPayload as ay, TransportGapPayloadSchema as az, type JsonValue as b, ANOMALY_TYPES as c, type Amount as d, AmountSchema as e, type AnchorEntry as f, AnchorEntrySchema as g, type AnchorsOutput as h, AnchorsOutputSchema as i, type ApiError as j, ApiErrorSchema as k, ChainHeadSchema as l, type CreatePolicyInput as m, CreatePolicyInputSchema as n, type CreatePolicyOutput as o, CreatePolicyOutputSchema as p, type CreateSessionInput as q, CreateSessionInputSchema as r, type CreateSessionOutput as s, CreateSessionOutputSchema as t, DecisionSchema as u, type DeclaredIntent as v, DeclaredIntentSchema as w, type DigestedEnvelope as x, type EvaluateInput as y, EvaluateInputSchema as z };
532
+ /**
533
+ * The verdict as a value (Fraud Engine RFC › API: ALLOW | DENY | REVIEW).
534
+ * Layers combine by severity (GAP-45); a synchronous seller hook turns
535
+ * REVIEW into a stop or a pass according to its `onReview` (GAP-52). Both
536
+ * halves of the SDK and the engine share this one rule.
537
+ */
538
+
539
+ type OnReview = 'abort' | 'allow';
540
+ declare class Verdict {
541
+ readonly value: Decision;
542
+ private constructor();
543
+ static readonly ALLOW: Verdict;
544
+ static readonly REVIEW: Verdict;
545
+ static readonly DENY: Verdict;
546
+ static of(value: Decision): Verdict;
547
+ /** The more severe of the two. */
548
+ atLeast(other: Verdict | Decision): Verdict;
549
+ /** Whether a synchronous gate must stop the call (GAP-52). */
550
+ blocks(onReview: OnReview): boolean;
551
+ /** What the gate effectively did: DENY when it blocked, else the verdict itself. */
552
+ effective(onReview: OnReview): Decision;
553
+ }
554
+
555
+ export { type LlmCallEndPayload as $, ALL_SOURCES as A, type EventResultStatus as B, type ChainHead as C, type Decision as D, type EvidenceSourceAll as E, EventResultStatusSchema as F, type EvidenceAck as G, EvidenceAckSchema as H, type EvidenceBatchInput as I, type JsonObject as J, EvidenceBatchInputSchema as K, type EvidenceEnvelope as L, type EvidenceEvent as M, EvidenceEventSchema as N, type EvidenceKind as O, type PaymentMomentPayload as P, EvidenceKindSchema as Q, type EvidenceSource as R, EvidenceSourceAllSchema as S, EvidenceSourceSchema as T, type GatewayDecisionPayload as U, GatewayDecisionPayloadSchema as V, type Hex64 as W, Hex64Schema as X, type IntentDeclaredPayload as Y, IntentDeclaredPayloadSchema as Z, JsonValueSchema as _, type PaymentSummary as a, LlmCallEndPayloadSchema as a0, type LlmCallStartPayload as a1, LlmCallStartPayloadSchema as a2, MAX_BATCH_EVENTS as a3, type OnReview as a4, PAYMENT_ARTIFACTS as a5, PLATFORM_KINDS as a6, type PayloadByKind as a7, PaymentMomentPayloadSchema as a8, PaymentSummarySchema as a9, type WireEvidenceKind as aA, WireEvidenceKindSchema as aB, compareBySessionSource as aC, compareBySourceSeq as aD, isPlatformKind as aE, isWireKind as aF, payloadSchemaFor as aG, type PlatformAnomalyPayload as aa, PlatformAnomalyPayloadSchema as ab, type PlatformEvidenceKind as ac, PlatformEvidenceKindSchema as ad, type PlatformObservationPayload as ae, PlatformObservationPayloadSchema as af, SESSION_CLOSE_REASONS as ag, SOURCE_ORDER as ah, SeqSchema as ai, type SessionClosePayload as aj, SessionClosePayloadSchema as ak, SessionIdSchema as al, type SessionOpenPayload as am, SessionOpenPayloadSchema as an, type Sig as ao, SigSchema as ap, TimestampSchema as aq, type ToolCallEndPayload as ar, ToolCallEndPayloadSchema as as, type ToolCallStartPayload as at, ToolCallStartPayloadSchema as au, type TransportGapPayload as av, TransportGapPayloadSchema as aw, Verdict as ax, WIRE_KINDS as ay, WIRE_SOURCES as az, type JsonValue as b, ANOMALY_TYPES as c, type Amount as d, AmountSchema as e, type ApiError as f, ApiErrorSchema as g, ChainHeadSchema as h, type CreatePolicyInput as i, CreatePolicyInputSchema as j, type CreatePolicyOutput as k, CreatePolicyOutputSchema as l, type CreateSessionInput as m, CreateSessionInputSchema as n, type CreateSessionOutput as o, CreateSessionOutputSchema as p, DecisionSchema as q, type DeclaredIntent as r, DeclaredIntentSchema as s, type DigestedEnvelope as t, type EvaluateInput as u, EvaluateInputSchema as v, type EvaluateOutput as w, EvaluateOutputSchema as x, type EventResult as y, EventResultSchema as z };
@@ -1,12 +1,21 @@
1
- import { RoutesConfig, x402ResourceServer } from '@x402/core/server';
1
+ import { PaywallConfig, RoutesConfig, x402ResourceServer } from '@x402/core/server';
2
2
  import { MiddlewareHandler } from 'hono';
3
- import { B as Beltic } from '../client-C-mV_3A0.js';
4
- import { G as GuardedMiddlewareOptions } from '../middleware-BwAYpBTl.js';
5
- export { a as attachX402 } from '../adapter-CF-cUYSA.js';
6
- import '../index-Bjs3BPPU.js';
3
+ import { B as Beltic } from '../session-gK51QVAM.js';
4
+ import { A as AttachOptions } from '../adapter-CLy44CD2.js';
5
+ export { a as attachX402 } from '../adapter-CLy44CD2.js';
6
+ import '../verdict-CDAsxktI.js';
7
7
  import 'zod';
8
- import '../verdict-BAahb5po.js';
9
- import '../session-5TClPLI4.js';
8
+
9
+ /**
10
+ * The seller half as one middleware: the framework's `@x402/*` payment
11
+ * middleware over an `x402HTTPResourceServer` with the Beltic hooks
12
+ * attached. `@belticlabs/agent-risk-sdk/hono` hands in its framework's
13
+ * `paymentMiddlewareFromHTTPServer`.
14
+ */
15
+
16
+ type GuardedMiddlewareOptions = AttachOptions & {
17
+ paywall?: PaywallConfig | undefined;
18
+ };
10
19
 
11
20
  /** Seller half for hono: `@x402/hono`'s payment middleware with the Beltic hooks attached. */
12
21
 
package/dist/x402/hono.js CHANGED
@@ -1,17 +1,23 @@
1
- import {
2
- guardedPaymentMiddleware
3
- } from "../chunk-U7HM37CB.js";
4
1
  import {
5
2
  attachX402
6
- } from "../chunk-SO6HPRJT.js";
7
- import "../chunk-VM7MK43J.js";
8
- import "../chunk-SFGM7KOG.js";
9
- import "../chunk-46QN2KEZ.js";
10
- import "../chunk-LM4NIYE5.js";
3
+ } from "../chunk-WY5ZX4BD.js";
11
4
  import "../chunk-FQDHFTVR.js";
5
+ import "../chunk-X3W2Z5GC.js";
12
6
 
13
7
  // src/x402/hono.ts
14
8
  import { paymentMiddlewareFromHTTPServer } from "@x402/hono";
9
+
10
+ // src/x402/middleware.ts
11
+ import {
12
+ x402HTTPResourceServer
13
+ } from "@x402/core/server";
14
+ function guardedPaymentMiddleware(fromHTTPServer, beltic, routes, server, opts = {}) {
15
+ const http = new x402HTTPResourceServer(server, routes);
16
+ attachX402(beltic, server, http, opts);
17
+ return fromHTTPServer(http, opts.paywall);
18
+ }
19
+
20
+ // src/x402/hono.ts
15
21
  function belticPaymentMiddleware(beltic, routes, server, opts) {
16
22
  return guardedPaymentMiddleware(paymentMiddlewareFromHTTPServer, beltic, routes, server, opts);
17
23
  }