@hlos-ai/schemas 0.4.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,21 +1,96 @@
1
1
  import {
2
2
  CorrelationIdSchema,
3
3
  CrossingIdSchema,
4
+ DispatchIdBrand,
5
+ DispatchIdSchema,
4
6
  IdempotencyKeySchema,
5
7
  PassportIdSchema,
6
8
  ReceiptIdSchema,
7
9
  WalletIdSchema,
8
- __require,
9
10
  generateCrossingId,
11
+ generateDispatchId,
10
12
  generateId,
11
13
  generatePassportId,
12
14
  generateReceiptId,
13
15
  generateWalletId
14
- } from "./chunk-RQP6MVT3.js";
16
+ } from "./chunk-ADIQW3HO.js";
17
+ import {
18
+ BASE64URL_SHA256_REGEX,
19
+ Base64urlEd25519SigSchema,
20
+ Base64urlSha256Schema,
21
+ RECEIPT_HASH_GOLDEN_FIXTURE,
22
+ ReceiptHashSchema,
23
+ base64urlToBytes,
24
+ bytesToBase64url,
25
+ computeContentHash,
26
+ computeReceiptHash,
27
+ jcsCanonicalize
28
+ } from "./chunk-I4QGTJTP.js";
29
+ import {
30
+ __require
31
+ } from "./chunk-DGUM43GV.js";
15
32
 
16
- // src/surface.ts
33
+ // src/aar-envelope-v0.ts
17
34
  import { z } from "zod";
