@opendatalabs/vana-sdk 3.22.0 → 3.23.0-pr.211.3227174

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 (79) hide show
  1. package/README.md +57 -0
  2. package/dist/auth/errors.cjs +1 -1
  3. package/dist/auth/web3-signed.cjs +1 -1
  4. package/dist/crypto/envelope/job-stream.test.d.ts +1 -0
  5. package/dist/crypto/envelope/job.cjs +818 -0
  6. package/dist/crypto/envelope/job.cjs.map +1 -0
  7. package/dist/crypto/envelope/job.d.ts +139 -0
  8. package/dist/crypto/envelope/job.js +792 -0
  9. package/dist/crypto/envelope/job.js.map +1 -0
  10. package/dist/direct/access-request-client.cjs +5 -1
  11. package/dist/direct/access-request-client.cjs.map +1 -1
  12. package/dist/direct/access-request-client.js +4 -0
  13. package/dist/direct/access-request-client.js.map +1 -1
  14. package/dist/direct/connect-flow.cjs +43 -1
  15. package/dist/direct/connect-flow.cjs.map +1 -1
  16. package/dist/direct/connect-flow.d.ts +12 -0
  17. package/dist/direct/connect-flow.js +43 -1
  18. package/dist/direct/connect-flow.js.map +1 -1
  19. package/dist/direct/controller.cjs +1 -1
  20. package/dist/direct/errors.cjs +1 -1
  21. package/dist/direct/personal-server-read.cjs +2 -2
  22. package/dist/direct/types.cjs.map +1 -1
  23. package/dist/direct/types.d.ts +7 -0
  24. package/dist/direct/types.js.map +1 -1
  25. package/dist/direct/use-direct-vana-connect.cjs +2 -1
  26. package/dist/direct/use-direct-vana-connect.cjs.map +1 -1
  27. package/dist/direct/use-direct-vana-connect.d.ts +3 -1
  28. package/dist/direct/use-direct-vana-connect.js +2 -1
  29. package/dist/direct/use-direct-vana-connect.js.map +1 -1
  30. package/dist/error-entry-points.test.d.ts +1 -0
  31. package/dist/errors.cjs +84 -0
  32. package/dist/errors.cjs.map +1 -1
  33. package/dist/errors.d.ts +133 -0
  34. package/dist/errors.js +73 -0
  35. package/dist/errors.js.map +1 -1
  36. package/dist/index.browser.d.ts +3 -0
  37. package/dist/index.browser.js +1143 -434
  38. package/dist/index.browser.js.map +4 -4
  39. package/dist/index.node.cjs +1801 -631
  40. package/dist/index.node.cjs.map +4 -4
  41. package/dist/index.node.d.ts +4 -0
  42. package/dist/index.node.js +1762 -522
  43. package/dist/index.node.js.map +4 -4
  44. package/dist/protocol/data-point-deletion.cjs +1 -1
  45. package/dist/protocol/derivative-questions.cjs +1 -1
  46. package/dist/protocol/derivative-status.cjs +1 -1
  47. package/dist/protocol/fixtures/moksha-identity.json +20 -0
  48. package/dist/protocol/gateway.cjs +1 -1
  49. package/dist/protocol/identity.cjs +224 -0
  50. package/dist/protocol/identity.cjs.map +1 -0
  51. package/dist/protocol/identity.d.ts +193 -0
  52. package/dist/protocol/identity.js +188 -0
  53. package/dist/protocol/identity.js.map +1 -0
  54. package/dist/protocol/identity.test.d.ts +1 -0
  55. package/dist/protocol/identity.vector.test.d.ts +1 -0
  56. package/dist/protocol/jobs-client.cjs +551 -0
  57. package/dist/protocol/jobs-client.cjs.map +1 -0
  58. package/dist/protocol/jobs-client.d.ts +169 -0
  59. package/dist/protocol/jobs-client.js +558 -0
  60. package/dist/protocol/jobs-client.js.map +1 -0
  61. package/dist/protocol/jobs-client.test.d.ts +1 -0
  62. package/dist/protocol/jobs.cjs +64 -0
  63. package/dist/protocol/jobs.cjs.map +1 -0
  64. package/dist/protocol/jobs.d.ts +193 -0
  65. package/dist/protocol/jobs.js +31 -0
  66. package/dist/protocol/jobs.js.map +1 -0
  67. package/dist/protocol/jobs.test.d.ts +1 -0
  68. package/dist/protocol/lineage.cjs +1 -1
  69. package/dist/protocol/personal-server-data.cjs +1 -1
  70. package/dist/protocol/personal-server-write.cjs +1 -1
  71. package/dist/protocol/write-request.cjs +1 -1
  72. package/dist/protocol/write-signer.cjs +1 -1
  73. package/dist/react.cjs.map +1 -1
  74. package/dist/react.d.ts +1 -1
  75. package/dist/react.js.map +1 -1
  76. package/dist/session-relay/client.cjs +1 -1
  77. package/dist/session-relay/errors.cjs +1 -1
  78. package/dist/session-relay/index.cjs +1 -1
  79. package/package.json +7 -1
@@ -20,6 +20,7 @@ var __copyProps = (to, from, except, desc) => {
20
20
  }
21
21
  return to;
22
22
  };
23
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
23
24
  var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
25
  // If the importer is in node compatibility mode or this is not an ESM
25
26
  // file that has been converted to a CommonJS file using a Babel-
