@belticlabs/agent-risk-sdk 0.2.0 → 0.3.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.
package/dist/mcp/index.js CHANGED
@@ -1,12 +1,13 @@
1
1
  import {
2
+ Sessions,
2
3
  recordCall
3
- } from "../chunk-GSH5APZW.js";
4
+ } from "../chunk-4MG6VNAU.js";
4
5
  import {
5
6
  SESSION_EXTENSION
6
- } from "../chunk-VM7MK43J.js";
7
+ } from "../chunk-FAQ442YH.js";
7
8
  import {
8
9
  uuidv7
9
- } from "../chunk-SFGM7KOG.js";
10
+ } from "../chunk-X3W2Z5GC.js";
10
11
  import {
11
12
  Verdict
12
13
  } from "../chunk-46QN2KEZ.js";
@@ -22,32 +23,36 @@ import {
22
23
  } from "../chunk-FQDHFTVR.js";
23
24
 
24
25
  // src/mcp/index.ts
25
- function wrapClient(session, client, opts = {}) {
26
- if (!session) return client;
26
+ function wrapClient(source, client, opts = {}) {
27
+ if (!source) return client;
27
28
  const original = client.callTool.bind(client);
28
- const callTool = (params, ...rest) => recordCall(
29
- session,
30
- "tool_call",
31
- uuidv7(),
32
- {
33
- toolName: params.name,
34
- input: toJson(params.arguments ?? {}),
35
- transport: "mcp",
36
- ...opts.server ? { server: opts.server } : {}
37
- },
38
- async () => {
39
- await session.flush();
40
- return original(
41
- { ...params, _meta: { ...params._meta ?? {}, [SESSION_EXTENSION]: session.id } },
42
- ...rest
43
- );
44
- },
45
- async (result) => {
46
- const ask = findPaymentAsk(result);
47
- if (ask) await session.emit("payment.requested", ask);
48
- return { output: toJson(result) };
49
- }
50
- );
29
+ const callTool = async (params, ...rest) => {
30
+ const session = await Sessions.resolve(source);
31
+ if (!session) return original(params, ...rest);
32
+ return recordCall(
33
+ session,
34
+ "tool_call",
35
+ uuidv7(),
36
+ {
37
+ toolName: params.name,
38
+ input: toJson(params.arguments ?? {}),
39
+ transport: "mcp",
40
+ ...opts.server ? { server: opts.server } : {}
41
+ },
42
+ async () => {
43
+ await session.flush();
44
+ return original(
45
+ { ...params, _meta: { ...params._meta ?? {}, [SESSION_EXTENSION]: session.id } },
46
+ ...rest
47
+ );
48
+ },
49
+ async (result) => {
50
+ const ask = findPaymentAsk(result);
51
+ if (ask) await session.emit("payment.requested", ask);
52
+ return { output: toJson(result) };
53
+ }
54
+ );
55
+ };
51
56
  return new Proxy(client, {
52
57
  get(target, prop, receiver) {
53
58
  return prop === "callTool" ? callTool : Reflect.get(target, prop, receiver);
@@ -1,5 +1,5 @@
1
1
  import { PaywallConfig } from '@x402/core/server';
2
- import { A as AttachOptions } from './adapter-CF-cUYSA.js';
2
+ import { A as AttachOptions } from './adapter-BEpzr2R3.js';
3
3
 
4
4
  /**
5
5
  * The seller half as one middleware: the framework's `@x402/*` payment
@@ -1,7 +1,6 @@
1
- import { b as JsonValue, E as EvidenceSourceAll } from '../index-Bjs3BPPU.js';
2
- export { A as ALL_SOURCES, c as ANOMALY_TYPES, d as Amount, e as AmountSchema, f as AnchorEntry, g as AnchorEntrySchema, h as AnchorsOutput, i as AnchorsOutputSchema, j as ApiError, k as ApiErrorSchema, C as ChainHead, l as ChainHeadSchema, m as CreatePolicyInput, n as CreatePolicyInputSchema, o as CreatePolicyOutput, p as CreatePolicyOutputSchema, q as CreateSessionInput, r as CreateSessionInputSchema, s as CreateSessionOutput, t as CreateSessionOutputSchema, D as Decision, u as DecisionSchema, v as DeclaredIntent, w as DeclaredIntentSchema, x as DigestedEnvelope, y as EvaluateInput, z as EvaluateInputSchema, B as EvaluateOutput, F as EvaluateOutputSchema, G as EventResult, H as EventResultSchema, I as EventResultStatus, K as EventResultStatusSchema, L as EvidenceAck, M as EvidenceAckSchema, N as EvidenceBatchInput, O as EvidenceBatchInputSchema, Q as EvidenceEnvelope, R as EvidenceEvent, S as EvidenceEventSchema, T as EvidenceKind, U as EvidenceKindSchema, V as EvidenceSource, W as EvidenceSourceAllSchema, X as EvidenceSourceSchema, Y as GatewayDecisionPayload, Z as GatewayDecisionPayloadSchema, _ as Hex64, $ as Hex64Schema, a0 as IntentDeclaredPayload, a1 as IntentDeclaredPayloadSchema, J as JsonObject, a2 as JsonValueSchema, a3 as LlmCallEndPayload, a4 as LlmCallEndPayloadSchema, a5 as LlmCallStartPayload, a6 as LlmCallStartPayloadSchema, a7 as MAX_BATCH_EVENTS, a8 as PAYMENT_ARTIFACTS, a9 as PLATFORM_KINDS, aa as PayloadByKind, P as PaymentMomentPayload, ab as PaymentMomentPayloadSchema, a as PaymentSummary, ac as PaymentSummarySchema, ad as PlatformAnomalyPayload, ae as PlatformAnomalyPayloadSchema, af as PlatformEvidenceKind, ag as PlatformEvidenceKindSchema, ah as PlatformObservationPayload, ai as PlatformObservationPayloadSchema, aj as SESSION_CLOSE_REASONS, ak as SOURCE_ORDER, al as SeqSchema, am as SessionClosePayload, an as SessionClosePayloadSchema, ao as SessionIdSchema, ap as SessionOpenPayload, aq as SessionOpenPayloadSchema, ar as Sig, as as SigSchema, at as TimestampSchema, au as ToolCallEndPayload, av as ToolCallEndPayloadSchema, aw as ToolCallStartPayload, ax as ToolCallStartPayloadSchema, ay as TransportGapPayload, az as TransportGapPayloadSchema, aA as WIRE_KINDS, aB as WIRE_SOURCES, aC as WireEvidenceKind, aD as WireEvidenceKindSchema, aE as compareBySessionSource, aF as compareBySourceSeq, aG as isPlatformKind, aH as isWireKind, aI as payloadSchemaFor } from '../index-Bjs3BPPU.js';
1
+ import { b as JsonValue, E as EvidenceSourceAll } from '../verdict-6vCyoAHE.js';
2
+ export { A as ALL_SOURCES, c as ANOMALY_TYPES, d as Amount, e as AmountSchema, f as AnchorEntry, g as AnchorEntrySchema, h as AnchorsOutput, i as AnchorsOutputSchema, j as ApiError, k as ApiErrorSchema, C as ChainHead, l as ChainHeadSchema, m as CreatePolicyInput, n as CreatePolicyInputSchema, o as CreatePolicyOutput, p as CreatePolicyOutputSchema, q as CreateSessionInput, r as CreateSessionInputSchema, s as CreateSessionOutput, t as CreateSessionOutputSchema, D as Decision, u as DecisionSchema, v as DeclaredIntent, w as DeclaredIntentSchema, x as DigestedEnvelope, y as EvaluateInput, z as EvaluateInputSchema, B as EvaluateOutput, F as EvaluateOutputSchema, G as EventResult, H as EventResultSchema, I as EventResultStatus, K as EventResultStatusSchema, L as EvidenceAck, M as EvidenceAckSchema, N as EvidenceBatchInput, O as EvidenceBatchInputSchema, Q as EvidenceEnvelope, R as EvidenceEvent, S as EvidenceEventSchema, T as EvidenceKind, U as EvidenceKindSchema, V as EvidenceSource, W as EvidenceSourceAllSchema, X as EvidenceSourceSchema, Y as GatewayDecisionPayload, Z as GatewayDecisionPayloadSchema, _ as Hex64, $ as Hex64Schema, a0 as IntentDeclaredPayload, a1 as IntentDeclaredPayloadSchema, J as JsonObject, a2 as JsonValueSchema, a3 as LlmCallEndPayload, a4 as LlmCallEndPayloadSchema, a5 as LlmCallStartPayload, a6 as LlmCallStartPayloadSchema, a7 as MAX_BATCH_EVENTS, a8 as OnReview, a9 as PAYMENT_ARTIFACTS, aa as PLATFORM_KINDS, ab as PayloadByKind, P as PaymentMomentPayload, ac as PaymentMomentPayloadSchema, a as PaymentSummary, ad as PaymentSummarySchema, ae as PlatformAnomalyPayload, af as PlatformAnomalyPayloadSchema, ag as PlatformEvidenceKind, ah as PlatformEvidenceKindSchema, ai as PlatformObservationPayload, aj as PlatformObservationPayloadSchema, ak as SESSION_CLOSE_REASONS, al as SOURCE_ORDER, am as SeqSchema, an as SessionClosePayload, ao as SessionClosePayloadSchema, ap as SessionIdSchema, aq as SessionOpenPayload, ar as SessionOpenPayloadSchema, as as Sig, at as SigSchema, au as TimestampSchema, av as ToolCallEndPayload, aw as ToolCallEndPayloadSchema, ax as ToolCallStartPayload, ay as ToolCallStartPayloadSchema, az as TransportGapPayload, aA as TransportGapPayloadSchema, aB as Verdict, aC as WIRE_KINDS, aD as WIRE_SOURCES, aE as WireEvidenceKind, aF as WireEvidenceKindSchema, aG as compareBySessionSource, aH as compareBySourceSeq, aI as isPlatformKind, aJ as isWireKind, aK as payloadSchemaFor } from '../verdict-6vCyoAHE.js';
3
3
  import { z } from 'zod';
4
- export { O as OnReview, V as Verdict } from '../verdict-BAahb5po.js';
5
4
 
6
5
  declare const PRIMITIVES: readonly ["THRESHOLD", "MEMBERSHIP", "MATCH", "PRESENCE", "FRESHNESS"];
7
6
  declare const PrimitiveSchema: z.ZodEnum<{
@@ -1,8 +1,6 @@
1
- import { B as Beltic } from '../client-C-mV_3A0.js';
2
- import '../index-Bjs3BPPU.js';
1
+ import { B as Beltic } from '../session-DsBWEP8d.js';
2
+ import '../verdict-6vCyoAHE.js';
3
3
  import 'zod';
4
- import '../verdict-BAahb5po.js';
5
- import '../session-5TClPLI4.js';
6
4
 
7
5
  /**
8
6
  * Adapter for the anti-fraud port already in Beltic's `platform` monorepo
@@ -0,0 +1,485 @@
1
+ import { L as EvidenceAck, G as EventResult, R as EvidenceEvent, B as EvaluateOutput, aB as Verdict, a8 as OnReview, a as PaymentSummary, P as PaymentMomentPayload, D as Decision$1, v as DeclaredIntent, ax as ToolCallStartPayload, b as JsonValue, J as JsonObject, an as SessionClosePayload, V as EvidenceSource, aE as WireEvidenceKind, C as ChainHead, ab as PayloadByKind } from './verdict-6vCyoAHE.js';
2
+
3
+ /**
4
+ * The edge signs event digests (Fraud SDK RFC › Modules › Identity Module);
5
+ * the platform signs its own PLATFORM chain and epoch anchors. Both are the
6
+ * same operation 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, …) (and /express)
143
+ * @belticlabs/agent-risk-sdk/mcp → wrapClient(session, …), wrapServer(beltic, …)
144
+ *
145
+ * Neither half decides risk locally: verdicts are platform-side.
146
+ *
147
+ * A host that runs its own agent loop takes `beltic.run(key)` — a `Run`
148
+ * keyed by its own session id that owns spans, verdicts and the mandate
149
+ * (GAP-79); every integration above accepts a `Run` where it accepts a
150
+ * `Session`. `Beltic.fromEnv()` reads `BELTIC_*` and, when none is set,
151
+ * answers a disabled client that records nothing and never throws into
152
+ * the work (GAP-78), so a host wires Beltic unconditionally.
153
+ *
154
+ * Evidence is a side channel of the work it observes. With `failOpen`
155
+ * nothing the SDK does throws into that work: `Session.emit` reports and
156
+ * answers `false`, `sessions.open` answers `null`, `evaluate` answers
157
+ * `null` — never an invented verdict; the host decides what to do without
158
+ * one (GAP-70). `sessions.start` and `sessions.ensure` throw either way:
159
+ * they are the primitives the fail-open entries are built on.
160
+ */
161
+
162
+ declare const SDK_VERSION = "0.3.0";
163
+ type Env = Record<string, string | undefined>;
164
+ interface BelticOptions extends Omit<ApiClientOptions, 'userAgent'> {
165
+ /** Buyer half. Without it, `sessions.start` is unavailable; the seller half works. */
166
+ identity?: AgentIdentity | undefined;
167
+ transport?: Partial<TransportOptions> | undefined;
168
+ /** What a synchronous seller hook does with REVIEW (GAP-52). */
169
+ onReview?: OnReview | undefined;
170
+ correlation?: CorrelationStore | undefined;
171
+ redact?: RedactFn | undefined;
172
+ now?: (() => Date) | undefined;
173
+ /** Evidence never fails the work it observes; see the module note (GAP-70). */
174
+ failOpen?: boolean | undefined;
175
+ /** Where fail-open failures go (and transport delivery failures unless `transport` names its own). Default: `console.error`. */
176
+ onError?: ((err: Error) => void) | undefined;
177
+ /** Fail-open only: how long `sessions.open` answers null after the platform refused to open a session (GAP-71). */
178
+ openRetryMs?: number | undefined;
179
+ /** `false` is what `Beltic.disabled()` sets: no platform is ever called (GAP-78). */
180
+ enabled?: boolean | undefined;
181
+ }
182
+ /** The platform's answer, with the verdict as a value the caller can ask `blocks(onReview)`. */
183
+ type Evaluation = EvaluateOutput & {
184
+ verdict: Verdict;
185
+ };
186
+ declare class Beltic {
187
+ readonly api: ApiClient;
188
+ readonly transport: Transport;
189
+ readonly sessions: Sessions;
190
+ readonly identity: AgentIdentity | undefined;
191
+ readonly correlation: CorrelationStore;
192
+ readonly onReview: OnReview;
193
+ readonly failOpen: boolean;
194
+ /** `false` for a disabled client (GAP-78): nothing is posted, `run`/`sessions.open` answer without a session. */
195
+ readonly enabled: boolean;
196
+ private readonly onError;
197
+ private readonly runs;
198
+ /**
199
+ * The client the environment describes: `BELTIC_API_KEY`,
200
+ * `BELTIC_BASE_URL`, `BELTIC_AGENT_SEED` (64 hex) and optionally
201
+ * `BELTIC_AGENT_CREDENTIAL`, fail-open by default. None set → a disabled
202
+ * client; some set → a configuration error, thrown (GAP-78).
203
+ */
204
+ static fromEnv(env?: Env, opts?: Partial<BelticOptions>): Beltic;
205
+ /** A client that records nothing and never throws into the work: the null object for "no evidence stream" (GAP-78). */
206
+ static disabled(opts?: Partial<BelticOptions>): Beltic;
207
+ constructor(opts: BelticOptions);
208
+ /**
209
+ * The platform's verdict on a payment — the seller's before it verifies,
210
+ * the buyer's before it presents. Read-your-writes: the buffered evidence
211
+ * is flushed first so the platform judges what the caller already saw
212
+ * (GAP-16). A recorded moment is accepted as is: only its comparable core
213
+ * (payee, amount, payer) is sent. `null` only under `failOpen`, when the
214
+ * platform could not be asked.
215
+ */
216
+ evaluate(sessionId: string, payment: PaymentSummary | PaymentMomentPayload): Promise<Evaluation | null>;
217
+ private decide;
218
+ /**
219
+ * The run for a key of the host's own — one object per key until it
220
+ * closes (the options count on the first call only). See `Run`.
221
+ */
222
+ run(key: string, opts?: RunOptions): Run;
223
+ flush(): Promise<void>;
224
+ shutdown(): Promise<void>;
225
+ /** `process.env` where there is a `process` (Node); `{}` on workerd, where the shell passes its `env`. */
226
+ private static processEnv;
227
+ }
228
+ declare function createBeltic(opts: BelticOptions): Beltic;
229
+
230
+ /**
231
+ * The platform's verdict on one payment as a value the host can ask
232
+ * questions of (Fraud Engine RFC › API: ALLOW | DENY | REVIEW). `absent`
233
+ * is the fail-open case: the platform could not be asked (GAP-70), and no
234
+ * verdict was invented — the host decides what to do without one. A
235
+ * `Run` memoizes decisions by the host's call id, so a re-run approval
236
+ * reads the verdict already given (GAP-79).
237
+ */
238
+
239
+ declare class Decision {
240
+ readonly evaluation: Evaluation | null;
241
+ private static readonly ABSENT;
242
+ private constructor();
243
+ static of(evaluation: Evaluation): Decision;
244
+ static absent(): Decision;
245
+ get value(): Decision$1 | null;
246
+ get reasonCodes(): readonly string[];
247
+ get decisionId(): string | null;
248
+ get allowed(): boolean;
249
+ get denied(): boolean;
250
+ get review(): boolean;
251
+ get absent(): boolean;
252
+ /** Whether a gate must stop the payment (GAP-52); an absent verdict never blocks. */
253
+ blocks(onReview: OnReview): boolean;
254
+ /** One sentence for the agent or the person: what Beltic said and why. */
255
+ explain(): string;
256
+ }
257
+
258
+ interface RunOptions {
259
+ /** What `sessions.open` sends when this run actually opens a session. */
260
+ open?: OpenSessionInput | undefined;
261
+ /** Close the session (`expired`) after this long without evidence; unset = only the host closes. */
262
+ idleMs?: number | undefined;
263
+ }
264
+ interface HumanDecisionInput {
265
+ /** Whether the person let the call proceed. */
266
+ allowed: boolean;
267
+ /** The host's own word for what happened: `approved`, `answered`, `rejected`, `cancelled`… */
268
+ outcome: string;
269
+ responder?: string | undefined;
270
+ /** The host's record of what was asked and chosen — a black box to the platform (GAP-75). */
271
+ record?: JsonObject | undefined;
272
+ }
273
+ interface DecideOptions {
274
+ /** The host's id for the call the verdict applies to: memoizes the decision and links it to the span. */
275
+ callId?: string | undefined;
276
+ /** The mandate as of now; declared first when it differs from the last one. */
277
+ intent?: DeclaredIntent | undefined;
278
+ }
279
+ interface RunDeps {
280
+ sessions: Sessions;
281
+ evaluate: (sessionId: string, payment: PaymentSummary | PaymentMomentPayload) => Promise<Evaluation | null>;
282
+ /** Called once the run closed, so the registry forgets it. */
283
+ onClosed: (run: Run) => void;
284
+ }
285
+ declare class Run {
286
+ private readonly deps;
287
+ readonly key: string;
288
+ private readonly opts;
289
+ private opened;
290
+ private current;
291
+ /** JCS hash of the mandate on the chain, and of the one the open input carried. */
292
+ private declared;
293
+ private openedWith;
294
+ private closed;
295
+ private timer;
296
+ private readonly calls;
297
+ private readonly decisions;
298
+ private readonly byPayment;
299
+ constructor(deps: RunDeps, key: string, opts?: RunOptions);
300
+ /** The session this run records into — opened on first use, `null` when there is none. */
301
+ session(): Promise<Session | null>;
302
+ private readonly opener;
303
+ /** `intent.declared`, unless the mandate is the one already on the chain. */
304
+ declare(intent: DeclaredIntent): Promise<boolean>;
305
+ /**
306
+ * The platform's verdict on a payment about to be presented. Asked once
307
+ * per call id: a host that re-runs its approval step reads the same
308
+ * `Decision`. An absent verdict is not memoized, so the next attempt
309
+ * asks again.
310
+ */
311
+ decide(payment: PaymentSummary | PaymentMomentPayload, opts?: DecideOptions): Promise<Decision>;
312
+ /** The decision given for a call id, or absent. */
313
+ decision(callId: string): Decision;
314
+ /**
315
+ * The decision given for a payment with the same comparable core (payee,
316
+ * amount, payer — or payee and amount when one side names no payer), or
317
+ * absent.
318
+ */
319
+ decisionFor(payment: PaymentSummary | PaymentMomentPayload): Decision;
320
+ /** A tool call the host runs itself, reported as two events by its own call id. */
321
+ readonly tools: {
322
+ start: (call: ToolCallStartPayload) => Promise<boolean>;
323
+ end: (callId: string, outcome?: {
324
+ output?: JsonValue;
325
+ }) => Promise<boolean>;
326
+ fail: (callId: string, error: unknown, outcome?: {
327
+ output?: JsonValue;
328
+ }) => Promise<boolean>;
329
+ };
330
+ /** A person's answer about a call, as the decision it was (GAP-75). */
331
+ humanDecided(callId: string, input: HumanDecisionInput): Promise<boolean>;
332
+ close(reason?: SessionClosePayload['reason']): Promise<void>;
333
+ private take;
334
+ private touch;
335
+ private static hash;
336
+ /** With the payer first, then without it. */
337
+ private static paymentKeys;
338
+ private static callOf;
339
+ }
340
+
341
+ /**
342
+ * A risk session as the SDK sees it: one chain per (sessionId, source),
343
+ * built at the edge (Fraud SDK RFC › Wire contract). The buyer half opens
344
+ * AGENT_TRACE sessions and announces them with `session.open` (seq 0) and
345
+ * `intent.declared` (seq 1; GAP-23/60); the seller half attaches to a bound
346
+ * session or opens its own INTERNAL_NETWORK session (GAP-13).
347
+ *
348
+ * `seq` is handed out only when the transport has room for the event
349
+ * (GAP-38): a dropped event never leaves a hole — the next accepted event
350
+ * is preceded by a `transport.gap` that counts the drops. `redact` is off
351
+ * by default (GAP-33).
352
+ *
353
+ * Evidence is a side channel of the agent's work: with `failOpen` an emit
354
+ * that cannot be chained (halted chain, closed transport) is reported and
355
+ * returns `false` instead of throwing into the model or tool call it
356
+ * observes (GAP-70).
357
+ */
358
+
359
+ type RedactFn = (kind: WireEvidenceKind, payload: JsonObject) => JsonObject;
360
+ /** Who created the session — the seller half treats a bound session as buyer-born. */
361
+ type SessionBorn = 'buyer' | 'seller';
362
+ interface SessionDeps {
363
+ transport: Transport;
364
+ signer?: Signer | undefined;
365
+ redact?: RedactFn | undefined;
366
+ now?: (() => Date) | undefined;
367
+ /** Called once the session closed, so the registry can forget it. */
368
+ onClosed?: ((session: Session) => void) | undefined;
369
+ /** Report instead of throw when an event cannot be chained (GAP-70). */
370
+ failOpen?: boolean | undefined;
371
+ onError?: ((err: Error) => void) | undefined;
372
+ }
373
+ /**
374
+ * One tool call as a span: `tool_call.start` now, `tool_call.end` with the
375
+ * outcome and the elapsed time when the host reports it. For hosts that run
376
+ * their own tool loop and cannot hand the SDK an `execute` to wrap.
377
+ */
378
+ interface ToolCallSpan {
379
+ readonly callId: string;
380
+ /** Resolves once `tool_call.start` is sequenced; `end` and `fail` wait for it. */
381
+ readonly opened: Promise<boolean>;
382
+ end(outcome?: {
383
+ output?: JsonValue;
384
+ }): Promise<boolean>;
385
+ fail(error: unknown, outcome?: {
386
+ output?: JsonValue;
387
+ }): Promise<boolean>;
388
+ }
389
+ declare class Session {
390
+ private readonly deps;
391
+ readonly id: string;
392
+ readonly source: EvidenceSource;
393
+ readonly expiresAt: string | null;
394
+ readonly born: SessionBorn;
395
+ private chain;
396
+ private building;
397
+ private dropped;
398
+ private droppedFirstTs;
399
+ private droppedLastTs;
400
+ private closed;
401
+ private readonly now;
402
+ constructor(deps: SessionDeps, id: string, source: EvidenceSource, expiresAt: string | null, born: SessionBorn);
403
+ get head(): ChainHead | null;
404
+ get droppedCount(): number;
405
+ get isClosed(): boolean;
406
+ /**
407
+ * Resolves once the event is sequenced and buffered — not once it is
408
+ * acknowledged. `false` when the event was dropped, or (fail-open) when
409
+ * the chain can no longer take it.
410
+ */
411
+ emit<K extends WireEvidenceKind>(kind: K, payload: PayloadByKind[K]): Promise<boolean>;
412
+ /** The tool call whose `execute` the host runs itself; see `ToolCallSpan`. */
413
+ toolCall(call: ToolCallStartPayload): ToolCallSpan;
414
+ private chainEvent;
415
+ close(reason?: SessionClosePayload['reason'], extra?: JsonObject): Promise<void>;
416
+ /** Read-your-writes: the platform must hold the evidence before anyone judges it (GAP-16/66). */
417
+ flush(): Promise<void>;
418
+ /** Serialized: two concurrent emits get consecutive seqs, never the same one. */
419
+ private next;
420
+ }
421
+ interface StartSessionInput {
422
+ intent?: DeclaredIntent;
423
+ runtime?: {
424
+ framework?: string;
425
+ model?: string;
426
+ };
427
+ attestations?: JsonObject;
428
+ }
429
+ /** What `open` sends when it actually opens: a value, or a resolver run only then. */
430
+ type OpenSessionInput = StartSessionInput | (() => StartSessionInput | Promise<StartSessionInput>);
431
+ /** What an integration takes: a session, or the run that owns one — resolved by `Sessions.resolve`. */
432
+ type SessionSource = Session | Run | null | undefined;
433
+ interface SessionsDeps {
434
+ api: ApiClient;
435
+ transport: Transport;
436
+ /** A disabled client (GAP-78): `open` answers null, `start`/`ensure` throw, nothing is posted. */
437
+ enabled?: boolean | undefined;
438
+ identity?: AgentIdentity | undefined;
439
+ redact?: RedactFn | undefined;
440
+ now?: (() => Date) | undefined;
441
+ sdkVersion: string;
442
+ failOpen?: boolean | undefined;
443
+ onError?: ((err: Error) => void) | undefined;
444
+ /** Fail-open only: after the platform refused to open a session, `open` resolves null for this long (GAP-71). */
445
+ openRetryMs?: number | undefined;
446
+ }
447
+ declare const DEFAULT_OPEN_RETRY_MS = 60000;
448
+ declare class Sessions {
449
+ private readonly deps;
450
+ /**
451
+ * One session object per (session, source) per process: a chain's head
452
+ * lives in it, so two objects for the same chain would both start at
453
+ * seq 0 and fork it. Closed sessions are forgotten; a process restart
454
+ * mid-session still loses the head (GAP-67).
455
+ */
456
+ private readonly attached;
457
+ /** Buyer sessions by the host's own key (GAP-71). */
458
+ private readonly opened;
459
+ private retryAt;
460
+ constructor(deps: SessionsDeps);
461
+ /** The session behind a source: itself, or the one the run opens (null when there is none). */
462
+ static resolve(source: SessionSource): Promise<Session | null>;
463
+ /**
464
+ * Buyer half: the evidence session for a key of the host's own (its
465
+ * session, run or conversation id), opened on first use and reused
466
+ * after. A halted chain is reopened as a fresh session that continues
467
+ * the same key; a closed key is forgotten. When the platform refuses to
468
+ * open one, a fail-open client resolves null — the host runs without
469
+ * evidence — until `openRetryMs` has passed (GAP-71); otherwise the
470
+ * refusal is thrown and the next call tries again. The identity is
471
+ * required either way: that is configuration.
472
+ */
473
+ open(key: string, input?: OpenSessionInput): Promise<Session | null>;
474
+ private forget;
475
+ private openFresh;
476
+ /** Buyer half: create an AGENT_TRACE session bound to the agent identity, then announce it on the chain. */
477
+ start(input?: StartSessionInput): Promise<Session>;
478
+ private identityFor;
479
+ private create;
480
+ /** Seller half: emit INTERNAL_NETWORK evidence into a session the buyer bound, or open a seller-born one. */
481
+ ensure(sessionId?: string | null): Promise<Session>;
482
+ private attach;
483
+ }
484
+
485
+ 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 };
@@ -470,6 +470,7 @@ declare const PaymentMomentPayloadSchema: z.ZodObject<{
470
470
  }>;
471
471
  raw: z.ZodRecord<z.ZodString, z.ZodType<JsonValue, unknown, z.core.$ZodTypeInternals<JsonValue, unknown>>>;
472
472
  }, z.core.$loose>;
473
+ /** Also the host's own decisions — its spend policy, a person's answer to an approval card or a question (GAP-75). */
473
474
  declare const GatewayDecisionPayloadSchema: z.ZodObject<{
474
475
  gateway: z.ZodString;
475
476
  call: z.ZodObject<{
@@ -544,4 +545,27 @@ interface PayloadByKind {
544
545
  'platform.anomaly': PlatformAnomalyPayload;
545
546
  }
546
547
 
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 };
548
+ /**
549
+ * The verdict as a value (Fraud Engine RFC › API: ALLOW | DENY | REVIEW).
550
+ * Layers combine by severity (GAP-45); a synchronous seller hook turns
551
+ * REVIEW into a stop or a pass according to its `onReview` (GAP-52). Both
552
+ * halves of the SDK and the engine share this one rule.
553
+ */
554
+
555
+ type OnReview = 'abort' | 'allow';
556
+ declare class Verdict {
557
+ readonly value: Decision;
558
+ private constructor();
559
+ static readonly ALLOW: Verdict;
560
+ static readonly REVIEW: Verdict;
561
+ static readonly DENY: Verdict;
562
+ static of(value: Decision): Verdict;
563
+ /** The more severe of the two. */
564
+ atLeast(other: Verdict | Decision): Verdict;
565
+ /** Whether a synchronous gate must stop the call (GAP-52). */
566
+ blocks(onReview: OnReview): boolean;
567
+ /** What the gate effectively did: DENY when it blocked, else the verdict itself. */
568
+ effective(onReview: OnReview): Decision;
569
+ }
570
+
571
+ 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, type OnReview as a8, PAYMENT_ARTIFACTS as a9, TransportGapPayloadSchema as aA, Verdict as aB, WIRE_KINDS as aC, WIRE_SOURCES as aD, type WireEvidenceKind as aE, WireEvidenceKindSchema as aF, compareBySessionSource as aG, compareBySourceSeq as aH, isPlatformKind as aI, isWireKind as aJ, payloadSchemaFor as aK, PLATFORM_KINDS as aa, type PayloadByKind as ab, PaymentMomentPayloadSchema as ac, PaymentSummarySchema as ad, type PlatformAnomalyPayload as ae, PlatformAnomalyPayloadSchema as af, type PlatformEvidenceKind as ag, PlatformEvidenceKindSchema as ah, type PlatformObservationPayload as ai, PlatformObservationPayloadSchema as aj, SESSION_CLOSE_REASONS as ak, SOURCE_ORDER as al, SeqSchema as am, type SessionClosePayload as an, SessionClosePayloadSchema as ao, SessionIdSchema as ap, type SessionOpenPayload as aq, SessionOpenPayloadSchema as ar, type Sig as as, SigSchema as at, TimestampSchema as au, type ToolCallEndPayload as av, ToolCallEndPayloadSchema as aw, type ToolCallStartPayload as ax, ToolCallStartPayloadSchema as ay, type TransportGapPayload 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 };
@@ -1,12 +1,10 @@
1
1
  import { RoutesConfig, x402ResourceServer } from '@x402/core/server';
2
2
  import { RequestHandler } from 'express';
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-DsBWEP8d.js';
4
+ import { G as GuardedMiddlewareOptions } from '../middleware-9gI0ou2i.js';
5
+ export { a as attachX402 } from '../adapter-BEpzr2R3.js';
6
+ import '../verdict-6vCyoAHE.js';
7
7
  import 'zod';
8
- import '../verdict-BAahb5po.js';
9
- import '../session-5TClPLI4.js';
10
8
 
11
9
  /** Seller half for express: `@x402/express`'s payment middleware with the Beltic hooks attached. */
12
10