18
- var SurfaceSchema = z.enum([
35
+ var AAR_ENVELOPE_TYPE = "https://hlos.ai/schema/AAREnvelopeV0";
36
+ var AAR_ENVELOPE_VERSION = 0;
37
+ var AAREnvelopeV0Schema = z.object({
38
+ "@type": z.literal(AAR_ENVELOPE_TYPE),
39
+ version: z.literal(AAR_ENVELOPE_VERSION),
40
+ content_type: z.string().min(1),
41
+ content_hash: Base64urlSha256Schema,
42
+ inner: z.unknown(),
43
+ signer_id: z.string().min(1),
44
+ signature: Base64urlEd25519SigSchema,
45
+ issued_at: z.string().datetime(),
46
+ previous_aar_hash: z.string().min(1)
47
+ });
48
+ var AAREnvelopeV0TypedSchema = (contentType, innerSchema) => AAREnvelopeV0Schema.extend({
49
+ content_type: z.literal(contentType),
50
+ inner: innerSchema
51
+ });
52
+
53
+ // src/verify-aar.ts
54
+ function toBuffer(bytes) {
55
+ const ab = new ArrayBuffer(bytes.byteLength);
56
+ new Uint8Array(ab).set(bytes);
57
+ return ab;
58
+ }
59
+ async function importPublicKey(publicKey) {
60
+ if (typeof CryptoKey !== "undefined" && publicKey instanceof CryptoKey) {
61
+ return publicKey;
62
+ }
63
+ const raw = publicKey;
64
+ return crypto.subtle.importKey(
65
+ "raw",
66
+ toBuffer(raw),
67
+ "Ed25519",
68
+ false,
69
+ ["verify"]
70
+ );
71
+ }
72
+ async function verifyAAR(envelope, publicKey) {
73
+ const parsed = AAREnvelopeV0Schema.parse(envelope);
74
+ const contentHash = computeContentHash(parsed.inner);
75
+ if (contentHash !== parsed.content_hash) {
76
+ throw new Error("AAR content hash mismatch");
77
+ }
78
+ const key = await importPublicKey(publicKey);
79
+ const verified = await crypto.subtle.verify(
80
+ "Ed25519",
81
+ key,
82
+ toBuffer(base64urlToBytes(parsed.signature)),
83
+ toBuffer(base64urlToBytes(parsed.content_hash))
84
+ );
85
+ if (!verified) {
86
+ throw new Error(`AAR signature verification failed for signer ${parsed.signer_id}`);
87
+ }
88
+ return parsed;
89
+ }
90
+
91
+ // src/surface.ts
92
+ import { z as z2 } from "zod";
93
+ var SurfaceSchema = z2.enum([
19
94
  "mcp",
20
95
  // Model Context Protocol servers
21
96
  "x402",
@@ -34,11 +109,11 @@ var SurfaceSchema = z.enum([
34
109
  var SURFACES = SurfaceSchema.options;
35
110
 
36
111
  // src/response.ts
37
- import { z as z3 } from "zod";
112
+ import { z as z4 } from "zod";
38
113
 
39
114
  // src/error-codes.ts
40
- import { z as z2 } from "zod";
41
- var KernelErrorCodeSchema = z2.enum([
115
+ import { z as z3 } from "zod";
116
+ var KernelErrorCodeSchema = z3.enum([
42
117
  // 4xx Client Errors
43
118
  "INVALID_REQUEST",
44
119
  // 400 - Malformed request body
@@ -87,49 +162,49 @@ function error(code, message, correlationId, details) {
87
162
  }
88
163
  };
89
164
  }
90
- var SuccessResponseSchema = (dataSchema) => z3.object({
91
- success: z3.literal(true),
165
+ var SuccessResponseSchema = (dataSchema) => z4.object({
166
+ success: z4.literal(true),
92
167
  data: dataSchema,
93
- meta: z3.object({
94
- request_id: z3.string().optional(),
95
- correlation_id: z3.string()
168
+ meta: z4.object({
169
+ request_id: z4.string().optional(),
170
+ correlation_id: z4.string()
96
171
  }).optional()
97
172
  });
98
- var ErrorResponseSchema = z3.object({
99
- success: z3.literal(false),
100
- error: z3.object({
173
+ var ErrorResponseSchema = z4.object({
174
+ success: z4.literal(false),
175
+ error: z4.object({
101
176
  code: KernelErrorCodeSchema,
102
- message: z3.string(),
103
- details: z3.unknown().optional(),
104
- correlation_id: z3.string()
177
+ message: z4.string(),
178
+ details: z4.unknown().optional(),
179
+ correlation_id: z4.string()
105
180
  })
106
181
  });
107
182
 
108
183
  // src/receipt-v0.ts
109
- import { z as z4 } from "zod";
184
+ import { z as z5 } from "zod";
110
185
  var RECEIPT_TYPE_URI = "https://hlos.ai/schema/SignedReceiptV0";
111
186
  var RECEIPT_VERSION = 0;
112
187
  var CONTENT_HASH_LENGTH = 43;
113
188
  var SIGNATURE_LENGTH = 86;
114
- var SignedReceiptV0Schema = (contentSchema) => z4.object({
115
- "@type": z4.literal(RECEIPT_TYPE_URI),
116
- version: z4.literal(RECEIPT_VERSION),
117
- receipt_id: z4.string(),
189
+ var SignedReceiptV0Schema = (contentSchema) => z5.object({
190
+ "@type": z5.literal(RECEIPT_TYPE_URI),
191
+ version: z5.literal(RECEIPT_VERSION),
192
+ receipt_id: z5.string(),
118
193
  content: contentSchema,
119
194
  // SHA-256 digest (32 bytes) = exactly 43 chars base64url
120
- content_hash: z4.string().regex(
195
+ content_hash: z5.string().regex(
121
196
  /^[A-Za-z0-9_-]{43}$/,
122
197
  "content_hash must be 43-char base64url (32-byte SHA-256)"
123
198
  ),
124
199
  // Ed25519 signature (64 bytes) = exactly 86 chars base64url
125
- signature: z4.string().regex(
200
+ signature: z5.string().regex(
126
201
  /^[A-Za-z0-9_-]{86}$/,
127
202
  "signature must be 86-char base64url (64-byte Ed25519)"
128
203
  ),
129
- key_id: z4.string().min(1),
130
- issued_at: z4.string().datetime()
204
+ key_id: z5.string().min(1),
205
+ issued_at: z5.string().datetime()
131
206
  });
132
- var SignedReceiptV0LooseSchema = SignedReceiptV0Schema(z4.unknown());
207
+ var SignedReceiptV0LooseSchema = SignedReceiptV0Schema(z5.unknown());
133
208
  function isSignedReceiptV0(value) {
134
209
  if (typeof value !== "object" || value === null) return false;
135
210
  const obj = value;
@@ -137,8 +212,8 @@ function isSignedReceiptV0(value) {
137
212
  }
138
213
 
139
214
  // src/shared-contract.ts
140
- import { z as z5 } from "zod";
141
- var KernelErrorCodeSchema2 = z5.enum([
215
+ import { z as z6 } from "zod";
216
+ var KernelErrorCodeSchema2 = z6.enum([
142
217
  // Validation / Request errors
143
218
  "VALIDATION_ERROR",
144
219
  // 400 - Input validation failed
@@ -200,30 +275,30 @@ var ERROR_CODE_STATUS = {
200
275
  INTERNAL_ERROR: 500,
201
276
  SERVICE_UNAVAILABLE: 503
202
277
  };
203
- var KernelOkSchema = (dataSchema) => z5.object({
204
- ok: z5.literal(true),
205
- status: z5.union([
206
- z5.number().int().min(200).max(299),
207
- z5.literal(304)
278
+ var KernelOkSchema = (dataSchema) => z6.object({
279
+ ok: z6.literal(true),
280
+ status: z6.union([
281
+ z6.number().int().min(200).max(299),
282
+ z6.literal(304)
208
283
  ]),
209
284
  data: dataSchema
210
285
  });
211
- var KernelErrorSchema = z5.object({
212
- ok: z5.literal(false),
213
- status: z5.number().int().min(400).max(599),
214
- error: z5.object({
286
+ var KernelErrorSchema = z6.object({
287
+ ok: z6.literal(false),
288
+ status: z6.number().int().min(400).max(599),
289
+ error: z6.object({
215
290
  code: KernelErrorCodeSchema2,
216
291
  // P0 FIX: was z.string()
217
- message: z5.string(),
218
- details: z5.record(z5.unknown()).optional()
292
+ message: z6.string(),
293
+ details: z6.record(z6.unknown()).optional()
219
294
  })
220
295
  });
221
- var CrossingIdFormatSchema = z5.string().regex(/^cross_[a-z0-9]{20,}$/i, "Invalid CrossingId format (expected: cross_...)");
222
- var ReceiptIdFormatSchema = z5.string().regex(/^rcpt_[0-9A-HJKMNP-TV-Z]{26}$/i, "Invalid ReceiptId format (expected: rcpt_...)");
223
- var PassportIdFormatSchema = z5.string().regex(/^passport_[a-z0-9]{20,}$/i, "Invalid PassportId format (expected: passport_...)");
224
- var WalletIdFormatSchema = z5.string().regex(/^wallet_[a-z0-9]{20,}$/i, "Invalid WalletId format (expected: wallet_...)");
225
- var FundingSourceSchema = z5.enum(["SPONSOR", "PLATFORM", "USER"]);
226
- var CredentialSourceSchema = z5.enum([
296
+ var CrossingIdFormatSchema = z6.string().regex(/^cross_[a-z0-9]{20,}$/i, "Invalid CrossingId format (expected: cross_...)");
297
+ var ReceiptIdFormatSchema = z6.string().regex(/^rcpt_[0-9A-HJKMNP-TV-Z]{26}$/i, "Invalid ReceiptId format (expected: rcpt_...)");
298
+ var PassportIdFormatSchema = z6.string().regex(/^passport_[a-z0-9]{20,}$/i, "Invalid PassportId format (expected: passport_...)");
299
+ var WalletIdFormatSchema = z6.string().regex(/^wallet_[a-z0-9]{20,}$/i, "Invalid WalletId format (expected: wallet_...)");
300
+ var FundingSourceSchema = z6.enum(["SPONSOR", "PLATFORM", "USER"]);
301
+ var CredentialSourceSchema = z6.enum([
227
302
  "SPONSOR_KEY",
228
303
  // Sponsor-provisioned key
229
304
  "BYOK",
@@ -241,46 +316,46 @@ function deriveFundingSource(credentialSource) {
241
316
  return "PLATFORM";
242
317
  }
243
318
  }
244
- var CrossingSnapshotV0Schema = z5.object({
319
+ var CrossingSnapshotV0Schema = z6.object({
245
320
  crossingId: CrossingIdFormatSchema,
246
- capabilityId: z5.string(),
321
+ capabilityId: z6.string(),
247
322
  passportId: PassportIdFormatSchema,
248
323
  // Scoping
249
- event_id: z5.string().nullable(),
250
- access_window_id: z5.string().nullable(),
251
- access_grant_id: z5.string().nullable(),
324
+ event_id: z6.string().nullable(),
325
+ access_window_id: z6.string().nullable(),
326
+ access_grant_id: z6.string().nullable(),
252
327
  // Attribution
253
- attribution_org_id: z5.string().nullable(),
328
+ attribution_org_id: z6.string().nullable(),
254
329
  funding_source: FundingSourceSchema.nullable(),
255
330
  credential_source: CredentialSourceSchema
256
331
  });
257
- var CrossingHashInputV0Schema = z5.object({
258
- v: z5.literal(0),
332
+ var CrossingHashInputV0Schema = z6.object({
333
+ v: z6.literal(0),
259
334
  snapshot: CrossingSnapshotV0Schema,
260
335
  attested_receipt_id: ReceiptIdFormatSchema
261
336
  });
262
337
  var SETTLEMENT_AUTHORITY = "hlos.ai";
263
- var CrossingSettledReceiptSchema = z5.object({
264
- type: z5.literal("CrossingSettled"),
338
+ var CrossingSettledReceiptSchema = z6.object({
339
+ type: z6.literal("CrossingSettled"),
265
340
  crossingId: CrossingIdFormatSchema,
266
341
  // Scoping (powers adoption + ROI views)
267
- event_id: z5.string().nullable(),
268
- access_window_id: z5.string().nullable(),
269
- access_grant_id: z5.string().nullable(),
342
+ event_id: z6.string().nullable(),
343
+ access_window_id: z6.string().nullable(),
344
+ access_grant_id: z6.string().nullable(),
270
345
  // Attribution
271
- attribution_org_id: z5.string().nullable(),
346
+ attribution_org_id: z6.string().nullable(),
272
347
  funding_source: FundingSourceSchema.nullable(),
273
348
  credential_source: CredentialSourceSchema,
274
349
  // Authority (LITERAL)
275
- settlement_authority: z5.literal(SETTLEMENT_AUTHORITY),
350
+ settlement_authority: z6.literal(SETTLEMENT_AUTHORITY),
276
351
  // Binding
277
- crossing_hash: z5.string(),
352
+ crossing_hash: z6.string(),
278
353
  // sha256 base64url of CrossingHashInputV0
279
- attested_receipt_id: z5.string(),
354
+ attested_receipt_id: z6.string(),
280
355
  // Timestamp
281
- settled_at: z5.string().datetime()
356
+ settled_at: z6.string().datetime()
282
357
  });
283
- var AvailabilityTypeSchema = z5.enum([
358
+ var AvailabilityTypeSchema = z6.enum([
284
359
  "EVENT_SPONSOR",
285
360
  // Sponsor-funded for specific event
286
361
  "EVERGREEN",
@@ -288,7 +363,7 @@ var AvailabilityTypeSchema = z5.enum([
288
363
  "CATALOG"
289
364
  // User-paid from catalog
290
365
  ]);
291
- var ProviderRoleSchema = z5.enum([
366
+ var ProviderRoleSchema = z6.enum([
292
367
  "AI",
293
368
  // AI/LLM providers (Gemini, GPT, Claude)
294
369
  "DATABASE",
@@ -308,35 +383,35 @@ var ProviderRoleSchema = z5.enum([
308
383
  "OTHER"
309
384
  // Catch-all for new categories
310
385
  ]);
311
- var StackProviderSchema = z5.object({
312
- provider_id: z5.string(),
386
+ var StackProviderSchema = z6.object({
387
+ provider_id: z6.string(),
313
388
  role: ProviderRoleSchema,
314
389
  // P1: Now a constrained enum
315
- display_name: z5.string(),
316
- budget_allocation: z5.number().nonnegative(),
317
- sku_ids: z5.array(z5.string()),
390
+ display_name: z6.string(),
391
+ budget_allocation: z6.number().nonnegative(),
392
+ sku_ids: z6.array(z6.string()),
318
393
  availability_type: AvailabilityTypeSchema
319
394
  });
320
- var StackSchema = z5.object({
321
- id: z5.string(),
322
- slug: z5.string(),
323
- name: z5.string(),
324
- tagline: z5.string(),
325
- icon: z5.string(),
326
- providers: z5.array(StackProviderSchema),
327
- github_template: z5.string().nullable(),
328
- total_budget: z5.number().nonnegative(),
329
- event_id: z5.string().nullable()
395
+ var StackSchema = z6.object({
396
+ id: z6.string(),
397
+ slug: z6.string(),
398
+ name: z6.string(),
399
+ tagline: z6.string(),
400
+ icon: z6.string(),
401
+ providers: z6.array(StackProviderSchema),
402
+ github_template: z6.string().nullable(),
403
+ total_budget: z6.number().nonnegative(),
404
+ event_id: z6.string().nullable()
330
405
  // null = evergreen
331
406
  });
332
- var StackConnectionSchema = z5.object({
333
- id: z5.string(),
334
- stack_id: z5.string(),
335
- passport_id: z5.string(),
336
- team_id: z5.string().nullable(),
337
- environment_id: z5.string(),
338
- connected_at: z5.string().datetime(),
339
- connected_providers: z5.array(z5.string())
407
+ var StackConnectionSchema = z6.object({
408
+ id: z6.string(),
409
+ stack_id: z6.string(),
410
+ passport_id: z6.string(),
411
+ team_id: z6.string().nullable(),
412
+ environment_id: z6.string(),
413
+ connected_at: z6.string().datetime(),
414
+ connected_providers: z6.array(z6.string())
340
415
  });
341
416
  function kernelOk(data, status = 200) {
342
417
  return { ok: true, status, data };
@@ -405,7 +480,7 @@ function isCrossingSettledReceipt(value) {
405
480
  }
406
481
 
407
482
  // src/w.ts
408
- import { z as z6 } from "zod";
483
+ import { z as z7 } from "zod";
409
484
  var W_RPID_DOMAIN = new TextEncoder().encode("W:RPID:v1");
410
485
  var W_TXCTX_DOMAIN = new TextEncoder().encode("W:TXCTX:v1");
411
486
  var RFC3339_CAPTURING = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.(\d{1,9}))?(Z|([+-])(\d{2}):(\d{2}))$/;
@@ -483,36 +558,36 @@ function encodeEpoch(epoch) {
483
558
  view.setBigUint64(0, BigInt(ms), false);
484
559
  return new Uint8Array(buf);
485
560
  }
486
- var RelyingPartyIdSchema = z6.object({
561
+ var RelyingPartyIdSchema = z7.object({
487
562
  /** RP domain (e.g., "merchant.example.com") */
488
- domain: z6.string().min(1).max(253),
563
+ domain: z7.string().min(1).max(253),
489
564
  /** Audience URI (e.g., "https://merchant.example.com/verify") */
490
- audience_uri: z6.string().url(),
565
+ audience_uri: z7.string().url(),
491
566
  /** SHA-256 hash of verifier's public key (hex, 64 chars) */
492
- verifier_key_hash: z6.string().regex(/^[a-f0-9]{64}$/, "Must be 64-char lowercase hex")
567
+ verifier_key_hash: z7.string().regex(/^[a-f0-9]{64}$/, "Must be 64-char lowercase hex")
493
568
  });
494
- var RotationEpochSchema = z6.union([
495
- z6.number().int().nonnegative(),
496
- z6.string().datetime({ offset: true })
569
+ var RotationEpochSchema = z7.union([
570
+ z7.number().int().nonnegative(),
571
+ z7.string().datetime({ offset: true })
497
572
  // Requires timezone offset (RFC3339)
498
573
  ]);
499
- var RPIDSchema = z6.string().length(43, "RPID must be base64url-encoded 32 bytes (43 chars, no padding)").regex(/^[A-Za-z0-9_-]+$/, "Must be base64url (no padding)");
500
- var TransactionContextSchema = z6.object({
574
+ var RPIDSchema = z7.string().length(43, "RPID must be base64url-encoded 32 bytes (43 chars, no padding)").regex(/^[A-Za-z0-9_-]+$/, "Must be base64url (no padding)");
575
+ var TransactionContextSchema = z7.object({
501
576
  // Required core (stable)
502
577
  relying_party_id: RelyingPartyIdSchema,
503
578
  /** sha256(JCS({ intent, request })) — see computeOperationHash() */
504
- operation_hash: z6.string().regex(/^[a-f0-9]{64}$/, "Must be 64-char lowercase hex"),
579
+ operation_hash: z7.string().regex(/^[a-f0-9]{64}$/, "Must be 64-char lowercase hex"),
505
580
  /** Validity start (RFC3339) */
506
- not_before: z6.string().datetime({ offset: true }),
581
+ not_before: z7.string().datetime({ offset: true }),
507
582
  /** Validity end (RFC3339) */
508
- not_after: z6.string().datetime({ offset: true }),
583
+ not_after: z7.string().datetime({ offset: true }),
509
584
  // Optional (part of hash, must be consistent)
510
- amount: z6.number().nonnegative().optional(),
511
- currency: z6.string().length(3).optional(),
512
- surface_id: z6.string().optional(),
513
- channel_id: z6.string().optional()
585
+ amount: z7.number().nonnegative().optional(),
586
+ currency: z7.string().length(3).optional(),
587
+ surface_id: z7.string().optional(),
588
+ channel_id: z7.string().optional()
514
589
  });
515
- var TransactionContextHashSchema = z6.string().regex(/^[a-f0-9]{64}$/, "Must be 64-char lowercase hex");
590
+ var TransactionContextHashSchema = z7.string().regex(/^[a-f0-9]{64}$/, "Must be 64-char lowercase hex");
516
591
  var W_GOLDEN_FIXTURES = {
517
592
  /**
518
593
  * encodeEpoch(1706486400000) = 2024-01-29T00:00:00.000Z
@@ -568,235 +643,199 @@ function validateTimeWindow(context) {
568
643
  }
569
644
 
570
645
  // src/agents.ts
571
- import { z as z7 } from "zod";
572
- var AgentStatusSchema = z7.enum(["ACTIVE", "PENDING", "SUSPENDED", "REVOKED"]).or(z7.string().min(1));
573
- var AgentTypeSchema = z7.enum(["CUSTOM", "CLAUDE", "GPT", "GEMINI", "CURSOR", "COPILOT", "OTHER"]).or(z7.string().min(1));
574
- var AgentListItemSchema = z7.object({
575
- id: z7.string().min(1),
576
- external_id: z7.string().min(1),
577
- name: z7.string().min(1),
646
+ import { z as z8 } from "zod";
647
+ var AgentStatusSchema = z8.enum(["ACTIVE", "PENDING", "SUSPENDED", "REVOKED"]).or(z8.string().min(1));
648
+ var AgentTypeSchema = z8.enum(["CUSTOM", "CLAUDE", "GPT", "GEMINI", "CURSOR", "COPILOT", "OTHER"]).or(z8.string().min(1));
649
+ var AgentListItemSchema = z8.object({
650
+ id: z8.string().min(1),
651
+ external_id: z8.string().min(1),
652
+ name: z8.string().min(1),
578
653
  status: AgentStatusSchema,
579
654
  agent_type: AgentTypeSchema,
580
- trust_score: z7.number().int().min(0).max(1e3),
581
- hosting_model: z7.null(),
582
- declared_tier: z7.null(),
583
- created_at: z7.string().datetime()
655
+ trust_score: z8.number().int().min(0).max(1e3),
656
+ hosting_model: z8.null(),
657
+ declared_tier: z8.null(),
658
+ created_at: z8.string().datetime()
584
659
  }).passthrough();
585
- var AgentsListResponseSchema = z7.object({
586
- agents: z7.array(AgentListItemSchema),
587
- _meta: z7.object({
588
- source: z7.literal("hlos")
660
+ var AgentsListResponseSchema = z8.object({
661
+ agents: z8.array(AgentListItemSchema),
662
+ _meta: z8.object({
663
+ source: z8.literal("hlos")
589
664
  })
590
665
  }).passthrough();
591
- var AgentPassportStubResponseSchema = z7.object({
592
- passport_id: z7.null(),
593
- agent_id: z7.string().min(1),
594
- hosting_model: z7.null(),
595
- declared_tier: z7.null(),
596
- effective_tier: z7.null(),
597
- finality_level: z7.null(),
598
- graph: z7.object({
599
- incoming_edges: z7.null(),
600
- outgoing_edges: z7.null(),
601
- active_visas: z7.null()
666
+ var AgentPassportStubResponseSchema = z8.object({
667
+ passport_id: z8.null(),
668
+ agent_id: z8.string().min(1),
669
+ hosting_model: z8.null(),
670
+ declared_tier: z8.null(),
671
+ effective_tier: z8.null(),
672
+ finality_level: z8.null(),
673
+ graph: z8.object({
674
+ incoming_edges: z8.null(),
675
+ outgoing_edges: z8.null(),
676
+ active_visas: z8.null()
602
677
  }).passthrough(),
603
- links: z7.object({
604
- passport_url: z7.string().startsWith("/agent-passport/agents/"),
605
- docs_url: z7.literal("/agents/passport")
678
+ links: z8.object({
679
+ passport_url: z8.string().startsWith("/agent-passport/agents/"),
680
+ docs_url: z8.literal("/agents/passport")
606
681
  }).passthrough(),
607
- _meta: z7.object({
608
- source: z7.literal("stub")
682
+ _meta: z8.object({
683
+ source: z8.literal("stub")
609
684
  })
610
685
  }).passthrough();
611
686
 
612
- // src/encoding.ts
613
- import { z as z8 } from "zod";
614
- function bytesToBase64url(bytes) {
615
- let binary = "";
616
- for (let i = 0; i < bytes.length; i++) {
617
- binary += String.fromCharCode(bytes[i]);
618
- }
619
- const base64 = btoa(binary);
620
- return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
621
- }
622
- function base64urlToBytes(str) {
623
- const base64 = str.replace(/-/g, "+").replace(/_/g, "/");
624
- const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
625
- const binary = atob(padded);
626
- const bytes = new Uint8Array(binary.length);
627
- for (let i = 0; i < binary.length; i++) {
628
- bytes[i] = binary.charCodeAt(i);
629
- }
630
- return bytes;
631
- }
632
- var BASE64URL_SHA256_REGEX = /^[A-Za-z0-9_-]{43}$/;
633
- var Base64urlSha256Schema = z8.string().regex(
634
- BASE64URL_SHA256_REGEX,
635
- "Must be 43-char base64url (32-byte SHA-256 digest)"
687
+ // src/dispatch-chain.ts
688
+ import { z as z9 } from "zod";
689
+ var CHAIN_STAGE_ORDER = ["CR", "LAT", "EGP", "SA"];
690
+ var ChainStageTypeSchema = z9.enum(CHAIN_STAGE_ORDER);
691
+ var ReceiptHashRefSchema = Base64urlSha256Schema.describe(
692
+ "receipt_hash: base64url(SHA-256(JCS(entire_receipt_envelope)))"
636
693
  );
637
- var Base64urlEd25519SigSchema = z8.string().regex(
638
- /^[A-Za-z0-9_-]{86}$/,
639
- "Must be 86-char base64url (64-byte Ed25519 signature)"
694
+ var ContentHashRefSchema = Base64urlSha256Schema.describe(
695
+ "content_hash reference: base64url(SHA-256(JCS(content_field_only)))"
640
696
  );
641
-
642
- // src/receipt-hash.ts
643
- var cachedSha256 = null;
644
- function sortKeysDeep(value) {
645
- if (Array.isArray(value)) return value.map(sortKeysDeep);
646
- if (value !== null && typeof value === "object") {
647
- const obj = value;
648
- const out = {};
649
- for (const key of Object.keys(obj).sort()) {
650
- out[key] = sortKeysDeep(obj[key]);
651
- }
652
- return out;
697
+ var CustodyReceiptContentSchema = z9.object({
698
+ type: z9.literal("CustodyReceipt"),
699
+ stage_type: z9.literal("CR"),
700
+ stage_version: z9.literal(0),
701
+ stage_index: z9.literal(0),
702
+ dispatch_id: DispatchIdSchema,
703
+ previous_receipt_hash: z9.null(),
704
+ // CR-specific
705
+ actor_passport_id: z9.string().min(1),
706
+ surface: z9.string().min(1),
707
+ task_scope: z9.string().min(1),
708
+ settlement_authority: z9.literal(SETTLEMENT_AUTHORITY)
709
+ }).strict();
710
+ var LiabilityAttestationContentSchema = z9.object({
711
+ type: z9.literal("LiabilityAttestation"),
712
+ stage_type: z9.literal("LAT"),
713
+ stage_version: z9.literal(0),
714
+ stage_index: z9.literal(1),
715
+ dispatch_id: DispatchIdSchema,
716
+ previous_receipt_hash: ReceiptHashRefSchema,
717
+ chain_root_content_hash: ContentHashRefSchema,
718
+ // LAT-specific
719
+ policy_snapshot_hash: Base64urlSha256Schema,
720
+ capabilities_granted: z9.array(z9.string().min(1)).min(1),
721
+ authorization_scope: z9.string().min(1),
722
+ /** Receipt issuer authority (HLOS issues all chain artifacts). */
723
+ settlement_authority: z9.literal(SETTLEMENT_AUTHORITY)
724
+ }).strict();
725
+ var EconomicGateProofContentSchema = z9.object({
726
+ type: z9.literal("EconomicGateProof"),
727
+ stage_type: z9.literal("EGP"),
728
+ stage_version: z9.literal(0),
729
+ stage_index: z9.literal(2),
730
+ dispatch_id: DispatchIdSchema,
731
+ previous_receipt_hash: ReceiptHashRefSchema,
732
+ chain_root_content_hash: ContentHashRefSchema,
733
+ // EGP-specific
734
+ wallet_id: z9.string().min(1),
735
+ hold_id: z9.string().min(1).optional(),
736
+ amount_mills: z9.number().int().nonnegative(),
737
+ currency: z9.literal("USD"),
738
+ settlement_authority: z9.literal(SETTLEMENT_AUTHORITY)
739
+ }).strict();
740
+ var SettlementAnchorContentSchema = z9.object({
741
+ type: z9.literal("SettlementAnchor"),
742
+ stage_type: z9.literal("SA"),
743
+ stage_version: z9.literal(0),
744
+ stage_index: z9.literal(3),
745
+ dispatch_id: DispatchIdSchema,
746
+ previous_receipt_hash: ReceiptHashRefSchema,
747
+ chain_root_content_hash: ContentHashRefSchema,
748
+ // SA-specific
749
+ settlement_receipt_hash: ReceiptHashRefSchema,
750
+ crossing_id: z9.string().optional(),
751
+ final_amount_mills: z9.number().int().nonnegative(),
752
+ settlement_authority: z9.literal(SETTLEMENT_AUTHORITY)
753
+ }).strict();
754
+ var DispatchChainContentSchema = z9.discriminatedUnion("type", [
755
+ CustodyReceiptContentSchema,
756
+ LiabilityAttestationContentSchema,
757
+ EconomicGateProofContentSchema,
758
+ SettlementAnchorContentSchema
759
+ ]);
760
+ function assertValidChainLink(expectedPreviousHash, actualPreviousHash, stageType) {
761
+ if (expectedPreviousHash !== actualPreviousHash) {
762
+ throw new Error(
763
+ `Chain link broken at ${stageType}: expected previous_receipt_hash=${expectedPreviousHash}, got=${actualPreviousHash}`
764
+ );
653
765
  }
654
- return value;
655
- }
656
- function jcsCanonicalize(value) {
657
- return JSON.stringify(sortKeysDeep(value), (_key, v) => {
658
- if (v === void 0) throw new Error("JCS: undefined is not allowed");
659
- if (typeof v === "function") throw new Error("JCS: function is not allowed");
660
- if (typeof v === "symbol") throw new Error("JCS: symbol is not allowed");
661
- if (typeof v === "bigint") throw new Error("JCS: bigint is not allowed");
662
- if (typeof v === "number" && !Number.isFinite(v))
663
- throw new Error("JCS: non-finite number is not allowed");
664
- return v;
665
- });
666
766
  }
667
- function computeReceiptHash(receipt) {
668
- const sha256 = loadSha256();
669
- const canonical = jcsCanonicalize(receipt);
670
- const digest = sha256(new TextEncoder().encode(canonical));
671
- return bytesToBase64url(digest);
672
- }
673
- function computeContentHash(content) {
674
- const sha256 = loadSha256();
675
- const canonical = jcsCanonicalize(content);
676
- const digest = sha256(new TextEncoder().encode(canonical));
677
- return bytesToBase64url(digest);
678
- }
679
- function loadSha256() {
680
- if (cachedSha256) return cachedSha256;
681
- let _require;
682
- try {
683
- const { createRequire } = __require("module");
684
- _require = createRequire(import.meta.url);
685
- } catch {
686
- _require = __require;
687
- }
688
- let sha256;
689
- try {
690
- sha256 = _require("@noble/hashes/sha2.js").sha256;
691
- } catch {
692
- try {
693
- sha256 = _require("@noble/hashes/sha2").sha256;
694
- } catch {
695
- throw new Error(
696
- "computeReceiptHash/computeContentHash requires @noble/hashes as a peer dependency. Install it: npm install @noble/hashes"
697
- );
698
- }
767
+ function assertRootHash(actualRootHash, expectedRootHash, stageType) {
768
+ if (actualRootHash !== expectedRootHash) {
769
+ throw new Error(
770
+ `Chain root mismatch at ${stageType}: expected chain_root_content_hash=${expectedRootHash}, got=${actualRootHash}`
771
+ );
699
772
  }
700
- cachedSha256 = sha256;
701
- return sha256;
702
773
  }
703
- var ReceiptHashSchema = Base64urlSha256Schema.describe(
704
- "receipt_hash: base64url(SHA-256(JCS(receipt)))"
705
- );
706
- var RECEIPT_HASH_GOLDEN_FIXTURE = {
707
- receipt: {
708
- "@type": "https://hlos.ai/schema/SignedReceiptV0",
709
- version: 0,
710
- receipt_id: "rcpt_01HZGOLDENTEST000000000000",
711
- content: {
712
- type: "CrossingSettled",
713
- crossingId: "cross_test123abc456def789ghi",
714
- settlement_authority: "hlos.ai"
715
- },
716
- // Placeholder bytes (NOT a valid cryptographic signature)
717
- content_hash: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
718
- signature: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
719
- key_id: "hlos-v2-1",
720
- issued_at: "2026-01-27T00:00:00.000Z"
721
- },
722
- /**
723
- * Expected JCS canonical form of the receipt.
724
- * Keys are lexicographically sorted at all levels.
725
- */
726
- expectedJcs: '{"@type":"https://hlos.ai/schema/SignedReceiptV0","content":{"crossingId":"cross_test123abc456def789ghi","settlement_authority":"hlos.ai","type":"CrossingSettled"},"content_hash":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","issued_at":"2026-01-27T00:00:00.000Z","key_id":"hlos-v2-1","receipt_id":"rcpt_01HZGOLDENTEST000000000000","signature":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","version":0}',
727
- /**
728
- * Expected receipt_hash (FROZEN).
729
- * Compute: JCS canonicalize receipt → SHA-256 → base64url (no padding)
730
- *
731
- * DO NOT CHANGE unless the receipt fixture above changes.
732
- */
733
- expectedReceiptHash: "uLiQVUeVKcE35Rdje2fArZQfTcECDgwK6UbmQB_36Pg"
734
- };
735
774
 
736
775
  // src/finality.ts
737
- import { z as z9 } from "zod";
776
+ import { z as z10 } from "zod";
738
777
  var NA_ID_PREFIX = "na_";
739
778
  var FinalityLevel = {
740
779
  SOFT: "SOFT",
741
780
  HARD: "HARD"
742
781
  };
743
- var NotaryAttestationIdFormatSchema = z9.string().regex(
782
+ var NotaryAttestationIdFormatSchema = z10.string().regex(
744
783
  /^na_[a-zA-Z0-9]{20,}$/,
745
784
  "NA ID must match na_[a-zA-Z0-9]{20,}"
746
785
  );
747
- var LogInclusionProofSchema = z9.object({
786
+ var LogInclusionProofSchema = z10.object({
748
787
  /** Merkle root hash (base64url SHA-256) */
749
788
  root: Base64urlSha256Schema,
750
789
  /** Sibling hashes along the path (base64url SHA-256 each) */
751
- proof: z9.array(Base64urlSha256Schema),
790
+ proof: z10.array(Base64urlSha256Schema),
752
791
  /** Leaf index in the log */
753
- index: z9.number().int().nonnegative()
792
+ index: z10.number().int().nonnegative()
754
793
  });
755
- var NotaryAttestationSchema = z9.object({
794
+ var NotaryAttestationSchema = z10.object({
756
795
  // --- Required ---
757
796
  /** Unique NA identifier */
758
797
  na_id: NotaryAttestationIdFormatSchema,
759
798
  /** The receipt_hash this NA attests to */
760
799
  receipt_hash: Base64urlSha256Schema,
761
800
  /** Notary service identifier (e.g. "staampid") */
762
- notary_id: z9.string().min(1),
801
+ notary_id: z10.string().min(1),
763
802
  /** ISO 8601 timestamp when NA was issued */
764
- issued_at: z9.string().datetime(),
803
+ issued_at: z10.string().datetime(),
765
804
  /** Notary's countersignature (base64url encoded) */
766
- signature: z9.string().min(1),
805
+ signature: z10.string().min(1),
767
806
  /** Signature algorithm (e.g. "EdDSA") */
768
- signature_alg: z9.string().min(1),
807
+ signature_alg: z10.string().min(1),
769
808
  // --- Optional (future-proof) ---
770
809
  /** Receipt type being attested */
771
- receipt_type: z9.string().optional(),
810
+ receipt_type: z10.string().optional(),
772
811
  /** Receipt version being attested */
773
- receipt_version: z9.number().int().nonnegative().optional(),
812
+ receipt_version: z10.number().int().nonnegative().optional(),
774
813
  /** Settlement authority that issued the receipt (cross-check) */
775
- settlement_authority: z9.string().optional(),
814
+ settlement_authority: z10.string().optional(),
776
815
  /** TTL in seconds for this attestation */
777
- validity_window_seconds: z9.number().int().positive().optional(),
816
+ validity_window_seconds: z10.number().int().positive().optional(),
778
817
  /** ISO 8601 expiry (derived from issued_at + validity_window_seconds) */
779
- expires_at: z9.string().datetime().optional(),
818
+ expires_at: z10.string().datetime().optional(),
780
819
  /** Merkle proof for append-only log inclusion */
781
820
  log_inclusion: LogInclusionProofSchema.optional()
782
821
  });
783
- var NotaryRequestSchema = z9.object({
822
+ var NotaryRequestSchema = z10.object({
784
823
  /** receipt_hash to be attested (base64url SHA-256) */
785
824
  receipt_hash: Base64urlSha256Schema,
786
825
  /** Must be literal 'hlos.ai' */
787
- settlement_authority: z9.literal(SETTLEMENT_AUTHORITY),
826
+ settlement_authority: z10.literal(SETTLEMENT_AUTHORITY),
788
827
  /** Crossing this receipt belongs to */
789
- crossing_id: z9.string().min(1),
828
+ crossing_id: z10.string().min(1),
790
829
  /** Type of the receipt being attested */
791
- receipt_type: z9.string().min(1),
830
+ receipt_type: z10.string().min(1),
792
831
  /** Version of the receipt being attested */
793
- receipt_version: z9.number().int().nonnegative(),
832
+ receipt_version: z10.number().int().nonnegative(),
794
833
  /** ISO 8601 timestamp of the request */
795
- timestamp: z9.string().datetime(),
834
+ timestamp: z10.string().datetime(),
796
835
  /** Optional: requested validity window in seconds */
797
- validity_window_seconds: z9.number().int().positive().optional()
836
+ validity_window_seconds: z10.number().int().positive().optional()
798
837
  });
799
- var NotarizeStatusSchema = z9.enum([
838
+ var NotarizeStatusSchema = z10.enum([
800
839
  "HARD",
801
840
  // NA obtained, finality upgraded
802
841
  "PENDING",
@@ -806,7 +845,7 @@ var NotarizeStatusSchema = z9.enum([
806
845
  "ALREADY_HARD"
807
846
  // Receipt already has NA
808
847
  ]);
809
- var NotarizeResponseSchema = z9.object({
848
+ var NotarizeResponseSchema = z10.object({
810
849
  /** Finality status after this operation */
811
850
  status: NotarizeStatusSchema,
812
851
  /** The receipt_hash that was notarized */
@@ -816,13 +855,13 @@ var NotarizeResponseSchema = z9.object({
816
855
  /** The full NA object (optional embed) */
817
856
  na: NotaryAttestationSchema.optional(),
818
857
  /** Notary service identifier */
819
- notary: z9.string().min(1).optional(),
858
+ notary: z10.string().min(1).optional(),
820
859
  /** NA ID for retrieval */
821
- notary_receipt_id: z9.string().optional(),
860
+ notary_receipt_id: z10.string().optional(),
822
861
  /** ISO 8601 timestamp */
823
- timestamp: z9.string().datetime(),
862
+ timestamp: z10.string().datetime(),
824
863
  /** Error details (present when status is FAILED) */
825
- error: z9.string().optional()
864
+ error: z10.string().optional()
826
865
  });
827
866
  function isNotaryAttestation(value) {
828
867
  return NotaryAttestationSchema.safeParse(value).success;
@@ -830,17 +869,17 @@ function isNotaryAttestation(value) {
830
869
  function isNotaryRequest(value) {
831
870
  return NotaryRequestSchema.safeParse(value).success;
832
871
  }
833
- var ArtifactRefSchema = z9.object({
872
+ var ArtifactRefSchema = z10.object({
834
873
  /** Artifact type */
835
- type: z9.enum(["CR", "LAT", "EGP", "SA", "SignedReceiptV0", "NA"]),
874
+ type: z10.enum(["CR", "LAT", "EGP", "SA", "SignedReceiptV0", "NA"]),
836
875
  /** base64url SHA-256 hash of the artifact */
837
876
  hash: Base64urlSha256Schema,
838
877
  /** Issuer of the artifact */
839
- issuer: z9.string().min(1),
878
+ issuer: z10.string().min(1),
840
879
  /** Schema version */
841
- version: z9.string().min(1),
880
+ version: z10.string().min(1),
842
881
  /** Optional retrieval URI */
843
- uri: z9.string().url().optional()
882
+ uri: z10.string().url().optional()
844
883
  });
845
884
  var FINALITY_GOLDEN_FIXTURES = {
846
885
  /** Sample NotaryAttestation */
@@ -874,7 +913,435 @@ var FINALITY_GOLDEN_FIXTURES = {
874
913
  timestamp: "2026-01-27T00:01:00.000Z"
875
914
  }
876
915
  };
916
+
917
+ // src/eval-artifact.ts
918
+ import { z as z11 } from "zod";
919
+ var ULID_REGEX = /^[0-9A-HJKMNP-TV-Z]{26}$/;
920
+ var EvalTranscriptStageSchema = z11.union([
921
+ ChainStageTypeSchema,
922
+ z11.literal("HTTP")
923
+ ]);
924
+ var EvalTranscriptStepSchema = z11.object({
925
+ step_index: z11.number().int().nonnegative(),
926
+ stage: EvalTranscriptStageSchema,
927
+ input_hash: Base64urlSha256Schema,
928
+ output_hash: Base64urlSha256Schema.nullable(),
929
+ verdict: z11.enum(["pass", "fail", "skip"]),
930
+ error: z11.string().nullable(),
931
+ elapsed_ms: z11.number().int().nonnegative()
932
+ }).strict();
933
+ var EvalGraderResultSchema = z11.object({
934
+ grader_id: z11.string().min(1),
935
+ verdict: z11.enum(["pass", "fail"]),
936
+ confidence: z11.number().min(0).max(1),
937
+ details: z11.string().nullable()
938
+ }).strict();
939
+ var EvalFailureSchema = z11.object({
940
+ step_index: z11.number().int().nonnegative(),
941
+ grader_id: z11.string().min(1),
942
+ code: z11.string().min(1),
943
+ message: z11.string().nullable()
944
+ }).strict();
945
+ var EvalArtifactSchema = z11.object({
946
+ schema_version: z11.literal(1),
947
+ // Trial metadata
948
+ trial_id: z11.string().regex(ULID_REGEX, "Expected ULID format"),
949
+ seed: z11.string().nullable(),
950
+ suite: z11.string().min(1),
951
+ environment: z11.enum(["local", "ci", "staging", "production"]),
952
+ started_at: z11.string().datetime(),
953
+ completed_at: z11.string().datetime().nullable(),
954
+ duration_ms: z11.number().int().nonnegative().nullable(),
955
+ // Transcript — ordered steps
956
+ transcript: z11.array(EvalTranscriptStepSchema),
957
+ // Grader results
958
+ grader_results: z11.array(EvalGraderResultSchema),
959
+ // Compact failure records
960
+ failures: z11.array(EvalFailureSchema),
961
+ // Aggregate metrics
962
+ pass_rate: z11.number().min(0).max(1),
963
+ consecutive_pass_rate: z11.number().min(0).max(1),
964
+ k: z11.number().int().positive()
965
+ }).strict();
966
+ var DUMMY_HASH = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
967
+ var EVAL_GOLDEN_FIXTURES = {
968
+ /**
969
+ * Valid 4-step transcript (CR→LAT→EGP→SA, all pass).
970
+ */
971
+ valid_full_pass: {
972
+ schema_version: 1,
973
+ trial_id: "01HZABCDEF1234567890ABCDEF",
974
+ seed: "test-seed-001",
975
+ suite: "kernel-invariant",
976
+ environment: "ci",
977
+ started_at: "2026-02-22T10:00:00.000Z",
978
+ completed_at: "2026-02-22T10:00:01.234Z",
979
+ duration_ms: 1234,
980
+ transcript: [
981
+ { step_index: 0, stage: "CR", input_hash: DUMMY_HASH, output_hash: DUMMY_HASH, verdict: "pass", error: null, elapsed_ms: 5 },
982
+ { step_index: 1, stage: "LAT", input_hash: DUMMY_HASH, output_hash: DUMMY_HASH, verdict: "pass", error: null, elapsed_ms: 8 },
983
+ { step_index: 2, stage: "EGP", input_hash: DUMMY_HASH, output_hash: DUMMY_HASH, verdict: "pass", error: null, elapsed_ms: 3 },
984
+ { step_index: 3, stage: "SA", input_hash: DUMMY_HASH, output_hash: DUMMY_HASH, verdict: "pass", error: null, elapsed_ms: 12 }
985
+ ],
986
+ grader_results: [
987
+ { grader_id: "cr_grader", verdict: "pass", confidence: 1, details: null },
988
+ { grader_id: "lat_grader", verdict: "pass", confidence: 1, details: null },
989
+ { grader_id: "egp_grader", verdict: "pass", confidence: 1, details: null },
990
+ { grader_id: "sa_grader", verdict: "pass", confidence: 1, details: null }
991
+ ],
992
+ failures: [],
993
+ pass_rate: 1,
994
+ consecutive_pass_rate: 1,
995
+ k: 10
996
+ },
997
+ /**
998
+ * Single failure: LAT grader fails (broken CR→LAT binding).
999
+ */
1000
+ lat_failure: {
1001
+ schema_version: 1,
1002
+ trial_id: "01HZABCDEF1234567890ABCDEG",
1003
+ seed: "test-seed-002",
1004
+ suite: "kernel-invariant",
1005
+ environment: "ci",
1006
+ started_at: "2026-02-22T10:01:00.000Z",
1007
+ completed_at: "2026-02-22T10:01:00.456Z",
1008
+ duration_ms: 456,
1009
+ transcript: [
1010
+ { step_index: 0, stage: "CR", input_hash: DUMMY_HASH, output_hash: DUMMY_HASH, verdict: "pass", error: null, elapsed_ms: 5 },
1011
+ { step_index: 1, stage: "LAT", input_hash: DUMMY_HASH, output_hash: null, verdict: "fail", error: "CR hash mismatch", elapsed_ms: 3 },
1012
+ { step_index: 2, stage: "EGP", input_hash: DUMMY_HASH, output_hash: null, verdict: "skip", error: null, elapsed_ms: 0 },
1013
+ { step_index: 3, stage: "SA", input_hash: DUMMY_HASH, output_hash: null, verdict: "skip", error: null, elapsed_ms: 0 }
1014
+ ],
1015
+ grader_results: [
1016
+ { grader_id: "cr_grader", verdict: "pass", confidence: 1, details: null },
1017
+ { grader_id: "lat_grader", verdict: "fail", confidence: 1, details: "LAT.cr_hash does not match computed CR hash" },
1018
+ { grader_id: "egp_grader", verdict: "pass", confidence: 0, details: "Skipped: LAT failed" },
1019
+ { grader_id: "sa_grader", verdict: "pass", confidence: 0, details: "Skipped: upstream failure" }
1020
+ ],
1021
+ failures: [
1022
+ { step_index: 1, grader_id: "lat_grader", code: "BINDING_MISMATCH", message: "LAT.cr_hash does not match computed CR hash" }
1023
+ ],
1024
+ pass_rate: 0.9,
1025
+ consecutive_pass_rate: 0.9,
1026
+ k: 10
1027
+ },
1028
+ /**
1029
+ * Partial artifact: run crashed mid-flight.
1030
+ */
1031
+ partial_crash: {
1032
+ schema_version: 1,
1033
+ trial_id: "01HZABCDEF1234567890ABCDEH",
1034
+ seed: null,
1035
+ suite: "kernel-invariant",
1036
+ environment: "local",
1037
+ started_at: "2026-02-22T10:02:00.000Z",
1038
+ completed_at: null,
1039
+ duration_ms: null,
1040
+ transcript: [
1041
+ { step_index: 0, stage: "CR", input_hash: DUMMY_HASH, output_hash: DUMMY_HASH, verdict: "pass", error: null, elapsed_ms: 5 }
1042
+ ],
1043
+ grader_results: [
1044
+ { grader_id: "cr_grader", verdict: "pass", confidence: 1, details: null }
1045
+ ],
1046
+ failures: [],
1047
+ pass_rate: 0,
1048
+ consecutive_pass_rate: 0,
1049
+ k: 10
1050
+ }
1051
+ };
1052
+
1053
+ // src/settlement-execute.ts
1054
+ import { z as z12 } from "zod";
1055
+ var ULID_REGEX2 = /^[0-9A-HJKMNP-TV-Z]{26}$/;
1056
+ var UlidSchema = z12.string().regex(ULID_REGEX2, "Expected ULID format");
1057
+ var UlidOrUuidSchema = z12.string().min(1);
1058
+ var HashVersionSchema = z12.enum(["v1", "v2"]);
1059
+ var SettlementModeSchema = z12.enum(["execute", "dry_run"]);
1060
+ var NotaryStatusSchema = z12.enum(["skipped", "verified", "failed"]);
1061
+ var SettlementExecuteRequestSchema = z12.object({
1062
+ idempotency_key: UlidOrUuidSchema,
1063
+ seed: z12.string().nullable().optional(),
1064
+ hash_version: HashVersionSchema.default("v2"),
1065
+ mode: SettlementModeSchema.default("execute"),
1066
+ flow: z12.object({
1067
+ wallet_id: z12.string().min(1),
1068
+ sku: z12.string().min(1),
1069
+ amount: z12.string().min(1),
1070
+ currency: z12.literal("USD"),
1071
+ metadata: z12.record(z12.unknown()).optional()
1072
+ })
1073
+ }).strict();
1074
+ var ArtifactsBlockSchema = z12.object({
1075
+ cr: z12.record(z12.unknown()).nullable(),
1076
+ lat: z12.record(z12.unknown()).nullable(),
1077
+ egp: z12.record(z12.unknown()).nullable(),
1078
+ sa: z12.record(z12.unknown()).nullable()
1079
+ });
1080
+ var HashesBlockSchema = z12.object({
1081
+ cr_hash: Base64urlSha256Schema.nullable(),
1082
+ lat_hash: Base64urlSha256Schema.nullable(),
1083
+ egp_hash: Base64urlSha256Schema.nullable(),
1084
+ sa_hash: Base64urlSha256Schema.nullable()
1085
+ });
1086
+ var SignatureEnvelopeSchema = z12.object({
1087
+ alg: z12.literal("ed25519"),
1088
+ sig: z12.string().min(1),
1089
+ pub: z12.string().min(1)
1090
+ });
1091
+ var NotaryBlockSchema = z12.object({
1092
+ status: NotaryStatusSchema,
1093
+ run_notary: z12.object({
1094
+ subject_hash: Base64urlSha256Schema,
1095
+ sig: z12.string().min(1),
1096
+ pub: z12.string().min(1)
1097
+ }).nullable(),
1098
+ graph_notary: z12.object({
1099
+ subject_hash: Base64urlSha256Schema,
1100
+ sig: z12.string().min(1),
1101
+ pub: z12.string().min(1)
1102
+ }).nullable()
1103
+ });
1104
+ var TimingBlockSchema = z12.object({
1105
+ started_at: z12.string().datetime(),
1106
+ completed_at: z12.string().datetime().nullable(),
1107
+ duration_ms: z12.number().int().nonnegative().nullable()
1108
+ });
1109
+ var SettlementExecuteSuccessSchema = z12.object({
1110
+ schema_version: z12.literal(1),
1111
+ flow_id: UlidSchema,
1112
+ suite_id: z12.string().min(1),
1113
+ seed: z12.string().nullable(),
1114
+ hash_version: HashVersionSchema,
1115
+ artifacts: ArtifactsBlockSchema.extend({
1116
+ cr: z12.record(z12.unknown()),
1117
+ lat: z12.record(z12.unknown()),
1118
+ egp: z12.record(z12.unknown()),
1119
+ sa: z12.record(z12.unknown())
1120
+ }),
1121
+ hashes: HashesBlockSchema.extend({
1122
+ cr_hash: Base64urlSha256Schema,
1123
+ lat_hash: Base64urlSha256Schema,
1124
+ egp_hash: Base64urlSha256Schema,
1125
+ sa_hash: Base64urlSha256Schema
1126
+ }),
1127
+ signatures: z12.object({
1128
+ settlement: z12.object({
1129
+ cr_sig: SignatureEnvelopeSchema,
1130
+ lat_sig: SignatureEnvelopeSchema,
1131
+ sa_sig: SignatureEnvelopeSchema
1132
+ }),
1133
+ notary: NotaryBlockSchema
1134
+ }),
1135
+ receipt: z12.object({
1136
+ // Kernel receipt IDs currently follow rcpt_ + variable base36/random suffix.
1137
+ receipt_id: z12.string().regex(/^rcpt_/, "Expected kernel receipt ID (rcpt_... format)"),
1138
+ status: z12.enum(["stored", "pending"]),
1139
+ receipt_hash: Base64urlSha256Schema
1140
+ }),
1141
+ run: z12.object({
1142
+ run_id: UlidSchema,
1143
+ final_state_hash: Base64urlSha256Schema,
1144
+ terminal_event_hash: Base64urlSha256Schema,
1145
+ sealed_at: z12.string().datetime()
1146
+ }),
1147
+ timing: TimingBlockSchema.extend({
1148
+ completed_at: z12.string().datetime(),
1149
+ duration_ms: z12.number().int().nonnegative()
1150
+ })
1151
+ });
1152
+ var SettlementErrorCodeSchema = z12.enum([
1153
+ "INSUFFICIENT_FUNDS",
1154
+ "POLICY_DENIED",
1155
+ "INVARIANT_FAILED",
1156
+ "INVALID_AMOUNT_FORMAT",
1157
+ "INVALID_AMOUNT_NEGATIVE",
1158
+ "INVALID_JSON",
1159
+ "INTERNAL"
1160
+ ]);
1161
+ var SettlementExecuteErrorSchema = z12.object({
1162
+ schema_version: z12.literal(1),
1163
+ flow_id: UlidSchema,
1164
+ suite_id: z12.string().min(1),
1165
+ seed: z12.string().nullable(),
1166
+ hash_version: HashVersionSchema,
1167
+ error: z12.object({
1168
+ code: SettlementErrorCodeSchema,
1169
+ message: z12.string(),
1170
+ details: z12.record(z12.unknown()).optional()
1171
+ }),
1172
+ partial: z12.object({
1173
+ artifacts: ArtifactsBlockSchema,
1174
+ hashes: HashesBlockSchema
1175
+ }),
1176
+ timing: TimingBlockSchema
1177
+ });
1178
+ var SettlementExecuteResponseSchema = z12.union([
1179
+ SettlementExecuteSuccessSchema,
1180
+ SettlementExecuteErrorSchema
1181
+ ]);
1182
+ function isSettlementExecuteSuccess(response) {
1183
+ return "artifacts" in response && !("error" in response);
1184
+ }
1185
+ function isSettlementExecuteError(response) {
1186
+ return "error" in response;
1187
+ }
1188
+
1189
+ // src/srr-v0.ts
1190
+ import { z as z13 } from "zod";
1191
+ var SRR_TYPE_URI = "https://hlos.ai/schema/SignedRejectionReceiptV0";
1192
+ var SRR_VERSION = 0;
1193
+ var SRR_REJECTION_DOMAIN = "kernel:k:rejection:v1";
1194
+ var SRR_SIGNATURE_ALGORITHM = "Ed25519";
1195
+ var SRR_INITIAL_REASON_CODES = [
1196
+ "BUDGET_EXCEEDED",
1197
+ "POLICY_VIOLATION",
1198
+ "SAFETY_GATE_FAILED",
1199
+ "DELEGATION_REVOKED",
1200
+ "SETTLEMENT_TIMEOUT"
1201
+ ];
1202
+ var REASON_CODE_PATTERN = /^[A-Z][A-Z0-9_]{2,63}$/;
1203
+ var SignedRejectionReceiptV0Schema = z13.object({
1204
+ "@type": z13.literal(SRR_TYPE_URI),
1205
+ version: z13.literal(SRR_VERSION),
1206
+ receipt_id: z13.string().regex(
1207
+ /^srr_[0-9A-HJKMNP-TV-Z]{26}$/i,
1208
+ "receipt_id must be srr_ + 26-char ULID"
1209
+ ),
1210
+ crossing_id: z13.string().min(1),
1211
+ reason_code: z13.string().regex(REASON_CODE_PATTERN, "reason_code must be UPPER_SNAKE_CASE, 3-64 chars"),
1212
+ reason_message: z13.string().min(1),
1213
+ details: z13.record(z13.unknown()).optional(),
1214
+ commitment_hash: Base64urlSha256Schema.optional(),
1215
+ issuer_id: z13.string().min(1),
1216
+ rejected_at: z13.string().datetime(),
1217
+ issuer_public_key_ref: z13.string().min(1),
1218
+ signature_algorithm: z13.literal(SRR_SIGNATURE_ALGORITHM),
1219
+ signature: Base64urlEd25519SigSchema
1220
+ }).strict();
1221
+
1222
+ // src/srr-signing.ts
1223
+ var textEncoder = new TextEncoder();
1224
+ var DOMAIN_BYTES = textEncoder.encode(SRR_REJECTION_DOMAIN);
1225
+ var cachedSha256 = null;
1226
+ function loadSha256() {
1227
+ if (cachedSha256) return cachedSha256;
1228
+ const moduleApi = typeof process.getBuiltinModule === "function" ? process.getBuiltinModule("module") : __require("module");
1229
+ const createRequire = moduleApi.createRequire;
1230
+ const requireBase = typeof __filename === "string" ? __filename : `${process.cwd()}/package.json`;
1231
+ const _require = createRequire(requireBase);
1232
+ let sha256;
1233
+ try {
1234
+ sha256 = _require("@noble/hashes/sha2.js").sha256;
1235
+ } catch {
1236
+ try {
1237
+ sha256 = _require("@noble/hashes/sha2").sha256;
1238
+ } catch {
1239
+ throw new Error(
1240
+ "SRR signing requires @noble/hashes as a peer dependency. Install it: npm install @noble/hashes"
1241
+ );
1242
+ }
1243
+ }
1244
+ cachedSha256 = sha256;
1245
+ return sha256;
1246
+ }
1247
+ function computeSrrSigningPayload(unsignedSrr) {
1248
+ const sha256 = loadSha256();
1249
+ const canonical = jcsCanonicalize(unsignedSrr);
1250
+ const digest = sha256(textEncoder.encode(canonical));
1251
+ const payload = new Uint8Array(DOMAIN_BYTES.length + digest.length);
1252
+ payload.set(DOMAIN_BYTES, 0);
1253
+ payload.set(digest, DOMAIN_BYTES.length);
1254
+ return payload;
1255
+ }
1256
+ function computeSrrDigest(signedSrr) {
1257
+ const sha256 = loadSha256();
1258
+ const canonical = jcsCanonicalize(signedSrr);
1259
+ return bytesToBase64url(sha256(textEncoder.encode(canonical)));
1260
+ }
1261
+
1262
+ // src/srr-verify.ts
1263
+ var cachedVerify = null;
1264
+ function loadVerify() {
1265
+ if (cachedVerify) return cachedVerify;
1266
+ const moduleApi = typeof process.getBuiltinModule === "function" ? process.getBuiltinModule("module") : __require("module");
1267
+ const createRequire = moduleApi.createRequire;
1268
+ const requireBase = typeof __filename === "string" ? __filename : `${process.cwd()}/package.json`;
1269
+ const _require = createRequire(requireBase);
1270
+ let ed25519Module;
1271
+ try {
1272
+ ed25519Module = _require("@noble/ed25519");
1273
+ } catch {
1274
+ throw new Error(
1275
+ "SRR verification requires @noble/ed25519 as a peer dependency. Install it: npm install @noble/ed25519"
1276
+ );
1277
+ }
1278
+ if (!ed25519Module.hashes?.sha512) {
1279
+ let sha512Fn;
1280
+ try {
1281
+ const sha2 = _require("@noble/hashes/sha2.js");
1282
+ sha512Fn = (...m) => sha2.sha512(ed25519Module.etc.concatBytes(...m));
1283
+ } catch {
1284
+ try {
1285
+ const sha2 = _require("@noble/hashes/sha2");
1286
+ sha512Fn = (...m) => sha2.sha512(ed25519Module.etc.concatBytes(...m));
1287
+ } catch {
1288
+ throw new Error(
1289
+ "SRR verification requires @noble/hashes as a peer dependency. Install it: npm install @noble/hashes"
1290
+ );
1291
+ }
1292
+ }
1293
+ if (!ed25519Module.hashes) ed25519Module.hashes = {};
1294
+ ed25519Module.hashes.sha512 = sha512Fn;
1295
+ }
1296
+ const verify = ed25519Module.verify;
1297
+ cachedVerify = verify;
1298
+ return verify;
1299
+ }
1300
+ async function verifyDetachedEd25519(params) {
1301
+ const verify = loadVerify();
1302
+ try {
1303
+ return await verify(params.signature, params.signingPayload, params.publicKey);
1304
+ } catch {
1305
+ return false;
1306
+ }
1307
+ }
1308
+ async function verifySignedRejectionReceipt(params) {
1309
+ const { srr, publicKey } = params;
1310
+ if (!srr || typeof srr !== "object") {
1311
+ return { valid: false, reason: "SCHEMA_VIOLATION" };
1312
+ }
1313
+ if (srr.signature_algorithm !== SRR_SIGNATURE_ALGORITHM) {
1314
+ return { valid: false, reason: "UNSUPPORTED_ALGORITHM" };
1315
+ }
1316
+ const parseResult = SignedRejectionReceiptV0Schema.safeParse(srr);
1317
+ if (!parseResult.success) {
1318
+ return { valid: false, reason: "SCHEMA_VIOLATION" };
1319
+ }
1320
+ let signingPayload;
1321
+ try {
1322
+ const { signature, ...unsignedFields } = srr;
1323
+ signingPayload = computeSrrSigningPayload(unsignedFields);
1324
+ } catch {
1325
+ return { valid: false, reason: "PAYLOAD_CONSTRUCTION_ERROR" };
1326
+ }
1327
+ let signatureBytes;
1328
+ try {
1329
+ signatureBytes = base64urlToBytes(srr.signature);
1330
+ } catch {
1331
+ return { valid: false, reason: "INVALID_SIGNATURE" };
1332
+ }
1333
+ const valid = await verifyDetachedEd25519({
1334
+ signingPayload,
1335
+ signature: signatureBytes,
1336
+ publicKey
1337
+ });
1338
+ return valid ? { valid: true } : { valid: false, reason: "INVALID_SIGNATURE" };
1339
+ }
877
1340
  export {
1341
+ AAREnvelopeV0Schema,
1342
+ AAREnvelopeV0TypedSchema,
1343
+ AAR_ENVELOPE_TYPE,
1344
+ AAR_ENVELOPE_VERSION,
878
1345
  AgentListItemSchema,
879
1346
  AgentPassportStubResponseSchema,
880
1347
  AgentStatusSchema,
@@ -885,7 +1352,9 @@ export {
885
1352
  BASE64URL_SHA256_REGEX,
886
1353
  Base64urlEd25519SigSchema,
887
1354
  Base64urlSha256Schema,
1355
+ CHAIN_STAGE_ORDER,
888
1356
  CONTENT_HASH_LENGTH,
1357
+ ChainStageTypeSchema,
889
1358
  CorrelationIdSchema,
890
1359
  CredentialSourceSchema,
891
1360
  CrossingHashInputV0Schema,
@@ -893,8 +1362,18 @@ export {
893
1362
  CrossingIdSchema,
894
1363
  CrossingSettledReceiptSchema,
895
1364
  CrossingSnapshotV0Schema,
1365
+ CustodyReceiptContentSchema,
1366
+ DispatchChainContentSchema,
1367
+ DispatchIdBrand,
1368
+ DispatchIdSchema,
896
1369
  ERROR_CODE_STATUS,
1370
+ EVAL_GOLDEN_FIXTURES,
1371
+ EconomicGateProofContentSchema,
897
1372
  ErrorResponseSchema,
1373
+ EvalArtifactSchema,
1374
+ EvalFailureSchema,
1375
+ EvalGraderResultSchema,
1376
+ EvalTranscriptStepSchema,
898
1377
  FINALITY_GOLDEN_FIXTURES,
899
1378
  FinalityLevel,
900
1379
  FundingSourceSchema,
@@ -903,6 +1382,7 @@ export {
903
1382
  KernelErrorCodeSchema2 as KernelErrorCodeSchema,
904
1383
  KernelErrorSchema,
905
1384
  KernelOkSchema,
1385
+ LiabilityAttestationContentSchema,
906
1386
  LogInclusionProofSchema,
907
1387
  NA_ID_PREFIX,
908
1388
  NotarizeResponseSchema,
@@ -913,6 +1393,7 @@ export {
913
1393
  PassportIdFormatSchema,
914
1394
  PassportIdSchema,
915
1395
  ProviderRoleSchema,
1396
+ REASON_CODE_PATTERN,
916
1397
  RECEIPT_HASH_GOLDEN_FIXTURE,
917
1398
  RECEIPT_TYPE_URI,
918
1399
  RECEIPT_VERSION,
@@ -924,9 +1405,20 @@ export {
924
1405
  RotationEpochSchema,
925
1406
  SETTLEMENT_AUTHORITY,
926
1407
  SIGNATURE_LENGTH,
1408
+ SRR_INITIAL_REASON_CODES,
1409
+ SRR_REJECTION_DOMAIN,
1410
+ SRR_SIGNATURE_ALGORITHM,
1411
+ SRR_TYPE_URI,
1412
+ SRR_VERSION,
927
1413
  SURFACES,
1414
+ SettlementAnchorContentSchema,
1415
+ SettlementExecuteErrorSchema,
1416
+ SettlementExecuteRequestSchema,
1417
+ SettlementExecuteResponseSchema,
1418
+ SettlementExecuteSuccessSchema,
928
1419
  SignedReceiptV0LooseSchema,
929
1420
  SignedReceiptV0Schema,
1421
+ SignedRejectionReceiptV0Schema,
930
1422
  StackConnectionSchema,
931
1423
  StackProviderSchema,
932
1424
  StackSchema,
@@ -939,14 +1431,19 @@ export {
939
1431
  W_TXCTX_DOMAIN,
940
1432
  WalletIdFormatSchema,
941
1433
  WalletIdSchema,
1434
+ assertRootHash,
1435
+ assertValidChainLink,
942
1436
  base64urlToBytes,
943
1437
  bytesToBase64url,
944
1438
  computeContentHash,
945
1439
  computeReceiptHash,
1440
+ computeSrrDigest,
1441
+ computeSrrSigningPayload,
946
1442
  deriveFundingSource,
947
1443
  encodeEpoch,
948
1444
  error,
949
1445
  generateCrossingId,
1446
+ generateDispatchId,
950
1447
  generateId,
951
1448
  generatePassportId,
952
1449
  generateReceiptId,
@@ -955,11 +1452,16 @@ export {
955
1452
  isCrossingSettledReceipt,
956
1453
  isNotaryAttestation,
957
1454
  isNotaryRequest,
1455
+ isSettlementExecuteError,
1456
+ isSettlementExecuteSuccess,
958
1457
  isSignedReceiptV0,
959
1458
  jcsCanonicalize,
960
1459
  kernelError,
961
1460
  kernelOk,
962
1461
  success,
963
- validateTimeWindow
1462
+ validateTimeWindow,
1463
+ verifyAAR,
1464
+ verifyDetachedEd25519,
1465
+ verifySignedRejectionReceipt
964
1466
  };
965
1467
  //# sourceMappingURL=index.js.map