@redditech/agent-protocol 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/LICENSE +21 -0
  3. package/README.md +394 -2
  4. package/dist/adl.d.ts +141 -0
  5. package/dist/adl.js +3601 -0
  6. package/dist/agent-stack-fixtures.d.ts +743 -0
  7. package/dist/agent-stack-fixtures.js +1554 -0
  8. package/dist/ai-catalog.d.ts +128 -0
  9. package/dist/ai-catalog.js +373 -0
  10. package/dist/attestation-reputation.d.ts +102 -0
  11. package/dist/attestation-reputation.js +279 -0
  12. package/dist/audd-rail-config.d.ts +102 -0
  13. package/dist/audd-rail-config.js +294 -0
  14. package/dist/browser-wallet-approval.d.ts +293 -0
  15. package/dist/browser-wallet-approval.js +1201 -0
  16. package/dist/discovery-source.d.ts +115 -0
  17. package/dist/discovery-source.js +251 -0
  18. package/dist/evidence-archive.d.ts +73 -0
  19. package/dist/evidence-archive.js +238 -0
  20. package/dist/index.d.ts +23 -0
  21. package/dist/index.js +23 -0
  22. package/dist/mpp-tempo-receipt-shapes.d.ts +201 -0
  23. package/dist/mpp-tempo-receipt-shapes.js +330 -0
  24. package/dist/okf-adapter.d.ts +229 -0
  25. package/dist/okf-adapter.js +556 -0
  26. package/dist/okf-conformance.d.ts +208 -0
  27. package/dist/okf-conformance.js +651 -0
  28. package/dist/okf-instruction-safety.d.ts +192 -0
  29. package/dist/okf-instruction-safety.js +509 -0
  30. package/dist/onboarding-analyser-handoff.d.ts +391 -0
  31. package/dist/onboarding-analyser-handoff.js +959 -0
  32. package/dist/onboarding-state-machine.d.ts +228 -0
  33. package/dist/onboarding-state-machine.js +432 -0
  34. package/dist/payment-records.d.ts +181 -0
  35. package/dist/payment-records.js +599 -0
  36. package/dist/policy.d.ts +33 -0
  37. package/dist/policy.js +45 -0
  38. package/dist/provider-trust.d.ts +113 -0
  39. package/dist/provider-trust.js +346 -0
  40. package/dist/quasar-registry-compatibility.d.ts +113 -0
  41. package/dist/quasar-registry-compatibility.js +214 -0
  42. package/dist/ranking-explainability.d.ts +202 -0
  43. package/dist/ranking-explainability.js +302 -0
  44. package/dist/receipt-v2.d.ts +202 -0
  45. package/dist/receipt-v2.js +418 -0
  46. package/dist/repo-explorer-evidence-manifest.d.ts +387 -0
  47. package/dist/repo-explorer-evidence-manifest.js +1187 -0
  48. package/dist/source-diagnostics.d.ts +84 -0
  49. package/dist/source-diagnostics.js +193 -0
  50. package/dist/source-trust-conformance-matrix.d.ts +207 -0
  51. package/dist/source-trust-conformance-matrix.js +672 -0
  52. package/examples/ard-no-spend-ai-catalog.json +51 -0
  53. package/examples/ard-no-spend-demo.mjs +355 -0
  54. package/examples/interpretation-guide-scenarios.mjs +302 -0
  55. package/package.json +144 -4