@@ -1178,42 +1179,34 @@ __export(index_node_exports, {
1178
1179
  AccountPersonalServerLiteOwnerBindingError: () => AccountPersonalServerLiteOwnerBindingError,
1179
1180
  AccountPersonalServerRegistrationError: () => AccountPersonalServerRegistrationError,
1180
1181
  BUILDER_REGISTRATION_TYPES: () => BUILDER_REGISTRATION_TYPES,
1181
- BlockchainError: () => BlockchainError,
1182
1182
  BrowserPlatformAdapter: () => BrowserPlatformAdapter,
1183
+ CLAIM_POLL_FLOOR_MS: () => CLAIM_POLL_FLOOR_MS,
1183
1184
  CONTRACTS: () => CONTRACTS,
1184
1185
  CallbackStorage: () => CallbackStorage,
1185
1186
  ContractFactory: () => ContractFactory,
1186
- ContractNotFoundError: () => ContractNotFoundError,
1187
1187
  DATA_ACCESS_OP_TYPE: () => DATA_ACCESS_OP_TYPE,
1188
1188
  DATA_REGISTRY_STATUS_ABI: () => DATA_REGISTRY_STATUS_ABI,
1189
1189
  DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS: () => DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS,
1190
1190
  DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS: () => DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS,
1191
+ DEFAULT_JOB_DEADLINE_SECONDS: () => DEFAULT_JOB_DEADLINE_SECONDS,
1192
+ DEFAULT_LEASE_SECONDS: () => DEFAULT_LEASE_SECONDS,
1191
1193
  DEFAULT_QUESTION_POLL_INTERVAL_MS: () => DEFAULT_QUESTION_POLL_INTERVAL_MS,
1192
1194
  DEFAULT_QUESTION_TIMEOUT_MS: () => DEFAULT_QUESTION_TIMEOUT_MS,
1193
1195
  DERIVATIVE_ERROR_CODES: () => DERIVATIVE_ERROR_CODES,
1194
1196
  DERIVATIVE_QUESTIONS_PATH: () => DERIVATIVE_QUESTIONS_PATH,
1195
1197
  DERIVATIVE_STATUS_PATH: () => DERIVATIVE_STATUS_PATH,
1196
1198
  DataFileEnvelopeSchema: () => DataFileEnvelopeSchema,
1197
- DataPointDeletedError: () => DataPointDeletedError,
1198
- DataPointNotFoundError: () => DataPointNotFoundError,
1199
1199
  DataPointStatus: () => DataPointStatus,
1200
- DataPointVersionConflictError: () => DataPointVersionConflictError,
1201
- DerivativeComputeUnavailableError: () => DerivativeComputeUnavailableError,
1202
- DerivativeCycleError: () => DerivativeCycleError,
1203
- DerivativeDerivedScopeRequiredError: () => DerivativeDerivedScopeRequiredError,
1204
1200
  DerivativeErrorCodeSchema: () => DerivativeErrorCodeSchema,
1205
- DerivativeQuestionFailedError: () => DerivativeQuestionFailedError,
1206
- DerivativeQuestionInvalidError: () => DerivativeQuestionInvalidError,
1207
- DerivativeQuestionNotFoundError: () => DerivativeQuestionNotFoundError,
1208
- DerivativeQuestionRejectedError: () => DerivativeQuestionRejectedError,
1209
1201
  DerivativeQuestionSchema: () => DerivativeQuestionSchema,
1210
- DerivativeQuestionTimeoutError: () => DerivativeQuestionTimeoutError,
1211
- DerivativeSourceNotGrantedError: () => DerivativeSourceNotGrantedError,
1212
1202
  DerivativeStatusSchema: () => DerivativeStatusSchema,
1213
1203
  DropboxStorage: () => DropboxStorage,
1214
1204
  ECIESError: () => ECIESError,
1205
+ ENCLAVE_IDENTITY_EVIDENCE_VERSION: () => ENCLAVE_IDENTITY_EVIDENCE_VERSION,
1206
+ ENCLAVE_TRUST_ANCHORS: () => ENCLAVE_TRUST_ANCHORS,
1207
+ ENCLAVE_WALLET_PURPOSE: () => ENCLAVE_WALLET_PURPOSE,
1215
1208
  ESCROW_DEPOSIT_ABI: () => ESCROW_DEPOSIT_ABI2,
1216
- ExpiredTokenError: () => ExpiredTokenError,
1209
+ ExpiredTokenError: () => import_errors14.ExpiredTokenError,
1217
1210
  FEE_REGISTRY_ABI: () => FEE_REGISTRY_ABI,
1218
1211
  GENERIC_PAYMENT_TYPES: () => GENERIC_PAYMENT_TYPES,
1219
1212
  GRANT_OP_TYPE: () => GRANT_OP_TYPE,
@@ -1222,28 +1215,36 @@ __export(index_node_exports, {
1222
1215
  GoogleDriveStorage: () => GoogleDriveStorage,
1223
1216
  InMemoryTokenStore: () => InMemoryTokenStore,
1224
1217
  IngestResponseSchema: () => IngestResponseSchema,
1225
- InvalidConfigurationError: () => InvalidConfigurationError,
1226
1218
  InvalidScopeEntryError: () => InvalidScopeEntryError,
1227
- InvalidSignatureError: () => InvalidSignatureError,
1219
+ InvalidSignatureError: () => import_errors14.InvalidSignatureError,
1228
1220
  IpfsStorage: () => IpfsStorage,
1221
+ JOB_OPERATIONS: () => JOB_OPERATIONS,
1222
+ JOB_PROTOCOL_VERSION: () => JOB_PROTOCOL_VERSION,
1223
+ JOB_RESULT_CHUNK_BYTES: () => JOB_RESULT_CHUNK_BYTES,
1224
+ JOB_RESULT_FORMAT_VERSION: () => JOB_RESULT_FORMAT_VERSION,
1225
+ JOB_STATES: () => JOB_STATES,
1226
+ JobEnvelopeError: () => JobEnvelopeError,
1229
1227
  LINEAGE_FIELD: () => LINEAGE_FIELD,
1230
1228
  LINEAGE_KEY: () => LINEAGE_KEY,
1231
1229
  LineageEntrySchema: () => LineageEntrySchema,
1232
1230
  LineageGraphSchema: () => LineageGraphSchema,
1233
1231
  LineageNodeSchema: () => LineageNodeSchema,
1234
- LineageReadError: () => LineageReadError,
1235
1232
  MASTER_KEY_MESSAGE: () => MASTER_KEY_MESSAGE,
1233
+ MASTER_SIGNATURE_DELIVERY_MAX_AGE_SECONDS: () => MASTER_SIGNATURE_DELIVERY_MAX_AGE_SECONDS,
1234
+ MASTER_SIGNATURE_DELIVERY_VERSION: () => MASTER_SIGNATURE_DELIVERY_VERSION,
1235
+ MAX_ATTEMPTS: () => MAX_ATTEMPTS,
1236
+ MAX_JOB_DEADLINE_SECONDS: () => MAX_JOB_DEADLINE_SECONDS,
1237
+ MAX_LEASE_SECONDS: () => MAX_LEASE_SECONDS,
1236
1238
  MAX_LINEAGE_SOURCES: () => MAX_LINEAGE_SOURCES,
1237
1239
  MAX_QUESTION_CHARS: () => MAX_QUESTION_CHARS,
1238
1240
  MAX_QUESTION_MODEL_CHARS: () => MAX_QUESTION_MODEL_CHARS,
1239
1241
  MAX_QUESTION_SOURCE_SCOPES: () => MAX_QUESTION_SOURCE_SCOPES,
1240
- MissingAuthError: () => MissingAuthError,
1242
+ MAX_WAIT_SECONDS: () => MAX_WAIT_SECONDS,
1243
+ MissingAuthError: () => import_errors14.MissingAuthError,
1241
1244
  NATIVE_ASSET_ADDRESS: () => NATIVE_ASSET_ADDRESS,
1242
1245
  NATIVE_VANA_ASSET: () => NATIVE_VANA_ASSET,
1243
- NetworkError: () => NetworkError,
1244
1246
  NodeECIESProvider: () => NodeECIESUint8Provider,
1245
1247
  NodePlatformAdapter: () => NodePlatformAdapter,
1246
- NonceError: () => NonceError,
1247
1248
  OAuthClient: () => OAuthClient,
1248
1249
  PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX: () => PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX,
1249
1250
  PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE: () => PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE,
@@ -1253,9 +1254,6 @@ __export(index_node_exports, {
1253
1254
  PKCE_CHALLENGE_PATTERN: () => PKCE_CHALLENGE_PATTERN,
1254
1255
  PKCE_VERIFIER_PATTERN: () => PKCE_VERIFIER_PATTERN,
1255
1256
  PSError: () => PSError,
1256
- PermissionError: () => PermissionError,
1257
- PersonalServerError: () => PersonalServerError,
1258
- PersonalServerWriteError: () => PersonalServerWriteError,
1259
1257
  PinataStorage: () => PinataStorage,
1260
1258
  QUESTION_STATUSES: () => QUESTION_STATUSES,
1261
1259
  QuestionDeleteResultSchema: () => QuestionDeleteResultSchema,
@@ -1266,24 +1264,18 @@ __export(index_node_exports, {
1266
1264
  RECORD_DATA_ACCESS_TYPES: () => RECORD_DATA_ACCESS_TYPES,
1267
1265
  REGISTRATION_KIND_FOR_OP: () => REGISTRATION_KIND_FOR_OP,
1268
1266
  RESERVED_WRITE_KEYS: () => RESERVED_WRITE_KEYS,
1269
- ReadOnlyError: () => ReadOnlyError,
1270
1267
  RedactedLineageNodeSchema: () => RedactedLineageNodeSchema,
1271
- RelayerError: () => RelayerError,
1272
1268
  SCOPE_ACTIONS: () => SCOPE_ACTIONS,
1269
+ SEALED_ENVELOPE_VERSION: () => SEALED_ENVELOPE_VERSION,
1273
1270
  SERVER_REGISTRATION_TYPES: () => SERVER_REGISTRATION_TYPES,
1274
1271
  ScopeSchema: () => ScopeSchema,
1275
- SerializationError: () => SerializationError,
1276
- ServerUrlMismatchError: () => ServerUrlMismatchError,
1277
- SignatureError: () => SignatureError,
1278
1272
  StorageError: () => StorageError,
1279
1273
  StorageManager: () => StorageManager,
1280
1274
  TOMBSTONE_DATA_HASH: () => TOMBSTONE_DATA_HASH,
1281
1275
  TOMBSTONE_DATA_HASH_PREIMAGE: () => TOMBSTONE_DATA_HASH_PREIMAGE,
1282
1276
  TOMBSTONE_METADATA_HASH: () => TOMBSTONE_METADATA_HASH,
1283
1277
  TOMBSTONE_METADATA_HASH_PREIMAGE: () => TOMBSTONE_METADATA_HASH_PREIMAGE,
1284
- TransactionPendingError: () => TransactionPendingError,
1285
- UserRejectedRequestError: () => UserRejectedRequestError,
1286
- VanaError: () => VanaError,
1278
+ USER_PS_ID_DOMAIN: () => USER_PS_ID_DOMAIN,
1287
1279
  VanaStorage: () => VanaStorage,
1288
1280
  WRITER_ATTRIBUTION_KEY: () => WRITER_ATTRIBUTION_KEY,
1289
1281
  WRITE_CONTENT_DISPOSITION_HEADER: () => WRITE_CONTENT_DISPOSITION_HEADER,
@@ -1291,15 +1283,7 @@ __export(index_node_exports, {
1291
1283
  WRITE_METADATA_HEADER: () => WRITE_METADATA_HEADER,
1292
1284
  WRITE_SESSION_PATH: () => WRITE_SESSION_PATH,
1293
1285
  WRITE_SIGNATURE_HEADER: () => WRITE_SIGNATURE_HEADER,
1294
- WriteConflictError: () => WriteConflictError,
1295
- WriteForbiddenError: () => WriteForbiddenError,
1296
- WriteLineageError: () => WriteLineageError,
1297
- WriteRejectedError: () => WriteRejectedError,
1298
- WriteRequestError: () => WriteRequestError,
1299
- WriteSessionError: () => WriteSessionError,
1300
- WriteSessionExpiredError: () => WriteSessionExpiredError,
1301
- WriteTransportError: () => WriteTransportError,
1302
- WriteUnauthorizedError: () => WriteUnauthorizedError,
1286
+ appRootPreimage: () => appRootPreimage,
1303
1287
  askPersonalServer: () => askPersonalServer,
1304
1288
  assertDerivedScopeNaming: () => assertDerivedScopeNaming,
1305
1289
  assertValidPkceVerifier: () => assertValidPkceVerifier,
@@ -1313,6 +1297,7 @@ __export(index_node_exports, {
1313
1297
  buildEscrowPaymentHeader: () => buildEscrowPaymentHeader,
1314
1298
  buildGrantPaymentHeader: () => buildGrantPaymentHeader,
1315
1299
  buildMarkDataPointUnavailableRequest: () => buildMarkDataPointUnavailableRequest,
1300
+ buildMasterSignatureDelivery: () => buildMasterSignatureDelivery,
1316
1301
  buildPersonalServerDataReadRequest: () => buildPersonalServerDataReadRequest,
1317
1302
  buildPersonalServerLiteOwnerBindingMessage: () => buildPersonalServerLiteOwnerBindingMessage,
1318
1303
  buildPersonalServerLiteOwnerBindingSignature: () => buildPersonalServerLiteOwnerBindingSignature,
@@ -1321,6 +1306,7 @@ __export(index_node_exports, {
1321
1306
  buildSetDataPointStatusRequest: () => buildSetDataPointStatusRequest,
1322
1307
  buildWeb3SignedHeader: () => buildWeb3SignedHeader,
1323
1308
  builderRegistrationDomain: () => builderRegistrationDomain,
1309
+ canonicalJobRequestBytes: () => canonicalJobRequestBytes,
1324
1310
  chains: () => chains,
1325
1311
  clearContractCache: () => clearContractCache,
1326
1312
  computeBodyHash: () => computeBodyHash,
@@ -1332,6 +1318,7 @@ __export(index_node_exports, {
1332
1318
  createDefaultNonceSource: () => createDefaultNonceSource,
1333
1319
  createEscrowGatewayClient: () => createEscrowGatewayClient,
1334
1320
  createGatewayClient: () => createGatewayClient,
1321
+ createJobsClient: () => createJobsClient,
1335
1322
  createNodePlatformAdapter: () => createNodePlatformAdapter,
1336
1323
  createPlatformAdapter: () => createPlatformAdapter,
1337
1324
  createPlatformAdapterFor: () => createPlatformAdapterFor,
@@ -1356,6 +1343,7 @@ __export(index_node_exports, {
1356
1343
  encodeDepositTokenData: () => encodeDepositTokenData,
1357
1344
  encodeSetDataPointStatusData: () => encodeSetDataPointStatusData,
1358
1345
  encodeWriteMetadataHeader: () => encodeWriteMetadataHeader,
1346
+ encryptMasterSignatureDelivery: () => encryptMasterSignatureDelivery,
1359
1347
  encryptWithPassword: () => encryptWithPassword,
1360
1348
  escrowContractAddress: () => escrowContractAddress,
1361
1349
  escrowPaymentDomain: () => escrowPaymentDomain,
@@ -1390,12 +1378,16 @@ __export(index_node_exports, {
1390
1378
  isPlatformSupported: () => isPlatformSupported,
1391
1379
  isRedactedLineageNode: () => isRedactedLineageNode,
1392
1380
  isTombstoneHashes: () => isTombstoneHashes,
1381
+ kmsIssuedPreimage: () => kmsIssuedPreimage,
1393
1382
  listQuestions: () => listQuestions,
1394
1383
  mainnetServices: () => mainnetServices,
1395
1384
  moksha: () => moksha,
1396
1385
  mokshaServices: () => mokshaServices,
1397
1386
  mokshaTestnet: () => mokshaTestnet2,
1398
1387
  normalizeBinaryMimeType: () => normalizeBinaryMimeType,
1388
+ openJobRequest: () => openJobRequest,
1389
+ openJobResult: () => openJobResult,
1390
+ openJobResultStream: () => openJobResultStream,
1399
1391
  openWriteSession: () => openWriteSession,
1400
1392
  parsePSError: () => parsePSError,
1401
1393
  parsePersonalServerPaymentRequired: () => parsePersonalServerPaymentRequired,
@@ -1419,6 +1411,9 @@ __export(index_node_exports, {
1419
1411
  scopeMatchesPattern: () => scopeMatchesPattern,
1420
1412
  scopeNamespace: () => scopeNamespace,
1421
1413
  scopeToPathSegments: () => scopeToPathSegments,
1414
+ sealJobRequest: () => sealJobRequest,
1415
+ sealJobResult: () => sealJobResult,
1416
+ sealJobResultStream: () => sealJobResultStream,
1422
1417
  serializeECIES: () => serializeECIES,
1423
1418
  serverRegistrationDomain: () => serverRegistrationDomain,
1424
1419
  sessionCoversScope: () => sessionCoversScope,
@@ -1429,7 +1424,9 @@ __export(index_node_exports, {
1429
1424
  toDirectPaymentReceipt: () => toDirectPaymentReceipt,
1430
1425
  tombstoneDeletedAt: () => tombstoneDeletedAt,
1431
1426
  tryGrantPermissions: () => tryGrantPermissions,
1427
+ userPsId: () => userPsId,
1432
1428
  vanaMainnet: () => vanaMainnet2,
1429
+ verifyEnclaveIdentityEvidence: () => verifyEnclaveIdentityEvidence,
1433
1430
  verifyGrantRegistration: () => verifyGrantRegistration,
1434
1431
  verifyPkceChallenge: () => verifyPkceChallenge,
1435
1432
  verifyWeb3Signed: () => verifyWeb3Signed,
@@ -1439,290 +1436,7 @@ __export(index_node_exports, {
1439
1436
  writePersonalServerData: () => writePersonalServerData
1440
1437
  });
1441
1438
  module.exports = __toCommonJS(index_node_exports);
1442
-
1443
- // src/errors.ts
1444
- var VanaError = class extends Error {
1445
- constructor(message, code) {
1446
- super(message);
1447
- this.code = code;
1448
- this.name = this.constructor.name;
1449
- if (Error.captureStackTrace) {
1450
- Error.captureStackTrace(this, this.constructor);
1451
- }
1452
- }
1453
- code;
1454
- };
1455
- var RelayerError = class extends VanaError {
1456
- constructor(message, statusCode, response) {
1457
- super(message, "RELAYER_ERROR");
1458
- this.statusCode = statusCode;
1459
- this.response = response;
1460
- }
1461
- statusCode;
1462
- response;
1463
- };
1464
- var UserRejectedRequestError = class extends VanaError {
1465
- constructor(message = "User rejected the signature request") {
1466
- super(message, "USER_REJECTED_REQUEST");
1467
- }
1468
- };
1469
- var InvalidConfigurationError = class extends VanaError {
1470
- constructor(message) {
1471
- super(message, "INVALID_CONFIGURATION");
1472
- }
1473
- };
1474
- var ContractNotFoundError = class extends VanaError {
1475
- constructor(contractName, chainId) {
1476
- super(
1477
- `Contract ${contractName} not found on chain ${chainId}`,
1478
- "CONTRACT_NOT_FOUND"
1479
- );
1480
- }
1481
- };
1482
- var BlockchainError = class extends VanaError {
1483
- constructor(message, originalError) {
1484
- super(message, "BLOCKCHAIN_ERROR");
1485
- this.originalError = originalError;
1486
- }
1487
- originalError;
1488
- };
1489
- var SerializationError = class extends VanaError {
1490
- constructor(message) {
1491
- super(message, "SERIALIZATION_ERROR");
1492
- }
1493
- };
1494
- var SignatureError = class extends VanaError {
1495
- constructor(message, originalError) {
1496
- super(message, "SIGNATURE_ERROR");
1497
- this.originalError = originalError;
1498
- }
1499
- originalError;
1500
- };
1501
- var NetworkError = class extends VanaError {
1502
- constructor(message, originalError) {
1503
- super(message, "NETWORK_ERROR");
1504
- this.originalError = originalError;
1505
- }
1506
- originalError;
1507
- };
1508
- var NonceError = class extends VanaError {
1509
- constructor(message) {
1510
- super(message, "NONCE_ERROR");
1511
- }
1512
- };
1513
- var PersonalServerError = class extends VanaError {
1514
- constructor(message, originalError) {
1515
- super(message, "PERSONAL_SERVER_ERROR");
1516
- this.originalError = originalError;
1517
- }
1518
- originalError;
1519
- };
1520
- var ServerUrlMismatchError = class extends VanaError {
1521
- constructor(existingUrl, providedUrl, serverId) {
1522
- super(
1523
- `Server ${serverId} is already registered with URL "${existingUrl}". Cannot change to "${providedUrl}".`,
1524
- "SERVER_URL_MISMATCH"
1525
- );
1526
- this.existingUrl = existingUrl;
1527
- this.providedUrl = providedUrl;
1528
- this.serverId = serverId;
1529
- }
1530
- existingUrl;
1531
- providedUrl;
1532
- serverId;
1533
- };
1534
- var PermissionError = class extends VanaError {
1535
- constructor(message, originalError) {
1536
- super(message, "PERMISSION_ERROR");
1537
- this.originalError = originalError;
1538
- }
1539
- originalError;
1540
- };
1541
- var ReadOnlyError = class extends VanaError {
1542
- constructor(operation, suggestion = "Initialize the SDK with a walletClient to perform this operation") {
1543
- super(
1544
- `Operation '${operation}' requires a wallet client. ${suggestion}`,
1545
- "READ_ONLY_ERROR"
1546
- );
1547
- this.operation = operation;
1548
- this.suggestion = suggestion;
1549
- }
1550
- /** The operation that was attempted */
1551
- operation;
1552
- /** Suggested solution for fixing the error */
1553
- suggestion;
1554
- };
1555
- var TransactionPendingError = class extends VanaError {
1556
- constructor(operationId, message, lastKnownStatus) {
1557
- super(
1558
- `Transaction operation pending: ${message} (operationId: ${operationId})`,
1559
- "TRANSACTION_PENDING"
1560
- );
1561
- this.operationId = operationId;
1562
- this.lastKnownStatus = lastKnownStatus;
1563
- }
1564
- operationId;
1565
- lastKnownStatus;
1566
- /**
1567
- * Converts the error to a JSON-serializable format.
1568
- *
1569
- * @remarks
1570
- * Useful for logging, storage, or transmission of error details.
1571
- *
1572
- * @returns JSON representation of the error
1573
- */
1574
- toJSON() {
1575
- return {
1576
- name: this.name,
1577
- code: this.code,
1578
- message: this.message,
1579
- operationId: this.operationId,
1580
- lastKnownStatus: this.lastKnownStatus
1581
- };
1582
- }
1583
- };
1584
- var PersonalServerWriteError = class extends VanaError {
1585
- constructor(message, code, status, errorCode = null, details) {
1586
- super(message, code);
1587
- this.status = status;
1588
- this.errorCode = errorCode;
1589
- this.details = details;
1590
- }
1591
- status;
1592
- errorCode;
1593
- details;
1594
- };
1595
- var WriteRequestError = class extends PersonalServerWriteError {
1596
- constructor(message, details) {
1597
- super(message, "WRITE_INVALID_REQUEST", void 0, null, details);
1598
- }
1599
- };
1600
- var WriteTransportError = class extends PersonalServerWriteError {
1601
- constructor(message, attempts, cause) {
1602
- super(message, "WRITE_TRANSPORT_ERROR", void 0, null, { attempts });
1603
- this.attempts = attempts;
1604
- this.cause = cause;
1605
- }
1606
- attempts;
1607
- };
1608
- var WriteSessionError = class extends PersonalServerWriteError {
1609
- constructor(message, status, errorCode = null, details) {
1610
- super(message, "WRITE_SESSION_REJECTED", status, errorCode, details);
1611
- }
1612
- };
1613
- var WriteSessionExpiredError = class extends PersonalServerWriteError {
1614
- constructor(message, details) {
1615
- super(message, "WRITE_SESSION_EXPIRED", void 0, null, details);
1616
- }
1617
- };
1618
- var WriteUnauthorizedError = class extends PersonalServerWriteError {
1619
- constructor(message, errorCode = null, details) {
1620
- super(message, "WRITE_UNAUTHORIZED", 401, errorCode, details);
1621
- }
1622
- };
1623
- var WriteForbiddenError = class extends PersonalServerWriteError {
1624
- constructor(message, errorCode = null, details) {
1625
- super(message, "WRITE_FORBIDDEN", 403, errorCode, details);
1626
- }
1627
- };
1628
- var WriteConflictError = class extends PersonalServerWriteError {
1629
- constructor(message, errorCode = null, details) {
1630
- super(message, "WRITE_CONFLICT", 409, errorCode, details);
1631
- }
1632
- };
1633
- var WriteLineageError = class extends PersonalServerWriteError {
1634
- constructor(message, status = 422, errorCode = null, details) {
1635
- super(message, "WRITE_LINEAGE_REJECTED", status, errorCode, details);
1636
- }
1637
- };
1638
- var WriteRejectedError = class extends PersonalServerWriteError {
1639
- constructor(message, status, errorCode = null, details) {
1640
- super(message, "WRITE_REJECTED", status, errorCode, details);
1641
- }
1642
- };
1643
- var LineageReadError = class extends VanaError {
1644
- constructor(message, status, errorCode = null, details) {
1645
- super(message, "LINEAGE_READ_ERROR");
1646
- this.status = status;
1647
- this.errorCode = errorCode;
1648
- this.details = details;
1649
- }
1650
- status;
1651
- errorCode;
1652
- details;
1653
- };
1654
- var DerivativeQuestionRejectedError = class extends PersonalServerWriteError {
1655
- constructor(message, status, errorCode = null, details) {
1656
- super(message, "DERIVATIVE_QUESTION_REJECTED", status, errorCode, details);
1657
- }
1658
- };
1659
- var DerivativeQuestionInvalidError = class extends PersonalServerWriteError {
1660
- constructor(message, status = 400, errorCode = null, details) {
1661
- super(message, "DERIVATIVE_QUESTION_INVALID", status, errorCode, details);
1662
- }
1663
- };
1664
- var DerivativeQuestionNotFoundError = class extends PersonalServerWriteError {
1665
- constructor(message, errorCode = null, details) {
1666
- super(message, "DERIVATIVE_QUESTION_NOT_FOUND", 404, errorCode, details);
1667
- }
1668
- };
1669
- var DerivativeDerivedScopeRequiredError = class extends PersonalServerWriteError {
1670
- constructor(message, errorCode = null, details) {
1671
- super(
1672
- message,
1673
- "DERIVATIVE_DERIVED_SCOPE_REQUIRED",
1674
- 400,
1675
- errorCode,
1676
- details
1677
- );
1678
- }
1679
- };
1680
- var DerivativeSourceNotGrantedError = class extends PersonalServerWriteError {
1681
- constructor(message, errorCode = null, details) {
1682
- super(message, "DERIVATIVE_SOURCE_NOT_GRANTED", 403, errorCode, details);
1683
- }
1684
- };
1685
- var DerivativeCycleError = class extends PersonalServerWriteError {
1686
- constructor(message, errorCode = null, details) {
1687
- super(message, "DERIVATIVE_CYCLE", 409, errorCode, details);
1688
- }
1689
- };
1690
- var DerivativeComputeUnavailableError = class extends PersonalServerWriteError {
1691
- constructor(message, errorCode = null, details) {
1692
- super(message, "DERIVATIVE_COMPUTE_UNAVAILABLE", 503, errorCode, details);
1693
- }
1694
- };
1695
- var DerivativeQuestionTimeoutError = class extends PersonalServerWriteError {
1696
- constructor(message, details) {
1697
- super(message, "DERIVATIVE_QUESTION_TIMEOUT", void 0, null, details);
1698
- }
1699
- };
1700
- var DerivativeQuestionFailedError = class extends PersonalServerWriteError {
1701
- constructor(message, details) {
1702
- super(message, "DERIVATIVE_QUESTION_FAILED", void 0, null, details);
1703
- }
1704
- };
1705
- var DataPointDeletedError = class extends VanaError {
1706
- constructor(message, details = {}) {
1707
- super(message, "DATA_POINT_DELETED");
1708
- this.details = details;
1709
- }
1710
- details;
1711
- };
1712
- var DataPointNotFoundError = class extends VanaError {
1713
- constructor(message, details = {}) {
1714
- super(message, "DATA_POINT_NOT_FOUND");
1715
- this.details = details;
1716
- }
1717
- details;
1718
- };
1719
- var DataPointVersionConflictError = class extends VanaError {
1720
- constructor(message, details = {}) {
1721
- super(message, "DATA_POINT_VERSION_CONFLICT");
1722
- this.details = details;
1723
- }
1724
- details;
1725
- };
1439
+ __reExport(index_node_exports, require("./errors.cjs"), module.exports);
1726
1440
 
1727
1441
  // src/contracts/contractController.ts
1728
1442
  var import_viem3 = require("viem");
@@ -31628,13 +31342,13 @@ var NodeCryptoAdapter = class {
31628
31342
  */
31629
31343
  async generateKeyPair() {
31630
31344
  try {
31631
- const secp256k14 = import_secp256k12.default;
31345
+ const secp256k15 = import_secp256k12.default;
31632
31346
  let privateKey;
31633
31347
  do {
31634
31348
  privateKey = (0, import_crypto2.randomBytes)(32);
31635
- } while (!secp256k14.privateKeyVerify(privateKey));
31349
+ } while (!secp256k15.privateKeyVerify(privateKey));
31636
31350
  const publicKey = Buffer.from(
31637
- secp256k14.publicKeyCreate(privateKey, true)
31351
+ secp256k15.publicKeyCreate(privateKey, true)
31638
31352
  );
31639
31353
  return {
31640
31354
  privateKey: privateKey.toString("hex"),
@@ -32084,31 +31798,7 @@ async function decryptWithPassword(encrypted, password) {
32084
31798
 
32085
31799
  // src/auth/web3-signed.ts
32086
31800
  var import_viem13 = require("viem");
32087
-
32088
- // src/auth/errors.ts
32089
- var MissingAuthError = class extends VanaError {
32090
- constructor(message = "Missing authentication", details) {
32091
- super(message, "MISSING_AUTH");
32092
- this.details = details;
32093
- }
32094
- details;
32095
- };
32096
- var InvalidSignatureError = class extends VanaError {
32097
- constructor(details, message = "Invalid signature") {
32098
- super(message, "INVALID_SIGNATURE");
32099
- this.details = details;
32100
- }
32101
- details;
32102
- };
32103
- var ExpiredTokenError = class extends VanaError {
32104
- constructor(details, message = "Token has expired") {
32105
- super(message, "EXPIRED_TOKEN");
32106
- this.details = details;
32107
- }
32108
- details;
32109
- };
32110
-
32111
- // src/auth/web3-signed.ts
31801
+ var import_errors = require("./auth/errors.cjs");
32112
31802
  var WEB3_SIGNED_PREFIX = "Web3Signed ";
32113
31803
  var CLOCK_SKEW_SECONDS = 60;
32114
31804
  function base64urlDecode(input) {
@@ -32122,14 +31812,14 @@ function isFiniteNumber(value) {
32122
31812
  }
32123
31813
  function parsePayload(value) {
32124
31814
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
32125
- throw new InvalidSignatureError({ reason: "Invalid payload shape" });
31815
+ throw new import_errors.InvalidSignatureError({ reason: "Invalid payload shape" });
32126
31816
  }
32127
31817
  const payload = value;
32128
31818
  if (typeof payload["aud"] !== "string" || typeof payload["method"] !== "string" || typeof payload["uri"] !== "string" || typeof payload["bodyHash"] !== "string" || !isFiniteNumber(payload["iat"]) || !isFiniteNumber(payload["exp"])) {
32129
- throw new InvalidSignatureError({ reason: "Invalid payload claims" });
31819
+ throw new import_errors.InvalidSignatureError({ reason: "Invalid payload claims" });
32130
31820
  }
32131
31821
  if (payload["grantId"] !== void 0 && typeof payload["grantId"] !== "string") {
32132
- throw new InvalidSignatureError({ reason: "Invalid grantId claim" });
31822
+ throw new import_errors.InvalidSignatureError({ reason: "Invalid grantId claim" });
32133
31823
  }
32134
31824
  return {
32135
31825
  aud: payload["aud"],
@@ -32143,28 +31833,28 @@ function parsePayload(value) {
32143
31833
  }
32144
31834
  function parseWeb3SignedHeader(headerValue) {
32145
31835
  if (!headerValue) {
32146
- throw new MissingAuthError();
31836
+ throw new import_errors.MissingAuthError();
32147
31837
  }
32148
31838
  if (!headerValue.startsWith(WEB3_SIGNED_PREFIX)) {
32149
- throw new InvalidSignatureError({ reason: "Missing Web3Signed prefix" });
31839
+ throw new import_errors.InvalidSignatureError({ reason: "Missing Web3Signed prefix" });
32150
31840
  }
32151
31841
  const value = headerValue.slice(WEB3_SIGNED_PREFIX.length);
32152
31842
  const dotIndex = value.indexOf(".");
32153
31843
  if (dotIndex === -1 || dotIndex === 0 || dotIndex === value.length - 1) {
32154
- throw new InvalidSignatureError({ reason: "Invalid header format" });
31844
+ throw new import_errors.InvalidSignatureError({ reason: "Invalid header format" });
32155
31845
  }
32156
31846
  const payloadBase64 = value.slice(0, dotIndex);
32157
31847
  const signatureStr = value.slice(dotIndex + 1);
32158
31848
  if (!signatureStr.startsWith("0x")) {
32159
- throw new InvalidSignatureError({ reason: "Invalid signature format" });
31849
+ throw new import_errors.InvalidSignatureError({ reason: "Invalid signature format" });
32160
31850
  }
32161
31851
  let payload;
32162
31852
  try {
32163
31853
  const decoded = base64urlDecode(payloadBase64);
32164
31854
  payload = parsePayload(JSON.parse(decoded));
32165
31855
  } catch (err) {
32166
- if (err instanceof InvalidSignatureError) throw err;
32167
- throw new InvalidSignatureError({ reason: "Invalid payload encoding" });
31856
+ if (err instanceof import_errors.InvalidSignatureError) throw err;
31857
+ throw new import_errors.InvalidSignatureError({ reason: "Invalid payload encoding" });
32168
31858
  }
32169
31859
  return {
32170
31860
  payloadBase64,
@@ -32183,24 +31873,24 @@ async function verifyWeb3Signed(params) {
32183
31873
  signature
32184
31874
  });
32185
31875
  } catch {
32186
- throw new InvalidSignatureError({ reason: "Signature recovery failed" });
31876
+ throw new import_errors.InvalidSignatureError({ reason: "Signature recovery failed" });
32187
31877
  }
32188
31878
  if (payload.aud !== params.expectedOrigin) {
32189
- throw new InvalidSignatureError({
31879
+ throw new import_errors.InvalidSignatureError({
32190
31880
  reason: "Audience mismatch",
32191
31881
  expected: params.expectedOrigin,
32192
31882
  actual: payload.aud
32193
31883
  });
32194
31884
  }
32195
31885
  if (payload.method !== params.expectedMethod) {
32196
- throw new InvalidSignatureError({
31886
+ throw new import_errors.InvalidSignatureError({
32197
31887
  reason: "Method mismatch",
32198
31888
  expected: params.expectedMethod,
32199
31889
  actual: payload.method
32200
31890
  });
32201
31891
  }
32202
31892
  if (payload.uri !== params.expectedPath) {
32203
- throw new InvalidSignatureError({
31893
+ throw new import_errors.InvalidSignatureError({
32204
31894
  reason: "URI mismatch",
32205
31895
  expected: params.expectedPath,
32206
31896
  actual: payload.uri
@@ -32209,7 +31899,7 @@ async function verifyWeb3Signed(params) {
32209
31899
  if (params.bodyBytes !== void 0) {
32210
31900
  const expectedBodyHash = computeBodyHash(params.bodyBytes);
32211
31901
  if (payload.bodyHash !== expectedBodyHash) {
32212
- throw new InvalidSignatureError({
31902
+ throw new import_errors.InvalidSignatureError({
32213
31903
  reason: "Body hash mismatch",
32214
31904
  expected: expectedBodyHash,
32215
31905
  actual: payload.bodyHash
@@ -32218,14 +31908,17 @@ async function verifyWeb3Signed(params) {
32218
31908
  }
32219
31909
  const now = params.now ?? Math.floor(Date.now() / 1e3);
32220
31910
  if (payload.exp < now - CLOCK_SKEW_SECONDS) {
32221
- throw new ExpiredTokenError({ reason: "Token expired" });
31911
+ throw new import_errors.ExpiredTokenError({ reason: "Token expired" });
32222
31912
  }
32223
31913
  if (payload.iat > now + CLOCK_SKEW_SECONDS) {
32224
- throw new ExpiredTokenError({ reason: "Token issued in the future" });
31914
+ throw new import_errors.ExpiredTokenError({ reason: "Token issued in the future" });
32225
31915
  }
32226
31916
  return { signer, payload };
32227
31917
  }
32228
31918
 
31919
+ // src/index.node.ts
31920
+ var import_errors14 = require("./auth/errors.cjs");
31921
+
32229
31922
  // src/auth/pkce.ts
32230
31923
  var PKCE_VERIFIER_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
32231
31924
  var PKCE_VERIFIER_MIN_LENGTH = 43;
@@ -32644,15 +32337,1534 @@ var RECORD_DATA_ACCESS_TYPES = {
32644
32337
  ]
32645
32338
  };
32646
32339
 
32647
- // src/protocol/personal-server-registration.ts
32340
+ // src/protocol/identity.ts
32341
+ var secp256k14 = __toESM(require("@noble/secp256k1"), 1);
32648
32342
  var import_viem14 = require("viem");
32343
+ var import_accounts = require("viem/accounts");
32344
+ init_interface();
32345
+ var ENCLAVE_IDENTITY_EVIDENCE_VERSION = 1;
32346
+ var USER_PS_ID_DOMAIN = "vana.ps-enclave.v1";
32347
+ var ENCLAVE_WALLET_PURPOSE = "vana.ps-enclave.wallet.v1";
32348
+ var MASTER_SIGNATURE_DELIVERY_VERSION = "vana.ps-enclave.delivery.v1";
32349
+ var MASTER_SIGNATURE_DELIVERY_MAX_AGE_SECONDS = 600;
32350
+ var SEALED_ENVELOPE_VERSION = 1;
32351
+ var VANA_MAINNET_CHAIN_ID = 1480;
32352
+ var MOKSHA_CHAIN_ID = 14800;
32353
+ var KMS_ISSUED_PREFIX = "dstack-kms-issued";
32354
+ var PREIMAGE_SEPARATOR = ":";
32355
+ var UNCOMPRESSED_PUBLIC_KEY_BYTES = 65;
32356
+ var UNCOMPRESSED_PUBLIC_KEY_PREFIX = "04";
32357
+ var EMPTY_HEX = "0x";
32358
+ function emptyAnchor() {
32359
+ return Object.freeze({
32360
+ kmsRootPubkey: EMPTY_HEX,
32361
+ appIds: Object.freeze([])
32362
+ });
32363
+ }
32364
+ var ENCLAVE_TRUST_ANCHORS = Object.freeze({
32365
+ // filled at fleet provisioning; verify fails closed while empty
32366
+ [VANA_MAINNET_CHAIN_ID]: emptyAnchor(),
32367
+ // Moksha workers share this dstack app and KMS root; the controller does not derive owner keys.
32368
+ [MOKSHA_CHAIN_ID]: Object.freeze({
32369
+ kmsRootPubkey: "0x0434c76e0c3f52ec64cbf9bbf5c910c272330166fd656c0a86bb330963e46910e1a0e6fa51bec74be2f9129342707636060d85856d102cee8290185409ecf7422f",
32370
+ appIds: Object.freeze([
32371
+ "0xec9a39de98c760e1ded9f1e97016dc5f0e357cf2"
32372
+ ])
32373
+ })
32374
+ });
32375
+ function userPsId(chainId, ownerAddress) {
32376
+ const packed = (0, import_viem14.encodePacked)(
32377
+ ["string", "uint256", "address"],
32378
+ [USER_PS_ID_DOMAIN, BigInt(chainId), (0, import_viem14.getAddress)(ownerAddress)]
32379
+ );
32380
+ return (0, import_viem14.keccak256)(packed);
32381
+ }
32382
+ function compressPublicKey(publicKey) {
32383
+ return secp256k14.ProjectivePoint.fromHex(
32384
+ (0, import_viem14.fromHex)(publicKey, "bytes")
32385
+ ).toRawBytes(true);
32386
+ }
32387
+ function sameKey(a, b) {
32388
+ return (0, import_viem14.toHex)(compressPublicKey(a)) === (0, import_viem14.toHex)(compressPublicKey(b));
32389
+ }
32390
+ function assertUncompressedKey(publicKey) {
32391
+ const hex = publicKey.slice(2);
32392
+ if (hex.length !== UNCOMPRESSED_PUBLIC_KEY_BYTES * 2 || !hex.startsWith(UNCOMPRESSED_PUBLIC_KEY_PREFIX) || !/^[0-9a-fA-F]+$/.test(hex)) {
32393
+ throw new Error("Public key must be a 65-byte uncompressed secp256k1 key");
32394
+ }
32395
+ }
32396
+ function appRootPreimage(purpose, publicKey) {
32397
+ const keyHex = (0, import_viem14.toHex)(compressPublicKey(publicKey)).slice(2);
32398
+ return (0, import_viem14.keccak256)((0, import_viem14.toBytes)(`${purpose}${PREIMAGE_SEPARATOR}${keyHex}`));
32399
+ }
32400
+ function kmsIssuedPreimage(appId, appRootPublicKey) {
32401
+ const prefix = (0, import_viem14.concat)([
32402
+ (0, import_viem14.toBytes)(`${KMS_ISSUED_PREFIX}${PREIMAGE_SEPARATOR}`),
32403
+ (0, import_viem14.fromHex)(appId, "bytes")
32404
+ ]);
32405
+ const compressed = compressPublicKey(appRootPublicKey);
32406
+ return (0, import_viem14.keccak256)((0, import_viem14.concat)([prefix, compressed]));
32407
+ }
32408
+ async function recoverChainKey(hash, signature, link) {
32409
+ try {
32410
+ return (await (0, import_viem14.recoverPublicKey)({ hash, signature })).toLowerCase();
32411
+ } catch {
32412
+ throw new Error(`Invalid enclave signature chain link ${link}`);
32413
+ }
32414
+ }
32415
+ async function verifyEnclaveIdentityEvidence(evidence, anchors, expected) {
32416
+ if (evidence.v !== ENCLAVE_IDENTITY_EVIDENCE_VERSION) {
32417
+ throw new Error("Unsupported enclave identity evidence version");
32418
+ }
32419
+ if (!Number.isInteger(evidence.epoch) || evidence.epoch < 1) {
32420
+ throw new Error("Invalid enclave identity epoch");
32421
+ }
32422
+ if (evidence.chainId !== expected.chainId) {
32423
+ throw new Error(
32424
+ "Enclave identity chain ID does not match expected chain ID"
32425
+ );
32426
+ }
32427
+ if (!(0, import_viem14.isAddressEqual)(evidence.ownerAddress, expected.ownerAddress)) {
32428
+ throw new Error("Enclave identity owner does not match expected owner");
32429
+ }
32430
+ if (evidence.epoch !== expected.epoch) {
32431
+ throw new Error("Enclave identity epoch does not match expected epoch");
32432
+ }
32433
+ const expectedUserPsId = userPsId(expected.chainId, expected.ownerAddress);
32434
+ if (evidence.userPsId.toLowerCase() !== expectedUserPsId.toLowerCase()) {
32435
+ throw new Error("Enclave userPsId does not match expected identity");
32436
+ }
32437
+ if (evidence.purpose !== ENCLAVE_WALLET_PURPOSE) {
32438
+ throw new Error("Unexpected enclave wallet purpose");
32439
+ }
32440
+ if (anchors.kmsRootPubkey === EMPTY_HEX) {
32441
+ throw new Error("KMS root trust anchor is not provisioned");
32442
+ }
32443
+ assertUncompressedKey(evidence.publicKey);
32444
+ const derivedAddress = (0, import_accounts.publicKeyToAddress)(evidence.publicKey);
32445
+ if ((0, import_viem14.getAddress)(derivedAddress) !== (0, import_viem14.getAddress)(evidence.address)) {
32446
+ throw new Error("Enclave public key does not match its address");
32447
+ }
32448
+ const appRootPublicKey = await recoverChainKey(
32449
+ appRootPreimage(evidence.purpose, evidence.publicKey),
32450
+ evidence.signatureChain[0],
32451
+ 0
32452
+ );
32453
+ const kmsRootPublicKey = await recoverChainKey(
32454
+ kmsIssuedPreimage(evidence.appId, appRootPublicKey),
32455
+ evidence.signatureChain[1],
32456
+ 1
32457
+ );
32458
+ let matchesAnchor;
32459
+ try {
32460
+ matchesAnchor = sameKey(kmsRootPublicKey, anchors.kmsRootPubkey);
32461
+ } catch {
32462
+ throw new Error("KMS root trust anchor is malformed");
32463
+ }
32464
+ if (!matchesAnchor) {
32465
+ throw new Error("KMS root public key does not match the trust anchor");
32466
+ }
32467
+ if ((0, import_viem14.keccak256)(kmsRootPublicKey) !== evidence.kmsRootFingerprint.toLowerCase()) {
32468
+ throw new Error("KMS root fingerprint does not match the evidence");
32469
+ }
32470
+ const appId = evidence.appId.toLowerCase();
32471
+ if (!anchors.appIds.some((allowedAppId) => allowedAppId.toLowerCase() === appId)) {
32472
+ throw new Error("Enclave app ID is not trusted");
32473
+ }
32474
+ }
32475
+ async function buildMasterSignatureDelivery(evidence, masterSignature, now = Math.floor(Date.now() / 1e3)) {
32476
+ deriveMasterKey(masterSignature);
32477
+ const signerAddress = await recoverServerOwner(masterSignature);
32478
+ if (!(0, import_viem14.isAddressEqual)(signerAddress, evidence.ownerAddress)) {
32479
+ throw new Error("Master signature signer does not match evidence owner");
32480
+ }
32481
+ return {
32482
+ v: MASTER_SIGNATURE_DELIVERY_VERSION,
32483
+ userPsId: evidence.userPsId,
32484
+ epoch: evidence.epoch,
32485
+ enclaveAddress: evidence.address,
32486
+ ownerAddress: evidence.ownerAddress,
32487
+ masterSignature,
32488
+ issuedAt: now
32489
+ };
32490
+ }
32491
+ async function encryptMasterSignatureDelivery(delivery, publicKey, ecies) {
32492
+ assertUncompressedKey(publicKey);
32493
+ if (!(0, import_viem14.isAddressEqual)((0, import_accounts.publicKeyToAddress)(publicKey), delivery.enclaveAddress)) {
32494
+ throw new Error(
32495
+ "Public key does not belong to the delivery's enclave address"
32496
+ );
32497
+ }
32498
+ const plaintext = (0, import_viem14.toBytes)(JSON.stringify(delivery));
32499
+ const encrypted = await ecies.encrypt((0, import_viem14.fromHex)(publicKey, "bytes"), plaintext);
32500
+ return `0x${serializeECIES(encrypted)}`;
32501
+ }
32502
+
32503
+ // src/protocol/jobs.ts
32504
+ var JOB_PROTOCOL_VERSION = 1;
32505
+ var JOB_OPERATIONS = ["raw_read", "inference"];
32506
+ var JOB_STATES = [
32507
+ "queued",
32508
+ "claimed",
32509
+ "running",
32510
+ "completed",
32511
+ "failed",
32512
+ "expired",
32513
+ "cancelled"
32514
+ ];
32515
+ var DEFAULT_LEASE_SECONDS = 30;
32516
+ var MAX_LEASE_SECONDS = 300;
32517
+ var MAX_ATTEMPTS = 3;
32518
+ var MAX_WAIT_SECONDS = 25;
32519
+ var CLAIM_POLL_FLOOR_MS = 1e3;
32520
+ var DEFAULT_JOB_DEADLINE_SECONDS = 600;
32521
+ var MAX_JOB_DEADLINE_SECONDS = 3600;
32522
+
32523
+ // src/protocol/jobs-client.ts
32524
+ var import_node_crypto = require("node:crypto");
32525
+ var import_sha26 = require("@noble/hashes/sha2");
32526
+ var import_viem16 = require("viem");
32527
+ var import_accounts2 = require("viem/accounts");
32528
+
32529
+ // src/crypto/envelope/job.ts
32530
+ var import_sha25 = require("@noble/hashes/sha2");
32531
+ var import_viem15 = require("viem");
32532
+ init_constants();
32533
+ init_interface();
32534
+ var textDecoder = new TextDecoder();
32535
+ var textEncoder = new TextEncoder();
32536
+ var MAX_JOB_RESULT_HEADER_BYTES = 4096;
32537
+ var WRAPPED_KEY_LENGTH_BYTES = 4;
32538
+ var FRAME_LENGTH_BYTES = 4;
32539
+ var FRAME_FLAGS_BYTES = 1;
32540
+ var AES_KEY_BYTES = 32;
32541
+ var AES_GCM_NONCE_BYTES = 12;
32542
+ var AES_GCM_TAG_BYTES = 16;
32543
+ var WRAPPED_METADATA_LENGTH_BYTES = 4;
32544
+ var WRAPPED_KEY_PLAINTEXT_PREFIX_BYTES = AES_KEY_BYTES + AES_GCM_NONCE_BYTES + WRAPPED_METADATA_LENGTH_BYTES;
32545
+ var MAX_WRAPPED_KEY_BYTES = 8192;
32546
+ var FINAL_FRAME_FLAG = 1;
32547
+ var MAX_CHUNK_INDEX = 4294967295;
32548
+ var JOB_RESULT_FORMAT_VERSION = 2;
32549
+ var JOB_RESULT_CHUNK_BYTES = 1024 * 1024;
32550
+ var JobEnvelopeError = class extends Error {
32551
+ constructor(message) {
32552
+ super(message);
32553
+ this.name = "JobEnvelopeError";
32554
+ }
32555
+ };
32556
+ function sortJsonKeys(value) {
32557
+ if (Array.isArray(value)) {
32558
+ return value.map(sortJsonKeys);
32559
+ }
32560
+ if (value !== null && typeof value === "object") {
32561
+ return Object.fromEntries(
32562
+ Object.keys(value).sort().map((key) => [
32563
+ key,
32564
+ sortJsonKeys(value[key])
32565
+ ])
32566
+ );
32567
+ }
32568
+ return value;
32569
+ }
32570
+ function canonicalJsonBytes(value) {
32571
+ return textEncoder.encode(JSON.stringify(sortJsonKeys(value)));
32572
+ }
32573
+ function canonicalJobRequestBytes(request) {
32574
+ validateJobRequest(request);
32575
+ return canonicalJsonBytes(request);
32576
+ }
32577
+ function requestPlaintext(envelope) {
32578
+ validateRequestEnvelope(envelope);
32579
+ return canonicalJsonBytes(envelope);
32580
+ }
32581
+ function resultMetadata(result) {
32582
+ return {
32583
+ v: result.v,
32584
+ jobId: result.jobId,
32585
+ scope: result.scope,
32586
+ version: result.version,
32587
+ contentType: result.contentType
32588
+ };
32589
+ }
32590
+ function encryptedBytesToBase64(encrypted) {
32591
+ return toBase64((0, import_viem15.fromHex)(`0x${serializeECIES(encrypted)}`, "bytes"));
32592
+ }
32593
+ function encryptedToBytes(encrypted) {
32594
+ const bytes = new Uint8Array(
32595
+ encrypted.iv.length + encrypted.ephemPublicKey.length + encrypted.ciphertext.length + encrypted.mac.length
32596
+ );
32597
+ let offset = 0;
32598
+ bytes.set(encrypted.iv, offset);
32599
+ offset += encrypted.iv.length;
32600
+ bytes.set(encrypted.ephemPublicKey, offset);
32601
+ offset += encrypted.ephemPublicKey.length;
32602
+ bytes.set(encrypted.ciphertext, offset);
32603
+ offset += encrypted.ciphertext.length;
32604
+ bytes.set(encrypted.mac, offset);
32605
+ return bytes;
32606
+ }
32607
+ function bytesToEncrypted(bytes) {
32608
+ const absoluteMinLength = FORMAT.IV_LENGTH + 1 + MAC.LENGTH + 1;
32609
+ if (bytes.length < absoluteMinLength) {
32610
+ throw new ECIESError(
32611
+ `Invalid ECIES data: too short (${bytes.length} bytes, minimum ${absoluteMinLength} bytes required)`,
32612
+ "DECRYPTION_FAILED"
32613
+ );
32614
+ }
32615
+ const prefix = bytes[FORMAT.EPHEMERAL_KEY_OFFSET];
32616
+ if (prefix !== CURVE.PREFIX.UNCOMPRESSED) {
32617
+ throw new ECIESError(
32618
+ `Invalid ephemeral public key: must be uncompressed format (0x04 prefix), got 0x${prefix.toString(16).padStart(2, "0")}`,
32619
+ "DECRYPTION_FAILED"
32620
+ );
32621
+ }
32622
+ const ephemKeySize = CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH;
32623
+ const minLength = FORMAT.IV_LENGTH + ephemKeySize + MAC.LENGTH + 1;
32624
+ if (bytes.length < minLength) {
32625
+ throw new ECIESError(
32626
+ `Invalid ECIES data: too short (${bytes.length} bytes, minimum ${minLength} bytes required)`,
32627
+ "DECRYPTION_FAILED"
32628
+ );
32629
+ }
32630
+ return {
32631
+ iv: bytes.subarray(FORMAT.IV_OFFSET, FORMAT.IV_OFFSET + FORMAT.IV_LENGTH),
32632
+ ephemPublicKey: bytes.subarray(
32633
+ FORMAT.EPHEMERAL_KEY_OFFSET,
32634
+ FORMAT.EPHEMERAL_KEY_OFFSET + ephemKeySize
32635
+ ),
32636
+ ciphertext: bytes.subarray(
32637
+ FORMAT.EPHEMERAL_KEY_OFFSET + ephemKeySize,
32638
+ bytes.length - MAC.LENGTH
32639
+ ),
32640
+ mac: bytes.subarray(bytes.length - MAC.LENGTH)
32641
+ };
32642
+ }
32643
+ function base64ToEncrypted(ciphertext) {
32644
+ return deserializeECIES((0, import_viem15.toHex)(fromBase64(ciphertext)));
32645
+ }
32646
+ function parseObject(plaintext, kind) {
32647
+ try {
32648
+ const value = JSON.parse(textDecoder.decode(plaintext));
32649
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
32650
+ throw new JobEnvelopeError(`Invalid ${kind}: expected an object`);
32651
+ }
32652
+ return value;
32653
+ } catch (error) {
32654
+ if (error instanceof JobEnvelopeError) throw error;
32655
+ throw new JobEnvelopeError(`Invalid ${kind}: malformed JSON`);
32656
+ }
32657
+ }
32658
+ function isPlainObject2(value) {
32659
+ if (value === null || typeof value !== "object") return false;
32660
+ const prototype = Object.getPrototypeOf(value);
32661
+ return prototype === Object.prototype || prototype === null;
32662
+ }
32663
+ function requirePlainObject(value, field, kind) {
32664
+ if (!isPlainObject2(value)) {
32665
+ throw new JobEnvelopeError(`Invalid ${kind}: invalid ${field}`);
32666
+ }
32667
+ }
32668
+ function requireExactKeys(value, expectedKeys, kind) {
32669
+ for (const key of expectedKeys) {
32670
+ if (!Object.hasOwn(value, key) || value[key] === void 0) {
32671
+ throw new JobEnvelopeError(`Invalid ${kind}: missing ${key}`);
32672
+ }
32673
+ }
32674
+ const expected = new Set(expectedKeys);
32675
+ for (const key of Reflect.ownKeys(value)) {
32676
+ if (!expected.has(key)) {
32677
+ throw new JobEnvelopeError(
32678
+ `Invalid ${kind}: unknown field ${String(key)}`
32679
+ );
32680
+ }
32681
+ }
32682
+ }
32683
+ function requireString(value, field, kind) {
32684
+ if (typeof value !== "string" || value.length === 0) {
32685
+ throw new JobEnvelopeError(`Invalid ${kind}: missing ${field}`);
32686
+ }
32687
+ }
32688
+ function validateJobRequest(value) {
32689
+ requirePlainObject(value, "request", "job request");
32690
+ requireExactKeys(
32691
+ value,
32692
+ [
32693
+ "v",
32694
+ "jobId",
32695
+ "owner",
32696
+ "builder",
32697
+ "builderPublicKey",
32698
+ "grantId",
32699
+ "scope",
32700
+ "operation",
32701
+ "pinnedVersion",
32702
+ "deadline"
32703
+ ],
32704
+ "job request"
32705
+ );
32706
+ if (value.v !== JOB_PROTOCOL_VERSION) {
32707
+ throw new JobEnvelopeError(
32708
+ `Unsupported job request version: ${String(value.v)}`
32709
+ );
32710
+ }
32711
+ requireString(value.jobId, "jobId", "job request");
32712
+ if (typeof value.owner !== "string" || !(0, import_viem15.isAddress)(value.owner)) {
32713
+ throw new JobEnvelopeError("Invalid job request: invalid owner");
32714
+ }
32715
+ if (typeof value.builder !== "string" || !(0, import_viem15.isAddress)(value.builder)) {
32716
+ throw new JobEnvelopeError("Invalid job request: invalid builder");
32717
+ }
32718
+ if (typeof value.builderPublicKey !== "string" || !(0, import_viem15.isHex)(value.builderPublicKey)) {
32719
+ throw new JobEnvelopeError("Invalid job request: invalid builderPublicKey");
32720
+ }
32721
+ if (typeof value.grantId !== "string" || !(0, import_viem15.isHex)(value.grantId)) {
32722
+ throw new JobEnvelopeError("Invalid job request: invalid grantId");
32723
+ }
32724
+ requireString(value.scope, "scope", "job request");
32725
+ if (!JOB_OPERATIONS.includes(value.operation)) {
32726
+ throw new JobEnvelopeError("Invalid job request: invalid operation");
32727
+ }
32728
+ if (value.pinnedVersion !== null && typeof value.pinnedVersion !== "string") {
32729
+ throw new JobEnvelopeError("Invalid job request: missing pinnedVersion");
32730
+ }
32731
+ if (typeof value.deadline !== "string" || !Number.isFinite(Date.parse(value.deadline))) {
32732
+ throw new JobEnvelopeError("Invalid job request: invalid deadline");
32733
+ }
32734
+ return value;
32735
+ }
32736
+ function validateRequestEnvelope(value) {
32737
+ requirePlainObject(value, "envelope", "job request envelope");
32738
+ requireExactKeys(value, ["request", "auth"], "job request envelope");
32739
+ validateJobRequest(value.request);
32740
+ requireString(value.auth, "auth", "job request envelope");
32741
+ return value;
32742
+ }
32743
+ function validateResultMetadata(value) {
32744
+ requirePlainObject(value, "metadata", "job result");
32745
+ requireExactKeys(
32746
+ value,
32747
+ ["v", "jobId", "scope", "version", "contentType"],
32748
+ "job result"
32749
+ );
32750
+ if (value.v !== JOB_PROTOCOL_VERSION) {
32751
+ throw new JobEnvelopeError(
32752
+ `Unsupported job result version: ${String(value.v)}`
32753
+ );
32754
+ }
32755
+ for (const field of ["jobId", "scope", "contentType"]) {
32756
+ requireString(value[field], field, "job result");
32757
+ }
32758
+ if (value.version !== null && typeof value.version !== "string") {
32759
+ throw new JobEnvelopeError("Invalid job result: missing version");
32760
+ }
32761
+ return value;
32762
+ }
32763
+ function validateResult(value) {
32764
+ requirePlainObject(value, "result", "job result");
32765
+ requireExactKeys(
32766
+ value,
32767
+ ["v", "jobId", "scope", "version", "contentType", "body"],
32768
+ "job result"
32769
+ );
32770
+ validateResultMetadata(resultMetadata(value));
32771
+ if (!(value.body instanceof Uint8Array)) {
32772
+ throw new JobEnvelopeError("Invalid job result: missing body");
32773
+ }
32774
+ return value;
32775
+ }
32776
+ function webCrypto() {
32777
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.getRandomValues !== "function" || !globalThis.crypto.subtle) {
32778
+ throw new JobEnvelopeError(
32779
+ "Job result streaming requires the Web Crypto API"
32780
+ );
32781
+ }
32782
+ return globalThis.crypto;
32783
+ }
32784
+ function uint32(value) {
32785
+ const bytes = new Uint8Array(4);
32786
+ new DataView(bytes.buffer).setUint32(0, value);
32787
+ return bytes;
32788
+ }
32789
+ function readUint32(bytes, offset = 0) {
32790
+ return new DataView(bytes.buffer, bytes.byteOffset + offset, 4).getUint32(0);
32791
+ }
32792
+ function wrappedKeyPlaintext(contentKey, noncePrefix, metadataBytes) {
32793
+ const plaintext = new Uint8Array(
32794
+ WRAPPED_KEY_PLAINTEXT_PREFIX_BYTES + metadataBytes.length
32795
+ );
32796
+ plaintext.set(contentKey, 0);
32797
+ plaintext.set(noncePrefix, AES_KEY_BYTES);
32798
+ new DataView(plaintext.buffer).setUint32(
32799
+ AES_KEY_BYTES + AES_GCM_NONCE_BYTES,
32800
+ metadataBytes.length
32801
+ );
32802
+ plaintext.set(metadataBytes, WRAPPED_KEY_PLAINTEXT_PREFIX_BYTES);
32803
+ return plaintext;
32804
+ }
32805
+ function parseWrappedKeyPlaintext(plaintext) {
32806
+ if (plaintext.length < WRAPPED_KEY_PLAINTEXT_PREFIX_BYTES) {
32807
+ throw new JobEnvelopeError("Invalid job result: wrapped key is truncated");
32808
+ }
32809
+ const metadataLength = readUint32(
32810
+ plaintext,
32811
+ AES_KEY_BYTES + AES_GCM_NONCE_BYTES
32812
+ );
32813
+ if (metadataLength > MAX_JOB_RESULT_HEADER_BYTES) {
32814
+ throw new JobEnvelopeError(
32815
+ `Invalid job result: header exceeds ${MAX_JOB_RESULT_HEADER_BYTES} bytes`
32816
+ );
32817
+ }
32818
+ if (plaintext.length !== WRAPPED_KEY_PLAINTEXT_PREFIX_BYTES + metadataLength) {
32819
+ throw new JobEnvelopeError(
32820
+ "Invalid job result: header length exceeds payload"
32821
+ );
32822
+ }
32823
+ const metadataBytes = plaintext.slice(WRAPPED_KEY_PLAINTEXT_PREFIX_BYTES);
32824
+ const metadata = validateResultMetadata(
32825
+ parseObject(metadataBytes, "job result header")
32826
+ );
32827
+ return {
32828
+ contentKey: plaintext.slice(0, AES_KEY_BYTES),
32829
+ noncePrefix: plaintext.slice(
32830
+ AES_KEY_BYTES,
32831
+ AES_KEY_BYTES + AES_GCM_NONCE_BYTES
32832
+ ),
32833
+ metadataBytes,
32834
+ metadata
32835
+ };
32836
+ }
32837
+ async function importAesKey(contentKey, usage) {
32838
+ return webCrypto().subtle.importKey(
32839
+ "raw",
32840
+ contentKey,
32841
+ { name: "AES-GCM" },
32842
+ false,
32843
+ [usage]
32844
+ );
32845
+ }
32846
+ function chunkNonce(noncePrefix, chunkIndex) {
32847
+ if (chunkIndex > MAX_CHUNK_INDEX) {
32848
+ throw new JobEnvelopeError("Invalid job result: too many chunks");
32849
+ }
32850
+ const nonce = noncePrefix.slice();
32851
+ const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength);
32852
+ view.setUint32(8, view.getUint32(8) ^ chunkIndex);
32853
+ return nonce;
32854
+ }
32855
+ function chunkAad(metadataBytes, chunkIndex, final, plaintextLength) {
32856
+ const aad = new Uint8Array(14 + metadataBytes.length);
32857
+ aad[0] = JOB_RESULT_FORMAT_VERSION;
32858
+ aad.set(uint32(metadataBytes.length), 1);
32859
+ aad.set(metadataBytes, 5);
32860
+ aad.set(uint32(chunkIndex), 5 + metadataBytes.length);
32861
+ aad[9 + metadataBytes.length] = final ? FINAL_FRAME_FLAG : 0;
32862
+ aad.set(uint32(plaintextLength), 10 + metadataBytes.length);
32863
+ return aad;
32864
+ }
32865
+ async function encryptResultChunk(key, noncePrefix, metadataBytes, plaintext, chunkIndex, final) {
32866
+ const encrypted = new Uint8Array(
32867
+ await webCrypto().subtle.encrypt(
32868
+ {
32869
+ name: "AES-GCM",
32870
+ iv: chunkNonce(noncePrefix, chunkIndex),
32871
+ additionalData: chunkAad(
32872
+ metadataBytes,
32873
+ chunkIndex,
32874
+ final,
32875
+ plaintext.length
32876
+ ),
32877
+ tagLength: AES_GCM_TAG_BYTES * 8
32878
+ },
32879
+ key,
32880
+ plaintext
32881
+ )
32882
+ );
32883
+ const frame = new Uint8Array(
32884
+ FRAME_LENGTH_BYTES + FRAME_FLAGS_BYTES + encrypted.length
32885
+ );
32886
+ new DataView(frame.buffer).setUint32(0, encrypted.length);
32887
+ frame[FRAME_LENGTH_BYTES] = final ? FINAL_FRAME_FLAG : 0;
32888
+ frame.set(encrypted, FRAME_LENGTH_BYTES + FRAME_FLAGS_BYTES);
32889
+ return frame;
32890
+ }
32891
+ function verifyResultBindings(metadata, expect) {
32892
+ if (metadata.jobId !== expect.jobId) {
32893
+ throw new JobEnvelopeError(
32894
+ `Job result ID ${metadata.jobId} does not match expected job ID ${expect.jobId}`
32895
+ );
32896
+ }
32897
+ if (expect.scope !== void 0 && metadata.scope !== expect.scope) {
32898
+ throw new JobEnvelopeError(
32899
+ `Job result scope ${metadata.scope} does not match expected scope ${expect.scope}`
32900
+ );
32901
+ }
32902
+ if (expect.version !== void 0 && metadata.version !== expect.version) {
32903
+ throw new JobEnvelopeError(
32904
+ `Job result version ${String(metadata.version)} does not match expected version ${String(expect.version)}`
32905
+ );
32906
+ }
32907
+ }
32908
+ var ByteStreamReader = class {
32909
+ reader;
32910
+ current;
32911
+ offset = 0;
32912
+ ended = false;
32913
+ constructor(stream) {
32914
+ this.reader = stream.getReader();
32915
+ }
32916
+ async ensureBytes() {
32917
+ while (!this.current || this.offset === this.current.length) {
32918
+ if (this.ended) return false;
32919
+ const next = await this.reader.read();
32920
+ if (next.done) {
32921
+ this.ended = true;
32922
+ this.current = void 0;
32923
+ return false;
32924
+ }
32925
+ if (!(next.value instanceof Uint8Array)) {
32926
+ throw new JobEnvelopeError(
32927
+ "Invalid job result: stream yielded non-byte data"
32928
+ );
32929
+ }
32930
+ this.current = next.value;
32931
+ this.offset = 0;
32932
+ }
32933
+ return true;
32934
+ }
32935
+ async readExactOrNull(length) {
32936
+ if (!await this.ensureBytes()) return null;
32937
+ const bytes = new Uint8Array(length);
32938
+ let written = 0;
32939
+ while (written < length) {
32940
+ if (!await this.ensureBytes()) {
32941
+ throw new JobEnvelopeError("Invalid job result: truncated payload");
32942
+ }
32943
+ const available = this.current.length - this.offset;
32944
+ const count = Math.min(available, length - written);
32945
+ bytes.set(
32946
+ this.current.subarray(this.offset, this.offset + count),
32947
+ written
32948
+ );
32949
+ this.offset += count;
32950
+ written += count;
32951
+ }
32952
+ return bytes;
32953
+ }
32954
+ async readExact(length) {
32955
+ const bytes = await this.readExactOrNull(length);
32956
+ if (!bytes) {
32957
+ throw new JobEnvelopeError("Invalid job result: truncated payload");
32958
+ }
32959
+ return bytes;
32960
+ }
32961
+ async hasRemaining() {
32962
+ return this.ensureBytes();
32963
+ }
32964
+ async cancel(reason) {
32965
+ await this.reader.cancel(reason);
32966
+ }
32967
+ };
32968
+ function normalizeChunkError(error) {
32969
+ if (error instanceof JobEnvelopeError) return error;
32970
+ return new JobEnvelopeError(
32971
+ `Invalid job result: chunk authentication failed${error instanceof Error ? `: ${error.message}` : ""}`
32972
+ );
32973
+ }
32974
+ async function sealJobRequest(envelope, enclavePublicKey, ecies) {
32975
+ const encrypted = await ecies.encrypt(
32976
+ (0, import_viem15.fromHex)(enclavePublicKey, "bytes"),
32977
+ requestPlaintext(envelope)
32978
+ );
32979
+ return encryptedBytesToBase64(encrypted);
32980
+ }
32981
+ async function openJobRequest(ciphertext, privateKey, ecies) {
32982
+ const plaintext = await ecies.decrypt(
32983
+ privateKey,
32984
+ base64ToEncrypted(ciphertext)
32985
+ );
32986
+ return validateRequestEnvelope(
32987
+ parseObject(plaintext, "job request envelope")
32988
+ );
32989
+ }
32990
+ async function sealJobResultStream(metadataValue, builderPublicKey, ecies) {
32991
+ const metadata = validateResultMetadata(metadataValue);
32992
+ const metadataBytes = canonicalJsonBytes(metadata);
32993
+ if (metadataBytes.length > MAX_JOB_RESULT_HEADER_BYTES) {
32994
+ throw new JobEnvelopeError(
32995
+ `Invalid job result: header exceeds ${MAX_JOB_RESULT_HEADER_BYTES} bytes`
32996
+ );
32997
+ }
32998
+ const crypto2 = webCrypto();
32999
+ const contentKey = crypto2.getRandomValues(new Uint8Array(AES_KEY_BYTES));
33000
+ const noncePrefix = crypto2.getRandomValues(
33001
+ new Uint8Array(AES_GCM_NONCE_BYTES)
33002
+ );
33003
+ const key = await importAesKey(contentKey, "encrypt");
33004
+ const keyPlaintext = wrappedKeyPlaintext(
33005
+ contentKey,
33006
+ noncePrefix,
33007
+ metadataBytes
33008
+ );
33009
+ const encryptedKey = await ecies.encrypt(
33010
+ (0, import_viem15.fromHex)(builderPublicKey, "bytes"),
33011
+ keyPlaintext
33012
+ );
33013
+ contentKey.fill(0);
33014
+ keyPlaintext.fill(0);
33015
+ const wrappedKey = encryptedToBytes(encryptedKey);
33016
+ if (wrappedKey.length > MAX_WRAPPED_KEY_BYTES) {
33017
+ throw new JobEnvelopeError("Invalid job result: wrapped key is too large");
33018
+ }
33019
+ const header = new Uint8Array(
33020
+ 1 + WRAPPED_KEY_LENGTH_BYTES + wrappedKey.length
33021
+ );
33022
+ header[0] = JOB_RESULT_FORMAT_VERSION;
33023
+ new DataView(header.buffer).setUint32(1, wrappedKey.length);
33024
+ header.set(wrappedKey, 1 + WRAPPED_KEY_LENGTH_BYTES);
33025
+ let pending = new Uint8Array(JOB_RESULT_CHUNK_BYTES);
33026
+ let pendingLength = 0;
33027
+ let chunkIndex = 0;
33028
+ const transform = new TransformStream({
33029
+ async transform(chunk, controller) {
33030
+ if (!(chunk instanceof Uint8Array)) {
33031
+ throw new JobEnvelopeError(
33032
+ "Invalid job result: stream yielded non-byte data"
33033
+ );
33034
+ }
33035
+ let offset = 0;
33036
+ while (offset < chunk.length) {
33037
+ if (pendingLength === JOB_RESULT_CHUNK_BYTES) {
33038
+ controller.enqueue(
33039
+ await encryptResultChunk(
33040
+ key,
33041
+ noncePrefix,
33042
+ metadataBytes,
33043
+ pending,
33044
+ chunkIndex,
33045
+ false
33046
+ )
33047
+ );
33048
+ chunkIndex += 1;
33049
+ pending = new Uint8Array(JOB_RESULT_CHUNK_BYTES);
33050
+ pendingLength = 0;
33051
+ }
33052
+ const count = Math.min(
33053
+ chunk.length - offset,
33054
+ JOB_RESULT_CHUNK_BYTES - pendingLength
33055
+ );
33056
+ pending.set(chunk.subarray(offset, offset + count), pendingLength);
33057
+ pendingLength += count;
33058
+ offset += count;
33059
+ }
33060
+ },
33061
+ async flush(controller) {
33062
+ controller.enqueue(
33063
+ await encryptResultChunk(
33064
+ key,
33065
+ noncePrefix,
33066
+ metadataBytes,
33067
+ pending.subarray(0, pendingLength),
33068
+ chunkIndex,
33069
+ true
33070
+ )
33071
+ );
33072
+ }
33073
+ });
33074
+ return { header, transform };
33075
+ }
33076
+ async function sealJobResult(result, builderPublicKey, ecies) {
33077
+ validateResult(result);
33078
+ const sealed = await sealJobResultStream(
33079
+ resultMetadata(result),
33080
+ builderPublicKey,
33081
+ ecies
33082
+ );
33083
+ const frameCount = Math.max(
33084
+ 1,
33085
+ Math.ceil(result.body.length / JOB_RESULT_CHUNK_BYTES)
33086
+ );
33087
+ const size = sealed.header.length + result.body.length + frameCount * (FRAME_LENGTH_BYTES + FRAME_FLAGS_BYTES + AES_GCM_TAG_BYTES);
33088
+ const bytes = new Uint8Array(size);
33089
+ bytes.set(sealed.header, 0);
33090
+ let outputOffset = sealed.header.length;
33091
+ const reader = sealed.transform.readable.getReader();
33092
+ const drain = (async () => {
33093
+ for (; ; ) {
33094
+ const next = await reader.read();
33095
+ if (next.done) break;
33096
+ bytes.set(next.value, outputOffset);
33097
+ outputOffset += next.value.length;
33098
+ }
33099
+ })();
33100
+ const writer = sealed.transform.writable.getWriter();
33101
+ const fill = (async () => {
33102
+ for (let offset = 0; offset < result.body.length; offset += JOB_RESULT_CHUNK_BYTES) {
33103
+ await writer.write(
33104
+ result.body.subarray(offset, offset + JOB_RESULT_CHUNK_BYTES)
33105
+ );
33106
+ }
33107
+ await writer.close();
33108
+ })();
33109
+ await Promise.all([drain, fill]);
33110
+ if (outputOffset !== bytes.length) {
33111
+ throw new JobEnvelopeError("Invalid job result: sealed size mismatch");
33112
+ }
33113
+ return { bytes, hash: (0, import_viem15.bytesToHex)((0, import_sha25.sha256)(bytes)), size };
33114
+ }
33115
+ async function openJobResultStream(bytesStream, builderPrivateKey, ecies, expect) {
33116
+ const reader = new ByteStreamReader(bytesStream);
33117
+ const headerPrefix = await reader.readExact(1 + WRAPPED_KEY_LENGTH_BYTES);
33118
+ const formatVersion = headerPrefix[0];
33119
+ if (formatVersion !== JOB_RESULT_FORMAT_VERSION) {
33120
+ throw new JobEnvelopeError(
33121
+ `Unsupported job result format: ${String(formatVersion)}`
33122
+ );
33123
+ }
33124
+ const wrappedKeyLength = readUint32(headerPrefix, 1);
33125
+ if (wrappedKeyLength === 0 || wrappedKeyLength > MAX_WRAPPED_KEY_BYTES) {
33126
+ throw new JobEnvelopeError(
33127
+ "Invalid job result: invalid wrapped key length"
33128
+ );
33129
+ }
33130
+ const wrappedKey = await reader.readExact(wrappedKeyLength);
33131
+ const keyPlaintext = await ecies.decrypt(
33132
+ (0, import_viem15.fromHex)(builderPrivateKey, "bytes"),
33133
+ bytesToEncrypted(wrappedKey)
33134
+ );
33135
+ const parsed = parseWrappedKeyPlaintext(keyPlaintext);
33136
+ verifyResultBindings(parsed.metadata, expect);
33137
+ const key = await importAesKey(parsed.contentKey, "decrypt");
33138
+ parsed.contentKey.fill(0);
33139
+ keyPlaintext.fill(0);
33140
+ let chunkIndex = 0;
33141
+ let finished = false;
33142
+ const body = new ReadableStream({
33143
+ async pull(controller) {
33144
+ if (finished) {
33145
+ controller.close();
33146
+ return;
33147
+ }
33148
+ try {
33149
+ const frameHeader = await reader.readExactOrNull(
33150
+ FRAME_LENGTH_BYTES + FRAME_FLAGS_BYTES
33151
+ );
33152
+ if (!frameHeader) {
33153
+ throw new JobEnvelopeError("Invalid job result: missing final chunk");
33154
+ }
33155
+ const encryptedLength = readUint32(frameHeader);
33156
+ if (encryptedLength < AES_GCM_TAG_BYTES || encryptedLength > JOB_RESULT_CHUNK_BYTES + AES_GCM_TAG_BYTES) {
33157
+ throw new JobEnvelopeError(
33158
+ "Invalid job result: invalid chunk length"
33159
+ );
33160
+ }
33161
+ const flags = frameHeader[FRAME_LENGTH_BYTES];
33162
+ if (flags !== 0 && flags !== FINAL_FRAME_FLAG) {
33163
+ throw new JobEnvelopeError("Invalid job result: invalid chunk flags");
33164
+ }
33165
+ const final = flags === FINAL_FRAME_FLAG;
33166
+ const plaintextLength = encryptedLength - AES_GCM_TAG_BYTES;
33167
+ if (!final && plaintextLength !== JOB_RESULT_CHUNK_BYTES) {
33168
+ throw new JobEnvelopeError(
33169
+ "Invalid job result: short non-final chunk"
33170
+ );
33171
+ }
33172
+ const encrypted = await reader.readExact(encryptedLength);
33173
+ const plaintext = new Uint8Array(
33174
+ await webCrypto().subtle.decrypt(
33175
+ {
33176
+ name: "AES-GCM",
33177
+ iv: chunkNonce(parsed.noncePrefix, chunkIndex),
33178
+ additionalData: chunkAad(
33179
+ parsed.metadataBytes,
33180
+ chunkIndex,
33181
+ final,
33182
+ plaintextLength
33183
+ ),
33184
+ tagLength: AES_GCM_TAG_BYTES * 8
33185
+ },
33186
+ key,
33187
+ encrypted
33188
+ )
33189
+ );
33190
+ if (plaintext.length !== plaintextLength) {
33191
+ throw new JobEnvelopeError(
33192
+ "Invalid job result: decrypted chunk length mismatch"
33193
+ );
33194
+ }
33195
+ chunkIndex += 1;
33196
+ if (final) {
33197
+ if (await reader.hasRemaining()) {
33198
+ throw new JobEnvelopeError(
33199
+ "Invalid job result: bytes follow final chunk"
33200
+ );
33201
+ }
33202
+ finished = true;
33203
+ }
33204
+ controller.enqueue(plaintext);
33205
+ if (finished) controller.close();
33206
+ } catch (error) {
33207
+ controller.error(normalizeChunkError(error));
33208
+ void reader.cancel(error).catch(() => void 0);
33209
+ }
33210
+ },
33211
+ cancel(reason) {
33212
+ return reader.cancel(reason);
33213
+ }
33214
+ });
33215
+ return { metadata: parsed.metadata, body };
33216
+ }
33217
+ function bufferedResultBodySize(sealedBytes) {
33218
+ if (sealedBytes.length < 1 + WRAPPED_KEY_LENGTH_BYTES) {
33219
+ throw new JobEnvelopeError("Invalid job result: truncated payload");
33220
+ }
33221
+ if (sealedBytes[0] !== JOB_RESULT_FORMAT_VERSION) {
33222
+ throw new JobEnvelopeError(
33223
+ `Unsupported job result format: ${String(sealedBytes[0])}`
33224
+ );
33225
+ }
33226
+ const wrappedKeyLength = readUint32(sealedBytes, 1);
33227
+ if (wrappedKeyLength === 0 || wrappedKeyLength > MAX_WRAPPED_KEY_BYTES) {
33228
+ throw new JobEnvelopeError(
33229
+ "Invalid job result: invalid wrapped key length"
33230
+ );
33231
+ }
33232
+ let offset = 1 + WRAPPED_KEY_LENGTH_BYTES + wrappedKeyLength;
33233
+ if (offset > sealedBytes.length) {
33234
+ throw new JobEnvelopeError("Invalid job result: truncated payload");
33235
+ }
33236
+ let bodySize = 0;
33237
+ let sawFinal = false;
33238
+ while (offset < sealedBytes.length) {
33239
+ if (sealedBytes.length - offset < FRAME_LENGTH_BYTES + FRAME_FLAGS_BYTES) {
33240
+ throw new JobEnvelopeError("Invalid job result: truncated payload");
33241
+ }
33242
+ const encryptedLength = readUint32(sealedBytes, offset);
33243
+ const flags = sealedBytes[offset + FRAME_LENGTH_BYTES];
33244
+ if (encryptedLength < AES_GCM_TAG_BYTES || encryptedLength > JOB_RESULT_CHUNK_BYTES + AES_GCM_TAG_BYTES || flags !== 0 && flags !== FINAL_FRAME_FLAG) {
33245
+ throw new JobEnvelopeError("Invalid job result: invalid chunk framing");
33246
+ }
33247
+ const plaintextLength = encryptedLength - AES_GCM_TAG_BYTES;
33248
+ if (flags === 0 && plaintextLength !== JOB_RESULT_CHUNK_BYTES) {
33249
+ throw new JobEnvelopeError("Invalid job result: short non-final chunk");
33250
+ }
33251
+ offset += FRAME_LENGTH_BYTES + FRAME_FLAGS_BYTES;
33252
+ if (encryptedLength > sealedBytes.length - offset) {
33253
+ throw new JobEnvelopeError("Invalid job result: truncated payload");
33254
+ }
33255
+ offset += encryptedLength;
33256
+ bodySize += plaintextLength;
33257
+ if (flags === FINAL_FRAME_FLAG) {
33258
+ sawFinal = true;
33259
+ if (offset !== sealedBytes.length) {
33260
+ throw new JobEnvelopeError(
33261
+ "Invalid job result: bytes follow final chunk"
33262
+ );
33263
+ }
33264
+ }
33265
+ }
33266
+ if (!sawFinal) {
33267
+ throw new JobEnvelopeError("Invalid job result: missing final chunk");
33268
+ }
33269
+ return bodySize;
33270
+ }
33271
+ async function openJobResult(sealedBytes, builderPrivateKey, ecies, expect) {
33272
+ const bodySize = bufferedResultBodySize(sealedBytes);
33273
+ const stream = new ReadableStream({
33274
+ start(controller) {
33275
+ controller.enqueue(sealedBytes);
33276
+ controller.close();
33277
+ }
33278
+ });
33279
+ const opened = await openJobResultStream(
33280
+ stream,
33281
+ builderPrivateKey,
33282
+ ecies,
33283
+ expect
33284
+ );
33285
+ const body = new Uint8Array(bodySize);
33286
+ let offset = 0;
33287
+ await opened.body.pipeTo(
33288
+ new WritableStream({
33289
+ write(chunk) {
33290
+ body.set(chunk, offset);
33291
+ offset += chunk.length;
33292
+ }
33293
+ })
33294
+ );
33295
+ if (offset !== body.length) {
33296
+ throw new JobEnvelopeError("Invalid job result: opened size mismatch");
33297
+ }
33298
+ return { ...opened.metadata, body };
33299
+ }
33300
+
33301
+ // src/protocol/jobs-client.ts
33302
+ var import_errors3 = require("./errors.cjs");
33303
+
33304
+ // src/protocol/write-signer.ts
33305
+ var import_errors2 = require("./errors.cjs");
33306
+ function isRecord(value) {
33307
+ return value !== null && typeof value === "object";
33308
+ }
33309
+ function isViemWriteAccount(source) {
33310
+ return isRecord(source) && source.type === "local" && typeof source.address === "string" && typeof source.signMessage === "function";
33311
+ }
33312
+ function isViemWriteWalletClient(source) {
33313
+ return isRecord(source) && typeof source.signMessage === "function" && source.type !== "local" && (source.type === "walletClient" || "transport" in source);
33314
+ }
33315
+ function accountAddress(account) {
33316
+ return typeof account === "string" ? account : account.address;
33317
+ }
33318
+ function resolveWriteSigner(source, options = {}) {
33319
+ if (isViemWriteWalletClient(source)) {
33320
+ const account = options.account ?? source.account;
33321
+ if (account === void 0) {
33322
+ throw new import_errors2.WriteRequestError(
33323
+ "Viem wallet client requires an account option or account property"
33324
+ );
33325
+ }
33326
+ return {
33327
+ address: accountAddress(account),
33328
+ signMessage: (message) => source.signMessage({ account, message })
33329
+ };
33330
+ }
33331
+ if (isViemWriteAccount(source)) {
33332
+ return {
33333
+ address: source.address,
33334
+ signMessage: (message) => source.signMessage({ message })
33335
+ };
33336
+ }
33337
+ if (!isRecord(source) || typeof source.signMessage !== "function") {
33338
+ throw new import_errors2.WriteRequestError(
33339
+ "signer must be a viem LocalAccount, a viem WalletClient, or a { signMessage } object"
33340
+ );
33341
+ }
33342
+ return source;
33343
+ }
33344
+
33345
+ // src/protocol/jobs-client.ts
33346
+ var IDENTITY_PATH = "/v1/identity";
33347
+ var JOBS_PATH = "/v1/jobs";
33348
+ var JOB_EXECUTE_PATH = "/v1/jobs/execute";
33349
+ var AUTHORIZATION_HEADER = "Authorization";
33350
+ var CONTENT_TYPE_HEADER = "Content-Type";
33351
+ var JSON_CONTENT_TYPE = "application/json";
33352
+ var GET_METHOD = "GET";
33353
+ var POST_METHOD = "POST";
33354
+ var RAW_READ_OPERATION = "raw_read";
33355
+ var SEALED_IDENTITY_STATE = "sealed";
33356
+ var HTTP_OK = 200;
33357
+ var HTTP_ACCEPTED = 202;
33358
+ var HTTP_UNAUTHORIZED = 401;
33359
+ var HTTP_FORBIDDEN = 403;
33360
+ var HTTP_NOT_FOUND = 404;
33361
+ var HTTP_CONFLICT = 409;
33362
+ var HTTP_PAYLOAD_TOO_LARGE = 413;
33363
+ var MILLISECONDS_PER_SECOND = 1e3;
33364
+ var DEFAULT_JOB_TIMEOUT_MS = 12e4;
33365
+ var DEFAULT_JOB_POLL_MS = CLAIM_POLL_FLOOR_MS;
33366
+ var TERMINAL_JOB_STATES = /* @__PURE__ */ new Set([
33367
+ "completed",
33368
+ "failed",
33369
+ "expired",
33370
+ "cancelled"
33371
+ ]);
33372
+ function isRecord2(value) {
33373
+ return value !== null && typeof value === "object" && !Array.isArray(value);
33374
+ }
33375
+ function normalizeGateway(gatewayUrl) {
33376
+ try {
33377
+ const url = new URL(gatewayUrl);
33378
+ if (url.pathname !== "/" || url.search !== "" || url.hash !== "") {
33379
+ throw new import_errors3.JobRejectedError(
33380
+ "gatewayUrl must be an origin without a path, query, or fragment"
33381
+ );
33382
+ }
33383
+ return {
33384
+ baseUrl: url.origin,
33385
+ audience: url.origin
33386
+ };
33387
+ } catch (error) {
33388
+ if (error instanceof import_errors3.JobRejectedError) throw error;
33389
+ throw new import_errors3.JobRejectedError(
33390
+ "gatewayUrl must be an absolute URL",
33391
+ void 0,
33392
+ null,
33393
+ {
33394
+ cause: error instanceof Error ? error.message : String(error)
33395
+ }
33396
+ );
33397
+ }
33398
+ }
33399
+ function resolveFetch(fetchFn) {
33400
+ const resolved = fetchFn ?? globalThis.fetch;
33401
+ if (resolved === void 0) {
33402
+ throw new import_errors3.JobRejectedError("No fetch implementation available");
33403
+ }
33404
+ return resolved;
33405
+ }
33406
+ function sourcePublicKey(source) {
33407
+ if (isRecord2(source) && typeof source["publicKey"] === "string") {
33408
+ return source["publicKey"];
33409
+ }
33410
+ return void 0;
33411
+ }
33412
+ function resolveBuilder(options) {
33413
+ if (options.builderPrivateKey && options.builderAccount) {
33414
+ throw new import_errors3.JobRejectedError(
33415
+ "Provide builderPrivateKey or builderAccount, not both"
33416
+ );
33417
+ }
33418
+ let source;
33419
+ try {
33420
+ source = options.builderPrivateKey ? (0, import_accounts2.privateKeyToAccount)(options.builderPrivateKey) : options.builderAccount;
33421
+ } catch (error) {
33422
+ throw new import_errors3.JobRejectedError("Invalid builder private key", void 0, null, {
33423
+ cause: error instanceof Error ? error.message : String(error)
33424
+ });
33425
+ }
33426
+ if (!source) {
33427
+ throw new import_errors3.JobRejectedError(
33428
+ "builderPrivateKey or builderAccount is required"
33429
+ );
33430
+ }
33431
+ let signer;
33432
+ try {
33433
+ signer = resolveWriteSigner(source);
33434
+ } catch (error) {
33435
+ throw new import_errors3.JobRejectedError("Invalid builder signer", void 0, null, {
33436
+ cause: error instanceof Error ? error.message : String(error)
33437
+ });
33438
+ }
33439
+ const publicKey = sourcePublicKey(source);
33440
+ if (!signer.address || !publicKey) {
33441
+ throw new import_errors3.JobRejectedError(
33442
+ "Builder signer must expose both address and publicKey"
33443
+ );
33444
+ }
33445
+ return {
33446
+ builder: {
33447
+ address: signer.address,
33448
+ publicKey,
33449
+ signMessage: signer.signMessage
33450
+ },
33451
+ ...options.builderPrivateKey ? { privateKey: options.builderPrivateKey } : {}
33452
+ };
33453
+ }
33454
+ function clampInteger(value, fallback, minimum, maximum, field) {
33455
+ const resolved = value ?? fallback;
33456
+ if (!Number.isFinite(resolved)) {
33457
+ throw new import_errors3.JobRejectedError(`${field} must be a finite number`);
33458
+ }
33459
+ return Math.min(maximum, Math.max(minimum, Math.trunc(resolved)));
33460
+ }
33461
+ async function responseBody(response) {
33462
+ try {
33463
+ return await response.json();
33464
+ } catch {
33465
+ return null;
33466
+ }
33467
+ }
33468
+ function gatewayErrorBody(body, fallback) {
33469
+ if (!isRecord2(body)) return { code: null, message: fallback };
33470
+ const code = typeof body["code"] === "string" ? body["code"] : null;
33471
+ const message = typeof body["error"] === "string" ? body["error"] : typeof body["message"] === "string" ? body["message"] : fallback;
33472
+ const reason = typeof body["reason"] === "string" ? body["reason"] : void 0;
33473
+ const details = isRecord2(body["details"]) ? body["details"] : void 0;
33474
+ return {
33475
+ code,
33476
+ message,
33477
+ ...reason ? { reason } : {},
33478
+ ...details ? { details } : {}
33479
+ };
33480
+ }
33481
+ async function rejectedResponse(response, fallback) {
33482
+ const parsed = gatewayErrorBody(await responseBody(response), fallback);
33483
+ const details = response.status === HTTP_UNAUTHORIZED && parsed.reason ? { ...parsed.details, reason: parsed.reason } : parsed.details;
33484
+ const message = response.status === HTTP_UNAUTHORIZED && parsed.reason ? `${parsed.message}: ${parsed.reason}` : parsed.message;
33485
+ if (response.status === HTTP_FORBIDDEN) {
33486
+ if (parsed.code === "BUILDER_UNKNOWN") {
33487
+ return new import_errors3.BuilderUnknownError(parsed.message, details);
33488
+ }
33489
+ if (parsed.code === "GRANT_INVALID") {
33490
+ return new import_errors3.GrantInvalidError(parsed.message, details);
33491
+ }
33492
+ if (parsed.code === "OWNER_NOT_READY") {
33493
+ return new import_errors3.OwnerNotReadyError(parsed.message, details);
33494
+ }
33495
+ }
33496
+ if (response.status === HTTP_NOT_FOUND) {
33497
+ return new import_errors3.JobNotFoundError(parsed.message, details);
33498
+ }
33499
+ if (response.status === HTTP_CONFLICT && parsed.code === "JOB_ID_TAKEN") {
33500
+ return new import_errors3.JobIdTakenError(parsed.message, details);
33501
+ }
33502
+ if (response.status === HTTP_PAYLOAD_TOO_LARGE) {
33503
+ return new import_errors3.JobRequestTooLargeError(parsed.message, parsed.code, details);
33504
+ }
33505
+ return new import_errors3.JobRejectedError(message, response.status, parsed.code, details);
33506
+ }
33507
+ function requireStatus(value, status) {
33508
+ if (!isRecord2(value) || !isNonEmptyString(value["jobId"]) || typeof value["state"] !== "string" || !JOB_STATES.includes(value["state"]) || !isNonEmptyString(value["owner"]) || !isNonEmptyString(value["grantId"]) || !isNonEmptyString(value["scope"]) || !isNonEmptyString(value["operation"]) || !JOB_OPERATIONS.includes(value["operation"]) || value["state"] === "completed" && !isResultHandle(value["result"])) {
33509
+ throw new import_errors3.JobRejectedError(
33510
+ "Gateway response did not contain a job status",
33511
+ status
33512
+ );
33513
+ }
33514
+ return value;
33515
+ }
33516
+ function isNonEmptyString(value) {
33517
+ return typeof value === "string" && value.length > 0;
33518
+ }
33519
+ function isResultHandle(value) {
33520
+ if (!isRecord2(value) || !isNonEmptyString(value["objectKey"]) || !isNonEmptyString(value["url"]) || typeof value["size"] !== "number" || !Number.isInteger(value["size"]) || value["size"] < 0 || typeof value["hash"] !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(value["hash"]) || typeof value["expiresAt"] !== "string" || Number.isNaN(Date.parse(value["expiresAt"]))) {
33521
+ return false;
33522
+ }
33523
+ try {
33524
+ const url = new URL(value["url"]);
33525
+ return url.protocol === "https:" || url.protocol === "http:";
33526
+ } catch {
33527
+ return false;
33528
+ }
33529
+ }
33530
+ function hasMatchingIdentityKey(value) {
33531
+ const address = value["address"];
33532
+ const publicKey = value["publicKey"];
33533
+ if (typeof address !== "string" || !(0, import_viem16.isAddress)(address) || typeof publicKey !== "string" || !(0, import_viem16.isHex)(publicKey)) {
33534
+ return false;
33535
+ }
33536
+ try {
33537
+ return (0, import_accounts2.publicKeyToAddress)(publicKey).toLowerCase() === address.toLowerCase();
33538
+ } catch {
33539
+ return false;
33540
+ }
33541
+ }
33542
+ function hasExpectedIdentity(value, owner, chainId) {
33543
+ const identityOwner = value["ownerAddress"];
33544
+ const identityChainId = value["chainId"];
33545
+ const identityUserPsId = value["userPsId"];
33546
+ if (!hasMatchingIdentityKey(value) || typeof identityOwner !== "string" || !(0, import_viem16.isAddress)(identityOwner) || typeof identityChainId !== "number" || typeof identityUserPsId !== "string" || !(0, import_viem16.isHex)(identityUserPsId)) {
33547
+ return false;
33548
+ }
33549
+ return (0, import_viem16.isAddressEqual)(identityOwner, owner) && identityChainId === chainId && identityUserPsId.toLowerCase() === userPsId(chainId, owner).toLowerCase();
33550
+ }
33551
+ function sleep2(ms) {
33552
+ return new Promise((resolve) => setTimeout(resolve, ms));
33553
+ }
33554
+ function requireFiniteDuration(value, field) {
33555
+ if (!Number.isFinite(value)) {
33556
+ throw new import_errors3.JobRejectedError(`${field} must be a finite number`);
33557
+ }
33558
+ return Math.max(0, value);
33559
+ }
33560
+ function createJobsClient(options) {
33561
+ const { baseUrl, audience } = normalizeGateway(options.gatewayUrl);
33562
+ const fetchFn = resolveFetch(options.fetch);
33563
+ const { builder, privateKey } = resolveBuilder(options);
33564
+ const ecies = options.ecies ?? new NodeECIESUint8Provider();
33565
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
33566
+ async function request(url, init, description) {
33567
+ try {
33568
+ return await fetchFn(url, init);
33569
+ } catch (error) {
33570
+ throw new import_errors3.JobTransportError(
33571
+ `${description} failed: ${error instanceof Error ? error.message : String(error)}`,
33572
+ error
33573
+ );
33574
+ }
33575
+ }
33576
+ async function getIdentity(owner) {
33577
+ const query = new URLSearchParams({
33578
+ owner,
33579
+ chainId: String(options.chainId)
33580
+ });
33581
+ const response = await request(
33582
+ `${baseUrl}${IDENTITY_PATH}?${query.toString()}`,
33583
+ { method: GET_METHOD },
33584
+ "Owner identity lookup"
33585
+ );
33586
+ if (response.status === HTTP_NOT_FOUND) {
33587
+ const parsed = gatewayErrorBody(
33588
+ await responseBody(response),
33589
+ "Owner identity not found"
33590
+ );
33591
+ throw new import_errors3.OwnerNotReadyError(parsed.message, parsed.details);
33592
+ }
33593
+ if (!response.ok) {
33594
+ throw await rejectedResponse(response, "Owner identity lookup rejected");
33595
+ }
33596
+ const body = await responseBody(response);
33597
+ if (!isRecord2(body) || body["state"] !== SEALED_IDENTITY_STATE || !isRecord2(body["identity"])) {
33598
+ throw new import_errors3.OwnerNotReadyError("Owner identity is not sealed", {
33599
+ state: isRecord2(body) ? body["state"] : void 0
33600
+ });
33601
+ }
33602
+ if (!hasExpectedIdentity(body["identity"], owner, options.chainId)) {
33603
+ throw new import_errors3.JobRejectedError(
33604
+ "Gateway returned a malformed or mismatched owner identity",
33605
+ response.status
33606
+ );
33607
+ }
33608
+ return body["identity"];
33609
+ }
33610
+ const client = {
33611
+ async submitRawRead(params) {
33612
+ const identity = await getIdentity(params.owner);
33613
+ const deadlineSeconds = clampInteger(
33614
+ params.deadlineSeconds,
33615
+ DEFAULT_JOB_DEADLINE_SECONDS,
33616
+ 1,
33617
+ MAX_JOB_DEADLINE_SECONDS,
33618
+ "deadlineSeconds"
33619
+ );
33620
+ const wait = clampInteger(params.wait, 0, 0, MAX_WAIT_SECONDS, "wait");
33621
+ const jobId = (0, import_node_crypto.randomUUID)();
33622
+ const nowMs = now().getTime();
33623
+ if (!Number.isFinite(nowMs)) {
33624
+ throw new import_errors3.JobRejectedError("now must return a valid Date");
33625
+ }
33626
+ const deadline = new Date(
33627
+ nowMs + deadlineSeconds * MILLISECONDS_PER_SECOND
33628
+ ).toISOString();
33629
+ const requestBody = {
33630
+ v: JOB_PROTOCOL_VERSION,
33631
+ jobId,
33632
+ owner: params.owner,
33633
+ builder: builder.address,
33634
+ builderPublicKey: builder.publicKey,
33635
+ grantId: params.grantId,
33636
+ scope: params.scope,
33637
+ operation: RAW_READ_OPERATION,
33638
+ pinnedVersion: params.pinnedVersion ?? null,
33639
+ deadline
33640
+ };
33641
+ const auth = await buildWeb3SignedHeader({
33642
+ signMessage: builder.signMessage,
33643
+ aud: audience,
33644
+ method: POST_METHOD,
33645
+ uri: JOB_EXECUTE_PATH,
33646
+ bodyHash: computeBodyHash(canonicalJobRequestBytes(requestBody)),
33647
+ nonce: (0, import_node_crypto.randomUUID)()
33648
+ });
33649
+ const requestCiphertext = await sealJobRequest(
33650
+ { request: requestBody, auth },
33651
+ identity.publicKey,
33652
+ ecies
33653
+ );
33654
+ const submission = {
33655
+ owner: requestBody.owner,
33656
+ grantId: requestBody.grantId,
33657
+ scope: requestBody.scope,
33658
+ operation: requestBody.operation,
33659
+ idempotencyKey: (0, import_node_crypto.randomUUID)(),
33660
+ jobId,
33661
+ deadline,
33662
+ requestCiphertext
33663
+ };
33664
+ const bodyBytes = new TextEncoder().encode(JSON.stringify(submission));
33665
+ const authorization = await buildWeb3SignedHeader({
33666
+ signMessage: builder.signMessage,
33667
+ aud: audience,
33668
+ method: POST_METHOD,
33669
+ uri: JOBS_PATH,
33670
+ body: bodyBytes,
33671
+ nonce: (0, import_node_crypto.randomUUID)()
33672
+ });
33673
+ const response = await request(
33674
+ `${baseUrl}${JOBS_PATH}?wait=${wait}`,
33675
+ {
33676
+ method: POST_METHOD,
33677
+ headers: {
33678
+ [AUTHORIZATION_HEADER]: authorization,
33679
+ [CONTENT_TYPE_HEADER]: JSON_CONTENT_TYPE
33680
+ },
33681
+ body: bodyBytes
33682
+ },
33683
+ "Job submission"
33684
+ );
33685
+ if (!response.ok) {
33686
+ throw await rejectedResponse(response, "Job submission rejected");
33687
+ }
33688
+ const body = await responseBody(response);
33689
+ if (response.status === HTTP_OK && isRecord2(body)) {
33690
+ const job = requireStatus(body["job"], response.status);
33691
+ if (job.jobId !== jobId) {
33692
+ throw new import_errors3.JobRejectedError(
33693
+ "Gateway returned a job id that does not match the submission",
33694
+ response.status
33695
+ );
33696
+ }
33697
+ return { jobId, state: job.state, job };
33698
+ }
33699
+ if (response.status === HTTP_ACCEPTED && isRecord2(body) && body["jobId"] === jobId && typeof body["state"] === "string" && JOB_STATES.includes(body["state"])) {
33700
+ return { jobId, state: body["state"] };
33701
+ }
33702
+ throw new import_errors3.JobRejectedError(
33703
+ "Gateway returned an undocumented job submission response",
33704
+ response.status
33705
+ );
33706
+ },
33707
+ async getJob(jobId) {
33708
+ const path = `${JOBS_PATH}/${encodeURIComponent(jobId)}`;
33709
+ const authorization = await buildWeb3SignedHeader({
33710
+ signMessage: builder.signMessage,
33711
+ aud: audience,
33712
+ method: GET_METHOD,
33713
+ uri: path,
33714
+ nonce: (0, import_node_crypto.randomUUID)()
33715
+ });
33716
+ const response = await request(
33717
+ `${baseUrl}${path}`,
33718
+ {
33719
+ method: GET_METHOD,
33720
+ headers: { [AUTHORIZATION_HEADER]: authorization }
33721
+ },
33722
+ "Job status read"
33723
+ );
33724
+ if (!response.ok) {
33725
+ throw await rejectedResponse(response, "Job status read rejected");
33726
+ }
33727
+ const body = await responseBody(response);
33728
+ return requireStatus(
33729
+ isRecord2(body) ? body["job"] : void 0,
33730
+ response.status
33731
+ );
33732
+ },
33733
+ async waitForJob(jobId, waitOptions = {}) {
33734
+ const timeoutMs = requireFiniteDuration(
33735
+ waitOptions.timeoutMs ?? DEFAULT_JOB_TIMEOUT_MS,
33736
+ "timeoutMs"
33737
+ );
33738
+ const pollMs = Math.max(
33739
+ CLAIM_POLL_FLOOR_MS,
33740
+ requireFiniteDuration(
33741
+ waitOptions.pollMs ?? DEFAULT_JOB_POLL_MS,
33742
+ "pollMs"
33743
+ )
33744
+ );
33745
+ const startedAt = Date.now();
33746
+ const callerDeadline = startedAt + timeoutMs;
33747
+ let latest;
33748
+ for (; ; ) {
33749
+ if (Date.now() >= callerDeadline) {
33750
+ throw new import_errors3.JobTimeoutError(
33751
+ `Timed out waiting for terminal job ${jobId}`,
33752
+ {
33753
+ jobId,
33754
+ timeoutMs,
33755
+ state: latest?.state
33756
+ }
33757
+ );
33758
+ }
33759
+ latest = await client.getJob(jobId);
33760
+ if (TERMINAL_JOB_STATES.has(latest.state)) return latest;
33761
+ const remaining = callerDeadline - Date.now();
33762
+ if (remaining <= 0) {
33763
+ throw new import_errors3.JobTimeoutError(
33764
+ `Timed out waiting for terminal job ${jobId}`,
33765
+ {
33766
+ jobId,
33767
+ timeoutMs,
33768
+ state: latest.state
33769
+ }
33770
+ );
33771
+ }
33772
+ await sleep2(Math.min(pollMs, remaining));
33773
+ }
33774
+ },
33775
+ async openResult(handle, openOptions) {
33776
+ if (!privateKey) {
33777
+ throw new import_errors3.JobRejectedError(
33778
+ "openResult requires createJobsClient({ builderPrivateKey })"
33779
+ );
33780
+ }
33781
+ const response = await request(
33782
+ handle.url,
33783
+ { method: GET_METHOD },
33784
+ "Job result fetch"
33785
+ );
33786
+ if (!response.ok) {
33787
+ throw await rejectedResponse(response, "Job result fetch rejected");
33788
+ }
33789
+ let bytes;
33790
+ try {
33791
+ bytes = new Uint8Array(await response.arrayBuffer());
33792
+ } catch (error) {
33793
+ throw new import_errors3.JobTransportError(
33794
+ `Job result fetch failed: ${error instanceof Error ? error.message : String(error)}`,
33795
+ error
33796
+ );
33797
+ }
33798
+ const actualHash = (0, import_viem16.bytesToHex)((0, import_sha26.sha256)(bytes));
33799
+ if (actualHash.toLowerCase() !== handle.hash.toLowerCase()) {
33800
+ throw new import_errors3.JobResultIntegrityError(
33801
+ "Fetched job result hash does not match its handle",
33802
+ {
33803
+ objectKey: handle.objectKey,
33804
+ expectedHash: handle.hash,
33805
+ actualHash
33806
+ }
33807
+ );
33808
+ }
33809
+ if (bytes.length !== handle.size) {
33810
+ throw new import_errors3.JobResultIntegrityError(
33811
+ "Fetched job result size does not match its handle",
33812
+ {
33813
+ objectKey: handle.objectKey,
33814
+ expectedSize: handle.size,
33815
+ actualSize: bytes.length
33816
+ }
33817
+ );
33818
+ }
33819
+ return openJobResult(bytes, privateKey, ecies, openOptions.expect);
33820
+ },
33821
+ async readRaw(params) {
33822
+ const submitted = await client.submitRawRead(params);
33823
+ const job = submitted.job && TERMINAL_JOB_STATES.has(submitted.job.state) ? submitted.job : await client.waitForJob(submitted.jobId, {
33824
+ timeoutMs: params.timeoutMs,
33825
+ pollMs: params.pollMs
33826
+ });
33827
+ if (job.state !== "completed") {
33828
+ throw new import_errors3.JobRejectedError(
33829
+ `Job ${job.jobId} ended in state ${job.state}${job.failureReason ? `: ${job.failureReason}` : ""}`,
33830
+ void 0,
33831
+ null,
33832
+ {
33833
+ jobId: job.jobId,
33834
+ state: job.state,
33835
+ ...job.failureReason ? { failureReason: job.failureReason } : {}
33836
+ }
33837
+ );
33838
+ }
33839
+ if (!job.result) {
33840
+ throw new import_errors3.JobRejectedError(
33841
+ "Completed job status does not include a result handle",
33842
+ void 0,
33843
+ null,
33844
+ { jobId: job.jobId, state: job.state }
33845
+ );
33846
+ }
33847
+ return client.openResult(job.result, {
33848
+ expect: {
33849
+ jobId: submitted.jobId,
33850
+ scope: params.scope,
33851
+ ...params.pinnedVersion !== void 0 && params.pinnedVersion !== null ? { version: params.pinnedVersion } : {}
33852
+ }
33853
+ });
33854
+ }
33855
+ };
33856
+ return client;
33857
+ }
33858
+
33859
+ // src/protocol/personal-server-registration.ts
33860
+ var import_viem17 = require("viem");
32649
33861
  var PERSONAL_SERVER_REGISTRATION_DEFAULT_CHAIN_ID = vanaMainnet2.id;
32650
33862
  var PERSONAL_SERVER_REGISTRATION_DEFAULT_VERIFYING_CONTRACT = getContractAddress(
32651
33863
  PERSONAL_SERVER_REGISTRATION_DEFAULT_CHAIN_ID,
32652
33864
  "DataPortabilityServers"
32653
33865
  );
32654
33866
  function assertAddress(value, name) {
32655
- if (!(0, import_viem14.isAddress)(value)) {
33867
+ if (!(0, import_viem17.isAddress)(value)) {
32656
33868
  throw new Error(`${name} must be a valid EVM address`);
32657
33869
  }
32658
33870
  }
@@ -32738,12 +33950,12 @@ async function buildPersonalServerRegistrationSignature(input) {
32738
33950
  var registerPersonalServerSignature = buildPersonalServerRegistrationSignature;
32739
33951
 
32740
33952
  // src/personal-server-lite/owner-binding.ts
32741
- var import_viem15 = require("viem");
33953
+ var import_viem18 = require("viem");
32742
33954
  var PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION = "vana.ps-lite.owner-binding.v1";
32743
33955
  var PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE = "ps-lite-owner";
32744
33956
  var PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX = `${PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION}:${PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE}:`;
32745
33957
  function assertAddress2(value, name) {
32746
- if (!(0, import_viem15.isAddress)(value)) {
33958
+ if (!(0, import_viem18.isAddress)(value)) {
32747
33959
  throw new Error(`${name} must be a valid EVM address`);
32748
33960
  }
32749
33961
  }
@@ -32793,7 +34005,7 @@ async function buildPersonalServerLiteOwnerBindingSignature(input) {
32793
34005
  var signPersonalServerLiteOwnerBinding = buildPersonalServerLiteOwnerBindingSignature;
32794
34006
 
32795
34007
  // src/account/personal-server-registration.ts
32796
- var import_viem16 = require("viem");
34008
+ var import_viem19 = require("viem");
32797
34009
  var ACCOUNT_PERSONAL_SERVER_REGISTRATION_INTENT = "personal_server.server_registration.v1";
32798
34010
  var AccountPersonalServerRegistrationError = class extends Error {
32799
34011
  status;
@@ -32812,7 +34024,7 @@ function trimTrailingSlash(value) {
32812
34024
  return value.replace(/\/+$/, "");
32813
34025
  }
32814
34026
  function assertAddress3(value, name) {
32815
- if (!(0, import_viem16.isAddress)(value)) {
34027
+ if (!(0, import_viem19.isAddress)(value)) {
32816
34028
  throw new Error(`${name} must be a valid EVM address`);
32817
34029
  }
32818
34030
  }
@@ -32833,7 +34045,7 @@ function accountErrorMessage(status, body) {
32833
34045
  if (nestedMessage) {
32834
34046
  return nestedMessage;
32835
34047
  }
32836
- if (isRecord(body) && typeof body.message === "string") {
34048
+ if (isRecord3(body) && typeof body.message === "string") {
32837
34049
  return body.message;
32838
34050
  }
32839
34051
  const code = accountErrorCode(body);
@@ -32847,7 +34059,7 @@ function accountErrorCode(body) {
32847
34059
  if (nestedCode) {
32848
34060
  return nestedCode;
32849
34061
  }
32850
- if (isRecord(body)) {
34062
+ if (isRecord3(body)) {
32851
34063
  if (typeof body.code === "string") {
32852
34064
  return body.code;
32853
34065
  }
@@ -32858,13 +34070,13 @@ function accountErrorCode(body) {
32858
34070
  return void 0;
32859
34071
  }
32860
34072
  function nestedAccountErrorField(body, field) {
32861
- if (!isRecord(body) || !isRecord(body.error)) {
34073
+ if (!isRecord3(body) || !isRecord3(body.error)) {
32862
34074
  return void 0;
32863
34075
  }
32864
34076
  const value = body.error[field];
32865
34077
  return typeof value === "string" ? value : void 0;
32866
34078
  }
32867
- function isRecord(value) {
34079
+ function isRecord3(value) {
32868
34080
  return typeof value === "object" && value !== null;
32869
34081
  }
32870
34082
  function normalizeAccountResponse(response) {
@@ -33076,7 +34288,7 @@ function accountOwnerBindingError(error) {
33076
34288
  }
33077
34289
 
33078
34290
  // src/protocol/grants.ts
33079
- var import_viem17 = require("viem");
34291
+ var import_viem20 = require("viem");
33080
34292
  function isHexString(value) {
33081
34293
  return typeof value === "string" && value.startsWith("0x");
33082
34294
  }
@@ -33121,7 +34333,7 @@ async function verifyGrantRegistration(input) {
33121
34333
  }
33122
34334
  let valid;
33123
34335
  try {
33124
- valid = await (0, import_viem17.verifyTypedData)({
34336
+ valid = await (0, import_viem20.verifyTypedData)({
33125
34337
  address: input.grantorAddress,
33126
34338
  domain: grantRegistrationDomain(input.gatewayConfig),
33127
34339
  types: GRANT_REGISTRATION_TYPES,
@@ -33156,8 +34368,8 @@ async function verifyGrantRegistration(input) {
33156
34368
  }
33157
34369
 
33158
34370
  // src/protocol/fee-registry.ts
33159
- var import_viem18 = require("viem");
33160
- var FEE_REGISTRY_ABI = (0, import_viem18.parseAbi)([
34371
+ var import_viem21 = require("viem");
34372
+ var FEE_REGISTRY_ABI = (0, import_viem21.parseAbi)([
33161
34373
  "struct Fee { uint256 amount; address asset; address payee; bool enabled; }",
33162
34374
  "function fees(bytes32 operation) view returns (Fee)",
33163
34375
  "function operationKey(string name) pure returns (bytes32)"
@@ -33240,7 +34452,7 @@ async function getOpFee(client, config, opType, opts) {
33240
34452
  }
33241
34453
 
33242
34454
  // src/protocol/escrow-deposit.ts
33243
- var import_viem19 = require("viem");
34455
+ var import_viem22 = require("viem");
33244
34456
  var ESCROW_DEPOSIT_ABI = [
33245
34457
  {
33246
34458
  type: "function",
@@ -33265,14 +34477,14 @@ function escrowContractAddress(config) {
33265
34477
  return config.contracts.dataPortabilityEscrow;
33266
34478
  }
33267
34479
  function encodeDepositNativeData(input) {
33268
- return (0, import_viem19.encodeFunctionData)({
34480
+ return (0, import_viem22.encodeFunctionData)({
33269
34481
  abi: ESCROW_DEPOSIT_ABI,
33270
34482
  functionName: "depositNative",
33271
34483
  args: [input.account]
33272
34484
  });
33273
34485
  }
33274
34486
  function encodeDepositTokenData(input) {
33275
- return (0, import_viem19.encodeFunctionData)({
34487
+ return (0, import_viem22.encodeFunctionData)({
33276
34488
  abi: ESCROW_DEPOSIT_ABI,
33277
34489
  functionName: "depositToken",
33278
34490
  args: [input.account, input.token, input.amount]
@@ -33293,7 +34505,7 @@ function buildDepositTokenRequest(config, input) {
33293
34505
  }
33294
34506
 
33295
34507
  // src/protocol/data-point-status.ts
33296
- var import_viem20 = require("viem");
34508
+ var import_viem23 = require("viem");
33297
34509
  var DataPointStatus = /* @__PURE__ */ ((DataPointStatus2) => {
33298
34510
  DataPointStatus2[DataPointStatus2["None"] = 0] = "None";
33299
34511
  DataPointStatus2[DataPointStatus2["Active"] = 1] = "Active";
@@ -33317,7 +34529,7 @@ function dataRegistryContractAddress(config) {
33317
34529
  return config.contracts.dataRegistry;
33318
34530
  }
33319
34531
  function encodeSetDataPointStatusData(input) {
33320
- return (0, import_viem20.encodeFunctionData)({
34532
+ return (0, import_viem23.encodeFunctionData)({
33321
34533
  abi: DATA_REGISTRY_STATUS_ABI,
33322
34534
  functionName: "setStatus",
33323
34535
  args: [input.scope, input.status]
@@ -33337,14 +34549,16 @@ function buildMarkDataPointUnavailableRequest(config, input) {
33337
34549
  }
33338
34550
 
33339
34551
  // src/protocol/data-point-deletion.ts
33340
- var import_viem22 = require("viem");
34552
+ var import_viem25 = require("viem");
34553
+ var import_errors5 = require("./errors.cjs");
33341
34554
 
33342
34555
  // src/protocol/lineage.ts
33343
- var import_viem21 = require("viem");
34556
+ var import_viem24 = require("viem");
33344
34557
  var import_zod = require("zod");
34558
+ var import_errors4 = require("./errors.cjs");
33345
34559
 
33346
34560
  // src/protocol/personal-server-error-body.ts
33347
- function isRecord2(value) {
34561
+ function isRecord4(value) {
33348
34562
  return value !== null && typeof value === "object" && !Array.isArray(value);
33349
34563
  }
33350
34564
  async function readPersonalServerErrorBody(response) {
@@ -33354,8 +34568,8 @@ async function readPersonalServerErrorBody(response) {
33354
34568
  } catch {
33355
34569
  return { errorCode: null, message: null };
33356
34570
  }
33357
- if (!isRecord2(body)) return { errorCode: null, message: null };
33358
- const nested = isRecord2(body.error) ? body.error : null;
34571
+ if (!isRecord4(body)) return { errorCode: null, message: null };
34572
+ const nested = isRecord4(body.error) ? body.error : null;
33359
34573
  const gatewayShape = typeof body.error === "string" && typeof body.code === "string";
33360
34574
  const code = nested?.errorCode ?? nested?.code ?? body.errorCode ?? (gatewayShape ? body.code : void 0) ?? (typeof body.error === "string" ? body.error : void 0) ?? body.code;
33361
34575
  const message = nested?.message ?? body.message ?? (gatewayShape ? body.error : void 0);
@@ -33368,63 +34582,23 @@ async function readPersonalServerErrorBody(response) {
33368
34582
  return {
33369
34583
  errorCode: typeof code === "string" ? code : null,
33370
34584
  message: typeof message === "string" ? message : null,
33371
- ...isRecord2(details) ? { details } : {}
34585
+ ...isRecord4(details) ? { details } : {}
33372
34586
  };
33373
34587
  }
33374
34588
 
33375
- // src/protocol/write-signer.ts
33376
- function isRecord3(value) {
33377
- return value !== null && typeof value === "object";
33378
- }
33379
- function isViemWriteAccount(source) {
33380
- return isRecord3(source) && source.type === "local" && typeof source.address === "string" && typeof source.signMessage === "function";
33381
- }
33382
- function isViemWriteWalletClient(source) {
33383
- return isRecord3(source) && typeof source.signMessage === "function" && source.type !== "local" && (source.type === "walletClient" || "transport" in source);
33384
- }
33385
- function accountAddress(account) {
33386
- return typeof account === "string" ? account : account.address;
33387
- }
33388
- function resolveWriteSigner(source, options = {}) {
33389
- if (isViemWriteWalletClient(source)) {
33390
- const account = options.account ?? source.account;
33391
- if (account === void 0) {
33392
- throw new WriteRequestError(
33393
- "Viem wallet client requires an account option or account property"
33394
- );
33395
- }
33396
- return {
33397
- address: accountAddress(account),
33398
- signMessage: (message) => source.signMessage({ account, message })
33399
- };
33400
- }
33401
- if (isViemWriteAccount(source)) {
33402
- return {
33403
- address: source.address,
33404
- signMessage: (message) => source.signMessage({ message })
33405
- };
33406
- }
33407
- if (!isRecord3(source) || typeof source.signMessage !== "function") {
33408
- throw new WriteRequestError(
33409
- "signer must be a viem LocalAccount, a viem WalletClient, or a { signMessage } object"
33410
- );
33411
- }
33412
- return source;
33413
- }
33414
-
33415
34589
  // src/protocol/lineage.ts
33416
34590
  var DATA_POINT_ID_PATTERN = /^0x[0-9a-fA-F]{64}$/;
33417
34591
  function isDataPointId(value) {
33418
34592
  return typeof value === "string" && DATA_POINT_ID_PATTERN.test(value);
33419
34593
  }
33420
34594
  function deriveDataPointId(ownerAddress, scope) {
33421
- if (!(0, import_viem21.isAddress)(ownerAddress, { strict: false })) {
34595
+ if (!(0, import_viem24.isAddress)(ownerAddress, { strict: false })) {
33422
34596
  throw new Error(
33423
34597
  `ownerAddress is not an EVM address: ${String(ownerAddress)}`
33424
34598
  );
33425
34599
  }
33426
- return (0, import_viem21.keccak256)(
33427
- (0, import_viem21.encodeAbiParameters)(
34600
+ return (0, import_viem24.keccak256)(
34601
+ (0, import_viem24.encodeAbiParameters)(
33428
34602
  [
33429
34603
  { name: "ownerAddress", type: "address" },
33430
34604
  { name: "scope", type: "string" }
@@ -33453,7 +34627,7 @@ function derivedScopeViolatesNaming(derivedScope, sourceScope) {
33453
34627
  function assertDerivedScopeNaming(derivedScope, sourceScopes) {
33454
34628
  for (const sourceScope of sourceScopes) {
33455
34629
  if (derivedScopeViolatesNaming(derivedScope, sourceScope)) {
33456
- throw new WriteRequestError(
34630
+ throw new import_errors4.WriteRequestError(
33457
34631
  `Derived scope ${derivedScope} must not share its first segment with source scope ${sourceScope}; put derivatives in the app's own namespace`,
33458
34632
  { scope: derivedScope, sourceScope }
33459
34633
  );
@@ -33513,10 +34687,10 @@ function gatewayLineagePath(dataPointId, version) {
33513
34687
  function normalizeBaseUrl(url) {
33514
34688
  return url.replace(/\/+$/, "");
33515
34689
  }
33516
- function resolveFetch(fetchFn) {
34690
+ function resolveFetch2(fetchFn) {
33517
34691
  const resolved = fetchFn ?? globalThis.fetch;
33518
34692
  if (resolved === void 0) {
33519
- throw new LineageReadError("No fetch implementation available");
34693
+ throw new import_errors4.LineageReadError("No fetch implementation available");
33520
34694
  }
33521
34695
  return resolved;
33522
34696
  }
@@ -33524,7 +34698,7 @@ function normalizeVersion(version) {
33524
34698
  if (version === void 0) return void 0;
33525
34699
  const text = String(version);
33526
34700
  if (!VERSION_PATTERN.test(text)) {
33527
- throw new LineageReadError(
34701
+ throw new import_errors4.LineageReadError(
33528
34702
  "version must be a positive decimal integer",
33529
34703
  void 0,
33530
34704
  "INVALID_VERSION",
@@ -33535,7 +34709,7 @@ function normalizeVersion(version) {
33535
34709
  }
33536
34710
  async function lineageReadFailure(source, response) {
33537
34711
  const { errorCode, message, details } = await readPersonalServerErrorBody(response);
33538
- return new LineageReadError(
34712
+ return new import_errors4.LineageReadError(
33539
34713
  message ?? `${source} lineage read failed: ${response.status} ${response.statusText}`,
33540
34714
  response.status,
33541
34715
  errorCode,
@@ -33547,24 +34721,24 @@ async function parseLineageGraph(source, response) {
33547
34721
  try {
33548
34722
  body = await response.json();
33549
34723
  } catch (err) {
33550
- throw new LineageReadError(
34724
+ throw new import_errors4.LineageReadError(
33551
34725
  `${source} lineage response is not JSON`,
33552
34726
  response.status,
33553
34727
  null,
33554
34728
  { cause: err instanceof Error ? err.message : String(err) }
33555
34729
  );
33556
34730
  }
33557
- const envelope = isRecord2(body) && isRecord2(body.data) ? body : void 0;
34731
+ const envelope = isRecord4(body) && isRecord4(body.data) ? body : void 0;
33558
34732
  const parsed = LineageGraphSchema.safeParse(envelope?.data ?? body);
33559
34733
  if (!parsed.success) {
33560
- throw new LineageReadError(
34734
+ throw new import_errors4.LineageReadError(
33561
34735
  `${source} lineage response is not a lineage view`,
33562
34736
  response.status,
33563
34737
  null,
33564
34738
  { issues: parsed.error.issues }
33565
34739
  );
33566
34740
  }
33567
- const proof = isRecord2(envelope?.proof) ? envelope.proof : void 0;
34741
+ const proof = isRecord4(envelope?.proof) ? envelope.proof : void 0;
33568
34742
  return proof === void 0 ? parsed.data : { ...parsed.data, proof };
33569
34743
  }
33570
34744
  async function sendLineageRead(source, fetchFn, url, headers) {
@@ -33572,7 +34746,7 @@ async function sendLineageRead(source, fetchFn, url, headers) {
33572
34746
  try {
33573
34747
  response = await fetchFn(url, { method: "GET", headers });
33574
34748
  } catch (err) {
33575
- throw new LineageReadError(
34749
+ throw new import_errors4.LineageReadError(
33576
34750
  `${source} lineage read failed: ${err instanceof Error ? err.message : String(err)}`,
33577
34751
  void 0,
33578
34752
  null,
@@ -33585,7 +34759,7 @@ async function sendLineageRead(source, fetchFn, url, headers) {
33585
34759
  return parseLineageGraph(source, response);
33586
34760
  }
33587
34761
  async function getPersonalServerLineage(params) {
33588
- const fetchFn = resolveFetch(params.fetch);
34762
+ const fetchFn = resolveFetch2(params.fetch);
33589
34763
  const baseUrl = normalizeBaseUrl(params.personalServerUrl);
33590
34764
  const audience = params.audience ?? baseUrl;
33591
34765
  const signer = resolveWriteSigner(params.signer, { account: params.account });
@@ -33613,14 +34787,14 @@ async function getPersonalServerLineage(params) {
33613
34787
  }
33614
34788
  async function getGatewayLineage(params) {
33615
34789
  if (!isDataPointId(params.dataPointId)) {
33616
- throw new LineageReadError(
34790
+ throw new import_errors4.LineageReadError(
33617
34791
  "dataPointId must be a 32-byte hex string (see deriveDataPointId)",
33618
34792
  void 0,
33619
34793
  "INVALID_DATA_POINT_ID",
33620
34794
  { dataPointId: params.dataPointId }
33621
34795
  );
33622
34796
  }
33623
- const fetchFn = resolveFetch(params.fetch);
34797
+ const fetchFn = resolveFetch2(params.fetch);
33624
34798
  const baseUrl = normalizeBaseUrl(params.gatewayUrl);
33625
34799
  const signer = resolveWriteSigner(params.signer, { account: params.account });
33626
34800
  const uri = gatewayLineagePath(
@@ -33650,7 +34824,7 @@ var TOMBSTONE_METADATA_HASH_PREIMAGE = "vana.data-point.tombstone.metadata.v1";
33650
34824
  var TOMBSTONE_DATA_HASH = "0x30c45ee72fe56d1927701316925ab7ceacd3b6f9267061735d59396f075c6222";
33651
34825
  var TOMBSTONE_METADATA_HASH = "0xc5255a141acd6a2ae55971b62c0a85977c2511989dc114ad2abc2b7644f57d90";
33652
34826
  function computeTombstoneHash(preimage) {
33653
- return (0, import_viem22.keccak256)((0, import_viem22.stringToBytes)(preimage));
34827
+ return (0, import_viem25.keccak256)((0, import_viem25.stringToBytes)(preimage));
33654
34828
  }
33655
34829
  function isTombstoneHashes(dataHash, metadataHash) {
33656
34830
  return typeof dataHash === "string" && typeof metadataHash === "string" && dataHash.toLowerCase() === TOMBSTONE_DATA_HASH && metadataHash.toLowerCase() === TOMBSTONE_METADATA_HASH;
@@ -33669,12 +34843,12 @@ function tombstoneDeletedAt(value) {
33669
34843
  return typeof deletedAt === "string" ? deletedAt : null;
33670
34844
  }
33671
34845
  function assertAddress4(value, name) {
33672
- if (!(0, import_viem22.isAddress)(value)) {
34846
+ if (!(0, import_viem25.isAddress)(value)) {
33673
34847
  throw new Error(`${name} must be a valid EVM address`);
33674
34848
  }
33675
34849
  }
33676
34850
  function assertUint256(value, name) {
33677
- if (value < 0n || value > import_viem22.maxUint256) {
34851
+ if (value < 0n || value > import_viem25.maxUint256) {
33678
34852
  throw new Error(`${name} must fit in uint256, got ${value}`);
33679
34853
  }
33680
34854
  }
@@ -33759,13 +34933,13 @@ async function deleteDataPoint(input) {
33759
34933
  if (currentVersion === void 0) {
33760
34934
  const record = await input.gateway.getDataPoint(dataPointId);
33761
34935
  if (record === null) {
33762
- throw new DataPointNotFoundError(
34936
+ throw new import_errors5.DataPointNotFoundError(
33763
34937
  `No data point registered for scope '${input.scope}' owned by ${ownerAddress}`,
33764
34938
  { dataPointId, scope: input.scope, ownerAddress }
33765
34939
  );
33766
34940
  }
33767
34941
  if (isDataPointTombstone(record)) {
33768
- throw new DataPointDeletedError(
34942
+ throw new import_errors5.DataPointDeletedError(
33769
34943
  `Data point ${dataPointId} (scope '${input.scope}') is already deleted`,
33770
34944
  {
33771
34945
  dataPointId,
@@ -33777,7 +34951,7 @@ async function deleteDataPoint(input) {
33777
34951
  }
33778
34952
  currentVersion = parseExpectedVersion(record.expectedVersion);
33779
34953
  }
33780
- if (currentVersion < 0n || currentVersion >= import_viem22.maxUint256) {
34954
+ if (currentVersion < 0n || currentVersion >= import_viem25.maxUint256) {
33781
34955
  throw new Error(
33782
34956
  `currentVersion ${currentVersion} cannot be incremented to a uint256 tombstone version`
33783
34957
  );
@@ -33811,6 +34985,9 @@ async function deleteDataPoint(input) {
33811
34985
  }
33812
34986
  }
33813
34987
 
34988
+ // src/protocol/personal-server-data.ts
34989
+ var import_errors6 = require("./errors.cjs");
34990
+
33814
34991
  // src/protocol/data-file.ts
33815
34992
  var import_zod2 = require("zod");
33816
34993
  var DataFileEnvelopeSchema = import_zod2.z.object({
@@ -33869,7 +35046,7 @@ async function readPersonalServerData(params) {
33869
35046
  const request = await buildPersonalServerDataReadRequest(params);
33870
35047
  const response = await fetchFn(request);
33871
35048
  if (response.status === 410) {
33872
- throw new DataPointDeletedError(
35049
+ throw new import_errors6.DataPointDeletedError(
33873
35050
  `Personal Server scope '${params.scope}' has been deleted`,
33874
35051
  {
33875
35052
  scope: params.scope,
@@ -33884,7 +35061,7 @@ async function readPersonalServerData(params) {
33884
35061
  }
33885
35062
  const body = await response.json();
33886
35063
  if (isDataPointTombstone(body)) {
33887
- throw new DataPointDeletedError(
35064
+ throw new import_errors6.DataPointDeletedError(
33888
35065
  `Personal Server scope '${params.scope}' has been deleted`,
33889
35066
  { scope: params.scope, deletedAt: tombstoneDeletedAt(body) }
33890
35067
  );
@@ -34084,20 +35261,22 @@ function tryGrantPermissions(scopes) {
34084
35261
  }
34085
35262
 
34086
35263
  // src/protocol/personal-server-write.ts
34087
- var import_sha26 = require("@noble/hashes/sha2");
34088
- var import_viem24 = require("viem");
35264
+ var import_sha28 = require("@noble/hashes/sha2");
35265
+ var import_viem27 = require("viem");
34089
35266
  var import_zod4 = require("zod");
35267
+ var import_errors8 = require("./errors.cjs");
34090
35268
 
34091
35269
  // src/protocol/write-request.ts
34092
- var import_sha25 = require("@noble/hashes/sha2");
34093
- var import_viem23 = require("viem");
35270
+ var import_sha27 = require("@noble/hashes/sha2");
35271
+ var import_viem26 = require("viem");
35272
+ var import_errors7 = require("./errors.cjs");
34094
35273
  function normalizeBaseUrl2(url) {
34095
35274
  return url.replace(/\/+$/, "");
34096
35275
  }
34097
- function resolveFetch2(fetchFn) {
35276
+ function resolveFetch3(fetchFn) {
34098
35277
  const resolved = fetchFn ?? globalThis.fetch;
34099
35278
  if (resolved === void 0) {
34100
- throw new WriteRequestError("No fetch implementation available");
35279
+ throw new import_errors7.WriteRequestError("No fetch implementation available");
34101
35280
  }
34102
35281
  return resolved;
34103
35282
  }
@@ -34107,7 +35286,7 @@ function errorMessage(err) {
34107
35286
  function finiteOr(value, fallback) {
34108
35287
  return typeof value === "number" && Number.isFinite(value) ? value : fallback;
34109
35288
  }
34110
- function sleep2(ms) {
35289
+ function sleep3(ms) {
34111
35290
  return new Promise((resolve) => setTimeout(resolve, ms));
34112
35291
  }
34113
35292
  var issuedProofIats = /* @__PURE__ */ new Map();
@@ -34149,30 +35328,30 @@ function nextProofIat(proofKey) {
34149
35328
  setIssuedProofIat(proofKey, iat, last);
34150
35329
  const waitSec = iat - nowSec - PROOF_IAT_MAX_AHEAD_SECONDS;
34151
35330
  if (waitSec <= 0) return Promise.resolve(iat);
34152
- return sleep2(waitSec * 1e3).then(() => iat);
35331
+ return sleep3(waitSec * 1e3).then(() => iat);
34153
35332
  }
34154
35333
  function freshProofNonce() {
34155
- const webCrypto = globalThis.crypto;
34156
- if (typeof webCrypto?.randomUUID === "function") {
34157
- return webCrypto.randomUUID();
35334
+ const webCrypto2 = globalThis.crypto;
35335
+ if (typeof webCrypto2?.randomUUID === "function") {
35336
+ return webCrypto2.randomUUID();
34158
35337
  }
34159
- if (typeof webCrypto?.getRandomValues === "function") {
34160
- return (0, import_viem23.bytesToHex)(webCrypto.getRandomValues(new Uint8Array(16)));
35338
+ if (typeof webCrypto2?.getRandomValues === "function") {
35339
+ return (0, import_viem26.bytesToHex)(webCrypto2.getRandomValues(new Uint8Array(16)));
34161
35340
  }
34162
- throw new WriteRequestError(
35341
+ throw new import_errors7.WriteRequestError(
34163
35342
  "No secure random source available to build a proof nonce; provide a crypto global"
34164
35343
  );
34165
35344
  }
34166
35345
  function proofKeyFor(parts) {
34167
- return (0, import_viem23.bytesToHex)(
34168
- (0, import_sha25.sha256)(
35346
+ return (0, import_viem26.bytesToHex)(
35347
+ (0, import_sha27.sha256)(
34169
35348
  new TextEncoder().encode(
34170
35349
  JSON.stringify([
34171
35350
  parts.aud,
34172
35351
  parts.method,
34173
35352
  parts.uri,
34174
35353
  parts.grantId,
34175
- parts.signedBytes ? (0, import_viem23.bytesToHex)((0, import_sha25.sha256)(parts.signedBytes)) : ""
35354
+ parts.signedBytes ? (0, import_viem26.bytesToHex)((0, import_sha27.sha256)(parts.signedBytes)) : ""
34176
35355
  ])
34177
35356
  )
34178
35357
  )
@@ -34190,11 +35369,11 @@ async function sendWithFreshProof(label, fetchFn, options, proofKey, build) {
34190
35369
  lastError = err;
34191
35370
  }
34192
35371
  if (attempt < attempts - 1) {
34193
- await sleep2(delayMs);
35372
+ await sleep3(delayMs);
34194
35373
  delayMs *= 2;
34195
35374
  }
34196
35375
  }
34197
- throw new WriteTransportError(
35376
+ throw new import_errors7.WriteTransportError(
34198
35377
  `${label} failed after ${attempts} attempt(s): ${errorMessage(lastError)}`,
34199
35378
  attempts,
34200
35379
  lastError
@@ -34229,7 +35408,7 @@ function dataPath(scope) {
34229
35408
  return `/v1/data/${encodeURIComponent(scope)}`;
34230
35409
  }
34231
35410
  async function openWriteSession(params) {
34232
- const fetchFn = resolveFetch2(params.fetch);
35411
+ const fetchFn = resolveFetch3(params.fetch);
34233
35412
  const personalServerUrl = normalizeBaseUrl2(params.personalServerUrl);
34234
35413
  const audience = params.audience ?? personalServerUrl;
34235
35414
  const signer = resolveWriteSigner(params.signer, { account: params.account });
@@ -34265,7 +35444,7 @@ async function openWriteSession(params) {
34265
35444
  const mintedAt = Date.now();
34266
35445
  if (!response.ok) {
34267
35446
  const { errorCode, message, details } = await readPersonalServerErrorBody(response);
34268
- throw new WriteSessionError(
35447
+ throw new import_errors8.WriteSessionError(
34269
35448
  message ?? `Write session handshake failed: ${response.status} ${response.statusText}`,
34270
35449
  response.status,
34271
35450
  errorCode,
@@ -34276,7 +35455,7 @@ async function openWriteSession(params) {
34276
35455
  try {
34277
35456
  body = await response.json();
34278
35457
  } catch (err) {
34279
- throw new WriteSessionError(
35458
+ throw new import_errors8.WriteSessionError(
34280
35459
  "Write session response is not JSON",
34281
35460
  response.status,
34282
35461
  null,
@@ -34285,7 +35464,7 @@ async function openWriteSession(params) {
34285
35464
  }
34286
35465
  const parsed = WriteSessionResponseSchema.safeParse(body);
34287
35466
  if (!parsed.success) {
34288
- throw new WriteSessionError(
35467
+ throw new import_errors8.WriteSessionError(
34289
35468
  "Write session response is not a session",
34290
35469
  response.status,
34291
35470
  null,
@@ -34293,7 +35472,7 @@ async function openWriteSession(params) {
34293
35472
  );
34294
35473
  }
34295
35474
  if (parsed.data.token_type.toLowerCase() !== "bearer") {
34296
- throw new WriteSessionError(
35475
+ throw new import_errors8.WriteSessionError(
34297
35476
  `Write session token type is not Bearer: ${parsed.data.token_type}`,
34298
35477
  response.status
34299
35478
  );
@@ -34309,13 +35488,13 @@ async function openWriteSession(params) {
34309
35488
  };
34310
35489
  }
34311
35490
  function isWriteSession(value) {
34312
- if (!isRecord2(value)) return false;
35491
+ if (!isRecord4(value)) return false;
34313
35492
  const signer = value.signer;
34314
- return typeof value.personalServerUrl === "string" && typeof value.audience === "string" && typeof value.grantId === "string" && typeof value.accessToken === "string" && value.accessToken.length > 0 && typeof value.expiresAt === "number" && Number.isFinite(value.expiresAt) && Array.isArray(value.writeScopes) && value.writeScopes.every((scope) => typeof scope === "string") && isRecord2(signer) && typeof signer.signMessage === "function";
35493
+ return typeof value.personalServerUrl === "string" && typeof value.audience === "string" && typeof value.grantId === "string" && typeof value.accessToken === "string" && value.accessToken.length > 0 && typeof value.expiresAt === "number" && Number.isFinite(value.expiresAt) && Array.isArray(value.writeScopes) && value.writeScopes.every((scope) => typeof scope === "string") && isRecord4(signer) && typeof signer.signMessage === "function";
34315
35494
  }
34316
35495
  function sessionCoversScope(session, scope) {
34317
- if (!isRecord2(session) || !Array.isArray(session.writeScopes) || !session.writeScopes.every((pattern) => typeof pattern === "string")) {
34318
- throw new WriteRequestError("session must come from openWriteSession");
35496
+ if (!isRecord4(session) || !Array.isArray(session.writeScopes) || !session.writeScopes.every((pattern) => typeof pattern === "string")) {
35497
+ throw new import_errors8.WriteRequestError("session must come from openWriteSession");
34319
35498
  }
34320
35499
  return session.writeScopes.some(
34321
35500
  (pattern) => scopeMatchesPattern(scope, pattern)
@@ -34340,12 +35519,12 @@ function encodeWriteMetadataHeader(metadata) {
34340
35519
  try {
34341
35520
  json = JSON.stringify(metadata);
34342
35521
  } catch (err) {
34343
- throw new WriteRequestError(
35522
+ throw new import_errors8.WriteRequestError(
34344
35523
  `metadata is not JSON-serialisable: ${errorMessage(err)}`
34345
35524
  );
34346
35525
  }
34347
35526
  if (typeof json !== "string") {
34348
- throw new WriteRequestError("metadata must serialise to JSON");
35527
+ throw new import_errors8.WriteRequestError("metadata must serialise to JSON");
34349
35528
  }
34350
35529
  return json.replace(
34351
35530
  /[\u007f-\uffff]/g,
@@ -34359,7 +35538,7 @@ function binaryWriteSignedBytes(input) {
34359
35538
  mimeType: normalizeBinaryMimeType(input.contentType),
34360
35539
  ...input.filename ? { filename: input.filename } : {},
34361
35540
  sizeBytes: input.bytes.length,
34362
- contentHash: (0, import_viem24.bytesToHex)((0, import_sha26.sha256)(input.bytes)),
35541
+ contentHash: (0, import_viem27.bytesToHex)((0, import_sha28.sha256)(input.bytes)),
34363
35542
  encoding: "base64",
34364
35543
  content: toBase64(input.bytes),
34365
35544
  ...metadata !== void 0 ? { metadata } : {}
@@ -34380,7 +35559,7 @@ function setFilenameHeader(headers, filename) {
34380
35559
  function assertNoReservedKeys(value, where) {
34381
35560
  for (const key of RESERVED_WRITE_KEYS) {
34382
35561
  if (Object.prototype.hasOwnProperty.call(value, key)) {
34383
- throw new WriteRequestError(
35562
+ throw new import_errors8.WriteRequestError(
34384
35563
  `${where} must not contain the reserved ${key} key; the Personal Server stamps it`,
34385
35564
  { key }
34386
35565
  );
@@ -34388,14 +35567,14 @@ function assertNoReservedKeys(value, where) {
34388
35567
  }
34389
35568
  }
34390
35569
  function isLineagePair(value) {
34391
- return isRecord2(value) && typeof value.ownerAddress === "string" && typeof value.scope === "string";
35570
+ return isRecord4(value) && typeof value.ownerAddress === "string" && typeof value.scope === "string";
34392
35571
  }
34393
35572
  function normalizeLineage(lineage, derivedScope) {
34394
35573
  if (!Array.isArray(lineage)) {
34395
- throw new WriteRequestError("lineage must be an array of data point ids");
35574
+ throw new import_errors8.WriteRequestError("lineage must be an array of data point ids");
34396
35575
  }
34397
35576
  if (lineage.length > MAX_LINEAGE_SOURCES) {
34398
- throw new WriteRequestError(
35577
+ throw new import_errors8.WriteRequestError(
34399
35578
  `lineage lists ${lineage.length} sources; the maximum is ${MAX_LINEAGE_SOURCES}`,
34400
35579
  { max: MAX_LINEAGE_SOURCES, count: lineage.length }
34401
35580
  );
@@ -34407,14 +35586,14 @@ function normalizeLineage(lineage, derivedScope) {
34407
35586
  for (const entry of lineage) {
34408
35587
  let id;
34409
35588
  if (isLineagePair(entry)) {
34410
- if (!(0, import_viem24.isAddress)(entry.ownerAddress, { strict: false })) {
34411
- throw new WriteRequestError(
35589
+ if (!(0, import_viem27.isAddress)(entry.ownerAddress, { strict: false })) {
35590
+ throw new import_errors8.WriteRequestError(
34412
35591
  "lineage source ownerAddress must be an EVM address",
34413
35592
  { ownerAddress: entry.ownerAddress }
34414
35593
  );
34415
35594
  }
34416
35595
  if (entry.scope.length === 0) {
34417
- throw new WriteRequestError("lineage source scope is required");
35596
+ throw new import_errors8.WriteRequestError("lineage source scope is required");
34418
35597
  }
34419
35598
  id = deriveDataPointId(entry.ownerAddress, entry.scope);
34420
35599
  sourceScopes.push(entry.scope);
@@ -34422,14 +35601,14 @@ function normalizeLineage(lineage, derivedScope) {
34422
35601
  } else if (isDataPointId(entry)) {
34423
35602
  id = entry;
34424
35603
  } else {
34425
- throw new WriteRequestError(
35604
+ throw new import_errors8.WriteRequestError(
34426
35605
  "lineage entries must be 32-byte hex data point ids or { ownerAddress, scope } pairs",
34427
35606
  { entry }
34428
35607
  );
34429
35608
  }
34430
35609
  const normalized = id.toLowerCase();
34431
35610
  if (seen.has(normalized)) {
34432
- throw new WriteRequestError("lineage must not repeat a data point id", {
35611
+ throw new import_errors8.WriteRequestError("lineage must not repeat a data point id", {
34433
35612
  dataPointId: normalized
34434
35613
  });
34435
35614
  }
@@ -34438,7 +35617,7 @@ function normalizeLineage(lineage, derivedScope) {
34438
35617
  }
34439
35618
  for (const own of ownIds) {
34440
35619
  if (seen.has(own)) {
34441
- throw new WriteRequestError(
35620
+ throw new import_errors8.WriteRequestError(
34442
35621
  "lineage must not cite the record's own data point",
34443
35622
  { dataPointId: own, scope: derivedScope }
34444
35623
  );
@@ -34449,15 +35628,15 @@ function normalizeLineage(lineage, derivedScope) {
34449
35628
  }
34450
35629
  function assertNoLineageField(value, where) {
34451
35630
  if (Object.prototype.hasOwnProperty.call(value, LINEAGE_FIELD)) {
34452
- throw new WriteRequestError(
35631
+ throw new import_errors8.WriteRequestError(
34453
35632
  `${where}.${LINEAGE_FIELD} is reserved; pass sources through the lineage option`
34454
35633
  );
34455
35634
  }
34456
35635
  }
34457
35636
  function buildMetadataHeader(metadata, sources) {
34458
35637
  if (metadata !== void 0) {
34459
- if (!isRecord2(metadata)) {
34460
- throw new WriteRequestError("metadata must be a plain object");
35638
+ if (!isRecord4(metadata)) {
35639
+ throw new import_errors8.WriteRequestError("metadata must be a plain object");
34461
35640
  }
34462
35641
  assertNoReservedKeys(metadata, "metadata");
34463
35642
  assertNoLineageField(metadata, "metadata");
@@ -34470,24 +35649,24 @@ function buildMetadataHeader(metadata, sources) {
34470
35649
  }
34471
35650
  function prepareWrite(params) {
34472
35651
  if (params.binary !== void 0 && params.data !== void 0) {
34473
- throw new WriteRequestError("Pass either data or binary, not both");
35652
+ throw new import_errors8.WriteRequestError("Pass either data or binary, not both");
34474
35653
  }
34475
35654
  const rawLineage = params.lineage;
34476
35655
  const sources = rawLineage === void 0 || rawLineage === null ? void 0 : normalizeLineage(rawLineage, params.scope);
34477
35656
  if (params.binary !== void 0) {
34478
35657
  const { bytes, contentType, filename } = params.binary;
34479
35658
  if (!(bytes instanceof Uint8Array)) {
34480
- throw new WriteRequestError("binary.bytes must be a Uint8Array");
35659
+ throw new import_errors8.WriteRequestError("binary.bytes must be a Uint8Array");
34481
35660
  }
34482
35661
  if (typeof contentType !== "string" || contentType.trim() === "") {
34483
- throw new WriteRequestError("binary.contentType is required");
35662
+ throw new import_errors8.WriteRequestError("binary.contentType is required");
34484
35663
  }
34485
35664
  if (filename !== void 0) {
34486
35665
  if (typeof filename !== "string") {
34487
- throw new WriteRequestError("binary.filename must be a string");
35666
+ throw new import_errors8.WriteRequestError("binary.filename must be a string");
34488
35667
  }
34489
35668
  if (filename !== filename.trim()) {
34490
- throw new WriteRequestError(
35669
+ throw new import_errors8.WriteRequestError(
34491
35670
  "binary.filename must not have leading or trailing whitespace"
34492
35671
  );
34493
35672
  }
@@ -34507,13 +35686,13 @@ function prepareWrite(params) {
34507
35686
  };
34508
35687
  }
34509
35688
  if (params.data === void 0) {
34510
- throw new WriteRequestError("Pass data (a JSON object) or binary");
35689
+ throw new import_errors8.WriteRequestError("Pass data (a JSON object) or binary");
34511
35690
  }
34512
- if (!isRecord2(params.data)) {
34513
- throw new WriteRequestError("data must be a plain JSON object");
35691
+ if (!isRecord4(params.data)) {
35692
+ throw new import_errors8.WriteRequestError("data must be a plain JSON object");
34514
35693
  }
34515
35694
  if (params.metadata !== void 0) {
34516
- throw new WriteRequestError(
35695
+ throw new import_errors8.WriteRequestError(
34517
35696
  "metadata applies to binary writes; put fields to store inside data"
34518
35697
  );
34519
35698
  }
@@ -34524,12 +35703,12 @@ function prepareWrite(params) {
34524
35703
  try {
34525
35704
  text = JSON.stringify(record);
34526
35705
  } catch (err) {
34527
- throw new WriteRequestError(
35706
+ throw new import_errors8.WriteRequestError(
34528
35707
  `data is not JSON-serialisable: ${errorMessage(err)}`
34529
35708
  );
34530
35709
  }
34531
35710
  if (typeof text !== "string" || !text.startsWith("{")) {
34532
- throw new WriteRequestError("data must serialise to a JSON object");
35711
+ throw new import_errors8.WriteRequestError("data must serialise to a JSON object");
34533
35712
  }
34534
35713
  const body = new TextEncoder().encode(text);
34535
35714
  return {
@@ -34542,31 +35721,31 @@ async function writeErrorFromResponse(response) {
34542
35721
  const { errorCode, message, details } = await readPersonalServerErrorBody(response);
34543
35722
  const text = message ?? `Personal Server write failed: ${response.status} ${response.statusText}`;
34544
35723
  if (response.status === 422 || errorCode?.startsWith("LINEAGE_")) {
34545
- return new WriteLineageError(text, response.status, errorCode, details);
35724
+ return new import_errors8.WriteLineageError(text, response.status, errorCode, details);
34546
35725
  }
34547
35726
  switch (response.status) {
34548
35727
  case 401:
34549
- return new WriteUnauthorizedError(text, errorCode, details);
35728
+ return new import_errors8.WriteUnauthorizedError(text, errorCode, details);
34550
35729
  case 403:
34551
- return new WriteForbiddenError(text, errorCode, details);
35730
+ return new import_errors8.WriteForbiddenError(text, errorCode, details);
34552
35731
  case 409:
34553
- return new WriteConflictError(text, errorCode, details);
35732
+ return new import_errors8.WriteConflictError(text, errorCode, details);
34554
35733
  default:
34555
- return new WriteRejectedError(text, response.status, errorCode, details);
35734
+ return new import_errors8.WriteRejectedError(text, response.status, errorCode, details);
34556
35735
  }
34557
35736
  }
34558
35737
  async function writeData(params) {
34559
35738
  const { session } = params;
34560
35739
  if (!isWriteSession(session)) {
34561
- throw new WriteRequestError("session must come from openWriteSession");
35740
+ throw new import_errors8.WriteRequestError("session must come from openWriteSession");
34562
35741
  }
34563
- const fetchFn = resolveFetch2(params.fetch);
35742
+ const fetchFn = resolveFetch3(params.fetch);
34564
35743
  if (typeof params.scope !== "string" || params.scope.length === 0) {
34565
- throw new WriteRequestError("scope is required");
35744
+ throw new import_errors8.WriteRequestError("scope is required");
34566
35745
  }
34567
35746
  const prepared = prepareWrite(params);
34568
35747
  if (Date.now() >= session.expiresAt) {
34569
- throw new WriteSessionExpiredError(
35748
+ throw new import_errors8.WriteSessionExpiredError(
34570
35749
  "Write session has expired; open a new session",
34571
35750
  { grantId: session.grantId, expiresAt: session.expiresAt }
34572
35751
  );
@@ -34622,7 +35801,7 @@ async function writeData(params) {
34622
35801
  try {
34623
35802
  body = await response.json();
34624
35803
  } catch (err) {
34625
- throw new WriteRejectedError(
35804
+ throw new import_errors8.WriteRejectedError(
34626
35805
  "Personal Server write response is not JSON",
34627
35806
  response.status,
34628
35807
  null,
@@ -34631,7 +35810,7 @@ async function writeData(params) {
34631
35810
  }
34632
35811
  const parsed = WriteDataResultSchema.safeParse(body);
34633
35812
  if (!parsed.success) {
34634
- throw new WriteRejectedError(
35813
+ throw new import_errors8.WriteRejectedError(
34635
35814
  "Personal Server write response is not an ingest result",
34636
35815
  response.status,
34637
35816
  null,
@@ -34658,6 +35837,7 @@ async function writePersonalServerData(params) {
34658
35837
 
34659
35838
  // src/protocol/derivative-questions.ts
34660
35839
  var import_zod5 = require("zod");
35840
+ var import_errors9 = require("./errors.cjs");
34661
35841
  var DERIVATIVE_QUESTIONS_PATH = "/v1/derivatives/questions";
34662
35842
  var MAX_QUESTION_SOURCE_SCOPES = 16;
34663
35843
  var MAX_QUESTION_CHARS = 8e3;
@@ -34740,19 +35920,19 @@ function fetchIdOf(fetchFn) {
34740
35920
  }
34741
35921
  function resolveRequest(params) {
34742
35922
  if (typeof params.personalServerUrl !== "string" || params.personalServerUrl.length === 0) {
34743
- throw new WriteRequestError("personalServerUrl is required");
35923
+ throw new import_errors9.WriteRequestError("personalServerUrl is required");
34744
35924
  }
34745
35925
  if (typeof params.grantId !== "string" || params.grantId.length === 0) {
34746
- throw new WriteRequestError(
35926
+ throw new import_errors9.WriteRequestError(
34747
35927
  "grantId is required; a question call runs under the grant carrying write:<derivedScope>"
34748
35928
  );
34749
35929
  }
34750
35930
  if (params.signer === null || typeof params.signer !== "object") {
34751
- throw new WriteRequestError(
35931
+ throw new import_errors9.WriteRequestError(
34752
35932
  "signer must be a viem LocalAccount, a viem WalletClient, or a { signMessage } object"
34753
35933
  );
34754
35934
  }
34755
- const fetchFn = resolveFetch2(params.fetch);
35935
+ const fetchFn = resolveFetch3(params.fetch);
34756
35936
  const baseUrl = normalizeBaseUrl2(params.personalServerUrl);
34757
35937
  const audience = params.audience ?? baseUrl;
34758
35938
  return {
@@ -34802,37 +35982,37 @@ async function questionErrorFromResponse(response, body) {
34802
35982
  const text = message ?? `Derivative question request failed: ${response.status} ${response.statusText}`;
34803
35983
  switch (errorCode) {
34804
35984
  case "DERIVATIVE_SOURCE_NOT_GRANTED":
34805
- return new DerivativeSourceNotGrantedError(text, errorCode, details);
35985
+ return new import_errors9.DerivativeSourceNotGrantedError(text, errorCode, details);
34806
35986
  case "DERIVATIVE_CYCLE":
34807
- return new DerivativeCycleError(text, errorCode, details);
35987
+ return new import_errors9.DerivativeCycleError(text, errorCode, details);
34808
35988
  case "DERIVATIVE_COMPUTE_UNAVAILABLE":
34809
- return new DerivativeComputeUnavailableError(text, errorCode, details);
35989
+ return new import_errors9.DerivativeComputeUnavailableError(text, errorCode, details);
34810
35990
  case "DERIVATIVE_QUESTION_INVALID":
34811
35991
  case "LINEAGE_SCOPE_UNDER_SOURCE_PREFIX":
34812
- return new DerivativeQuestionInvalidError(
35992
+ return new import_errors9.DerivativeQuestionInvalidError(
34813
35993
  text,
34814
35994
  response.status,
34815
35995
  errorCode,
34816
35996
  details
34817
35997
  );
34818
35998
  case "DERIVATIVE_QUESTION_NOT_FOUND":
34819
- return new DerivativeQuestionNotFoundError(text, errorCode, details);
35999
+ return new import_errors9.DerivativeQuestionNotFoundError(text, errorCode, details);
34820
36000
  case "DERIVATIVE_DERIVED_SCOPE_REQUIRED":
34821
- return new DerivativeDerivedScopeRequiredError(text, errorCode, details);
36001
+ return new import_errors9.DerivativeDerivedScopeRequiredError(text, errorCode, details);
34822
36002
  default:
34823
36003
  break;
34824
36004
  }
34825
36005
  switch (response.status) {
34826
36006
  case 401:
34827
- return new WriteUnauthorizedError(text, errorCode, details);
36007
+ return new import_errors9.WriteUnauthorizedError(text, errorCode, details);
34828
36008
  case 403:
34829
- return new WriteForbiddenError(text, errorCode, details);
36009
+ return new import_errors9.WriteForbiddenError(text, errorCode, details);
34830
36010
  case 404:
34831
- return new DerivativeQuestionNotFoundError(text, errorCode, details);
36011
+ return new import_errors9.DerivativeQuestionNotFoundError(text, errorCode, details);
34832
36012
  case 409:
34833
- return new WriteConflictError(text, errorCode, details);
36013
+ return new import_errors9.WriteConflictError(text, errorCode, details);
34834
36014
  default:
34835
- return new DerivativeQuestionRejectedError(
36015
+ return new import_errors9.DerivativeQuestionRejectedError(
34836
36016
  text,
34837
36017
  response.status,
34838
36018
  errorCode,
@@ -34912,7 +36092,7 @@ async function sendQuestionRequest(params, spec, schema) {
34912
36092
  try {
34913
36093
  body = await response.json();
34914
36094
  } catch (err) {
34915
- throw new DerivativeQuestionRejectedError(
36095
+ throw new import_errors9.DerivativeQuestionRejectedError(
34916
36096
  `${spec.label} response is not JSON`,
34917
36097
  response.status,
34918
36098
  null,
@@ -34921,7 +36101,7 @@ async function sendQuestionRequest(params, spec, schema) {
34921
36101
  }
34922
36102
  const parsed = schema.safeParse(body);
34923
36103
  if (!parsed.success) {
34924
- throw new DerivativeQuestionRejectedError(
36104
+ throw new import_errors9.DerivativeQuestionRejectedError(
34925
36105
  `${spec.label} response is not a derivative question answer`,
34926
36106
  response.status,
34927
36107
  null,
@@ -34932,22 +36112,22 @@ async function sendQuestionRequest(params, spec, schema) {
34932
36112
  }
34933
36113
  function assertQuestionId(questionId) {
34934
36114
  if (typeof questionId !== "string" || questionId.length === 0) {
34935
- throw new WriteRequestError("questionId is required");
36115
+ throw new import_errors9.WriteRequestError("questionId is required");
34936
36116
  }
34937
36117
  return `${DERIVATIVE_QUESTIONS_PATH}/${encodeURIComponent(questionId)}`;
34938
36118
  }
34939
36119
  function registrationBody(params) {
34940
36120
  const { derivedScope, question } = params;
34941
36121
  if (typeof derivedScope !== "string" || derivedScope.length === 0) {
34942
- throw new WriteRequestError("derivedScope is required");
36122
+ throw new import_errors9.WriteRequestError("derivedScope is required");
34943
36123
  }
34944
36124
  if (!Array.isArray(params.sourceScopes) || params.sourceScopes.length === 0) {
34945
- throw new WriteRequestError(
36125
+ throw new import_errors9.WriteRequestError(
34946
36126
  "sourceScopes must be a non-empty array of scopes"
34947
36127
  );
34948
36128
  }
34949
36129
  if (params.sourceScopes.length > MAX_QUESTION_SOURCE_SCOPES) {
34950
- throw new WriteRequestError(
36130
+ throw new import_errors9.WriteRequestError(
34951
36131
  `sourceScopes lists ${params.sourceScopes.length} scopes; the maximum is ${MAX_QUESTION_SOURCE_SCOPES}`,
34952
36132
  { max: MAX_QUESTION_SOURCE_SCOPES, count: params.sourceScopes.length }
34953
36133
  );
@@ -34955,15 +36135,15 @@ function registrationBody(params) {
34955
36135
  const sourceScopes = [];
34956
36136
  for (const scope of params.sourceScopes) {
34957
36137
  if (typeof scope !== "string" || scope.length === 0) {
34958
- throw new WriteRequestError("sourceScopes entries must be scope strings");
36138
+ throw new import_errors9.WriteRequestError("sourceScopes entries must be scope strings");
34959
36139
  }
34960
36140
  if (sourceScopes.includes(scope)) {
34961
- throw new WriteRequestError("sourceScopes must not repeat a scope", {
36141
+ throw new import_errors9.WriteRequestError("sourceScopes must not repeat a scope", {
34962
36142
  duplicate: scope
34963
36143
  });
34964
36144
  }
34965
36145
  if (scope === derivedScope) {
34966
- throw new WriteRequestError(
36146
+ throw new import_errors9.WriteRequestError(
34967
36147
  "derivedScope cannot be one of its own sources",
34968
36148
  { scope }
34969
36149
  );
@@ -34971,17 +36151,17 @@ function registrationBody(params) {
34971
36151
  sourceScopes.push(scope);
34972
36152
  }
34973
36153
  if (typeof question !== "string" || question.trim() === "") {
34974
- throw new WriteRequestError("question must be a non-empty string");
36154
+ throw new import_errors9.WriteRequestError("question must be a non-empty string");
34975
36155
  }
34976
36156
  if (question.length > MAX_QUESTION_CHARS) {
34977
- throw new WriteRequestError(
36157
+ throw new import_errors9.WriteRequestError(
34978
36158
  `question is ${question.length} characters; the maximum is ${MAX_QUESTION_CHARS}`,
34979
36159
  { max: MAX_QUESTION_CHARS, length: question.length }
34980
36160
  );
34981
36161
  }
34982
36162
  if (params.model !== void 0) {
34983
36163
  if (typeof params.model !== "string" || params.model.length > MAX_QUESTION_MODEL_CHARS || !MODEL_ID_PATTERN.test(params.model)) {
34984
- throw new WriteRequestError("model must be a provider model id", {
36164
+ throw new import_errors9.WriteRequestError("model must be a provider model id", {
34985
36165
  model: params.model
34986
36166
  });
34987
36167
  }
@@ -35017,7 +36197,7 @@ async function getQuestion(params) {
35017
36197
  }
35018
36198
  async function listQuestions(params) {
35019
36199
  if (typeof params.derivedScope !== "string" || params.derivedScope.length === 0) {
35020
- throw new WriteRequestError(
36200
+ throw new import_errors9.WriteRequestError(
35021
36201
  "derivedScope is required; a builder may only list its own questions on a scope it may write"
35022
36202
  );
35023
36203
  }
@@ -35075,7 +36255,7 @@ async function waitForQuestion(params) {
35075
36255
  if (isSettled(latest.status)) return latest;
35076
36256
  const remaining = deadline - Date.now();
35077
36257
  if (remaining <= 0) {
35078
- throw new DerivativeQuestionTimeoutError(
36258
+ throw new import_errors9.DerivativeQuestionTimeoutError(
35079
36259
  `Derivative question ${latest.questionId} was still ${latest.status} after ${timeoutMs}ms`,
35080
36260
  {
35081
36261
  questionId: latest.questionId,
@@ -35085,7 +36265,7 @@ async function waitForQuestion(params) {
35085
36265
  }
35086
36266
  );
35087
36267
  }
35088
- await sleep2(Math.min(pollIntervalMs, remaining));
36268
+ await sleep3(Math.min(pollIntervalMs, remaining));
35089
36269
  }
35090
36270
  }
35091
36271
  async function askPersonalServer(params) {
@@ -35095,7 +36275,7 @@ async function askPersonalServer(params) {
35095
36275
  questionId: registered.questionId
35096
36276
  });
35097
36277
  if (registration.status !== "ready") {
35098
- throw new DerivativeQuestionFailedError(
36278
+ throw new import_errors9.DerivativeQuestionFailedError(
35099
36279
  `Derivative question ${registration.questionId} failed: ${registration.error ?? "no reason given"}`,
35100
36280
  {
35101
36281
  questionId: registration.questionId,
@@ -35122,6 +36302,7 @@ async function askPersonalServer(params) {
35122
36302
 
35123
36303
  // src/protocol/derivative-status.ts
35124
36304
  var import_zod6 = require("zod");
36305
+ var import_errors10 = require("./errors.cjs");
35125
36306
  var DERIVATIVE_STATUS_PATH = "/v1/derivatives/status";
35126
36307
  var DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS = 12e4;
35127
36308
  var DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS = 2e3;
@@ -35149,20 +36330,20 @@ function derivativeStatusTarget(derivedScope) {
35149
36330
  function normalizeBaseUrl3(url) {
35150
36331
  return url.replace(/\/+$/, "");
35151
36332
  }
35152
- function resolveFetch3(fetchFn) {
36333
+ function resolveFetch4(fetchFn) {
35153
36334
  const resolved = fetchFn ?? globalThis.fetch;
35154
36335
  if (resolved === void 0) {
35155
- throw new WriteRequestError("No fetch implementation available");
36336
+ throw new import_errors10.WriteRequestError("No fetch implementation available");
35156
36337
  }
35157
36338
  return resolved;
35158
36339
  }
35159
36340
  function requireDerivedScope(derivedScope) {
35160
36341
  if (typeof derivedScope !== "string" || derivedScope.length === 0) {
35161
- throw new WriteRequestError("derivedScope is required");
36342
+ throw new import_errors10.WriteRequestError("derivedScope is required");
35162
36343
  }
35163
36344
  return derivedScope;
35164
36345
  }
35165
- function sleep3(ms, signal) {
36346
+ function sleep4(ms, signal) {
35166
36347
  if (ms <= 0) return Promise.resolve();
35167
36348
  return new Promise((resolve, reject) => {
35168
36349
  const timer = setTimeout(() => {
@@ -35177,7 +36358,7 @@ function sleep3(ms, signal) {
35177
36358
  });
35178
36359
  }
35179
36360
  function timeoutError(latest, timeoutMs) {
35180
- return new DerivativeQuestionTimeoutError(
36361
+ return new import_errors10.DerivativeQuestionTimeoutError(
35181
36362
  `Derived scope ${latest.derivedScope} was still ${latest.status} after ${timeoutMs}ms`,
35182
36363
  {
35183
36364
  derivedScope: latest.derivedScope,
@@ -35190,7 +36371,7 @@ function timeoutError(latest, timeoutMs) {
35190
36371
  }
35191
36372
  function abortError2(signal) {
35192
36373
  const reason = signal?.reason;
35193
- return reason instanceof Error ? reason : new WriteRequestError("Derivative status wait was aborted");
36374
+ return reason instanceof Error ? reason : new import_errors10.WriteRequestError("Derivative status wait was aborted");
35194
36375
  }
35195
36376
  function isDerivativeStatusSettled(status) {
35196
36377
  if (status.status === "ready") return true;
@@ -35198,7 +36379,7 @@ function isDerivativeStatusSettled(status) {
35198
36379
  }
35199
36380
  async function getDerivativeStatus(params) {
35200
36381
  const derivedScope = requireDerivedScope(params.derivedScope);
35201
- const fetchFn = resolveFetch3(params.fetch);
36382
+ const fetchFn = resolveFetch4(params.fetch);
35202
36383
  const baseUrl = normalizeBaseUrl3(params.personalServerUrl);
35203
36384
  const signer = resolveWriteSigner(params.signer, { account: params.account });
35204
36385
  const headers = new Headers(params.headers);
@@ -35223,7 +36404,7 @@ async function getDerivativeStatus(params) {
35223
36404
  }
35224
36405
  );
35225
36406
  } catch (err) {
35226
- throw new WriteTransportError(
36407
+ throw new import_errors10.WriteTransportError(
35227
36408
  `Derivative status read failed: ${err instanceof Error ? err.message : String(err)}`,
35228
36409
  1,
35229
36410
  err
@@ -35238,7 +36419,7 @@ async function getDerivativeStatus(params) {
35238
36419
  try {
35239
36420
  body = await response.json();
35240
36421
  } catch (err) {
35241
- throw new DerivativeQuestionRejectedError(
36422
+ throw new import_errors10.DerivativeQuestionRejectedError(
35242
36423
  "Derivative status response is not JSON",
35243
36424
  response.status,
35244
36425
  null,
@@ -35247,7 +36428,7 @@ async function getDerivativeStatus(params) {
35247
36428
  }
35248
36429
  const parsed = DerivativeStatusSchema.safeParse(body);
35249
36430
  if (!parsed.success) {
35250
- throw new DerivativeQuestionRejectedError(
36431
+ throw new import_errors10.DerivativeQuestionRejectedError(
35251
36432
  "Derivative status response is not a status view",
35252
36433
  response.status,
35253
36434
  null,
@@ -35276,11 +36457,12 @@ async function waitForDerivativeStatus(params) {
35276
36457
  if (waitMs > remaining) {
35277
36458
  throw timeoutError(latest, timeoutMs);
35278
36459
  }
35279
- await sleep3(waitMs, params.signal);
36460
+ await sleep4(waitMs, params.signal);
35280
36461
  }
35281
36462
  }
35282
36463
 
35283
36464
  // src/protocol/gateway.ts
36465
+ var import_errors11 = require("./errors.cjs");
35284
36466
  function withGrantPermissions(grant) {
35285
36467
  const stripped = { ...grant };
35286
36468
  delete stripped.permissions;
@@ -35326,7 +36508,7 @@ function createGatewayClient(baseUrl) {
35326
36508
  }
35327
36509
  async function deletedError(res, details) {
35328
36510
  const body = await readBody(res);
35329
- return new DataPointDeletedError(
36511
+ return new import_errors11.DataPointDeletedError(
35330
36512
  `Data point ${details.dataPointId ?? details.scope ?? ""} has been deleted`,
35331
36513
  { ...details, deletedAt: tombstoneDeletedAt(body) }
35332
36514
  );
@@ -35399,7 +36581,7 @@ function createGatewayClient(baseUrl) {
35399
36581
  }
35400
36582
  const record = await unwrapEnvelope(res);
35401
36583
  if (!options?.includeDeleted && isDataPointTombstone(record)) {
35402
- throw new DataPointDeletedError(
36584
+ throw new import_errors11.DataPointDeletedError(
35403
36585
  `Data point ${dataPointId} has been deleted`,
35404
36586
  {
35405
36587
  dataPointId,
@@ -35561,7 +36743,7 @@ function createGatewayClient(baseUrl) {
35561
36743
  })
35562
36744
  });
35563
36745
  if (res.status === 404) {
35564
- throw new DataPointNotFoundError(
36746
+ throw new import_errors11.DataPointNotFoundError(
35565
36747
  `Data point ${dataPointId} (scope '${params.scope}') is not registered`,
35566
36748
  details
35567
36749
  );
@@ -35572,7 +36754,7 @@ function createGatewayClient(baseUrl) {
35572
36754
  body2["currentExpectedVersion"]
35573
36755
  );
35574
36756
  const detail = stringOrUndefined(body2["error"]) ?? res.statusText;
35575
- throw new DataPointVersionConflictError(
36757
+ throw new import_errors11.DataPointVersionConflictError(
35576
36758
  `Gateway error: 409 ${detail}`,
35577
36759
  {
35578
36760
  ...details,
@@ -36051,18 +37233,9 @@ async function authorizeEscrowPayment(params) {
36051
37233
  return toDirectPaymentReceipt(result);
36052
37234
  }
36053
37235
 
36054
- // src/direct/errors.ts
36055
- var PersonalServerReadError = class extends VanaError {
36056
- constructor(message, status, details) {
36057
- super(message, "DIRECT_PERSONAL_SERVER_READ_ERROR");
36058
- this.status = status;
36059
- this.details = details;
36060
- }
36061
- status;
36062
- details;
36063
- };
36064
-
36065
37236
  // src/direct/personal-server-read.ts
37237
+ var import_errors12 = require("./direct/errors.cjs");
37238
+ var import_errors13 = require("./errors.cjs");
36066
37239
  function asRecord2(value) {
36067
37240
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
36068
37241
  }
@@ -36106,7 +37279,7 @@ function parseLegacyGrantOperation(params) {
36106
37279
  const { challengeGrantId, challengeOpId, challengeOpType, grantId } = params;
36107
37280
  const opType = challengeOpType ?? GRANT_OP_TYPE;
36108
37281
  if (opType !== GRANT_OP_TYPE) {
36109
- throw new PersonalServerReadError(
37282
+ throw new import_errors12.PersonalServerReadError(
36110
37283
  "Personal Server payment challenge used an unsupported escrow op type",
36111
37284
  402,
36112
37285
  { opType: challengeOpType }
@@ -36114,14 +37287,14 @@ function parseLegacyGrantOperation(params) {
36114
37287
  }
36115
37288
  const opId = challengeOpId ?? challengeGrantId ?? grantId;
36116
37289
  if (!opId || !isBytes32Hex(opId)) {
36117
- throw new PersonalServerReadError(
37290
+ throw new import_errors12.PersonalServerReadError(
36118
37291
  "Personal Server payment challenge used an invalid escrow op id",
36119
37292
  402,
36120
37293
  { opId }
36121
37294
  );
36122
37295
  }
36123
37296
  if (opId.toLowerCase() !== grantId.toLowerCase()) {
36124
- throw new PersonalServerReadError(
37297
+ throw new import_errors12.PersonalServerReadError(
36125
37298
  "Personal Server payment challenge did not match the requested grant",
36126
37299
  402,
36127
37300
  { opId, grantId }
@@ -36167,7 +37340,7 @@ function parseCanonicalDataAccessAccept(value) {
36167
37340
  function parseCanonicalDataAccessPayment(params) {
36168
37341
  const { body, grantId, raw } = params;
36169
37342
  if (body.x402Version !== 1 || body.error !== "PAYMENT_REQUIRED") {
36170
- throw new PersonalServerReadError(
37343
+ throw new import_errors12.PersonalServerReadError(
36171
37344
  "Personal Server data-access payment response was not a canonical x402 challenge",
36172
37345
  402
36173
37346
  );
@@ -36206,20 +37379,20 @@ async function parsePersonalServerPaymentRequired(res, grantId) {
36206
37379
  "accepts"
36207
37380
  );
36208
37381
  if (hasAcceptsEnvelope && (body.x402Version !== 1 || body.error !== "PAYMENT_REQUIRED")) {
36209
- throw new PersonalServerReadError(
37382
+ throw new import_errors12.PersonalServerReadError(
36210
37383
  "Personal Server grant payment response was not a canonical x402 challenge",
36211
37384
  402
36212
37385
  );
36213
37386
  }
36214
37387
  const accept = preferredLegacyAccept(body);
36215
37388
  if (hasDataAccessMarker(body) && !accept) {
36216
- throw new PersonalServerReadError(
37389
+ throw new import_errors12.PersonalServerReadError(
36217
37390
  "Personal Server data-access payment challenge was untrusted or incomplete",
36218
37391
  402
36219
37392
  );
36220
37393
  }
36221
37394
  if (hasAcceptsEnvelope && !accept) {
36222
- throw new PersonalServerReadError(
37395
+ throw new import_errors12.PersonalServerReadError(
36223
37396
  "Personal Server grant payment challenge had no compatible escrow offer",
36224
37397
  402
36225
37398
  );
@@ -36237,7 +37410,7 @@ async function parsePersonalServerPaymentRequired(res, grantId) {
36237
37410
  const accessRecord2 = parseAccessRecord(accept.accessRecord);
36238
37411
  const hasAccessRecord = accept.accessRecord !== void 0;
36239
37412
  if (!network || !payerAddress || !isAddressHex(payerAddress) || !opId || !isBytes32Hex(opId) || !asset || !isAddressHex(asset) || !amount || !isUint256Decimal2(amount, true) || !paymentNonce || !isUint256Decimal2(paymentNonce, false) || !acceptAsset || acceptAsset.toLowerCase() !== asset.toLowerCase() || acceptAmount !== amount || hasAccessRecord && (!accessRecord2 || !isValidDataAccessRecord(accessRecord2) || accessRecord2.accessor.toLowerCase() !== payerAddress.toLowerCase()) || amount === "0" && !accessRecord2) {
36240
- throw new PersonalServerReadError(
37413
+ throw new import_errors12.PersonalServerReadError(
36241
37414
  "Personal Server grant payment challenge was untrusted or incomplete",
36242
37415
  402
36243
37416
  );
@@ -36309,7 +37482,7 @@ var KNOWN_CODES = /* @__PURE__ */ new Set([
36309
37482
  "server_not_configured",
36310
37483
  "content_too_large"
36311
37484
  ]);
36312
- function isRecord4(value) {
37485
+ function isRecord5(value) {
36313
37486
  return value !== null && typeof value === "object" && !Array.isArray(value);
36314
37487
  }
36315
37488
  function normalizeCode(value) {
@@ -36320,10 +37493,10 @@ function normalizeCode(value) {
36320
37493
  return KNOWN_CODES.has(code) ? code : null;
36321
37494
  }
36322
37495
  function extractPSErrorBody(body) {
36323
- if (!isRecord4(body)) {
37496
+ if (!isRecord5(body)) {
36324
37497
  return null;
36325
37498
  }
36326
- const nested = isRecord4(body.error) ? body.error : null;
37499
+ const nested = isRecord5(body.error) ? body.error : null;
36327
37500
  const code = normalizeCode(
36328
37501
  nested?.errorCode ?? nested?.code ?? body.errorCode ?? body.code
36329
37502
  );
@@ -36353,40 +37526,32 @@ async function parsePSError(response) {
36353
37526
  AccountPersonalServerLiteOwnerBindingError,
36354
37527
  AccountPersonalServerRegistrationError,
36355
37528
  BUILDER_REGISTRATION_TYPES,
36356
- BlockchainError,
36357
37529
  BrowserPlatformAdapter,
37530
+ CLAIM_POLL_FLOOR_MS,
36358
37531
  CONTRACTS,
36359
37532
  CallbackStorage,
36360
37533
  ContractFactory,
36361
- ContractNotFoundError,
36362
37534
  DATA_ACCESS_OP_TYPE,
36363
37535
  DATA_REGISTRY_STATUS_ABI,
36364
37536
  DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS,
36365
37537
  DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS,
37538
+ DEFAULT_JOB_DEADLINE_SECONDS,
37539
+ DEFAULT_LEASE_SECONDS,
36366
37540
  DEFAULT_QUESTION_POLL_INTERVAL_MS,
36367
37541
  DEFAULT_QUESTION_TIMEOUT_MS,
36368
37542
  DERIVATIVE_ERROR_CODES,
36369
37543
  DERIVATIVE_QUESTIONS_PATH,
36370
37544
  DERIVATIVE_STATUS_PATH,
36371
37545
  DataFileEnvelopeSchema,
36372
- DataPointDeletedError,
36373
- DataPointNotFoundError,
36374
37546
  DataPointStatus,
36375
- DataPointVersionConflictError,
36376
- DerivativeComputeUnavailableError,
36377
- DerivativeCycleError,
36378
- DerivativeDerivedScopeRequiredError,
36379
37547
  DerivativeErrorCodeSchema,
36380
- DerivativeQuestionFailedError,
36381
- DerivativeQuestionInvalidError,
36382
- DerivativeQuestionNotFoundError,
36383
- DerivativeQuestionRejectedError,
36384
37548
  DerivativeQuestionSchema,
36385
- DerivativeQuestionTimeoutError,
36386
- DerivativeSourceNotGrantedError,
36387
37549
  DerivativeStatusSchema,
36388
37550
  DropboxStorage,
36389
37551
  ECIESError,
37552
+ ENCLAVE_IDENTITY_EVIDENCE_VERSION,
37553
+ ENCLAVE_TRUST_ANCHORS,
37554
+ ENCLAVE_WALLET_PURPOSE,
36390
37555
  ESCROW_DEPOSIT_ABI,
36391
37556
  ExpiredTokenError,
36392
37557
  FEE_REGISTRY_ABI,
@@ -36397,28 +37562,36 @@ async function parsePSError(response) {
36397
37562
  GoogleDriveStorage,
36398
37563
  InMemoryTokenStore,
36399
37564
  IngestResponseSchema,
36400
- InvalidConfigurationError,
36401
37565
  InvalidScopeEntryError,
36402
37566
  InvalidSignatureError,
36403
37567
  IpfsStorage,
37568
+ JOB_OPERATIONS,
37569
+ JOB_PROTOCOL_VERSION,
37570
+ JOB_RESULT_CHUNK_BYTES,
37571
+ JOB_RESULT_FORMAT_VERSION,
37572
+ JOB_STATES,
37573
+ JobEnvelopeError,
36404
37574
  LINEAGE_FIELD,
36405
37575
  LINEAGE_KEY,
36406
37576
  LineageEntrySchema,
36407
37577
  LineageGraphSchema,
36408
37578
  LineageNodeSchema,
36409
- LineageReadError,
36410
37579
  MASTER_KEY_MESSAGE,
37580
+ MASTER_SIGNATURE_DELIVERY_MAX_AGE_SECONDS,
37581
+ MASTER_SIGNATURE_DELIVERY_VERSION,
37582
+ MAX_ATTEMPTS,
37583
+ MAX_JOB_DEADLINE_SECONDS,
37584
+ MAX_LEASE_SECONDS,
36411
37585
  MAX_LINEAGE_SOURCES,
36412
37586
  MAX_QUESTION_CHARS,
36413
37587
  MAX_QUESTION_MODEL_CHARS,
36414
37588
  MAX_QUESTION_SOURCE_SCOPES,
37589
+ MAX_WAIT_SECONDS,
36415
37590
  MissingAuthError,
36416
37591
  NATIVE_ASSET_ADDRESS,
36417
37592
  NATIVE_VANA_ASSET,
36418
- NetworkError,
36419
37593
  NodeECIESProvider,
36420
37594
  NodePlatformAdapter,
36421
- NonceError,
36422
37595
  OAuthClient,
36423
37596
  PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX,
36424
37597
  PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE,
@@ -36428,9 +37601,6 @@ async function parsePSError(response) {
36428
37601
  PKCE_CHALLENGE_PATTERN,
36429
37602
  PKCE_VERIFIER_PATTERN,
36430
37603
  PSError,
36431
- PermissionError,
36432
- PersonalServerError,
36433
- PersonalServerWriteError,
36434
37604
  PinataStorage,
36435
37605
  QUESTION_STATUSES,
36436
37606
  QuestionDeleteResultSchema,
@@ -36441,24 +37611,18 @@ async function parsePSError(response) {
36441
37611
  RECORD_DATA_ACCESS_TYPES,
36442
37612
  REGISTRATION_KIND_FOR_OP,
36443
37613
  RESERVED_WRITE_KEYS,
36444
- ReadOnlyError,
36445
37614
  RedactedLineageNodeSchema,
36446
- RelayerError,
36447
37615
  SCOPE_ACTIONS,
37616
+ SEALED_ENVELOPE_VERSION,
36448
37617
  SERVER_REGISTRATION_TYPES,
36449
37618
  ScopeSchema,
36450
- SerializationError,
36451
- ServerUrlMismatchError,
36452
- SignatureError,
36453
37619
  StorageError,
36454
37620
  StorageManager,
36455
37621
  TOMBSTONE_DATA_HASH,
36456
37622
  TOMBSTONE_DATA_HASH_PREIMAGE,
36457
37623
  TOMBSTONE_METADATA_HASH,
36458
37624
  TOMBSTONE_METADATA_HASH_PREIMAGE,
36459
- TransactionPendingError,
36460
- UserRejectedRequestError,
36461
- VanaError,
37625
+ USER_PS_ID_DOMAIN,
36462
37626
  VanaStorage,
36463
37627
  WRITER_ATTRIBUTION_KEY,
36464
37628
  WRITE_CONTENT_DISPOSITION_HEADER,
@@ -36466,15 +37630,7 @@ async function parsePSError(response) {
36466
37630
  WRITE_METADATA_HEADER,
36467
37631
  WRITE_SESSION_PATH,
36468
37632
  WRITE_SIGNATURE_HEADER,
36469
- WriteConflictError,
36470
- WriteForbiddenError,
36471
- WriteLineageError,
36472
- WriteRejectedError,
36473
- WriteRequestError,
36474
- WriteSessionError,
36475
- WriteSessionExpiredError,
36476
- WriteTransportError,
36477
- WriteUnauthorizedError,
37633
+ appRootPreimage,
36478
37634
  askPersonalServer,
36479
37635
  assertDerivedScopeNaming,
36480
37636
  assertValidPkceVerifier,
@@ -36488,6 +37644,7 @@ async function parsePSError(response) {
36488
37644
  buildEscrowPaymentHeader,
36489
37645
  buildGrantPaymentHeader,
36490
37646
  buildMarkDataPointUnavailableRequest,
37647
+ buildMasterSignatureDelivery,
36491
37648
  buildPersonalServerDataReadRequest,
36492
37649
  buildPersonalServerLiteOwnerBindingMessage,
36493
37650
  buildPersonalServerLiteOwnerBindingSignature,
@@ -36496,6 +37653,7 @@ async function parsePSError(response) {
36496
37653
  buildSetDataPointStatusRequest,
36497
37654
  buildWeb3SignedHeader,
36498
37655
  builderRegistrationDomain,
37656
+ canonicalJobRequestBytes,
36499
37657
  chains,
36500
37658
  clearContractCache,
36501
37659
  computeBodyHash,
@@ -36507,6 +37665,7 @@ async function parsePSError(response) {
36507
37665
  createDefaultNonceSource,
36508
37666
  createEscrowGatewayClient,
36509
37667
  createGatewayClient,
37668
+ createJobsClient,
36510
37669
  createNodePlatformAdapter,
36511
37670
  createPlatformAdapter,
36512
37671
  createPlatformAdapterFor,
@@ -36531,6 +37690,7 @@ async function parsePSError(response) {
36531
37690
  encodeDepositTokenData,
36532
37691
  encodeSetDataPointStatusData,
36533
37692
  encodeWriteMetadataHeader,
37693
+ encryptMasterSignatureDelivery,
36534
37694
  encryptWithPassword,
36535
37695
  escrowContractAddress,
36536
37696
  escrowPaymentDomain,
@@ -36565,12 +37725,16 @@ async function parsePSError(response) {
36565
37725
  isPlatformSupported,
36566
37726
  isRedactedLineageNode,
36567
37727
  isTombstoneHashes,
37728
+ kmsIssuedPreimage,
36568
37729
  listQuestions,
36569
37730
  mainnetServices,
36570
37731
  moksha,
36571
37732
  mokshaServices,
36572
37733
  mokshaTestnet,
36573
37734
  normalizeBinaryMimeType,
37735
+ openJobRequest,
37736
+ openJobResult,
37737
+ openJobResultStream,
36574
37738
  openWriteSession,
36575
37739
  parsePSError,
36576
37740
  parsePersonalServerPaymentRequired,
@@ -36594,6 +37758,9 @@ async function parsePSError(response) {
36594
37758
  scopeMatchesPattern,
36595
37759
  scopeNamespace,
36596
37760
  scopeToPathSegments,
37761
+ sealJobRequest,
37762
+ sealJobResult,
37763
+ sealJobResultStream,
36597
37764
  serializeECIES,
36598
37765
  serverRegistrationDomain,
36599
37766
  sessionCoversScope,
@@ -36604,13 +37771,16 @@ async function parsePSError(response) {
36604
37771
  toDirectPaymentReceipt,
36605
37772
  tombstoneDeletedAt,
36606
37773
  tryGrantPermissions,
37774
+ userPsId,
36607
37775
  vanaMainnet,
37776
+ verifyEnclaveIdentityEvidence,
36608
37777
  verifyGrantRegistration,
36609
37778
  verifyPkceChallenge,
36610
37779
  verifyWeb3Signed,
36611
37780
  waitForDerivativeStatus,
36612
37781
  waitForQuestion,
36613
37782
  writeData,
36614
- writePersonalServerData
37783
+ writePersonalServerData,
37784
+ ...require("./errors.cjs")
36615
37785
  });
36616
37786
  //# sourceMappingURL=index.node.cjs.map