@redditech/agent-protocol 0.0.0-stage → 0.2.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.
Files changed (55) hide show
  1. package/CHANGELOG.md +89 -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,599 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { AUDD_ASSET, AUDD_DECIMALS, SPL_TOKEN_PROGRAM_ID, canonicalSolanaNetworkAlias, deriveCanonicalAuddRailEnvironment, getAuddRailEnvironmentConfig, isAuddAsset, isKnownAuddMint, networkAliasForCaip2, validateAuddRailIdentity, } from './audd-rail-config.js';
3
+ export const REDDI_PAYMENT_CANONICALIZATION = 'reddi.canonical-json.sha256.v1';
4
+ export const REDDI_PAYMENT_JOB_SCHEMA_VERSION = 'reddi.payment-job.v1';
5
+ export const REDDI_PAYMENT_AGREEMENT_SCHEMA_VERSION = 'reddi.payment-agreement.v1';
6
+ export const REDDI_PAYMENT_INTENT_SCHEMA_VERSION = 'reddi.payment-intent.v1';
7
+ export const REDDI_PAYMENT_OBSERVATION_SCHEMA_VERSION = 'reddi.payment-observation.v1';
8
+ export const REDDI_REFUND_RECORD_SCHEMA_VERSION = 'reddi.refund-record.v1';
9
+ const HASH_PATTERN = /^sha256:[a-f0-9]{64}$/;
10
+ const POSITIVE_AMOUNT_PATTERN = /^[1-9]\d*$/;
11
+ const ID_PREFIXES = {
12
+ job: 'reddi.job',
13
+ agreement: 'reddi.agreement',
14
+ 'payment-intent': 'reddi.payment-intent',
15
+ 'payment-observation': 'reddi.payment-observation',
16
+ refund: 'reddi.refund',
17
+ };
18
+ const NON_ELIGIBLE_ENVIRONMENTS = new Set([
19
+ 'deterministic-fixture',
20
+ 'local-test-mint',
21
+ 'devnet-unverified',
22
+ ]);
23
+ const PARTNER_ACCEPTANCE_ENVIRONMENTS = new Set([
24
+ 'mainnet-gated',
25
+ 'controlled-live',
26
+ ]);
27
+ export function canonicalizePaymentObject(value) {
28
+ return canonicalize(value);
29
+ }
30
+ export function canonicalPaymentHash(value) {
31
+ return `sha256:${createHash('sha256').update(canonicalize(value)).digest('hex')}`;
32
+ }
33
+ export function deriveReddiPaymentId(kind, payload) {
34
+ const hash = createHash('sha256')
35
+ .update(canonicalize({ kind, payload }))
36
+ .digest('hex');
37
+ return `${ID_PREFIXES[kind]}:${hash}`;
38
+ }
39
+ export function validatePaymentRecordLabels(labels, path = '$.labels') {
40
+ const errors = [];
41
+ if (!isPlainObject(labels)) {
42
+ return { ok: false, errors: [error('malformed_labels', path, 'payment record labels are required')] };
43
+ }
44
+ const record = labels;
45
+ if (!isPaymentEnvironment(record.environment)) {
46
+ errors.push(error('malformed_labels', `${path}.environment`, 'environment label is invalid'));
47
+ }
48
+ if (!isPaymentEligibility(record.eligibility)) {
49
+ errors.push(error('malformed_labels', `${path}.eligibility`, 'eligibility label is invalid'));
50
+ }
51
+ if (isPaymentEnvironment(record.environment) && record.eligibility === 'eligible' && NON_ELIGIBLE_ENVIRONMENTS.has(record.environment)) {
52
+ errors.push(error('non_live_evidence_marked_eligible', `${path}.eligibility`, `${record.environment} payment evidence is not eligible for grant-volume claims`));
53
+ }
54
+ if (isPaymentEnvironment(record.environment) && PARTNER_ACCEPTANCE_ENVIRONMENTS.has(record.environment) && record.eligibility === 'eligible' && !isNonEmptyString(record.partnerAcceptanceRef)) {
55
+ errors.push(error('mainnet_partner_acceptance_missing', `${path}.partnerAcceptanceRef`, `${record.environment} AUDD evidence cannot be marked eligible without partner acceptance provenance`));
56
+ }
57
+ if (record.exclusionReason !== undefined && !isNonEmptyString(record.exclusionReason)) {
58
+ errors.push(error('malformed_labels', `${path}.exclusionReason`, 'exclusionReason must be non-empty when present'));
59
+ }
60
+ if (record.partnerAcceptanceRef !== undefined && !isNonEmptyString(record.partnerAcceptanceRef)) {
61
+ errors.push(error('malformed_labels', `${path}.partnerAcceptanceRef`, 'partnerAcceptanceRef must be non-empty when present'));
62
+ }
63
+ return errors.length === 0 ? { ok: true, record } : { ok: false, errors };
64
+ }
65
+ export function createPaymentJobRecord(input) {
66
+ const id = input.id ?? deriveReddiPaymentId('job', {
67
+ requestDisclosureHash: input.requestDisclosureHash,
68
+ sourceId: input.sourceId,
69
+ specialistId: input.specialistId,
70
+ nonce: input.nonce,
71
+ });
72
+ const record = {
73
+ schemaVersion: REDDI_PAYMENT_JOB_SCHEMA_VERSION,
74
+ id,
75
+ canonicalization: REDDI_PAYMENT_CANONICALIZATION,
76
+ labels: input.labels,
77
+ requestDisclosureHash: input.requestDisclosureHash,
78
+ sourceId: input.sourceId,
79
+ specialistId: input.specialistId,
80
+ nonce: input.nonce,
81
+ createdAt: input.createdAt,
82
+ };
83
+ throwIfInvalid(validatePaymentJobRecord(record), 'invalid_payment_job_record');
84
+ return record;
85
+ }
86
+ export function validatePaymentJobRecord(input) {
87
+ const errors = [];
88
+ if (!isPlainObject(input))
89
+ return { ok: false, errors: [error('malformed_record', '$', 'payment job record must be an object')] };
90
+ const record = input;
91
+ requireLiteral(record.schemaVersion, REDDI_PAYMENT_JOB_SCHEMA_VERSION, '$.schemaVersion', errors);
92
+ requirePrefix(record.id, 'reddi.job:', '$.id', errors);
93
+ requireLiteral(record.canonicalization, REDDI_PAYMENT_CANONICALIZATION, '$.canonicalization', errors);
94
+ appendLabelErrors(validatePaymentRecordLabels(record.labels), errors);
95
+ requireHash(record.requestDisclosureHash, '$.requestDisclosureHash', errors);
96
+ requireString(record.sourceId, '$.sourceId', errors);
97
+ requireString(record.specialistId, '$.specialistId', errors);
98
+ requireString(record.nonce, '$.nonce', errors);
99
+ validateOptionalTimestamp(record.createdAt, '$.createdAt', errors);
100
+ return errors.length === 0 ? { ok: true, record } : { ok: false, errors };
101
+ }
102
+ export function createPaymentAgreementRecord(input) {
103
+ const id = input.id ?? deriveReddiPaymentId('agreement', {
104
+ jobId: input.jobId,
105
+ signedOfferHash: input.signedOfferHash,
106
+ buyerPolicyDecisionHash: input.buyerPolicyDecisionHash,
107
+ sellerTermsHash: input.sellerTermsHash,
108
+ quoteExpiresAt: input.quoteExpiresAt,
109
+ });
110
+ const record = {
111
+ schemaVersion: REDDI_PAYMENT_AGREEMENT_SCHEMA_VERSION,
112
+ id,
113
+ canonicalization: REDDI_PAYMENT_CANONICALIZATION,
114
+ labels: input.labels,
115
+ jobId: input.jobId,
116
+ signedOfferHash: input.signedOfferHash,
117
+ buyerPolicyDecisionHash: input.buyerPolicyDecisionHash,
118
+ sellerTermsHash: input.sellerTermsHash,
119
+ quoteExpiresAt: input.quoteExpiresAt,
120
+ createdAt: input.createdAt,
121
+ };
122
+ throwIfInvalid(validatePaymentAgreementRecord(record), 'invalid_payment_agreement_record');
123
+ return record;
124
+ }
125
+ export function validatePaymentAgreementRecord(input) {
126
+ const errors = [];
127
+ if (!isPlainObject(input))
128
+ return { ok: false, errors: [error('malformed_record', '$', 'payment agreement record must be an object')] };
129
+ const record = input;
130
+ requireLiteral(record.schemaVersion, REDDI_PAYMENT_AGREEMENT_SCHEMA_VERSION, '$.schemaVersion', errors);
131
+ requirePrefix(record.id, 'reddi.agreement:', '$.id', errors);
132
+ requireLiteral(record.canonicalization, REDDI_PAYMENT_CANONICALIZATION, '$.canonicalization', errors);
133
+ appendLabelErrors(validatePaymentRecordLabels(record.labels), errors);
134
+ requirePrefix(record.jobId, 'reddi.job:', '$.jobId', errors);
135
+ requireHash(record.signedOfferHash, '$.signedOfferHash', errors);
136
+ requireHash(record.buyerPolicyDecisionHash, '$.buyerPolicyDecisionHash', errors);
137
+ requireHash(record.sellerTermsHash, '$.sellerTermsHash', errors);
138
+ validateTimestamp(record.quoteExpiresAt, '$.quoteExpiresAt', errors);
139
+ validateOptionalTimestamp(record.createdAt, '$.createdAt', errors);
140
+ return errors.length === 0 ? { ok: true, record } : { ok: false, errors };
141
+ }
142
+ export function createPaymentIntentRecord(input) {
143
+ const id = input.id ?? deriveReddiPaymentId('payment-intent', {
144
+ agreementId: input.agreementId,
145
+ network: input.network.caip2,
146
+ mint: input.asset.mint,
147
+ tokenProgram: input.asset.tokenProgram,
148
+ amountBaseUnits: input.asset.amountBaseUnits,
149
+ payTo: input.payTo,
150
+ destinationTokenAccount: input.destinationTokenAccount,
151
+ memo: input.memo,
152
+ validUntil: input.expiresAt,
153
+ });
154
+ const record = {
155
+ schemaVersion: REDDI_PAYMENT_INTENT_SCHEMA_VERSION,
156
+ id,
157
+ canonicalization: REDDI_PAYMENT_CANONICALIZATION,
158
+ labels: input.labels,
159
+ agreementId: input.agreementId,
160
+ network: input.network,
161
+ asset: input.asset,
162
+ payTo: input.payTo,
163
+ destinationTokenAccount: input.destinationTokenAccount,
164
+ memo: input.memo,
165
+ evidenceRequired: input.evidenceRequired,
166
+ quoteExpiresAt: input.quoteExpiresAt,
167
+ expiresAt: input.expiresAt,
168
+ refundPolicy: input.refundPolicy,
169
+ authorization: input.authorization,
170
+ createdAt: input.createdAt,
171
+ };
172
+ throwIfInvalid(validatePaymentIntentRecord(record), 'invalid_payment_intent_record');
173
+ return record;
174
+ }
175
+ export function createPaymentIntentDraft(input) {
176
+ return createPaymentIntentRecord({
177
+ ...input,
178
+ authorization: {
179
+ state: 'model_draft',
180
+ modelMayAuthorize: false,
181
+ operatorApprovalRequired: input.operatorApprovalRequired ?? input.labels.environment !== 'deterministic-fixture',
182
+ policyDecisionRef: input.policyDecisionRef,
183
+ },
184
+ });
185
+ }
186
+ export function validatePaymentIntentRecord(input) {
187
+ const errors = [];
188
+ if (!isPlainObject(input))
189
+ return { ok: false, errors: [error('malformed_record', '$', 'payment intent record must be an object')] };
190
+ const record = input;
191
+ requireLiteral(record.schemaVersion, REDDI_PAYMENT_INTENT_SCHEMA_VERSION, '$.schemaVersion', errors);
192
+ requirePrefix(record.id, 'reddi.payment-intent:', '$.id', errors);
193
+ requireLiteral(record.canonicalization, REDDI_PAYMENT_CANONICALIZATION, '$.canonicalization', errors);
194
+ appendLabelErrors(validatePaymentRecordLabels(record.labels), errors);
195
+ requirePrefix(record.agreementId, 'reddi.agreement:', '$.agreementId', errors);
196
+ validateNetwork(record.network, '$.network', errors);
197
+ requireString(record.asset?.symbol, '$.asset.symbol', errors);
198
+ requirePositiveAmount(record.asset?.amountBaseUnits, '$.asset.amountBaseUnits', errors);
199
+ validateOptionalNumber(record.asset?.decimals, '$.asset.decimals', errors);
200
+ validateOptionalString(record.asset?.mint, '$.asset.mint', errors);
201
+ validateOptionalString(record.asset?.tokenProgram, '$.asset.tokenProgram', errors);
202
+ requireString(record.payTo, '$.payTo', errors);
203
+ validateOptionalString(record.destinationTokenAccount, '$.destinationTokenAccount', errors);
204
+ validateOptionalString(record.memo, '$.memo', errors);
205
+ if (typeof record.evidenceRequired !== 'boolean')
206
+ errors.push(error('malformed_record', '$.evidenceRequired', 'evidenceRequired must be boolean'));
207
+ validateTimestamp(record.quoteExpiresAt, '$.quoteExpiresAt', errors);
208
+ validateTimestamp(record.expiresAt, '$.expiresAt', errors);
209
+ validateRefundPolicy(record.refundPolicy, '$.refundPolicy', errors);
210
+ validateAuthorization(record.authorization, '$.authorization', errors);
211
+ validateOptionalTimestamp(record.createdAt, '$.createdAt', errors);
212
+ validateAuddIntentRail(record, errors);
213
+ return errors.length === 0 ? { ok: true, record } : { ok: false, errors };
214
+ }
215
+ function validateAuddIntentRail(record, errors) {
216
+ if (!isPlainObject(record.labels) || !isPlainObject(record.asset) || !isPlainObject(record.network))
217
+ return;
218
+ const asset = record.asset;
219
+ const labels = record.labels;
220
+ const usesAudd = isAuddAsset(asset.symbol) || isKnownAuddMint(asset.mint);
221
+ if (!usesAudd)
222
+ return;
223
+ if (asset.symbol !== AUDD_ASSET) {
224
+ errors.push(error('audd_rail_identity_mismatch', '$.asset.symbol', 'AUDD payment intents must use the canonical AUDD asset symbol'));
225
+ }
226
+ if (!isNonEmptyString(asset.mint)) {
227
+ errors.push(error('audd_rail_identity_mismatch', '$.asset.mint', 'AUDD payment intents must include the mint'));
228
+ return;
229
+ }
230
+ if (asset.tokenProgram !== SPL_TOKEN_PROGRAM_ID) {
231
+ errors.push(error('audd_rail_identity_mismatch', '$.asset.tokenProgram', 'AUDD payment intents must use the SPL Token program'));
232
+ }
233
+ if (asset.decimals !== AUDD_DECIMALS) {
234
+ errors.push(error('audd_rail_identity_mismatch', '$.asset.decimals', 'AUDD payment intents must use six decimals'));
235
+ }
236
+ const railEnvironment = deriveCanonicalAuddRailEnvironment({
237
+ network: record.network.rapAlias ?? record.network.caip2,
238
+ caip2Network: record.network.caip2,
239
+ mint: asset.mint,
240
+ });
241
+ if (!railEnvironment) {
242
+ errors.push(error('audd_rail_identity_mismatch', '$.asset', 'AUDD payment intent identity must resolve to a configured rail'));
243
+ return;
244
+ }
245
+ if (labels.environment !== railEnvironment) {
246
+ errors.push(error('audd_rail_label_mismatch', '$.labels.environment', `AUDD payment intent environment must be ${railEnvironment}`));
247
+ }
248
+ if (labels.eligibility !== getAuddRailEnvironmentConfig(railEnvironment).grantEligibility) {
249
+ errors.push(error('audd_rail_label_mismatch', '$.labels.eligibility', `AUDD payment intent eligibility must match the ${railEnvironment} rail`));
250
+ }
251
+ if (railEnvironment !== 'deterministic-fixture' && record.authorization?.operatorApprovalRequired !== true) {
252
+ errors.push(error('audd_rail_label_mismatch', '$.authorization.operatorApprovalRequired', `${railEnvironment} AUDD payment intents require operator approval`));
253
+ }
254
+ const identity = validateAuddRailIdentity({
255
+ environment: railEnvironment,
256
+ network: canonicalObservationNetworkAlias(record.network, railEnvironment),
257
+ caip2: record.network.caip2,
258
+ mint: asset.mint,
259
+ tokenProgram: asset.tokenProgram,
260
+ decimals: asset.decimals,
261
+ enableGatedMainnet: true,
262
+ });
263
+ if (!identity.ok && identity.reasonCodes.some(isAuddRailIdentityMismatchReason)) {
264
+ errors.push(error('audd_rail_identity_mismatch', '$.asset', 'AUDD payment intent identity components must resolve to the same rail'));
265
+ }
266
+ }
267
+ export function formatPaymentObservationProofRef(input) {
268
+ const network = input.network.rapAlias ?? input.network.caip2;
269
+ const params = new URLSearchParams();
270
+ params.set('ix', String(input.instructionIndex));
271
+ if (input.mint)
272
+ params.set('mint', input.mint);
273
+ params.set('amount', input.amountBaseUnits);
274
+ return `${network}:${input.asset}:${input.signature}#${params.toString()}`;
275
+ }
276
+ export function createPaymentObservationRecord(input) {
277
+ const paymentProofRef = input.payment.paymentProofRef ?? formatPaymentObservationProofRef({
278
+ network: input.payment.network,
279
+ asset: input.payment.asset,
280
+ signature: input.payment.signature,
281
+ instructionIndex: input.payment.instructionIndex,
282
+ mint: input.payment.mint,
283
+ amountBaseUnits: input.payment.amountBaseUnits,
284
+ });
285
+ const id = input.id ?? deriveReddiPaymentId('payment-observation', {
286
+ network: input.payment.network.caip2,
287
+ signature: input.payment.signature,
288
+ instructionIndex: input.payment.instructionIndex,
289
+ mint: input.payment.mint,
290
+ amountBaseUnits: input.payment.amountBaseUnits,
291
+ destinationTokenAccount: input.payment.destinationTokenAccount,
292
+ });
293
+ const record = {
294
+ schemaVersion: REDDI_PAYMENT_OBSERVATION_SCHEMA_VERSION,
295
+ id,
296
+ canonicalization: REDDI_PAYMENT_CANONICALIZATION,
297
+ labels: input.labels,
298
+ paymentIntentId: input.paymentIntentId,
299
+ agreementId: input.agreementId,
300
+ observedAt: input.observedAt,
301
+ verifier: input.verifier,
302
+ payment: {
303
+ ...input.payment,
304
+ paymentProofRef,
305
+ },
306
+ confirmation: input.confirmation,
307
+ status: input.status,
308
+ };
309
+ throwIfInvalid(validatePaymentObservationRecord(record), 'invalid_payment_observation_record');
310
+ return record;
311
+ }
312
+ export function validatePaymentObservationRecord(input) {
313
+ const errors = [];
314
+ if (!isPlainObject(input))
315
+ return { ok: false, errors: [error('malformed_record', '$', 'payment observation record must be an object')] };
316
+ const record = input;
317
+ requireLiteral(record.schemaVersion, REDDI_PAYMENT_OBSERVATION_SCHEMA_VERSION, '$.schemaVersion', errors);
318
+ requirePrefix(record.id, 'reddi.payment-observation:', '$.id', errors);
319
+ requireLiteral(record.canonicalization, REDDI_PAYMENT_CANONICALIZATION, '$.canonicalization', errors);
320
+ appendLabelErrors(validatePaymentRecordLabels(record.labels), errors);
321
+ validateOptionalPrefix(record.paymentIntentId, 'reddi.payment-intent:', '$.paymentIntentId', errors);
322
+ validateOptionalPrefix(record.agreementId, 'reddi.agreement:', '$.agreementId', errors);
323
+ validateTimestamp(record.observedAt, '$.observedAt', errors);
324
+ requireString(record.verifier?.name, '$.verifier.name', errors);
325
+ requireString(record.verifier?.version, '$.verifier.version', errors);
326
+ requireString(record.payment?.rail, '$.payment.rail', errors);
327
+ validateNetwork(record.payment?.network, '$.payment.network', errors);
328
+ requireString(record.payment?.asset, '$.payment.asset', errors);
329
+ requirePositiveAmount(record.payment?.amountBaseUnits, '$.payment.amountBaseUnits', errors);
330
+ validateOptionalString(record.payment?.mint, '$.payment.mint', errors);
331
+ validateOptionalString(record.payment?.tokenProgram, '$.payment.tokenProgram', errors);
332
+ requireString(record.payment?.payTo, '$.payment.payTo', errors);
333
+ validateOptionalString(record.payment?.sourceTokenAccount, '$.payment.sourceTokenAccount', errors);
334
+ requireString(record.payment?.destinationTokenAccount, '$.payment.destinationTokenAccount', errors);
335
+ validateOptionalString(record.payment?.authority, '$.payment.authority', errors);
336
+ requireString(record.payment?.signature, '$.payment.signature', errors);
337
+ requireString(record.payment?.instructionIndex, '$.payment.instructionIndex', errors);
338
+ validateOptionalString(record.payment?.memo, '$.payment.memo', errors);
339
+ requireString(record.payment?.paymentProofRef, '$.payment.paymentProofRef', errors);
340
+ if (!isPlainObject(record.confirmation)) {
341
+ errors.push(error('malformed_record', '$.confirmation', 'confirmation metadata is required'));
342
+ }
343
+ else {
344
+ if (!Number.isSafeInteger(record.confirmation.slot) || record.confirmation.slot <= 0) {
345
+ errors.push(error('malformed_record', '$.confirmation.slot', 'slot must be a positive safe integer'));
346
+ }
347
+ validateOptionalNumber(record.confirmation.blockTime, '$.confirmation.blockTime', errors);
348
+ if (!['confirmed', 'finalized'].includes(String(record.confirmation.commitment))) {
349
+ errors.push(error('malformed_record', '$.confirmation.commitment', 'commitment must be confirmed or finalized'));
350
+ }
351
+ }
352
+ if (!['observed_confirmed', 'observed_failed', 'observation_inconclusive'].includes(String(record.status))) {
353
+ errors.push(error('malformed_record', '$.status', 'observation status is invalid'));
354
+ }
355
+ validateAuddObservationRail(record, errors);
356
+ return errors.length === 0 ? { ok: true, record } : { ok: false, errors };
357
+ }
358
+ function validateAuddObservationRail(record, errors) {
359
+ if (!isPlainObject(record.labels) || !isPlainObject(record.payment) || !isPlainObject(record.payment.network))
360
+ return;
361
+ const payment = record.payment;
362
+ const labels = record.labels;
363
+ const observesAudd = isAuddAsset(payment.asset) || isKnownAuddMint(payment.mint);
364
+ if (!observesAudd)
365
+ return;
366
+ if (payment.asset !== AUDD_ASSET) {
367
+ errors.push(error('audd_rail_identity_mismatch', '$.payment.asset', 'AUDD payment observations must use the canonical AUDD asset symbol'));
368
+ }
369
+ if (payment.rail !== 'svm-spl-token-transfer-checked') {
370
+ errors.push(error('audd_rail_identity_mismatch', '$.payment.rail', 'AUDD payment observations must use the SVM SPL Token TransferChecked rail'));
371
+ }
372
+ if (!isNonEmptyString(payment.mint)) {
373
+ errors.push(error('audd_rail_identity_mismatch', '$.payment.mint', 'AUDD payment observations must include the observed mint'));
374
+ return;
375
+ }
376
+ if (payment.tokenProgram !== SPL_TOKEN_PROGRAM_ID) {
377
+ errors.push(error('audd_rail_identity_mismatch', '$.payment.tokenProgram', 'AUDD payment observations must use the SPL Token program'));
378
+ }
379
+ const observedRail = deriveCanonicalAuddRailEnvironment({
380
+ network: payment.network.rapAlias ?? payment.network.caip2,
381
+ caip2Network: payment.network.caip2,
382
+ mint: payment.mint,
383
+ });
384
+ if (!observedRail) {
385
+ errors.push(error('audd_rail_identity_mismatch', '$.payment', 'AUDD payment observation identity must resolve to a configured rail'));
386
+ return;
387
+ }
388
+ if (labels.environment !== observedRail) {
389
+ errors.push(error('audd_rail_label_mismatch', '$.labels.environment', `AUDD payment observation environment must be ${observedRail}`));
390
+ }
391
+ if (labels.eligibility !== getAuddRailEnvironmentConfig(observedRail).grantEligibility) {
392
+ errors.push(error('audd_rail_label_mismatch', '$.labels.eligibility', `AUDD payment observation eligibility must match the ${observedRail} rail`));
393
+ }
394
+ const identity = validateAuddRailIdentity({
395
+ environment: observedRail,
396
+ network: canonicalObservationNetworkAlias(payment.network, observedRail),
397
+ caip2: payment.network.caip2,
398
+ mint: payment.mint,
399
+ tokenProgram: payment.tokenProgram,
400
+ decimals: AUDD_DECIMALS,
401
+ enableGatedMainnet: true,
402
+ });
403
+ if (!identity.ok && identity.reasonCodes.some(isAuddRailIdentityMismatchReason)) {
404
+ errors.push(error('audd_rail_identity_mismatch', '$.payment', 'AUDD payment observation identity components must resolve to the same rail'));
405
+ }
406
+ }
407
+ export function createRefundRecord(input) {
408
+ const id = input.id ?? deriveReddiPaymentId('refund', {
409
+ originalPaymentObservationId: input.originalPaymentObservationId,
410
+ refundObservationId: input.refundObservationId,
411
+ refundSignature: input.refundSignature,
412
+ amountBaseUnits: input.amountBaseUnits,
413
+ reason: input.reason,
414
+ });
415
+ const record = {
416
+ schemaVersion: REDDI_REFUND_RECORD_SCHEMA_VERSION,
417
+ id,
418
+ canonicalization: REDDI_PAYMENT_CANONICALIZATION,
419
+ labels: input.labels,
420
+ originalPaymentObservationId: input.originalPaymentObservationId,
421
+ refundObservationId: input.refundObservationId,
422
+ refundSignature: input.refundSignature,
423
+ amountBaseUnits: input.amountBaseUnits,
424
+ reason: input.reason,
425
+ state: input.state,
426
+ createdAt: input.createdAt,
427
+ };
428
+ throwIfInvalid(validateRefundRecord(record), 'invalid_refund_record');
429
+ return record;
430
+ }
431
+ export function validateRefundRecord(input) {
432
+ const errors = [];
433
+ if (!isPlainObject(input))
434
+ return { ok: false, errors: [error('malformed_record', '$', 'refund record must be an object')] };
435
+ const record = input;
436
+ requireLiteral(record.schemaVersion, REDDI_REFUND_RECORD_SCHEMA_VERSION, '$.schemaVersion', errors);
437
+ requirePrefix(record.id, 'reddi.refund:', '$.id', errors);
438
+ requireLiteral(record.canonicalization, REDDI_PAYMENT_CANONICALIZATION, '$.canonicalization', errors);
439
+ appendLabelErrors(validatePaymentRecordLabels(record.labels), errors);
440
+ requirePrefix(record.originalPaymentObservationId, 'reddi.payment-observation:', '$.originalPaymentObservationId', errors);
441
+ validateOptionalPrefix(record.refundObservationId, 'reddi.payment-observation:', '$.refundObservationId', errors);
442
+ validateOptionalString(record.refundSignature, '$.refundSignature', errors);
443
+ requirePositiveAmount(record.amountBaseUnits, '$.amountBaseUnits', errors);
444
+ requireString(record.reason, '$.reason', errors);
445
+ if (!['requested', 'operator_approved', 'observed_confirmed', 'failed', 'manual_review'].includes(String(record.state))) {
446
+ errors.push(error('malformed_record', '$.state', 'refund state is invalid'));
447
+ }
448
+ validateTimestamp(record.createdAt, '$.createdAt', errors);
449
+ return errors.length === 0 ? { ok: true, record } : { ok: false, errors };
450
+ }
451
+ function canonicalize(value) {
452
+ if (value === null)
453
+ return 'null';
454
+ if (typeof value === 'string' || typeof value === 'boolean')
455
+ return JSON.stringify(value);
456
+ if (typeof value === 'number') {
457
+ if (!Number.isFinite(value))
458
+ throw new Error('canonicalize_non_finite_number');
459
+ return JSON.stringify(value);
460
+ }
461
+ if (typeof value === 'bigint')
462
+ return JSON.stringify(value.toString());
463
+ if (Array.isArray(value))
464
+ return `[${value.map((item) => canonicalize(item)).join(',')}]`;
465
+ if (!isPlainObject(value))
466
+ throw new Error('canonicalize_unsupported_value');
467
+ const entries = Object.entries(value)
468
+ .filter(([, nested]) => nested !== undefined)
469
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));
470
+ return `{${entries.map(([key, nested]) => `${JSON.stringify(key)}:${canonicalize(nested)}`).join(',')}}`;
471
+ }
472
+ function canonicalObservationNetworkAlias(network, railEnvironment) {
473
+ return canonicalSolanaNetworkAlias(network.rapAlias)
474
+ ?? networkAliasForCaip2(network.caip2)
475
+ ?? (railEnvironment === 'local-test-mint' && network.rapAlias === getAuddRailEnvironmentConfig('local-test-mint').networkAlias ? network.rapAlias : undefined);
476
+ }
477
+ function isAuddRailIdentityMismatchReason(reason) {
478
+ return [
479
+ 'malformed_audd_rail_identity',
480
+ 'unknown_audd_rail_environment',
481
+ 'wrong_network',
482
+ 'wrong_caip2_network',
483
+ 'wrong_mint',
484
+ 'wrong_token_program',
485
+ 'wrong_decimals',
486
+ 'local_test_mint_required',
487
+ ].includes(reason);
488
+ }
489
+ function validateAuthorization(value, path, errors) {
490
+ if (!isPlainObject(value)) {
491
+ errors.push(error('malformed_record', path, 'authorization metadata is required'));
492
+ return;
493
+ }
494
+ const authorization = value;
495
+ if (!['model_draft', 'policy_approved', 'operator_approved'].includes(String(authorization.state))) {
496
+ errors.push(error('malformed_record', `${path}.state`, 'authorization state is invalid'));
497
+ }
498
+ if (authorization.modelMayAuthorize !== false) {
499
+ errors.push(error('model_spend_authority_rejected', `${path}.modelMayAuthorize`, 'models may draft payment intents but must never authorize spend'));
500
+ }
501
+ if (typeof authorization.operatorApprovalRequired !== 'boolean') {
502
+ errors.push(error('malformed_record', `${path}.operatorApprovalRequired`, 'operatorApprovalRequired must be boolean'));
503
+ }
504
+ validateOptionalString(authorization.policyDecisionRef, `${path}.policyDecisionRef`, errors);
505
+ validateOptionalString(authorization.operatorApprovalRef, `${path}.operatorApprovalRef`, errors);
506
+ validateOptionalTimestamp(authorization.approvedAt, `${path}.approvedAt`, errors);
507
+ if (authorization.state === 'operator_approved' && !isNonEmptyString(authorization.operatorApprovalRef)) {
508
+ errors.push(error('malformed_record', `${path}.operatorApprovalRef`, 'operator-approved intents require an operator approval reference'));
509
+ }
510
+ }
511
+ function validateRefundPolicy(value, path, errors) {
512
+ if (!isPlainObject(value)) {
513
+ errors.push(error('malformed_record', path, 'refund policy is required'));
514
+ return;
515
+ }
516
+ if (!['none', 'automatic', 'manual_review'].includes(String(value.mode))) {
517
+ errors.push(error('malformed_record', `${path}.mode`, 'refund mode is invalid'));
518
+ }
519
+ requireString(value.description, `${path}.description`, errors);
520
+ validateOptionalString(value.refundAddress, `${path}.refundAddress`, errors);
521
+ }
522
+ function validateNetwork(value, path, errors) {
523
+ if (!isPlainObject(value)) {
524
+ errors.push(error('malformed_record', path, 'network ref is required'));
525
+ return;
526
+ }
527
+ requireString(value.caip2, `${path}.caip2`, errors);
528
+ validateOptionalString(value.rapAlias, `${path}.rapAlias`, errors);
529
+ }
530
+ function appendLabelErrors(result, errors) {
531
+ if (!result.ok)
532
+ errors.push(...result.errors);
533
+ }
534
+ function throwIfInvalid(result, prefix) {
535
+ if (!result.ok)
536
+ throw new Error(`${prefix}:${result.errors.map((item) => `${item.code}:${item.path}`).join(',')}`);
537
+ }
538
+ function requireLiteral(value, expected, path, errors) {
539
+ if (value !== expected)
540
+ errors.push(error('malformed_record', path, `expected ${expected}`));
541
+ }
542
+ function requirePrefix(value, prefix, path, errors) {
543
+ if (!isNonEmptyString(value) || !value.startsWith(prefix))
544
+ errors.push(error('malformed_record', path, `expected id prefix ${prefix}`));
545
+ }
546
+ function validateOptionalPrefix(value, prefix, path, errors) {
547
+ if (value !== undefined && (!isNonEmptyString(value) || !value.startsWith(prefix))) {
548
+ errors.push(error('malformed_record', path, `expected id prefix ${prefix}`));
549
+ }
550
+ }
551
+ function requireHash(value, path, errors) {
552
+ if (!isNonEmptyString(value) || !HASH_PATTERN.test(value))
553
+ errors.push(error('malformed_record', path, 'expected sha256:<hex> hash'));
554
+ }
555
+ function requireString(value, path, errors) {
556
+ if (!isNonEmptyString(value))
557
+ errors.push(error('malformed_record', path, 'required string is missing'));
558
+ }
559
+ function validateOptionalString(value, path, errors) {
560
+ if (value !== undefined && !isNonEmptyString(value))
561
+ errors.push(error('malformed_record', path, 'must be a non-empty string when present'));
562
+ }
563
+ function requirePositiveAmount(value, path, errors) {
564
+ if (!isNonEmptyString(value) || !POSITIVE_AMOUNT_PATTERN.test(value)) {
565
+ errors.push(error('malformed_record', path, 'amount must be a positive integer string in base units'));
566
+ }
567
+ }
568
+ function validateOptionalNumber(value, path, errors) {
569
+ if (value !== undefined && (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)) {
570
+ errors.push(error('malformed_record', path, 'must be a non-negative safe integer when present'));
571
+ }
572
+ }
573
+ function validateTimestamp(value, path, errors) {
574
+ if (!isNonEmptyString(value) || Number.isNaN(Date.parse(value))) {
575
+ errors.push(error('malformed_record', path, 'timestamp must be an ISO-parseable string'));
576
+ }
577
+ }
578
+ function validateOptionalTimestamp(value, path, errors) {
579
+ if (value !== undefined)
580
+ validateTimestamp(value, path, errors);
581
+ }
582
+ function isPaymentEnvironment(value) {
583
+ return ['deterministic-fixture', 'local-test-mint', 'devnet-unverified', 'mainnet-gated', 'controlled-live'].includes(String(value));
584
+ }
585
+ function isPaymentEligibility(value) {
586
+ return ['non_eligible', 'pending_partner_acceptance', 'eligible', 'excluded'].includes(String(value));
587
+ }
588
+ function isPlainObject(value) {
589
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
590
+ return false;
591
+ const prototype = Object.getPrototypeOf(value);
592
+ return prototype === Object.prototype || prototype === null;
593
+ }
594
+ function isNonEmptyString(value) {
595
+ return typeof value === 'string' && value.trim().length > 0;
596
+ }
597
+ function error(code, path, message) {
598
+ return { code, path, message };
599
+ }
@@ -0,0 +1,33 @@
1
+ export type ReddiPolicyReasonCode = 'allowed' | 'budget_policy_missing' | 'invalid_quote' | 'malformed_limit' | 'request_amount_exceeds_limit' | 'session_budget_exceeded' | 'source_budget_exceeded' | 'specialist_budget_exceeded' | 'asset_network_budget_exceeded' | 'call_count_exceeded' | 'unsupported_asset_network' | 'operator_denied' | 'operator_approval_required' | 'payment_proof_missing' | 'unsupported_network_asset' | 'malformed_receipt' | 'credential_leakage_rejected';
2
+ export type ReddiPolicyApprovalState = 'approved' | 'denied' | 'requires_operator_approval';
3
+ export type ReddiPolicyDecision = {
4
+ schemaVersion: 'reddi.policy-decision.v1';
5
+ allowed: boolean;
6
+ reasonCodes: ReddiPolicyReasonCode[];
7
+ quotedAmount: {
8
+ amount: string;
9
+ asset: string;
10
+ network: string;
11
+ source?: string;
12
+ specialist?: string;
13
+ } | null;
14
+ limits?: Record<string, string | number | boolean | null>;
15
+ asset: string;
16
+ network: string;
17
+ approvalState: ReddiPolicyApprovalState;
18
+ auditNotes: string[];
19
+ operatorNote?: string;
20
+ };
21
+ export type BudgetPolicyDecisionLike = {
22
+ allowed: boolean;
23
+ reasonCodes: string[];
24
+ quotedAmount: ReddiPolicyDecision['quotedAmount'];
25
+ remainingBudget?: Record<string, string | number | boolean | null>;
26
+ auditNotes: string[];
27
+ };
28
+ export declare const REDDI_POLICY_REASON_CODES: readonly ReddiPolicyReasonCode[];
29
+ export declare function policyDecisionFromBudgetPolicyDecision(decision: BudgetPolicyDecisionLike, options?: {
30
+ approvalState?: ReddiPolicyApprovalState;
31
+ operatorNote?: string;
32
+ }): ReddiPolicyDecision;
33
+ export declare function isReddiPolicyReasonCode(code: unknown): code is ReddiPolicyReasonCode;