@@ -0,0 +1,302 @@
1
+ /**
2
+ * Source-aware ranking explainability (#344, epic #336).
3
+ *
4
+ * Enriches resolve/ranking output with a typed, per-candidate explainability
5
+ * block so users and operators can see WHY a source/specialist was selected,
6
+ * rejected, or deferred — without ever blending discovery relevance into
7
+ * trust, safety, budget, payment, invocation, or publication decisions
8
+ * (`docs/DISCOVER-DECIDE-PROVE-BOUNDARIES.md`, #452).
9
+ *
10
+ * This module is PURE and read-model only: no network, no filesystem, no
11
+ * LLM/provider call, no MCP/tool call, no wallet/RPC action, no registry
12
+ * write, no publication, no payment, no trust or reputation mutation. It only
13
+ * explains in-memory candidates the caller already holds.
14
+ *
15
+ * Vocabulary reuse (no new words where existing ones fit):
16
+ * - Per-candidate lane diagnostics come from `source-diagnostics.ts`
17
+ * (`reddi.source-diagnostics.v1`, the #344 lane vocabulary incl.
18
+ * `relevance_only_not_trust`).
19
+ * - Gate/rejection reason codes reuse `discovery-source.ts`
20
+ * (`DiscoveryCandidateReasonCode`) wherever a code exists there.
21
+ * - The relevance boundary mirrors the #593 conformance matrix
22
+ * (`discoveryBoundary.scoreMeaning: 'relevance_only_not_trust'`).
23
+ *
24
+ * Fail-closed contract:
25
+ * - Every candidate always carries ALL required gates — including
26
+ * `settlement` and `attestation` — so no source kind can silently bypass
27
+ * settlement or attestation constraints (#344 AC).
28
+ * - A gate that has not produced positive evidence is `not_evaluated`, which
29
+ * is never treated as passed.
30
+ * - Relevance influences ranking ORDER only; it never changes a gate state
31
+ * and a high-relevance candidate with any failed gate is still `rejected`.
32
+ */
33
+ import { evaluateDiscoveryCandidatePolicyPreflight, } from './discovery-source.js';
34
+ import { createSourceAwareCandidateDiagnostics, } from './source-diagnostics.js';
35
+ export const RANKING_EXPLAINABILITY_SCHEMA_VERSION = 'reddi.ranking-explainability.v1';
36
+ /** Where the relevance-is-never-trust boundary is defined. */
37
+ export const RANKING_EXPLAINABILITY_BOUNDARIES_DOC_REF = 'docs/DISCOVER-DECIDE-PROVE-BOUNDARIES.md';
38
+ export const REQUIRED_RANKING_GATES = [
39
+ 'trust',
40
+ 'policy',
41
+ 'quote',
42
+ 'evidence',
43
+ 'payment',
44
+ 'budget',
45
+ 'settlement',
46
+ 'attestation',
47
+ ];
48
+ const GUARDRAILS = {
49
+ trustGranted: false,
50
+ invocationAuthorized: false,
51
+ paymentAuthorized: false,
52
+ publicationAuthorized: false,
53
+ settlementBypassPossible: false,
54
+ attestationBypassPossible: false,
55
+ };
56
+ const BOUNDARY = {
57
+ scoreMeaning: 'relevance_only_not_trust',
58
+ relevanceInfluencedGates: false,
59
+ boundariesDocRef: RANKING_EXPLAINABILITY_BOUNDARIES_DOC_REF,
60
+ };
61
+ const POLICY_GATE_CODES = ['source_not_allowed'];
62
+ const TRUST_GATE_CODES = ['trust_verification_required', 'provider_trust_mismatch'];
63
+ const QUOTE_GATE_CODES = ['missing_quote', 'malformed_candidate'];
64
+ const PAYMENT_GATE_CODES = ['unsupported_asset', 'unsupported_network'];
65
+ const BUDGET_GATE_CODES = ['over_budget'];
66
+ function decisionCodes(decision) {
67
+ if (!decision || decision.allowed)
68
+ return [];
69
+ return decision.reasonCodes;
70
+ }
71
+ function gateCell(gate, state, reasonCodes, summary) {
72
+ return { gate, state, reasonCodes, summary };
73
+ }
74
+ function trustGate(candidate, codes) {
75
+ const status = candidate.providerTrust?.verification?.status ?? 'missing';
76
+ const failedCodes = codes.filter((code) => TRUST_GATE_CODES.includes(code));
77
+ if (status === 'failed_verification') {
78
+ return gateCell('trust', 'failed', ['trust_failed_verification', ...failedCodes], 'RAP-side trust verification failed for this provider.');
79
+ }
80
+ if (failedCodes.length > 0) {
81
+ return gateCell('trust', 'failed', failedCodes, `Trust gate denied this candidate: ${failedCodes.join(', ')}.`);
82
+ }
83
+ if (status === 'verified') {
84
+ return gateCell('trust', 'passed', ['trust_verified'], 'RAP-side verification marked this provider as verified.');
85
+ }
86
+ return gateCell('trust', 'not_evaluated', [status === 'claimed' ? 'trust_claimed_unverified' : 'trust_unverified'], 'No RAP-side trust verification has passed for this provider; unverified is never treated as trusted.');
87
+ }
88
+ function policyGate(decision, codes) {
89
+ const failedCodes = codes.filter((code) => POLICY_GATE_CODES.includes(code));
90
+ if (failedCodes.length > 0) {
91
+ return gateCell('policy', 'failed', failedCodes, `Policy gate denied this candidate: ${failedCodes.join(', ')}.`);
92
+ }
93
+ if (decision) {
94
+ return decision.allowed
95
+ ? gateCell('policy', 'passed', ['policy_allowed'], 'Policy preflight allowed this candidate.')
96
+ : gateCell('policy', 'failed', decision.reasonCodes, `Policy preflight denied this candidate: ${decision.reasonCodes.join(', ')}.`);
97
+ }
98
+ return gateCell('policy', 'not_evaluated', ['policy_preflight_required'], 'RAP policy preflight has not run for this candidate.');
99
+ }
100
+ function quoteGate(candidate, decision, codes) {
101
+ const failedCodes = codes.filter((code) => QUOTE_GATE_CODES.includes(code));
102
+ if (!candidate.quote) {
103
+ return gateCell('quote', 'failed', ['missing_quote'], 'No quote is attached; quote preflight fails closed without one.');
104
+ }
105
+ if (failedCodes.length > 0) {
106
+ return gateCell('quote', 'failed', failedCodes, `Quote gate denied this candidate: ${failedCodes.join(', ')}.`);
107
+ }
108
+ if (decision) {
109
+ return gateCell('quote', 'passed', ['payment_quote_present'], `Quote is ${candidate.quote.amount} ${candidate.quote.asset} on ${candidate.quote.network}.`);
110
+ }
111
+ return gateCell('quote', 'not_evaluated', ['policy_preflight_required'], 'A quote is attached but quote preflight has not run.');
112
+ }
113
+ function paymentGate(candidate, decision, codes) {
114
+ const failedCodes = codes.filter((code) => PAYMENT_GATE_CODES.includes(code));
115
+ if (failedCodes.length > 0) {
116
+ return gateCell('payment', 'failed', failedCodes, `Payment gate denied this candidate: ${failedCodes.join(', ')}.`);
117
+ }
118
+ if (decision && candidate.quote) {
119
+ return gateCell('payment', 'passed', ['payment_policy_fit'], 'Quote asset and network fit the evaluated payment policy.');
120
+ }
121
+ return gateCell('payment', 'not_evaluated', ['policy_preflight_required'], 'Payment policy fit has not been evaluated for this candidate.');
122
+ }
123
+ function budgetGate(candidate, decision, codes) {
124
+ const failedCodes = codes.filter((code) => BUDGET_GATE_CODES.includes(code));
125
+ if (failedCodes.length > 0) {
126
+ return gateCell('budget', 'failed', failedCodes, 'Quote exceeds the policy budget or does not match the expected asset/network.');
127
+ }
128
+ if (decision && candidate.quote) {
129
+ return gateCell('budget', 'passed', ['budget_within_policy'], 'Quote is within the evaluated policy budget.');
130
+ }
131
+ return gateCell('budget', 'not_evaluated', ['policy_preflight_required'], 'Budget fit has not been evaluated for this candidate.');
132
+ }
133
+ function evidenceGate(evidence) {
134
+ const receiptCount = evidence?.receiptCount ?? 0;
135
+ const attestationCount = evidence?.attestationCount ?? 0;
136
+ if (receiptCount > 0 || attestationCount > 0) {
137
+ return gateCell('evidence', 'passed', ['reputation_history_present'], `Prior evidence exists: ${receiptCount} receipt(s), ${attestationCount} attestation(s).`);
138
+ }
139
+ return gateCell('evidence', 'not_evaluated', ['reputation_history_absent'], 'No prior receipt or attestation history is attached; the candidate is unproven.');
140
+ }
141
+ function settlementGate(evidence) {
142
+ const refs = evidence?.settlementReceiptRefs ?? [];
143
+ if (refs.length > 0) {
144
+ return gateCell('settlement', 'passed', ['settlement_receipts_recorded'], `Settlement receipts recorded: ${refs.join(', ')}.`);
145
+ }
146
+ return gateCell('settlement', 'not_evaluated', ['settlement_evidence_missing'], 'No settlement receipt evidence is attached; settlement constraints are never bypassed for any source.');
147
+ }
148
+ function attestationGate(evidence) {
149
+ const refs = evidence?.attestationRefs ?? [];
150
+ if (refs.length > 0) {
151
+ return gateCell('attestation', 'passed', ['attestation_evidence_recorded'], `Attestation evidence recorded: ${refs.join(', ')}.`);
152
+ }
153
+ return gateCell('attestation', 'not_evaluated', ['attestation_evidence_missing'], 'No attestation evidence is attached; attestation constraints are never bypassed for any source.');
154
+ }
155
+ function selectionFor(gates) {
156
+ const failed = gates.filter((cell) => cell.state === 'failed');
157
+ if (failed.length > 0) {
158
+ return {
159
+ state: 'rejected',
160
+ rankInfluencedByGates: false,
161
+ summary: `Rejected: gate(s) failed — ${failed.map((cell) => cell.gate).join(', ')}. Relevance never overrides a failed gate.`,
162
+ };
163
+ }
164
+ const outstanding = gates.filter((cell) => cell.state === 'not_evaluated');
165
+ if (outstanding.length > 0) {
166
+ return {
167
+ state: 'deferred',
168
+ rankInfluencedByGates: false,
169
+ summary: `Deferred: gate(s) outstanding — ${outstanding.map((cell) => cell.gate).join(', ')}. Not-evaluated gates never count as passed.`,
170
+ };
171
+ }
172
+ return {
173
+ state: 'selected',
174
+ rankInfluencedByGates: false,
175
+ summary: 'Selected: every required gate passed. Invocation, payment, and publication still require their own explicit flows.',
176
+ };
177
+ }
178
+ /**
179
+ * Derive the `reddi.ranking-explainability.v1` block for one candidate.
180
+ *
181
+ * All eight required gates are always emitted; there is no option to omit,
182
+ * override, or pre-pass a gate. Settlement and attestation gates only pass on
183
+ * explicit caller-held evidence references.
184
+ */
185
+ export function deriveRankingCandidateExplainability(candidate, options = {}) {
186
+ const policyDecision = options.policyDecision
187
+ ?? (options.policy ? evaluateDiscoveryCandidatePolicyPreflight(candidate, options.policy) : undefined);
188
+ const codes = decisionCodes(policyDecision);
189
+ const diagnostics = createSourceAwareCandidateDiagnostics(candidate, {
190
+ policyDecision,
191
+ reputation: {
192
+ receiptCount: options.evidence?.receiptCount,
193
+ attestationCount: options.evidence?.attestationCount,
194
+ },
195
+ });
196
+ const gates = [
197
+ trustGate(candidate, codes),
198
+ policyGate(policyDecision, codes),
199
+ quoteGate(candidate, policyDecision, codes),
200
+ evidenceGate(options.evidence),
201
+ paymentGate(candidate, policyDecision, codes),
202
+ budgetGate(candidate, policyDecision, codes),
203
+ settlementGate(options.evidence),
204
+ attestationGate(options.evidence),
205
+ ];
206
+ const orderedGates = REQUIRED_RANKING_GATES.map((gateId) => {
207
+ const found = gates.find((cell) => cell.gate === gateId);
208
+ if (!found) {
209
+ throw new Error(`ranking explainability is missing required gate: ${gateId}`);
210
+ }
211
+ return found;
212
+ });
213
+ const rejectionReasons = orderedGates
214
+ .filter((cell) => cell.state === 'failed')
215
+ .flatMap((cell) => cell.reasonCodes.map((code) => ({ gate: cell.gate, code, summary: cell.summary })));
216
+ const endpointHealth = options.health?.endpointHealth ?? 'not_probed';
217
+ const snapshotGeneratedAt = options.health?.snapshotGeneratedAt;
218
+ return {
219
+ schemaVersion: RANKING_EXPLAINABILITY_SCHEMA_VERSION,
220
+ sourceIdentity: {
221
+ identifier: candidate.identifier,
222
+ name: candidate.name,
223
+ sourceKind: candidate.sourceKind,
224
+ publisher: candidate.publisher,
225
+ url: candidate.url,
226
+ endpoint: candidate.endpoint,
227
+ rawSnapshotRef: candidate.rawSnapshotRef,
228
+ },
229
+ capabilityMatch: {
230
+ resourceType: candidate.resourceType,
231
+ mediaType: candidate.mediaType,
232
+ relevanceScore: candidate.relevance?.score,
233
+ scoreMeaning: 'relevance_only_not_trust',
234
+ matchedFields: options.matchedFields ?? [],
235
+ summary: candidate.relevance?.score === undefined
236
+ ? 'No relevance score was supplied; relevance would not affect any gate either way.'
237
+ : `Relevance score ${candidate.relevance.score} is a capability/search signal only — never trust, safety, budget, payment, invocation, or publication approval.`,
238
+ },
239
+ trustState: {
240
+ status: candidate.providerTrust?.verification?.status ?? 'missing',
241
+ reasonCodes: candidate.providerTrust?.verification?.reasonCodes ?? ['no_trust_record'],
242
+ failureReasons: candidate.providerTrust?.verification?.failureReasons ?? [],
243
+ summary: diagnostics.trustEvidence.summary,
244
+ },
245
+ paymentPolicyFit: {
246
+ quote: diagnostics.paymentFit.quote,
247
+ allowed: diagnostics.paymentFit.allowed,
248
+ reasonCodes: diagnostics.paymentFit.reasonCodes,
249
+ summary: diagnostics.paymentFit.summary,
250
+ },
251
+ healthFreshness: {
252
+ endpointHealth,
253
+ freshness: snapshotGeneratedAt || candidate.rawSnapshotRef ? 'snapshot_backed' : 'unknown',
254
+ snapshotGeneratedAt,
255
+ snapshotRef: candidate.rawSnapshotRef,
256
+ summary: endpointHealth === 'not_probed'
257
+ ? 'Endpoint health has not been probed; freshness comes from the recorded discovery snapshot only.'
258
+ : `Endpoint health is recorded as ${endpointHealth} by the discovery surface; nothing was probed here.`,
259
+ },
260
+ gates: orderedGates,
261
+ rejectionReasons,
262
+ selection: selectionFor(orderedGates),
263
+ diagnostics,
264
+ boundary: BOUNDARY,
265
+ guardrails: GUARDRAILS,
266
+ };
267
+ }
268
+ function relevanceOf(candidate) {
269
+ return candidate.relevance?.score ?? -1;
270
+ }
271
+ /**
272
+ * Enrich a resolve/ranking candidate list with per-candidate explainability.
273
+ *
274
+ * Ordering is relevance-descending (ties broken by identifier) and is the ONLY
275
+ * thing relevance controls: rejected candidates keep their relevance rank and
276
+ * are marked `rejected` with reasons instead of being silently re-ordered or
277
+ * hidden.
278
+ */
279
+ export function explainSourceRanking(candidates, options = {}) {
280
+ const ordered = [...candidates].sort((a, b) => {
281
+ const delta = relevanceOf(b) - relevanceOf(a);
282
+ if (delta !== 0)
283
+ return delta;
284
+ return a.identifier.localeCompare(b.identifier);
285
+ });
286
+ const ranked = ordered.map((candidate, index) => ({
287
+ rank: index + 1,
288
+ explainability: deriveRankingCandidateExplainability(candidate, {
289
+ policy: options.policy,
290
+ ...options.perCandidate?.[candidate.identifier],
291
+ }),
292
+ }));
293
+ return {
294
+ schemaVersion: RANKING_EXPLAINABILITY_SCHEMA_VERSION,
295
+ generatedAt: options.generatedAt,
296
+ ordering: 'relevance_desc_then_identifier_asc',
297
+ total: ranked.length,
298
+ candidates: ranked,
299
+ boundary: BOUNDARY,
300
+ guardrails: GUARDRAILS,
301
+ };
302
+ }
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Reddi receipt v2 (#739, #740).
3
+ *
4
+ * `reddi.receipt.v2` is a receipt the provider issues and signs. It names the
5
+ * provider, the model the provider declares it served, the hashes of the
6
+ * request and response, and the transaction the call was paid with. The
7
+ * provider signs those fields with its wallet key, so the receipt can be
8
+ * checked offline against the provider's address.
9
+ *
10
+ * It is the receipt for every paid call in V1 (#776). It also states what was
11
+ * paid: the currency and mint, the listed price, the protocol fee and where it
12
+ * went, and whether the call was paid directly or through escrow. A v1
13
+ * validator rejects a v2 receipt and this module rejects a v1 receipt.
14
+ *
15
+ * The payment fields are the provider's statement. A verifier that needs to
16
+ * rely on them checks the named transaction on chain; this module does not.
17
+ *
18
+ * What a valid signature shows: the holder of the provider key stated these
19
+ * fields. It does not show which model actually ran. "Declared model" is a
20
+ * declaration, not verified execution.
21
+ *
22
+ * Everything here is offline: no network, no clock unless a caller passes one,
23
+ * and no private key is ever accepted. Signing goes through a caller-supplied
24
+ * signer function.
25
+ */
26
+ export declare const REDDI_RECEIPT_V2_VERSION: "reddi.receipt.v2";
27
+ export declare const REDDI_RECEIPT_V2_PROOF_TYPE: "ed25519";
28
+ export type ReddiReceiptV2Network = 'solana-devnet' | 'solana-mainnet-beta';
29
+ export declare const REDDI_RECEIPT_V2_CURRENCIES: readonly ["SOL", "USDC", "PYUSD", "USDG", "AUDD"];
30
+ export type ReddiReceiptV2Currency = (typeof REDDI_RECEIPT_V2_CURRENCIES)[number];
31
+ export type ReddiReceiptV2Settlement = 'direct' | 'escrow' | 'metered-escrow';
32
+ /**
33
+ * What a per-token call used and settled. Present exactly when `settlement`
34
+ * is 'metered-escrow'. Token counts are the provider's report; `maxAmount` is
35
+ * what the buyer authorised and locked, `amount` is the actual cost paid, and
36
+ * `refunded` is the rest, returned to the buyer.
37
+ */
38
+ export type ReddiReceiptV2Metered = {
39
+ inputTokens: string;
40
+ outputTokens: string;
41
+ maxAmount: string;
42
+ refunded: string;
43
+ };
44
+ export type ReddiReceiptV2Payment = {
45
+ network: ReddiReceiptV2Network;
46
+ /** Signature of the transaction that paid for this call (base58). */
47
+ txSignature: string;
48
+ currency: ReddiReceiptV2Currency;
49
+ /** Token mint address (base58). Required for every currency except SOL, which has none. */
50
+ mint?: string;
51
+ /** What the buyer paid in total, in the currency's smallest unit, as a decimal string. For a metered call, the actual cost. */
52
+ amount: string;
53
+ /**
54
+ * Protocol fee taken out of `amount`, in the smallest unit. "0" when no fee
55
+ * applied. `treasury` is the address that received it and is required when
56
+ * the fee is above zero.
57
+ */
58
+ fee: {
59
+ amount: string;
60
+ treasury?: string;
61
+ };
62
+ /** Paying wallet (base58). Present only when the provider checked it against the transaction. */
63
+ payer?: string;
64
+ settlement: ReddiReceiptV2Settlement;
65
+ /** Token counts and the authorised maximum of a per-token call. */
66
+ metered?: ReddiReceiptV2Metered;
67
+ };
68
+ /**
69
+ * One call of a session: many calls paid from one metered escrow lock and
70
+ * settled once. Each call's receipt carries the running totals and the hash of
71
+ * the previous receipt, so the buyer holds a signed chain for every unit
72
+ * charged. Before the session settles a receipt has a `session` block and no
73
+ * `payment`: it is the provider's signed statement of what the lock owes, not
74
+ * proof of a transfer. The closing receipt has both, and its payment amount is
75
+ * the session's cumulative cost.
76
+ */
77
+ export type ReddiReceiptV2Session = {
78
+ /** The metered escrow paying for the session (base58). */
79
+ escrow: string;
80
+ /** The wallet that locked it (base58). */
81
+ payer: string;
82
+ network: ReddiReceiptV2Network;
83
+ currency: ReddiReceiptV2Currency;
84
+ /** Token mint address (base58). Required for every currency except SOL. */
85
+ mint?: string;
86
+ /** What the buyer locked, in smallest units. Cumulative cost never exceeds it. */
87
+ maxAmount: string;
88
+ /** 1 for the first call, then each call one more, with no gaps. */
89
+ sequence: string;
90
+ /** This call's token counts, as the provider reports them. A close request without a call states 0 and 0. */
91
+ inputTokens: string;
92
+ outputTokens: string;
93
+ /** Totals over every call up to and including this one. */
94
+ cumulativeInputTokens: string;
95
+ cumulativeOutputTokens: string;
96
+ /** What the totals cost at the provider's price, in smallest units, capped at `maxAmount`: what the settle will charge. */
97
+ cumulativeCost: string;
98
+ /** `hashReddiReceiptV2` of the previous call's receipt. Absent only on sequence 1. */
99
+ previousReceiptHash?: string;
100
+ /** True only on the receipt of the settle, which also carries `payment`. */
101
+ closed: boolean;
102
+ };
103
+ export type ReddiReceiptV2 = {
104
+ schemaVersion: typeof REDDI_RECEIPT_V2_VERSION;
105
+ /** The provider's Solana wallet address (base58). The signature must verify against it. */
106
+ providerId: string;
107
+ /** The model the provider says it served. A declaration, not proof of execution. */
108
+ declaredModel: string;
109
+ /** SHA-256 of the request body bytes, lowercase hex. */
110
+ requestHash: string;
111
+ /** SHA-256 of the response body bytes, lowercase hex. */
112
+ responseHash: string;
113
+ /** The transfer that paid. Absent only on a session receipt before the session settles. */
114
+ payment?: ReddiReceiptV2Payment;
115
+ /** Present on every call of a session. */
116
+ session?: ReddiReceiptV2Session;
117
+ /** The job this call was recorded as, when the provider knows it. */
118
+ jobId?: string;
119
+ /** ISO 8601 UTC time the provider issued this receipt. */
120
+ issuedAt: string;
121
+ };
122
+ export type SignedReddiReceiptV2 = {
123
+ receipt: ReddiReceiptV2;
124
+ proof: {
125
+ type: typeof REDDI_RECEIPT_V2_PROOF_TYPE;
126
+ /** Base64 of the 64-byte ed25519 signature over the canonical receipt bytes. */
127
+ signature: string;
128
+ };
129
+ };
130
+ export type ReddiReceiptV2ErrorCode = 'malformed_receipt' | 'unsupported_version' | 'malformed_proof' | 'signature_invalid' | 'provider_mismatch' | 'declared_model_mismatch' | 'request_hash_mismatch' | 'response_hash_mismatch' | 'payment_mismatch' | 'session_mismatch' | 'session_chain_broken';
131
+ export type ReddiReceiptV2Error = {
132
+ code: ReddiReceiptV2ErrorCode;
133
+ path: string;
134
+ message: string;
135
+ };
136
+ export type ReddiReceiptV2Verification = {
137
+ ok: true;
138
+ receipt: ReddiReceiptV2;
139
+ } | {
140
+ ok: false;
141
+ errors: ReddiReceiptV2Error[];
142
+ };
143
+ /** What the verifier itself knows about the call. Every field given must match the signed receipt. */
144
+ export type ReddiReceiptV2Expectation = {
145
+ providerId?: string;
146
+ declaredModel?: string;
147
+ requestHash?: string;
148
+ responseHash?: string;
149
+ /** `network` and `txSignature` always compare; each other field compares when given. */
150
+ payment?: {
151
+ network: ReddiReceiptV2Network;
152
+ txSignature: string;
153
+ } & Partial<Omit<ReddiReceiptV2Payment, 'network' | 'txSignature' | 'fee'>> & {
154
+ fee?: {
155
+ amount: string;
156
+ treasury?: string;
157
+ };
158
+ };
159
+ /** Each field given must equal the signed session block. A receipt without one fails. */
160
+ session?: Partial<ReddiReceiptV2Session>;
161
+ };
162
+ /** Signs the canonical bytes with the provider's key and returns the 64-byte signature. The key never enters this module. */
163
+ export type ReddiReceiptV2Signer = (message: Uint8Array) => Uint8Array | Promise<Uint8Array>;
164
+ /** SHA-256 of a body, lowercase hex. Strings are hashed as UTF-8. */
165
+ export declare function hashReddiReceiptV2Body(body: string | Uint8Array): string;
166
+ export declare function validateReddiReceiptV2(input: unknown): ReddiReceiptV2Verification;
167
+ /**
168
+ * The exact bytes the provider signs: JSON with a fixed field order and no
169
+ * whitespace. The version string is the first field, so a signature for this
170
+ * receipt cannot be replayed as a signature for another kind of message.
171
+ */
172
+ export declare function canonicalizeReddiReceiptV2(receipt: ReddiReceiptV2): string;
173
+ /** SHA-256 of a receipt's canonical bytes, lowercase hex: what the next call of a session names as `previousReceiptHash`. */
174
+ export declare function hashReddiReceiptV2(receipt: ReddiReceiptV2): string;
175
+ /** Validates the receipt, asks the signer for a signature, and refuses to return one that does not verify. */
176
+ export declare function signReddiReceiptV2(receipt: ReddiReceiptV2, signer: ReddiReceiptV2Signer): Promise<SignedReddiReceiptV2>;
177
+ /**
178
+ * Verifies a signed receipt offline. The signature must verify against the
179
+ * `providerId` inside the receipt, and every field of `expected` that is given
180
+ * must equal the signed value. Pass what you know yourself: the provider you
181
+ * paid, the hashes of the bytes you sent and received, the transaction you paid
182
+ * with. Without `expected`, a pass only says some key signed some statement.
183
+ */
184
+ export declare function verifyReddiReceiptV2(input: unknown, expected?: ReddiReceiptV2Expectation): ReddiReceiptV2Verification;
185
+ /**
186
+ * Checks a session's receipts as one chain, oldest first: each verifies on its
187
+ * own (pass `expected` for what every receipt must state, for example the
188
+ * provider and the escrow), they share provider, escrow, payer, network,
189
+ * currency, mint and maximum, sequences run 1, 2, 3 with no gap, each names the
190
+ * previous receipt's hash, the totals are the running sums of each call's
191
+ * counts, the cost never goes down, and only the last may be closed. It does
192
+ * not recompute cost from a price: compare `cumulativeCost` with your own
193
+ * count of tokens at the price you were quoted.
194
+ */
195
+ export declare function verifyReddiReceiptV2Session(chain: readonly unknown[], expected?: ReddiReceiptV2Expectation): {
196
+ ok: true;
197
+ receipts: ReddiReceiptV2[];
198
+ closed: boolean;
199
+ } | {
200
+ ok: false;
201
+ errors: ReddiReceiptV2Error[];
202
+ };