@opendatalabs/vana-sdk 3.20.1 → 3.22.0-pr.207.0a5d07b

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 (69) hide show
  1. package/README.md +64 -0
  2. package/dist/crypto/envelope/job.cjs +263 -0
  3. package/dist/crypto/envelope/job.cjs.map +1 -0
  4. package/dist/crypto/envelope/job.d.ts +122 -0
  5. package/dist/crypto/envelope/job.js +240 -0
  6. package/dist/crypto/envelope/job.js.map +1 -0
  7. package/dist/direct/access-request-client.cjs +100 -2
  8. package/dist/direct/access-request-client.cjs.map +1 -1
  9. package/dist/direct/access-request-client.d.ts +23 -1
  10. package/dist/direct/access-request-client.js +98 -1
  11. package/dist/direct/access-request-client.js.map +1 -1
  12. package/dist/direct/controller.cjs +4 -0
  13. package/dist/direct/controller.cjs.map +1 -1
  14. package/dist/direct/controller.d.ts +10 -1
  15. package/dist/direct/controller.js +6 -1
  16. package/dist/direct/controller.js.map +1 -1
  17. package/dist/direct/types.cjs.map +1 -1
  18. package/dist/direct/types.d.ts +45 -0
  19. package/dist/direct/types.js.map +1 -1
  20. package/dist/errors.cjs +77 -0
  21. package/dist/errors.cjs.map +1 -1
  22. package/dist/errors.d.ts +123 -0
  23. package/dist/errors.js +67 -0
  24. package/dist/errors.js.map +1 -1
  25. package/dist/index.browser.d.ts +5 -1
  26. package/dist/index.browser.js +721 -24
  27. package/dist/index.browser.js.map +4 -4
  28. package/dist/index.node.cjs +1309 -107
  29. package/dist/index.node.cjs.map +4 -4
  30. package/dist/index.node.d.ts +6 -1
  31. package/dist/index.node.js +1261 -97
  32. package/dist/index.node.js.map +4 -4
  33. package/dist/protocol/derivative-questions.cjs +22 -0
  34. package/dist/protocol/derivative-questions.cjs.map +1 -1
  35. package/dist/protocol/derivative-questions.d.ts +53 -0
  36. package/dist/protocol/derivative-questions.js +19 -0
  37. package/dist/protocol/derivative-questions.js.map +1 -1
  38. package/dist/protocol/derivative-status.cjs +209 -0
  39. package/dist/protocol/derivative-status.cjs.map +1 -0
  40. package/dist/protocol/derivative-status.d.ts +196 -0
  41. package/dist/protocol/derivative-status.js +190 -0
  42. package/dist/protocol/derivative-status.js.map +1 -0
  43. package/dist/protocol/derivative-status.test.d.ts +1 -0
  44. package/dist/protocol/identity.cjs +219 -0
  45. package/dist/protocol/identity.cjs.map +1 -0
  46. package/dist/protocol/identity.d.ts +193 -0
  47. package/dist/protocol/identity.js +183 -0
  48. package/dist/protocol/identity.js.map +1 -0
  49. package/dist/protocol/identity.test.d.ts +1 -0
  50. package/dist/protocol/identity.vector.test.d.ts +1 -0
  51. package/dist/protocol/jobs-client.cjs +493 -0
  52. package/dist/protocol/jobs-client.cjs.map +1 -0
  53. package/dist/protocol/jobs-client.d.ts +167 -0
  54. package/dist/protocol/jobs-client.js +498 -0
  55. package/dist/protocol/jobs-client.js.map +1 -0
  56. package/dist/protocol/jobs-client.test.d.ts +1 -0
  57. package/dist/protocol/jobs.cjs +67 -0
  58. package/dist/protocol/jobs.cjs.map +1 -0
  59. package/dist/protocol/jobs.d.ts +185 -0
  60. package/dist/protocol/jobs.js +33 -0
  61. package/dist/protocol/jobs.js.map +1 -0
  62. package/dist/protocol/jobs.test.d.ts +1 -0
  63. package/dist/server.cjs +4 -2
  64. package/dist/server.cjs.map +1 -1
  65. package/dist/server.d.ts +2 -2
  66. package/dist/server.js +4 -2
  67. package/dist/server.js.map +1 -1
  68. package/dist/tests/mock-personal-server.d.ts +9 -0
  69. package/package.json +7 -1
@@ -1180,15 +1180,23 @@ __export(index_node_exports, {
1180
1180
  BUILDER_REGISTRATION_TYPES: () => BUILDER_REGISTRATION_TYPES,
1181
1181
  BlockchainError: () => BlockchainError,
1182
1182
  BrowserPlatformAdapter: () => BrowserPlatformAdapter,
1183
+ BuilderUnknownError: () => BuilderUnknownError,
1184
+ CLAIM_POLL_FLOOR_MS: () => CLAIM_POLL_FLOOR_MS,
1183
1185
  CONTRACTS: () => CONTRACTS,
1184
1186
  CallbackStorage: () => CallbackStorage,
1185
1187
  ContractFactory: () => ContractFactory,
1186
1188
  ContractNotFoundError: () => ContractNotFoundError,
1187
1189
  DATA_ACCESS_OP_TYPE: () => DATA_ACCESS_OP_TYPE,
1188
1190
  DATA_REGISTRY_STATUS_ABI: () => DATA_REGISTRY_STATUS_ABI,
1191
+ DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS: () => DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS,
1192
+ DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS: () => DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS,
1193
+ DEFAULT_JOB_DEADLINE_SECONDS: () => DEFAULT_JOB_DEADLINE_SECONDS,
1194
+ DEFAULT_LEASE_SECONDS: () => DEFAULT_LEASE_SECONDS,
1189
1195
  DEFAULT_QUESTION_POLL_INTERVAL_MS: () => DEFAULT_QUESTION_POLL_INTERVAL_MS,
1190
1196
  DEFAULT_QUESTION_TIMEOUT_MS: () => DEFAULT_QUESTION_TIMEOUT_MS,
1197
+ DERIVATIVE_ERROR_CODES: () => DERIVATIVE_ERROR_CODES,
1191
1198
  DERIVATIVE_QUESTIONS_PATH: () => DERIVATIVE_QUESTIONS_PATH,
1199
+ DERIVATIVE_STATUS_PATH: () => DERIVATIVE_STATUS_PATH,
1192
1200
  DataFileEnvelopeSchema: () => DataFileEnvelopeSchema,
1193
1201
  DataPointDeletedError: () => DataPointDeletedError,
1194
1202
  DataPointNotFoundError: () => DataPointNotFoundError,
@@ -1197,6 +1205,7 @@ __export(index_node_exports, {
1197
1205
  DerivativeComputeUnavailableError: () => DerivativeComputeUnavailableError,
1198
1206
  DerivativeCycleError: () => DerivativeCycleError,
1199
1207
  DerivativeDerivedScopeRequiredError: () => DerivativeDerivedScopeRequiredError,
1208
+ DerivativeErrorCodeSchema: () => DerivativeErrorCodeSchema,
1200
1209
  DerivativeQuestionFailedError: () => DerivativeQuestionFailedError,
1201
1210
  DerivativeQuestionInvalidError: () => DerivativeQuestionInvalidError,
1202
1211
  DerivativeQuestionNotFoundError: () => DerivativeQuestionNotFoundError,
@@ -1204,8 +1213,12 @@ __export(index_node_exports, {
1204
1213
  DerivativeQuestionSchema: () => DerivativeQuestionSchema,
1205
1214
  DerivativeQuestionTimeoutError: () => DerivativeQuestionTimeoutError,
1206
1215
  DerivativeSourceNotGrantedError: () => DerivativeSourceNotGrantedError,
1216
+ DerivativeStatusSchema: () => DerivativeStatusSchema,
1207
1217
  DropboxStorage: () => DropboxStorage,
1208
1218
  ECIESError: () => ECIESError,
1219
+ ENCLAVE_IDENTITY_EVIDENCE_VERSION: () => ENCLAVE_IDENTITY_EVIDENCE_VERSION,
1220
+ ENCLAVE_TRUST_ANCHORS: () => ENCLAVE_TRUST_ANCHORS,
1221
+ ENCLAVE_WALLET_PURPOSE: () => ENCLAVE_WALLET_PURPOSE,
1209
1222
  ESCROW_DEPOSIT_ABI: () => ESCROW_DEPOSIT_ABI2,
1210
1223
  ExpiredTokenError: () => ExpiredTokenError,
1211
1224
  FEE_REGISTRY_ABI: () => FEE_REGISTRY_ABI,
@@ -1214,12 +1227,24 @@ __export(index_node_exports, {
1214
1227
  GRANT_REGISTRATION_TYPES: () => GRANT_REGISTRATION_TYPES,
1215
1228
  GRANT_REVOCATION_TYPES: () => GRANT_REVOCATION_TYPES,
1216
1229
  GoogleDriveStorage: () => GoogleDriveStorage,
1230
+ GrantInvalidError: () => GrantInvalidError,
1217
1231
  InMemoryTokenStore: () => InMemoryTokenStore,
1218
1232
  IngestResponseSchema: () => IngestResponseSchema,
1219
1233
  InvalidConfigurationError: () => InvalidConfigurationError,
1220
1234
  InvalidScopeEntryError: () => InvalidScopeEntryError,
1221
1235
  InvalidSignatureError: () => InvalidSignatureError,
1222
1236
  IpfsStorage: () => IpfsStorage,
1237
+ JOB_OPERATIONS: () => JOB_OPERATIONS,
1238
+ JOB_PROTOCOL_VERSION: () => JOB_PROTOCOL_VERSION,
1239
+ JOB_STATES: () => JOB_STATES,
1240
+ JobEnvelopeError: () => JobEnvelopeError,
1241
+ JobIdTakenError: () => JobIdTakenError,
1242
+ JobNotFoundError: () => JobNotFoundError,
1243
+ JobRejectedError: () => JobRejectedError,
1244
+ JobRequestTooLargeError: () => JobRequestTooLargeError,
1245
+ JobTimeoutError: () => JobTimeoutError,
1246
+ JobTransportError: () => JobTransportError,
1247
+ JobsClientError: () => JobsClientError,
1223
1248
  LINEAGE_FIELD: () => LINEAGE_FIELD,
1224
1249
  LINEAGE_KEY: () => LINEAGE_KEY,
1225
1250
  LineageEntrySchema: () => LineageEntrySchema,
@@ -1227,10 +1252,17 @@ __export(index_node_exports, {
1227
1252
  LineageNodeSchema: () => LineageNodeSchema,
1228
1253
  LineageReadError: () => LineageReadError,
1229
1254
  MASTER_KEY_MESSAGE: () => MASTER_KEY_MESSAGE,
1255
+ MASTER_SIGNATURE_DELIVERY_MAX_AGE_SECONDS: () => MASTER_SIGNATURE_DELIVERY_MAX_AGE_SECONDS,
1256
+ MASTER_SIGNATURE_DELIVERY_VERSION: () => MASTER_SIGNATURE_DELIVERY_VERSION,
1257
+ MAX_ATTEMPTS: () => MAX_ATTEMPTS,
1258
+ MAX_INLINE_RESULT_BYTES: () => MAX_INLINE_RESULT_BYTES,
1259
+ MAX_JOB_DEADLINE_SECONDS: () => MAX_JOB_DEADLINE_SECONDS,
1260
+ MAX_LEASE_SECONDS: () => MAX_LEASE_SECONDS,
1230
1261
  MAX_LINEAGE_SOURCES: () => MAX_LINEAGE_SOURCES,
1231
1262
  MAX_QUESTION_CHARS: () => MAX_QUESTION_CHARS,
1232
1263
  MAX_QUESTION_MODEL_CHARS: () => MAX_QUESTION_MODEL_CHARS,
1233
1264
  MAX_QUESTION_SOURCE_SCOPES: () => MAX_QUESTION_SOURCE_SCOPES,
1265
+ MAX_WAIT_SECONDS: () => MAX_WAIT_SECONDS,
1234
1266
  MissingAuthError: () => MissingAuthError,
1235
1267
  NATIVE_ASSET_ADDRESS: () => NATIVE_ASSET_ADDRESS,
1236
1268
  NATIVE_VANA_ASSET: () => NATIVE_VANA_ASSET,
@@ -1239,6 +1271,7 @@ __export(index_node_exports, {
1239
1271
  NodePlatformAdapter: () => NodePlatformAdapter,
1240
1272
  NonceError: () => NonceError,
1241
1273
  OAuthClient: () => OAuthClient,
1274
+ OwnerNotReadyError: () => OwnerNotReadyError,
1242
1275
  PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX: () => PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX,
1243
1276
  PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE: () => PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE,
1244
1277
  PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION: () => PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION,
@@ -1264,6 +1297,7 @@ __export(index_node_exports, {
1264
1297
  RedactedLineageNodeSchema: () => RedactedLineageNodeSchema,
1265
1298
  RelayerError: () => RelayerError,
1266
1299
  SCOPE_ACTIONS: () => SCOPE_ACTIONS,
1300
+ SEALED_ENVELOPE_VERSION: () => SEALED_ENVELOPE_VERSION,
1267
1301
  SERVER_REGISTRATION_TYPES: () => SERVER_REGISTRATION_TYPES,
1268
1302
  ScopeSchema: () => ScopeSchema,
1269
1303
  SerializationError: () => SerializationError,
@@ -1276,6 +1310,7 @@ __export(index_node_exports, {
1276
1310
  TOMBSTONE_METADATA_HASH: () => TOMBSTONE_METADATA_HASH,
1277
1311
  TOMBSTONE_METADATA_HASH_PREIMAGE: () => TOMBSTONE_METADATA_HASH_PREIMAGE,
1278
1312
  TransactionPendingError: () => TransactionPendingError,
1313
+ USER_PS_ID_DOMAIN: () => USER_PS_ID_DOMAIN,
1279
1314
  UserRejectedRequestError: () => UserRejectedRequestError,
1280
1315
  VanaError: () => VanaError,
1281
1316
  VanaStorage: () => VanaStorage,
@@ -1294,6 +1329,7 @@ __export(index_node_exports, {
1294
1329
  WriteSessionExpiredError: () => WriteSessionExpiredError,
1295
1330
  WriteTransportError: () => WriteTransportError,
1296
1331
  WriteUnauthorizedError: () => WriteUnauthorizedError,
1332
+ appRootPreimage: () => appRootPreimage,
1297
1333
  askPersonalServer: () => askPersonalServer,
1298
1334
  assertDerivedScopeNaming: () => assertDerivedScopeNaming,
1299
1335
  assertValidPkceVerifier: () => assertValidPkceVerifier,
@@ -1307,6 +1343,7 @@ __export(index_node_exports, {
1307
1343
  buildEscrowPaymentHeader: () => buildEscrowPaymentHeader,
1308
1344
  buildGrantPaymentHeader: () => buildGrantPaymentHeader,
1309
1345
  buildMarkDataPointUnavailableRequest: () => buildMarkDataPointUnavailableRequest,
1346
+ buildMasterSignatureDelivery: () => buildMasterSignatureDelivery,
1310
1347
  buildPersonalServerDataReadRequest: () => buildPersonalServerDataReadRequest,
1311
1348
  buildPersonalServerLiteOwnerBindingMessage: () => buildPersonalServerLiteOwnerBindingMessage,
1312
1349
  buildPersonalServerLiteOwnerBindingSignature: () => buildPersonalServerLiteOwnerBindingSignature,
@@ -1315,6 +1352,7 @@ __export(index_node_exports, {
1315
1352
  buildSetDataPointStatusRequest: () => buildSetDataPointStatusRequest,
1316
1353
  buildWeb3SignedHeader: () => buildWeb3SignedHeader,
1317
1354
  builderRegistrationDomain: () => builderRegistrationDomain,
1355
+ canonicalJobRequestBytes: () => canonicalJobRequestBytes,
1318
1356
  chains: () => chains,
1319
1357
  clearContractCache: () => clearContractCache,
1320
1358
  computeBodyHash: () => computeBodyHash,
@@ -1326,6 +1364,7 @@ __export(index_node_exports, {
1326
1364
  createDefaultNonceSource: () => createDefaultNonceSource,
1327
1365
  createEscrowGatewayClient: () => createEscrowGatewayClient,
1328
1366
  createGatewayClient: () => createGatewayClient,
1367
+ createJobsClient: () => createJobsClient,
1329
1368
  createNodePlatformAdapter: () => createNodePlatformAdapter,
1330
1369
  createPlatformAdapter: () => createPlatformAdapter,
1331
1370
  createPlatformAdapterFor: () => createPlatformAdapterFor,
@@ -1339,6 +1378,7 @@ __export(index_node_exports, {
1339
1378
  decryptWithPassword: () => decryptWithPassword,
1340
1379
  deleteDataPoint: () => deleteDataPoint,
1341
1380
  deleteQuestion: () => deleteQuestion,
1381
+ derivativeStatusTarget: () => derivativeStatusTarget,
1342
1382
  deriveDataPointId: () => deriveDataPointId,
1343
1383
  deriveMasterKey: () => deriveMasterKey,
1344
1384
  deriveScopeKey: () => deriveScopeKey,
@@ -1349,6 +1389,7 @@ __export(index_node_exports, {
1349
1389
  encodeDepositTokenData: () => encodeDepositTokenData,
1350
1390
  encodeSetDataPointStatusData: () => encodeSetDataPointStatusData,
1351
1391
  encodeWriteMetadataHeader: () => encodeWriteMetadataHeader,
1392
+ encryptMasterSignatureDelivery: () => encryptMasterSignatureDelivery,
1352
1393
  encryptWithPassword: () => encryptWithPassword,
1353
1394
  escrowContractAddress: () => escrowContractAddress,
1354
1395
  escrowPaymentDomain: () => escrowPaymentDomain,
@@ -1362,6 +1403,7 @@ __export(index_node_exports, {
1362
1403
  getContractAddress: () => getContractAddress,
1363
1404
  getContractController: () => getContractController,
1364
1405
  getContractInfo: () => getContractInfo,
1406
+ getDerivativeStatus: () => getDerivativeStatus,
1365
1407
  getFee: () => getFee,
1366
1408
  getGatewayLineage: () => getGatewayLineage,
1367
1409
  getLineage: () => getLineage,
@@ -1377,16 +1419,20 @@ __export(index_node_exports, {
1377
1419
  isDataPointId: () => isDataPointId,
1378
1420
  isDataPointTombstone: () => isDataPointTombstone,
1379
1421
  isDataPortabilityGatewayConfig: () => isDataPortabilityGatewayConfig,
1422
+ isDerivativeStatusSettled: () => isDerivativeStatusSettled,
1380
1423
  isECIESEncrypted: () => isECIESEncrypted,
1381
1424
  isPlatformSupported: () => isPlatformSupported,
1382
1425
  isRedactedLineageNode: () => isRedactedLineageNode,
1383
1426
  isTombstoneHashes: () => isTombstoneHashes,
1427
+ kmsIssuedPreimage: () => kmsIssuedPreimage,
1384
1428
  listQuestions: () => listQuestions,
1385
1429
  mainnetServices: () => mainnetServices,
1386
1430
  moksha: () => moksha,
1387
1431
  mokshaServices: () => mokshaServices,
1388
1432
  mokshaTestnet: () => mokshaTestnet2,
1389
1433
  normalizeBinaryMimeType: () => normalizeBinaryMimeType,
1434
+ openJobRequest: () => openJobRequest,
1435
+ openJobResult: () => openJobResult,
1390
1436
  openWriteSession: () => openWriteSession,
1391
1437
  parsePSError: () => parsePSError,
1392
1438
  parsePersonalServerPaymentRequired: () => parsePersonalServerPaymentRequired,
@@ -1410,6 +1456,8 @@ __export(index_node_exports, {
1410
1456
  scopeMatchesPattern: () => scopeMatchesPattern,
1411
1457
  scopeNamespace: () => scopeNamespace,
1412
1458
  scopeToPathSegments: () => scopeToPathSegments,
1459
+ sealJobRequest: () => sealJobRequest,
1460
+ sealJobResult: () => sealJobResult,
1413
1461
  serializeECIES: () => serializeECIES,
1414
1462
  serverRegistrationDomain: () => serverRegistrationDomain,
1415
1463
  sessionCoversScope: () => sessionCoversScope,
@@ -1420,10 +1468,13 @@ __export(index_node_exports, {
1420
1468
  toDirectPaymentReceipt: () => toDirectPaymentReceipt,
1421
1469
  tombstoneDeletedAt: () => tombstoneDeletedAt,
1422
1470
  tryGrantPermissions: () => tryGrantPermissions,
1471
+ userPsId: () => userPsId,
1423
1472
  vanaMainnet: () => vanaMainnet2,
1473
+ verifyEnclaveIdentityEvidence: () => verifyEnclaveIdentityEvidence,
1424
1474
  verifyGrantRegistration: () => verifyGrantRegistration,
1425
1475
  verifyPkceChallenge: () => verifyPkceChallenge,
1426
1476
  verifyWeb3Signed: () => verifyWeb3Signed,
1477
+ waitForDerivativeStatus: () => waitForDerivativeStatus,
1427
1478
  waitForQuestion: () => waitForQuestion,
1428
1479
  writeData: () => writeData,
1429
1480
  writePersonalServerData: () => writePersonalServerData
@@ -1630,6 +1681,63 @@ var WriteRejectedError = class extends PersonalServerWriteError {
1630
1681
  super(message, "WRITE_REJECTED", status, errorCode, details);
1631
1682
  }
1632
1683
  };
1684
+ var JobsClientError = class extends VanaError {
1685
+ constructor(message, code, status, errorCode = null, details) {
1686
+ super(message, code);
1687
+ this.status = status;
1688
+ this.errorCode = errorCode;
1689
+ this.details = details;
1690
+ }
1691
+ status;
1692
+ errorCode;
1693
+ details;
1694
+ };
1695
+ var BuilderUnknownError = class extends JobsClientError {
1696
+ constructor(message, details) {
1697
+ super(message, "JOB_BUILDER_UNKNOWN", 403, "BUILDER_UNKNOWN", details);
1698
+ }
1699
+ };
1700
+ var GrantInvalidError = class extends JobsClientError {
1701
+ constructor(message, details) {
1702
+ super(message, "JOB_GRANT_INVALID", 403, "GRANT_INVALID", details);
1703
+ }
1704
+ };
1705
+ var OwnerNotReadyError = class extends JobsClientError {
1706
+ constructor(message, details) {
1707
+ super(message, "JOB_OWNER_NOT_READY", 403, "OWNER_NOT_READY", details);
1708
+ }
1709
+ };
1710
+ var JobIdTakenError = class extends JobsClientError {
1711
+ constructor(message, details) {
1712
+ super(message, "JOB_ID_TAKEN", 409, "JOB_ID_TAKEN", details);
1713
+ }
1714
+ };
1715
+ var JobNotFoundError = class extends JobsClientError {
1716
+ constructor(message, details) {
1717
+ super(message, "JOB_NOT_FOUND", 404, "JOB_NOT_FOUND", details);
1718
+ }
1719
+ };
1720
+ var JobRequestTooLargeError = class extends JobsClientError {
1721
+ constructor(message, errorCode = "BODY_TOO_LARGE", details) {
1722
+ super(message, "JOB_REQUEST_TOO_LARGE", 413, errorCode, details);
1723
+ }
1724
+ };
1725
+ var JobTimeoutError = class extends JobsClientError {
1726
+ constructor(message, details) {
1727
+ super(message, "JOB_TIMEOUT", void 0, null, details);
1728
+ }
1729
+ };
1730
+ var JobRejectedError = class extends JobsClientError {
1731
+ constructor(message, status, errorCode = null, details) {
1732
+ super(message, "JOB_REJECTED", status, errorCode, details);
1733
+ }
1734
+ };
1735
+ var JobTransportError = class extends JobsClientError {
1736
+ constructor(message, cause) {
1737
+ super(message, "JOB_TRANSPORT_ERROR");
1738
+ this.cause = cause;
1739
+ }
1740
+ };
1633
1741
  var LineageReadError = class extends VanaError {
1634
1742
  constructor(message, status, errorCode = null, details) {
1635
1743
  super(message, "LINEAGE_READ_ERROR");
@@ -31618,13 +31726,13 @@ var NodeCryptoAdapter = class {
31618
31726
  */
31619
31727
  async generateKeyPair() {
31620
31728
  try {
31621
- const secp256k14 = import_secp256k12.default;
31729
+ const secp256k15 = import_secp256k12.default;
31622
31730
  let privateKey;
31623
31731
  do {
31624
31732
  privateKey = (0, import_crypto2.randomBytes)(32);
31625
- } while (!secp256k14.privateKeyVerify(privateKey));
31733
+ } while (!secp256k15.privateKeyVerify(privateKey));
31626
31734
  const publicKey = Buffer.from(
31627
- secp256k14.publicKeyCreate(privateKey, true)
31735
+ secp256k15.publicKeyCreate(privateKey, true)
31628
31736
  );
31629
31737
  return {
31630
31738
  privateKey: privateKey.toString("hex"),
@@ -32634,15 +32742,922 @@ var RECORD_DATA_ACCESS_TYPES = {
32634
32742
  ]
32635
32743
  };
32636
32744
 
32637
- // src/protocol/personal-server-registration.ts
32745
+ // src/protocol/identity.ts
32746
+ var secp256k14 = __toESM(require("@noble/secp256k1"), 1);
32638
32747
  var import_viem14 = require("viem");
32748
+ var import_accounts = require("viem/accounts");
32749
+ init_interface();
32750
+ var ENCLAVE_IDENTITY_EVIDENCE_VERSION = 1;
32751
+ var USER_PS_ID_DOMAIN = "vana.ps-enclave.v1";
32752
+ var ENCLAVE_WALLET_PURPOSE = "vana.ps-enclave.wallet.v1";
32753
+ var MASTER_SIGNATURE_DELIVERY_VERSION = "vana.ps-enclave.delivery.v1";
32754
+ var MASTER_SIGNATURE_DELIVERY_MAX_AGE_SECONDS = 600;
32755
+ var SEALED_ENVELOPE_VERSION = 1;
32756
+ var VANA_MAINNET_CHAIN_ID = 1480;
32757
+ var MOKSHA_CHAIN_ID = 14800;
32758
+ var KMS_ISSUED_PREFIX = "dstack-kms-issued";
32759
+ var PREIMAGE_SEPARATOR = ":";
32760
+ var UNCOMPRESSED_PUBLIC_KEY_BYTES = 65;
32761
+ var UNCOMPRESSED_PUBLIC_KEY_PREFIX = "04";
32762
+ var EMPTY_HEX = "0x";
32763
+ function emptyAnchor() {
32764
+ return Object.freeze({
32765
+ kmsRootPubkey: EMPTY_HEX,
32766
+ appIds: Object.freeze([])
32767
+ });
32768
+ }
32769
+ var ENCLAVE_TRUST_ANCHORS = Object.freeze({
32770
+ // filled at fleet provisioning; verify fails closed while empty
32771
+ [VANA_MAINNET_CHAIN_ID]: emptyAnchor(),
32772
+ // filled at fleet provisioning; verify fails closed while empty
32773
+ [MOKSHA_CHAIN_ID]: emptyAnchor()
32774
+ });
32775
+ function userPsId(chainId, ownerAddress) {
32776
+ const packed = (0, import_viem14.encodePacked)(
32777
+ ["string", "uint256", "address"],
32778
+ [USER_PS_ID_DOMAIN, BigInt(chainId), (0, import_viem14.getAddress)(ownerAddress)]
32779
+ );
32780
+ return (0, import_viem14.keccak256)(packed);
32781
+ }
32782
+ function compressPublicKey(publicKey) {
32783
+ return secp256k14.ProjectivePoint.fromHex(
32784
+ (0, import_viem14.fromHex)(publicKey, "bytes")
32785
+ ).toRawBytes(true);
32786
+ }
32787
+ function sameKey(a, b) {
32788
+ return (0, import_viem14.toHex)(compressPublicKey(a)) === (0, import_viem14.toHex)(compressPublicKey(b));
32789
+ }
32790
+ function assertUncompressedKey(publicKey) {
32791
+ const hex = publicKey.slice(2);
32792
+ if (hex.length !== UNCOMPRESSED_PUBLIC_KEY_BYTES * 2 || !hex.startsWith(UNCOMPRESSED_PUBLIC_KEY_PREFIX) || !/^[0-9a-fA-F]+$/.test(hex)) {
32793
+ throw new Error("Public key must be a 65-byte uncompressed secp256k1 key");
32794
+ }
32795
+ }
32796
+ function appRootPreimage(purpose, publicKey) {
32797
+ const keyHex = (0, import_viem14.toHex)(compressPublicKey(publicKey)).slice(2);
32798
+ return (0, import_viem14.keccak256)((0, import_viem14.toBytes)(`${purpose}${PREIMAGE_SEPARATOR}${keyHex}`));
32799
+ }
32800
+ function kmsIssuedPreimage(appId, appRootPublicKey) {
32801
+ const prefix = (0, import_viem14.concat)([
32802
+ (0, import_viem14.toBytes)(`${KMS_ISSUED_PREFIX}${PREIMAGE_SEPARATOR}`),
32803
+ (0, import_viem14.fromHex)(appId, "bytes")
32804
+ ]);
32805
+ const compressed = compressPublicKey(appRootPublicKey);
32806
+ return (0, import_viem14.keccak256)((0, import_viem14.concat)([prefix, compressed]));
32807
+ }
32808
+ async function recoverChainKey(hash, signature, link) {
32809
+ try {
32810
+ return (await (0, import_viem14.recoverPublicKey)({ hash, signature })).toLowerCase();
32811
+ } catch {
32812
+ throw new Error(`Invalid enclave signature chain link ${link}`);
32813
+ }
32814
+ }
32815
+ async function verifyEnclaveIdentityEvidence(evidence, anchors, expected) {
32816
+ if (evidence.v !== ENCLAVE_IDENTITY_EVIDENCE_VERSION) {
32817
+ throw new Error("Unsupported enclave identity evidence version");
32818
+ }
32819
+ if (!Number.isInteger(evidence.epoch) || evidence.epoch < 1) {
32820
+ throw new Error("Invalid enclave identity epoch");
32821
+ }
32822
+ if (evidence.chainId !== expected.chainId) {
32823
+ throw new Error(
32824
+ "Enclave identity chain ID does not match expected chain ID"
32825
+ );
32826
+ }
32827
+ if (!(0, import_viem14.isAddressEqual)(evidence.ownerAddress, expected.ownerAddress)) {
32828
+ throw new Error("Enclave identity owner does not match expected owner");
32829
+ }
32830
+ if (evidence.epoch !== expected.epoch) {
32831
+ throw new Error("Enclave identity epoch does not match expected epoch");
32832
+ }
32833
+ const expectedUserPsId = userPsId(expected.chainId, expected.ownerAddress);
32834
+ if (evidence.userPsId.toLowerCase() !== expectedUserPsId.toLowerCase()) {
32835
+ throw new Error("Enclave userPsId does not match expected identity");
32836
+ }
32837
+ if (evidence.purpose !== ENCLAVE_WALLET_PURPOSE) {
32838
+ throw new Error("Unexpected enclave wallet purpose");
32839
+ }
32840
+ if (anchors.kmsRootPubkey === EMPTY_HEX) {
32841
+ throw new Error("KMS root trust anchor is not provisioned");
32842
+ }
32843
+ assertUncompressedKey(evidence.publicKey);
32844
+ const derivedAddress = (0, import_accounts.publicKeyToAddress)(evidence.publicKey);
32845
+ if ((0, import_viem14.getAddress)(derivedAddress) !== (0, import_viem14.getAddress)(evidence.address)) {
32846
+ throw new Error("Enclave public key does not match its address");
32847
+ }
32848
+ const appRootPublicKey = await recoverChainKey(
32849
+ appRootPreimage(evidence.purpose, evidence.publicKey),
32850
+ evidence.signatureChain[0],
32851
+ 0
32852
+ );
32853
+ const kmsRootPublicKey = await recoverChainKey(
32854
+ kmsIssuedPreimage(evidence.appId, appRootPublicKey),
32855
+ evidence.signatureChain[1],
32856
+ 1
32857
+ );
32858
+ let matchesAnchor;
32859
+ try {
32860
+ matchesAnchor = sameKey(kmsRootPublicKey, anchors.kmsRootPubkey);
32861
+ } catch {
32862
+ throw new Error("KMS root trust anchor is malformed");
32863
+ }
32864
+ if (!matchesAnchor) {
32865
+ throw new Error("KMS root public key does not match the trust anchor");
32866
+ }
32867
+ if ((0, import_viem14.keccak256)(kmsRootPublicKey) !== evidence.kmsRootFingerprint.toLowerCase()) {
32868
+ throw new Error("KMS root fingerprint does not match the evidence");
32869
+ }
32870
+ const appId = evidence.appId.toLowerCase();
32871
+ if (!anchors.appIds.some((allowedAppId) => allowedAppId.toLowerCase() === appId)) {
32872
+ throw new Error("Enclave app ID is not trusted");
32873
+ }
32874
+ }
32875
+ async function buildMasterSignatureDelivery(evidence, masterSignature, now = Math.floor(Date.now() / 1e3)) {
32876
+ deriveMasterKey(masterSignature);
32877
+ const signerAddress = await recoverServerOwner(masterSignature);
32878
+ if (!(0, import_viem14.isAddressEqual)(signerAddress, evidence.ownerAddress)) {
32879
+ throw new Error("Master signature signer does not match evidence owner");
32880
+ }
32881
+ return {
32882
+ v: MASTER_SIGNATURE_DELIVERY_VERSION,
32883
+ userPsId: evidence.userPsId,
32884
+ epoch: evidence.epoch,
32885
+ enclaveAddress: evidence.address,
32886
+ ownerAddress: evidence.ownerAddress,
32887
+ masterSignature,
32888
+ issuedAt: now
32889
+ };
32890
+ }
32891
+ async function encryptMasterSignatureDelivery(delivery, publicKey, ecies) {
32892
+ assertUncompressedKey(publicKey);
32893
+ if (!(0, import_viem14.isAddressEqual)((0, import_accounts.publicKeyToAddress)(publicKey), delivery.enclaveAddress)) {
32894
+ throw new Error(
32895
+ "Public key does not belong to the delivery's enclave address"
32896
+ );
32897
+ }
32898
+ const plaintext = (0, import_viem14.toBytes)(JSON.stringify(delivery));
32899
+ const encrypted = await ecies.encrypt((0, import_viem14.fromHex)(publicKey, "bytes"), plaintext);
32900
+ return `0x${serializeECIES(encrypted)}`;
32901
+ }
32902
+
32903
+ // src/protocol/jobs.ts
32904
+ var JOB_PROTOCOL_VERSION = 1;
32905
+ var JOB_OPERATIONS = ["raw_read", "inference"];
32906
+ var JOB_STATES = [
32907
+ "queued",
32908
+ "claimed",
32909
+ "running",
32910
+ "completed",
32911
+ "failed",
32912
+ "expired",
32913
+ "cancelled"
32914
+ ];
32915
+ var DEFAULT_LEASE_SECONDS = 30;
32916
+ var MAX_LEASE_SECONDS = 300;
32917
+ var MAX_ATTEMPTS = 3;
32918
+ var MAX_WAIT_SECONDS = 25;
32919
+ var CLAIM_POLL_FLOOR_MS = 1e3;
32920
+ var MAX_INLINE_RESULT_BYTES = 1048576;
32921
+ var DEFAULT_JOB_DEADLINE_SECONDS = 600;
32922
+ var MAX_JOB_DEADLINE_SECONDS = 3600;
32923
+
32924
+ // src/protocol/jobs-client.ts
32925
+ var import_node_crypto = require("node:crypto");
32926
+ var import_viem16 = require("viem");
32927
+ var import_accounts2 = require("viem/accounts");
32928
+
32929
+ // src/crypto/envelope/job.ts
32930
+ var import_sha25 = require("@noble/hashes/sha2");
32931
+ var import_viem15 = require("viem");
32932
+ init_interface();
32933
+ var textDecoder = new TextDecoder();
32934
+ var textEncoder = new TextEncoder();
32935
+ var JobEnvelopeError = class extends Error {
32936
+ constructor(message) {
32937
+ super(message);
32938
+ this.name = "JobEnvelopeError";
32939
+ }
32940
+ };
32941
+ function sortJsonKeys(value) {
32942
+ if (Array.isArray(value)) {
32943
+ return value.map(sortJsonKeys);
32944
+ }
32945
+ if (value !== null && typeof value === "object") {
32946
+ return Object.fromEntries(
32947
+ Object.keys(value).sort().map((key) => [
32948
+ key,
32949
+ sortJsonKeys(value[key])
32950
+ ])
32951
+ );
32952
+ }
32953
+ return value;
32954
+ }
32955
+ function canonicalJsonBytes(value) {
32956
+ return textEncoder.encode(JSON.stringify(sortJsonKeys(value)));
32957
+ }
32958
+ function canonicalJobRequestBytes(request) {
32959
+ validateJobRequest(request);
32960
+ return canonicalJsonBytes(request);
32961
+ }
32962
+ function requestPlaintext(envelope) {
32963
+ validateRequestEnvelope(envelope);
32964
+ return canonicalJsonBytes(envelope);
32965
+ }
32966
+ function resultPlaintext(result) {
32967
+ return textEncoder.encode(
32968
+ JSON.stringify({
32969
+ v: result.v,
32970
+ jobId: result.jobId,
32971
+ scope: result.scope,
32972
+ version: result.version,
32973
+ contentType: result.contentType,
32974
+ body: result.body
32975
+ })
32976
+ );
32977
+ }
32978
+ function encryptedBytesToBase64(encrypted) {
32979
+ return toBase64((0, import_viem15.fromHex)(`0x${serializeECIES(encrypted)}`, "bytes"));
32980
+ }
32981
+ function base64ToEncrypted(ciphertext) {
32982
+ return deserializeECIES((0, import_viem15.toHex)(fromBase64(ciphertext)));
32983
+ }
32984
+ function parseObject(plaintext, kind) {
32985
+ try {
32986
+ const value = JSON.parse(textDecoder.decode(plaintext));
32987
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
32988
+ throw new JobEnvelopeError(`Invalid ${kind}: expected an object`);
32989
+ }
32990
+ return value;
32991
+ } catch (error) {
32992
+ if (error instanceof JobEnvelopeError) throw error;
32993
+ throw new JobEnvelopeError(`Invalid ${kind}: malformed JSON`);
32994
+ }
32995
+ }
32996
+ function isPlainObject2(value) {
32997
+ if (value === null || typeof value !== "object") return false;
32998
+ const prototype = Object.getPrototypeOf(value);
32999
+ return prototype === Object.prototype || prototype === null;
33000
+ }
33001
+ function requirePlainObject(value, field, kind) {
33002
+ if (!isPlainObject2(value)) {
33003
+ throw new JobEnvelopeError(`Invalid ${kind}: invalid ${field}`);
33004
+ }
33005
+ }
33006
+ function requireExactKeys(value, expectedKeys, kind) {
33007
+ for (const key of expectedKeys) {
33008
+ if (!Object.hasOwn(value, key) || value[key] === void 0) {
33009
+ throw new JobEnvelopeError(`Invalid ${kind}: missing ${key}`);
33010
+ }
33011
+ }
33012
+ const expected = new Set(expectedKeys);
33013
+ for (const key of Reflect.ownKeys(value)) {
33014
+ if (!expected.has(key)) {
33015
+ throw new JobEnvelopeError(
33016
+ `Invalid ${kind}: unknown field ${String(key)}`
33017
+ );
33018
+ }
33019
+ }
33020
+ }
33021
+ function requireString(value, field, kind) {
33022
+ if (typeof value !== "string" || value.length === 0) {
33023
+ throw new JobEnvelopeError(`Invalid ${kind}: missing ${field}`);
33024
+ }
33025
+ }
33026
+ function validateJobRequest(value) {
33027
+ requirePlainObject(value, "request", "job request");
33028
+ requireExactKeys(
33029
+ value,
33030
+ [
33031
+ "v",
33032
+ "jobId",
33033
+ "owner",
33034
+ "builder",
33035
+ "builderPublicKey",
33036
+ "grantId",
33037
+ "scope",
33038
+ "operation",
33039
+ "pinnedVersion",
33040
+ "deadline"
33041
+ ],
33042
+ "job request"
33043
+ );
33044
+ if (value.v !== JOB_PROTOCOL_VERSION) {
33045
+ throw new JobEnvelopeError(
33046
+ `Unsupported job request version: ${String(value.v)}`
33047
+ );
33048
+ }
33049
+ requireString(value.jobId, "jobId", "job request");
33050
+ if (typeof value.owner !== "string" || !(0, import_viem15.isAddress)(value.owner)) {
33051
+ throw new JobEnvelopeError("Invalid job request: invalid owner");
33052
+ }
33053
+ if (typeof value.builder !== "string" || !(0, import_viem15.isAddress)(value.builder)) {
33054
+ throw new JobEnvelopeError("Invalid job request: invalid builder");
33055
+ }
33056
+ if (typeof value.builderPublicKey !== "string" || !(0, import_viem15.isHex)(value.builderPublicKey)) {
33057
+ throw new JobEnvelopeError("Invalid job request: invalid builderPublicKey");
33058
+ }
33059
+ if (typeof value.grantId !== "string" || !(0, import_viem15.isHex)(value.grantId)) {
33060
+ throw new JobEnvelopeError("Invalid job request: invalid grantId");
33061
+ }
33062
+ requireString(value.scope, "scope", "job request");
33063
+ if (!JOB_OPERATIONS.includes(value.operation)) {
33064
+ throw new JobEnvelopeError("Invalid job request: invalid operation");
33065
+ }
33066
+ if (value.pinnedVersion !== null && typeof value.pinnedVersion !== "string") {
33067
+ throw new JobEnvelopeError("Invalid job request: missing pinnedVersion");
33068
+ }
33069
+ if (typeof value.deadline !== "string" || !Number.isFinite(Date.parse(value.deadline))) {
33070
+ throw new JobEnvelopeError("Invalid job request: invalid deadline");
33071
+ }
33072
+ return value;
33073
+ }
33074
+ function validateRequestEnvelope(value) {
33075
+ requirePlainObject(value, "envelope", "job request envelope");
33076
+ requireExactKeys(value, ["request", "auth"], "job request envelope");
33077
+ validateJobRequest(value.request);
33078
+ requireString(value.auth, "auth", "job request envelope");
33079
+ return value;
33080
+ }
33081
+ function validateResult(value) {
33082
+ requirePlainObject(value, "result", "job result");
33083
+ requireExactKeys(
33084
+ value,
33085
+ ["v", "jobId", "scope", "version", "contentType", "body"],
33086
+ "job result"
33087
+ );
33088
+ if (value.v !== JOB_PROTOCOL_VERSION) {
33089
+ throw new JobEnvelopeError(
33090
+ `Unsupported job result version: ${String(value.v)}`
33091
+ );
33092
+ }
33093
+ for (const field of ["jobId", "scope", "contentType"]) {
33094
+ requireString(value[field], field, "job result");
33095
+ }
33096
+ if (typeof value.body !== "string") {
33097
+ throw new JobEnvelopeError("Invalid job result: missing body");
33098
+ }
33099
+ if (value.version !== null && typeof value.version !== "string") {
33100
+ throw new JobEnvelopeError("Invalid job result: missing version");
33101
+ }
33102
+ return value;
33103
+ }
33104
+ async function sealJobRequest(envelope, enclavePublicKey, ecies) {
33105
+ const encrypted = await ecies.encrypt(
33106
+ (0, import_viem15.fromHex)(enclavePublicKey, "bytes"),
33107
+ requestPlaintext(envelope)
33108
+ );
33109
+ return encryptedBytesToBase64(encrypted);
33110
+ }
33111
+ async function openJobRequest(ciphertext, privateKey, ecies) {
33112
+ const plaintext = await ecies.decrypt(
33113
+ privateKey,
33114
+ base64ToEncrypted(ciphertext)
33115
+ );
33116
+ return validateRequestEnvelope(
33117
+ parseObject(plaintext, "job request envelope")
33118
+ );
33119
+ }
33120
+ async function sealJobResult(result, builderPublicKey, ecies) {
33121
+ validateResult(result);
33122
+ const encrypted = await ecies.encrypt(
33123
+ (0, import_viem15.fromHex)(builderPublicKey, "bytes"),
33124
+ resultPlaintext(result)
33125
+ );
33126
+ const ciphertext = encryptedBytesToBase64(encrypted);
33127
+ const bytes = fromBase64(ciphertext);
33128
+ return { ciphertext, hash: (0, import_viem15.bytesToHex)((0, import_sha25.sha256)(bytes)), size: bytes.length };
33129
+ }
33130
+ async function openJobResult(ciphertext, builderPrivateKey, ecies, expect) {
33131
+ const plaintext = await ecies.decrypt(
33132
+ (0, import_viem15.fromHex)(builderPrivateKey, "bytes"),
33133
+ base64ToEncrypted(ciphertext)
33134
+ );
33135
+ const result = validateResult(parseObject(plaintext, "job result"));
33136
+ if (result.jobId !== expect.jobId) {
33137
+ throw new JobEnvelopeError(
33138
+ `Job result ID ${result.jobId} does not match expected job ID ${expect.jobId}`
33139
+ );
33140
+ }
33141
+ if (expect.scope !== void 0 && result.scope !== expect.scope) {
33142
+ throw new JobEnvelopeError(
33143
+ `Job result scope ${result.scope} does not match expected scope ${expect.scope}`
33144
+ );
33145
+ }
33146
+ if (expect.version !== void 0 && result.version !== expect.version) {
33147
+ throw new JobEnvelopeError(
33148
+ `Job result version ${String(result.version)} does not match expected version ${String(expect.version)}`
33149
+ );
33150
+ }
33151
+ return result;
33152
+ }
33153
+
33154
+ // src/protocol/write-signer.ts
33155
+ function isRecord(value) {
33156
+ return value !== null && typeof value === "object";
33157
+ }
33158
+ function isViemWriteAccount(source) {
33159
+ return isRecord(source) && source.type === "local" && typeof source.address === "string" && typeof source.signMessage === "function";
33160
+ }
33161
+ function isViemWriteWalletClient(source) {
33162
+ return isRecord(source) && typeof source.signMessage === "function" && source.type !== "local" && (source.type === "walletClient" || "transport" in source);
33163
+ }
33164
+ function accountAddress(account) {
33165
+ return typeof account === "string" ? account : account.address;
33166
+ }
33167
+ function resolveWriteSigner(source, options = {}) {
33168
+ if (isViemWriteWalletClient(source)) {
33169
+ const account = options.account ?? source.account;
33170
+ if (account === void 0) {
33171
+ throw new WriteRequestError(
33172
+ "Viem wallet client requires an account option or account property"
33173
+ );
33174
+ }
33175
+ return {
33176
+ address: accountAddress(account),
33177
+ signMessage: (message) => source.signMessage({ account, message })
33178
+ };
33179
+ }
33180
+ if (isViemWriteAccount(source)) {
33181
+ return {
33182
+ address: source.address,
33183
+ signMessage: (message) => source.signMessage({ message })
33184
+ };
33185
+ }
33186
+ if (!isRecord(source) || typeof source.signMessage !== "function") {
33187
+ throw new WriteRequestError(
33188
+ "signer must be a viem LocalAccount, a viem WalletClient, or a { signMessage } object"
33189
+ );
33190
+ }
33191
+ return source;
33192
+ }
33193
+
33194
+ // src/protocol/jobs-client.ts
33195
+ var IDENTITY_PATH = "/v1/identity";
33196
+ var JOBS_PATH = "/v1/jobs";
33197
+ var JOB_EXECUTE_PATH = "/v1/jobs/execute";
33198
+ var AUTHORIZATION_HEADER = "Authorization";
33199
+ var CONTENT_TYPE_HEADER = "Content-Type";
33200
+ var JSON_CONTENT_TYPE = "application/json";
33201
+ var GET_METHOD = "GET";
33202
+ var POST_METHOD = "POST";
33203
+ var RAW_READ_OPERATION = "raw_read";
33204
+ var SEALED_IDENTITY_STATE = "sealed";
33205
+ var HTTP_OK = 200;
33206
+ var HTTP_ACCEPTED = 202;
33207
+ var HTTP_FORBIDDEN = 403;
33208
+ var HTTP_NOT_FOUND = 404;
33209
+ var HTTP_CONFLICT = 409;
33210
+ var HTTP_PAYLOAD_TOO_LARGE = 413;
33211
+ var MILLISECONDS_PER_SECOND = 1e3;
33212
+ var DEFAULT_JOB_TIMEOUT_MS = 12e4;
33213
+ var DEFAULT_JOB_POLL_MS = CLAIM_POLL_FLOOR_MS;
33214
+ var TERMINAL_JOB_STATES = /* @__PURE__ */ new Set([
33215
+ "completed",
33216
+ "failed",
33217
+ "expired",
33218
+ "cancelled"
33219
+ ]);
33220
+ function isRecord2(value) {
33221
+ return value !== null && typeof value === "object" && !Array.isArray(value);
33222
+ }
33223
+ function normalizeGateway(gatewayUrl) {
33224
+ try {
33225
+ const url = new URL(gatewayUrl);
33226
+ if (url.pathname !== "/" || url.search !== "" || url.hash !== "") {
33227
+ throw new JobRejectedError(
33228
+ "gatewayUrl must be an origin without a path, query, or fragment"
33229
+ );
33230
+ }
33231
+ return {
33232
+ baseUrl: url.origin,
33233
+ audience: url.origin
33234
+ };
33235
+ } catch (error) {
33236
+ if (error instanceof JobRejectedError) throw error;
33237
+ throw new JobRejectedError(
33238
+ "gatewayUrl must be an absolute URL",
33239
+ void 0,
33240
+ null,
33241
+ {
33242
+ cause: error instanceof Error ? error.message : String(error)
33243
+ }
33244
+ );
33245
+ }
33246
+ }
33247
+ function resolveFetch(fetchFn) {
33248
+ const resolved = fetchFn ?? globalThis.fetch;
33249
+ if (resolved === void 0) {
33250
+ throw new JobRejectedError("No fetch implementation available");
33251
+ }
33252
+ return resolved;
33253
+ }
33254
+ function sourcePublicKey(source) {
33255
+ if (isRecord2(source) && typeof source["publicKey"] === "string") {
33256
+ return source["publicKey"];
33257
+ }
33258
+ return void 0;
33259
+ }
33260
+ function resolveBuilder(options) {
33261
+ if (options.builderPrivateKey && options.builderAccount) {
33262
+ throw new JobRejectedError(
33263
+ "Provide builderPrivateKey or builderAccount, not both"
33264
+ );
33265
+ }
33266
+ let source;
33267
+ try {
33268
+ source = options.builderPrivateKey ? (0, import_accounts2.privateKeyToAccount)(options.builderPrivateKey) : options.builderAccount;
33269
+ } catch (error) {
33270
+ throw new JobRejectedError("Invalid builder private key", void 0, null, {
33271
+ cause: error instanceof Error ? error.message : String(error)
33272
+ });
33273
+ }
33274
+ if (!source) {
33275
+ throw new JobRejectedError(
33276
+ "builderPrivateKey or builderAccount is required"
33277
+ );
33278
+ }
33279
+ let signer;
33280
+ try {
33281
+ signer = resolveWriteSigner(source);
33282
+ } catch (error) {
33283
+ throw new JobRejectedError("Invalid builder signer", void 0, null, {
33284
+ cause: error instanceof Error ? error.message : String(error)
33285
+ });
33286
+ }
33287
+ const publicKey = sourcePublicKey(source);
33288
+ if (!signer.address || !publicKey) {
33289
+ throw new JobRejectedError(
33290
+ "Builder signer must expose both address and publicKey"
33291
+ );
33292
+ }
33293
+ return {
33294
+ builder: {
33295
+ address: signer.address,
33296
+ publicKey,
33297
+ signMessage: signer.signMessage
33298
+ },
33299
+ ...options.builderPrivateKey ? { privateKey: options.builderPrivateKey } : {}
33300
+ };
33301
+ }
33302
+ function clampInteger(value, fallback, minimum, maximum, field) {
33303
+ const resolved = value ?? fallback;
33304
+ if (!Number.isFinite(resolved)) {
33305
+ throw new JobRejectedError(`${field} must be a finite number`);
33306
+ }
33307
+ return Math.min(maximum, Math.max(minimum, Math.trunc(resolved)));
33308
+ }
33309
+ async function responseBody(response) {
33310
+ try {
33311
+ return await response.json();
33312
+ } catch {
33313
+ return null;
33314
+ }
33315
+ }
33316
+ function gatewayErrorBody(body, fallback) {
33317
+ if (!isRecord2(body)) return { code: null, message: fallback };
33318
+ const code = typeof body["code"] === "string" ? body["code"] : null;
33319
+ const message = typeof body["error"] === "string" ? body["error"] : typeof body["message"] === "string" ? body["message"] : fallback;
33320
+ const details = isRecord2(body["details"]) ? body["details"] : void 0;
33321
+ return { code, message, ...details ? { details } : {} };
33322
+ }
33323
+ async function rejectedResponse(response, fallback) {
33324
+ const parsed = gatewayErrorBody(await responseBody(response), fallback);
33325
+ const details = parsed.details;
33326
+ if (response.status === HTTP_FORBIDDEN) {
33327
+ if (parsed.code === "BUILDER_UNKNOWN") {
33328
+ return new BuilderUnknownError(parsed.message, details);
33329
+ }
33330
+ if (parsed.code === "GRANT_INVALID") {
33331
+ return new GrantInvalidError(parsed.message, details);
33332
+ }
33333
+ if (parsed.code === "OWNER_NOT_READY") {
33334
+ return new OwnerNotReadyError(parsed.message, details);
33335
+ }
33336
+ }
33337
+ if (response.status === HTTP_NOT_FOUND) {
33338
+ return new JobNotFoundError(parsed.message, details);
33339
+ }
33340
+ if (response.status === HTTP_CONFLICT && parsed.code === "JOB_ID_TAKEN") {
33341
+ return new JobIdTakenError(parsed.message, details);
33342
+ }
33343
+ if (response.status === HTTP_PAYLOAD_TOO_LARGE) {
33344
+ return new JobRequestTooLargeError(parsed.message, parsed.code, details);
33345
+ }
33346
+ return new JobRejectedError(
33347
+ parsed.message,
33348
+ response.status,
33349
+ parsed.code,
33350
+ details
33351
+ );
33352
+ }
33353
+ function requireStatus(value, status) {
33354
+ 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"])) {
33355
+ throw new JobRejectedError(
33356
+ "Gateway response did not contain a job status",
33357
+ status
33358
+ );
33359
+ }
33360
+ return value;
33361
+ }
33362
+ function isNonEmptyString(value) {
33363
+ return typeof value === "string" && value.length > 0;
33364
+ }
33365
+ function hasMatchingIdentityKey(value) {
33366
+ const address = value["address"];
33367
+ const publicKey = value["publicKey"];
33368
+ if (typeof address !== "string" || !(0, import_viem16.isAddress)(address) || typeof publicKey !== "string" || !(0, import_viem16.isHex)(publicKey)) {
33369
+ return false;
33370
+ }
33371
+ try {
33372
+ return (0, import_accounts2.publicKeyToAddress)(publicKey).toLowerCase() === address.toLowerCase();
33373
+ } catch {
33374
+ return false;
33375
+ }
33376
+ }
33377
+ function jobDeadline(job) {
33378
+ const candidate = job;
33379
+ for (const field of ["deadlineAt", "deadline"]) {
33380
+ if (typeof candidate[field] === "string") {
33381
+ const parsed = Date.parse(candidate[field]);
33382
+ if (Number.isFinite(parsed)) return parsed;
33383
+ }
33384
+ }
33385
+ return void 0;
33386
+ }
33387
+ function sleep2(ms) {
33388
+ return new Promise((resolve) => setTimeout(resolve, ms));
33389
+ }
33390
+ function requireFiniteDuration(value, field) {
33391
+ if (!Number.isFinite(value)) {
33392
+ throw new JobRejectedError(`${field} must be a finite number`);
33393
+ }
33394
+ return Math.max(0, value);
33395
+ }
33396
+ function createJobsClient(options) {
33397
+ const { baseUrl, audience } = normalizeGateway(options.gatewayUrl);
33398
+ const fetchFn = resolveFetch(options.fetch);
33399
+ const { builder, privateKey } = resolveBuilder(options);
33400
+ const ecies = options.ecies ?? new NodeECIESUint8Provider();
33401
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
33402
+ async function request(url, init, description) {
33403
+ try {
33404
+ return await fetchFn(url, init);
33405
+ } catch (error) {
33406
+ throw new JobTransportError(
33407
+ `${description} failed: ${error instanceof Error ? error.message : String(error)}`,
33408
+ error
33409
+ );
33410
+ }
33411
+ }
33412
+ async function getIdentity(owner) {
33413
+ const query = new URLSearchParams({
33414
+ owner,
33415
+ chainId: String(options.chainId)
33416
+ });
33417
+ const response = await request(
33418
+ `${baseUrl}${IDENTITY_PATH}?${query.toString()}`,
33419
+ { method: GET_METHOD },
33420
+ "Owner identity lookup"
33421
+ );
33422
+ if (!response.ok) {
33423
+ throw await rejectedResponse(response, "Owner identity lookup rejected");
33424
+ }
33425
+ const body = await responseBody(response);
33426
+ if (!isRecord2(body) || body["state"] !== SEALED_IDENTITY_STATE || !isRecord2(body["identity"])) {
33427
+ throw new OwnerNotReadyError("Owner identity is not sealed", {
33428
+ state: isRecord2(body) ? body["state"] : void 0
33429
+ });
33430
+ }
33431
+ if (!hasMatchingIdentityKey(body["identity"])) {
33432
+ throw new JobRejectedError(
33433
+ "Gateway returned a malformed or mismatched owner identity",
33434
+ response.status
33435
+ );
33436
+ }
33437
+ return body["identity"];
33438
+ }
33439
+ const client = {
33440
+ async submitRawRead(params) {
33441
+ const identity = await getIdentity(params.owner);
33442
+ const deadlineSeconds = clampInteger(
33443
+ params.deadlineSeconds,
33444
+ DEFAULT_JOB_DEADLINE_SECONDS,
33445
+ 1,
33446
+ MAX_JOB_DEADLINE_SECONDS,
33447
+ "deadlineSeconds"
33448
+ );
33449
+ const wait = clampInteger(params.wait, 0, 0, MAX_WAIT_SECONDS, "wait");
33450
+ const jobId = (0, import_node_crypto.randomUUID)();
33451
+ const nowMs = now().getTime();
33452
+ if (!Number.isFinite(nowMs)) {
33453
+ throw new JobRejectedError("now must return a valid Date");
33454
+ }
33455
+ const deadline = new Date(
33456
+ nowMs + deadlineSeconds * MILLISECONDS_PER_SECOND
33457
+ ).toISOString();
33458
+ const requestBody = {
33459
+ v: JOB_PROTOCOL_VERSION,
33460
+ jobId,
33461
+ owner: params.owner,
33462
+ builder: builder.address,
33463
+ builderPublicKey: builder.publicKey,
33464
+ grantId: params.grantId,
33465
+ scope: params.scope,
33466
+ operation: RAW_READ_OPERATION,
33467
+ pinnedVersion: params.pinnedVersion ?? null,
33468
+ deadline
33469
+ };
33470
+ const auth = await buildWeb3SignedHeader({
33471
+ signMessage: builder.signMessage,
33472
+ aud: audience,
33473
+ method: POST_METHOD,
33474
+ uri: JOB_EXECUTE_PATH,
33475
+ bodyHash: computeBodyHash(canonicalJobRequestBytes(requestBody)),
33476
+ nonce: (0, import_node_crypto.randomUUID)()
33477
+ });
33478
+ const requestCiphertext = await sealJobRequest(
33479
+ { request: requestBody, auth },
33480
+ identity.publicKey,
33481
+ ecies
33482
+ );
33483
+ const submission = {
33484
+ owner: requestBody.owner,
33485
+ grantId: requestBody.grantId,
33486
+ scope: requestBody.scope,
33487
+ operation: requestBody.operation,
33488
+ idempotencyKey: (0, import_node_crypto.randomUUID)(),
33489
+ jobId,
33490
+ deadline,
33491
+ requestCiphertext
33492
+ };
33493
+ const bodyBytes = new TextEncoder().encode(JSON.stringify(submission));
33494
+ const authorization = await buildWeb3SignedHeader({
33495
+ signMessage: builder.signMessage,
33496
+ aud: audience,
33497
+ method: POST_METHOD,
33498
+ uri: JOBS_PATH,
33499
+ body: bodyBytes,
33500
+ nonce: (0, import_node_crypto.randomUUID)()
33501
+ });
33502
+ const response = await request(
33503
+ `${baseUrl}${JOBS_PATH}?wait=${wait}`,
33504
+ {
33505
+ method: POST_METHOD,
33506
+ headers: {
33507
+ [AUTHORIZATION_HEADER]: authorization,
33508
+ [CONTENT_TYPE_HEADER]: JSON_CONTENT_TYPE
33509
+ },
33510
+ body: bodyBytes
33511
+ },
33512
+ "Job submission"
33513
+ );
33514
+ if (!response.ok) {
33515
+ throw await rejectedResponse(response, "Job submission rejected");
33516
+ }
33517
+ const body = await responseBody(response);
33518
+ if (response.status === HTTP_OK && isRecord2(body)) {
33519
+ const job = requireStatus(body["job"], response.status);
33520
+ if (job.jobId !== jobId) {
33521
+ throw new JobRejectedError(
33522
+ "Gateway returned a job id that does not match the submission",
33523
+ response.status
33524
+ );
33525
+ }
33526
+ return { jobId, state: job.state, job };
33527
+ }
33528
+ if (response.status === HTTP_ACCEPTED && isRecord2(body) && body["jobId"] === jobId && typeof body["state"] === "string" && JOB_STATES.includes(body["state"])) {
33529
+ return { jobId, state: body["state"] };
33530
+ }
33531
+ throw new JobRejectedError(
33532
+ "Gateway returned an undocumented job submission response",
33533
+ response.status
33534
+ );
33535
+ },
33536
+ async getJob(jobId) {
33537
+ const path = `${JOBS_PATH}/${encodeURIComponent(jobId)}`;
33538
+ const authorization = await buildWeb3SignedHeader({
33539
+ signMessage: builder.signMessage,
33540
+ aud: audience,
33541
+ method: GET_METHOD,
33542
+ uri: path,
33543
+ nonce: (0, import_node_crypto.randomUUID)()
33544
+ });
33545
+ const response = await request(
33546
+ `${baseUrl}${path}`,
33547
+ {
33548
+ method: GET_METHOD,
33549
+ headers: { [AUTHORIZATION_HEADER]: authorization }
33550
+ },
33551
+ "Job status read"
33552
+ );
33553
+ if (!response.ok) {
33554
+ throw await rejectedResponse(response, "Job status read rejected");
33555
+ }
33556
+ const body = await responseBody(response);
33557
+ return requireStatus(
33558
+ isRecord2(body) ? body["job"] : void 0,
33559
+ response.status
33560
+ );
33561
+ },
33562
+ async waitForJob(jobId, waitOptions = {}) {
33563
+ const timeoutMs = requireFiniteDuration(
33564
+ waitOptions.timeoutMs ?? DEFAULT_JOB_TIMEOUT_MS,
33565
+ "timeoutMs"
33566
+ );
33567
+ const pollMs = Math.max(
33568
+ CLAIM_POLL_FLOOR_MS,
33569
+ requireFiniteDuration(
33570
+ waitOptions.pollMs ?? DEFAULT_JOB_POLL_MS,
33571
+ "pollMs"
33572
+ )
33573
+ );
33574
+ const startedAt = Date.now();
33575
+ const callerDeadline = startedAt + timeoutMs;
33576
+ let latest;
33577
+ for (; ; ) {
33578
+ if (Date.now() >= callerDeadline || latest && Date.now() >= (jobDeadline(latest) ?? Infinity)) {
33579
+ throw new JobTimeoutError(
33580
+ `Timed out waiting for terminal job ${jobId}`,
33581
+ {
33582
+ jobId,
33583
+ timeoutMs,
33584
+ state: latest?.state
33585
+ }
33586
+ );
33587
+ }
33588
+ latest = await client.getJob(jobId);
33589
+ if (TERMINAL_JOB_STATES.has(latest.state)) return latest;
33590
+ const effectiveDeadline = Math.min(
33591
+ callerDeadline,
33592
+ jobDeadline(latest) ?? Infinity
33593
+ );
33594
+ const remaining = effectiveDeadline - Date.now();
33595
+ if (remaining <= 0) {
33596
+ throw new JobTimeoutError(
33597
+ `Timed out waiting for terminal job ${jobId}`,
33598
+ {
33599
+ jobId,
33600
+ timeoutMs,
33601
+ state: latest.state
33602
+ }
33603
+ );
33604
+ }
33605
+ await sleep2(Math.min(pollMs, remaining));
33606
+ }
33607
+ },
33608
+ async openResult(job, openOptions) {
33609
+ if (!job.resultCiphertext) {
33610
+ throw new JobRejectedError(
33611
+ "Job status does not include inline resultCiphertext",
33612
+ void 0,
33613
+ null,
33614
+ {
33615
+ jobId: job.jobId,
33616
+ state: job.state,
33617
+ resultHandle: job.resultHandle,
33618
+ maxInlineResultBytes: MAX_INLINE_RESULT_BYTES
33619
+ }
33620
+ );
33621
+ }
33622
+ if (!privateKey) {
33623
+ throw new JobRejectedError(
33624
+ "openResult requires createJobsClient({ builderPrivateKey })"
33625
+ );
33626
+ }
33627
+ return openJobResult(
33628
+ job.resultCiphertext,
33629
+ privateKey,
33630
+ ecies,
33631
+ openOptions.expect
33632
+ );
33633
+ },
33634
+ async readRaw(params) {
33635
+ const submitted = await client.submitRawRead(params);
33636
+ const job = submitted.job && TERMINAL_JOB_STATES.has(submitted.job.state) ? submitted.job : await client.waitForJob(submitted.jobId, {
33637
+ timeoutMs: params.timeoutMs,
33638
+ pollMs: params.pollMs
33639
+ });
33640
+ return client.openResult(job, {
33641
+ expect: {
33642
+ jobId: submitted.jobId,
33643
+ scope: params.scope,
33644
+ ...params.pinnedVersion !== void 0 && params.pinnedVersion !== null ? { version: params.pinnedVersion } : {}
33645
+ }
33646
+ });
33647
+ }
33648
+ };
33649
+ return client;
33650
+ }
33651
+
33652
+ // src/protocol/personal-server-registration.ts
33653
+ var import_viem17 = require("viem");
32639
33654
  var PERSONAL_SERVER_REGISTRATION_DEFAULT_CHAIN_ID = vanaMainnet2.id;
32640
33655
  var PERSONAL_SERVER_REGISTRATION_DEFAULT_VERIFYING_CONTRACT = getContractAddress(
32641
33656
  PERSONAL_SERVER_REGISTRATION_DEFAULT_CHAIN_ID,
32642
33657
  "DataPortabilityServers"
32643
33658
  );
32644
33659
  function assertAddress(value, name) {
32645
- if (!(0, import_viem14.isAddress)(value)) {
33660
+ if (!(0, import_viem17.isAddress)(value)) {
32646
33661
  throw new Error(`${name} must be a valid EVM address`);
32647
33662
  }
32648
33663
  }
@@ -32728,12 +33743,12 @@ async function buildPersonalServerRegistrationSignature(input) {
32728
33743
  var registerPersonalServerSignature = buildPersonalServerRegistrationSignature;
32729
33744
 
32730
33745
  // src/personal-server-lite/owner-binding.ts
32731
- var import_viem15 = require("viem");
33746
+ var import_viem18 = require("viem");
32732
33747
  var PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION = "vana.ps-lite.owner-binding.v1";
32733
33748
  var PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE = "ps-lite-owner";
32734
33749
  var PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX = `${PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION}:${PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE}:`;
32735
33750
  function assertAddress2(value, name) {
32736
- if (!(0, import_viem15.isAddress)(value)) {
33751
+ if (!(0, import_viem18.isAddress)(value)) {
32737
33752
  throw new Error(`${name} must be a valid EVM address`);
32738
33753
  }
32739
33754
  }
@@ -32783,7 +33798,7 @@ async function buildPersonalServerLiteOwnerBindingSignature(input) {
32783
33798
  var signPersonalServerLiteOwnerBinding = buildPersonalServerLiteOwnerBindingSignature;
32784
33799
 
32785
33800
  // src/account/personal-server-registration.ts
32786
- var import_viem16 = require("viem");
33801
+ var import_viem19 = require("viem");
32787
33802
  var ACCOUNT_PERSONAL_SERVER_REGISTRATION_INTENT = "personal_server.server_registration.v1";
32788
33803
  var AccountPersonalServerRegistrationError = class extends Error {
32789
33804
  status;
@@ -32802,7 +33817,7 @@ function trimTrailingSlash(value) {
32802
33817
  return value.replace(/\/+$/, "");
32803
33818
  }
32804
33819
  function assertAddress3(value, name) {
32805
- if (!(0, import_viem16.isAddress)(value)) {
33820
+ if (!(0, import_viem19.isAddress)(value)) {
32806
33821
  throw new Error(`${name} must be a valid EVM address`);
32807
33822
  }
32808
33823
  }
@@ -32823,7 +33838,7 @@ function accountErrorMessage(status, body) {
32823
33838
  if (nestedMessage) {
32824
33839
  return nestedMessage;
32825
33840
  }
32826
- if (isRecord(body) && typeof body.message === "string") {
33841
+ if (isRecord3(body) && typeof body.message === "string") {
32827
33842
  return body.message;
32828
33843
  }
32829
33844
  const code = accountErrorCode(body);
@@ -32837,7 +33852,7 @@ function accountErrorCode(body) {
32837
33852
  if (nestedCode) {
32838
33853
  return nestedCode;
32839
33854
  }
32840
- if (isRecord(body)) {
33855
+ if (isRecord3(body)) {
32841
33856
  if (typeof body.code === "string") {
32842
33857
  return body.code;
32843
33858
  }
@@ -32848,13 +33863,13 @@ function accountErrorCode(body) {
32848
33863
  return void 0;
32849
33864
  }
32850
33865
  function nestedAccountErrorField(body, field) {
32851
- if (!isRecord(body) || !isRecord(body.error)) {
33866
+ if (!isRecord3(body) || !isRecord3(body.error)) {
32852
33867
  return void 0;
32853
33868
  }
32854
33869
  const value = body.error[field];
32855
33870
  return typeof value === "string" ? value : void 0;
32856
33871
  }
32857
- function isRecord(value) {
33872
+ function isRecord3(value) {
32858
33873
  return typeof value === "object" && value !== null;
32859
33874
  }
32860
33875
  function normalizeAccountResponse(response) {
@@ -33066,7 +34081,7 @@ function accountOwnerBindingError(error) {
33066
34081
  }
33067
34082
 
33068
34083
  // src/protocol/grants.ts
33069
- var import_viem17 = require("viem");
34084
+ var import_viem20 = require("viem");
33070
34085
  function isHexString(value) {
33071
34086
  return typeof value === "string" && value.startsWith("0x");
33072
34087
  }
@@ -33111,7 +34126,7 @@ async function verifyGrantRegistration(input) {
33111
34126
  }
33112
34127
  let valid;
33113
34128
  try {
33114
- valid = await (0, import_viem17.verifyTypedData)({
34129
+ valid = await (0, import_viem20.verifyTypedData)({
33115
34130
  address: input.grantorAddress,
33116
34131
  domain: grantRegistrationDomain(input.gatewayConfig),
33117
34132
  types: GRANT_REGISTRATION_TYPES,
@@ -33146,8 +34161,8 @@ async function verifyGrantRegistration(input) {
33146
34161
  }
33147
34162
 
33148
34163
  // src/protocol/fee-registry.ts
33149
- var import_viem18 = require("viem");
33150
- var FEE_REGISTRY_ABI = (0, import_viem18.parseAbi)([
34164
+ var import_viem21 = require("viem");
34165
+ var FEE_REGISTRY_ABI = (0, import_viem21.parseAbi)([
33151
34166
  "struct Fee { uint256 amount; address asset; address payee; bool enabled; }",
33152
34167
  "function fees(bytes32 operation) view returns (Fee)",
33153
34168
  "function operationKey(string name) pure returns (bytes32)"
@@ -33230,7 +34245,7 @@ async function getOpFee(client, config, opType, opts) {
33230
34245
  }
33231
34246
 
33232
34247
  // src/protocol/escrow-deposit.ts
33233
- var import_viem19 = require("viem");
34248
+ var import_viem22 = require("viem");
33234
34249
  var ESCROW_DEPOSIT_ABI = [
33235
34250
  {
33236
34251
  type: "function",
@@ -33255,14 +34270,14 @@ function escrowContractAddress(config) {
33255
34270
  return config.contracts.dataPortabilityEscrow;
33256
34271
  }
33257
34272
  function encodeDepositNativeData(input) {
33258
- return (0, import_viem19.encodeFunctionData)({
34273
+ return (0, import_viem22.encodeFunctionData)({
33259
34274
  abi: ESCROW_DEPOSIT_ABI,
33260
34275
  functionName: "depositNative",
33261
34276
  args: [input.account]
33262
34277
  });
33263
34278
  }
33264
34279
  function encodeDepositTokenData(input) {
33265
- return (0, import_viem19.encodeFunctionData)({
34280
+ return (0, import_viem22.encodeFunctionData)({
33266
34281
  abi: ESCROW_DEPOSIT_ABI,
33267
34282
  functionName: "depositToken",
33268
34283
  args: [input.account, input.token, input.amount]
@@ -33283,7 +34298,7 @@ function buildDepositTokenRequest(config, input) {
33283
34298
  }
33284
34299
 
33285
34300
  // src/protocol/data-point-status.ts
33286
- var import_viem20 = require("viem");
34301
+ var import_viem23 = require("viem");
33287
34302
  var DataPointStatus = /* @__PURE__ */ ((DataPointStatus2) => {
33288
34303
  DataPointStatus2[DataPointStatus2["None"] = 0] = "None";
33289
34304
  DataPointStatus2[DataPointStatus2["Active"] = 1] = "Active";
@@ -33307,7 +34322,7 @@ function dataRegistryContractAddress(config) {
33307
34322
  return config.contracts.dataRegistry;
33308
34323
  }
33309
34324
  function encodeSetDataPointStatusData(input) {
33310
- return (0, import_viem20.encodeFunctionData)({
34325
+ return (0, import_viem23.encodeFunctionData)({
33311
34326
  abi: DATA_REGISTRY_STATUS_ABI,
33312
34327
  functionName: "setStatus",
33313
34328
  args: [input.scope, input.status]
@@ -33327,14 +34342,14 @@ function buildMarkDataPointUnavailableRequest(config, input) {
33327
34342
  }
33328
34343
 
33329
34344
  // src/protocol/data-point-deletion.ts
33330
- var import_viem22 = require("viem");
34345
+ var import_viem25 = require("viem");
33331
34346
 
33332
34347
  // src/protocol/lineage.ts
33333
- var import_viem21 = require("viem");
34348
+ var import_viem24 = require("viem");
33334
34349
  var import_zod = require("zod");
33335
34350
 
33336
34351
  // src/protocol/personal-server-error-body.ts
33337
- function isRecord2(value) {
34352
+ function isRecord4(value) {
33338
34353
  return value !== null && typeof value === "object" && !Array.isArray(value);
33339
34354
  }
33340
34355
  async function readPersonalServerErrorBody(response) {
@@ -33344,8 +34359,8 @@ async function readPersonalServerErrorBody(response) {
33344
34359
  } catch {
33345
34360
  return { errorCode: null, message: null };
33346
34361
  }
33347
- if (!isRecord2(body)) return { errorCode: null, message: null };
33348
- const nested = isRecord2(body.error) ? body.error : null;
34362
+ if (!isRecord4(body)) return { errorCode: null, message: null };
34363
+ const nested = isRecord4(body.error) ? body.error : null;
33349
34364
  const gatewayShape = typeof body.error === "string" && typeof body.code === "string";
33350
34365
  const code = nested?.errorCode ?? nested?.code ?? body.errorCode ?? (gatewayShape ? body.code : void 0) ?? (typeof body.error === "string" ? body.error : void 0) ?? body.code;
33351
34366
  const message = nested?.message ?? body.message ?? (gatewayShape ? body.error : void 0);
@@ -33358,63 +34373,23 @@ async function readPersonalServerErrorBody(response) {
33358
34373
  return {
33359
34374
  errorCode: typeof code === "string" ? code : null,
33360
34375
  message: typeof message === "string" ? message : null,
33361
- ...isRecord2(details) ? { details } : {}
34376
+ ...isRecord4(details) ? { details } : {}
33362
34377
  };
33363
34378
  }
33364
34379
 
33365
- // src/protocol/write-signer.ts
33366
- function isRecord3(value) {
33367
- return value !== null && typeof value === "object";
33368
- }
33369
- function isViemWriteAccount(source) {
33370
- return isRecord3(source) && source.type === "local" && typeof source.address === "string" && typeof source.signMessage === "function";
33371
- }
33372
- function isViemWriteWalletClient(source) {
33373
- return isRecord3(source) && typeof source.signMessage === "function" && source.type !== "local" && (source.type === "walletClient" || "transport" in source);
33374
- }
33375
- function accountAddress(account) {
33376
- return typeof account === "string" ? account : account.address;
33377
- }
33378
- function resolveWriteSigner(source, options = {}) {
33379
- if (isViemWriteWalletClient(source)) {
33380
- const account = options.account ?? source.account;
33381
- if (account === void 0) {
33382
- throw new WriteRequestError(
33383
- "Viem wallet client requires an account option or account property"
33384
- );
33385
- }
33386
- return {
33387
- address: accountAddress(account),
33388
- signMessage: (message) => source.signMessage({ account, message })
33389
- };
33390
- }
33391
- if (isViemWriteAccount(source)) {
33392
- return {
33393
- address: source.address,
33394
- signMessage: (message) => source.signMessage({ message })
33395
- };
33396
- }
33397
- if (!isRecord3(source) || typeof source.signMessage !== "function") {
33398
- throw new WriteRequestError(
33399
- "signer must be a viem LocalAccount, a viem WalletClient, or a { signMessage } object"
33400
- );
33401
- }
33402
- return source;
33403
- }
33404
-
33405
34380
  // src/protocol/lineage.ts
33406
34381
  var DATA_POINT_ID_PATTERN = /^0x[0-9a-fA-F]{64}$/;
33407
34382
  function isDataPointId(value) {
33408
34383
  return typeof value === "string" && DATA_POINT_ID_PATTERN.test(value);
33409
34384
  }
33410
34385
  function deriveDataPointId(ownerAddress, scope) {
33411
- if (!(0, import_viem21.isAddress)(ownerAddress, { strict: false })) {
34386
+ if (!(0, import_viem24.isAddress)(ownerAddress, { strict: false })) {
33412
34387
  throw new Error(
33413
34388
  `ownerAddress is not an EVM address: ${String(ownerAddress)}`
33414
34389
  );
33415
34390
  }
33416
- return (0, import_viem21.keccak256)(
33417
- (0, import_viem21.encodeAbiParameters)(
34391
+ return (0, import_viem24.keccak256)(
34392
+ (0, import_viem24.encodeAbiParameters)(
33418
34393
  [
33419
34394
  { name: "ownerAddress", type: "address" },
33420
34395
  { name: "scope", type: "string" }
@@ -33503,7 +34478,7 @@ function gatewayLineagePath(dataPointId, version) {
33503
34478
  function normalizeBaseUrl(url) {
33504
34479
  return url.replace(/\/+$/, "");
33505
34480
  }
33506
- function resolveFetch(fetchFn) {
34481
+ function resolveFetch2(fetchFn) {
33507
34482
  const resolved = fetchFn ?? globalThis.fetch;
33508
34483
  if (resolved === void 0) {
33509
34484
  throw new LineageReadError("No fetch implementation available");
@@ -33544,7 +34519,7 @@ async function parseLineageGraph(source, response) {
33544
34519
  { cause: err instanceof Error ? err.message : String(err) }
33545
34520
  );
33546
34521
  }
33547
- const envelope = isRecord2(body) && isRecord2(body.data) ? body : void 0;
34522
+ const envelope = isRecord4(body) && isRecord4(body.data) ? body : void 0;
33548
34523
  const parsed = LineageGraphSchema.safeParse(envelope?.data ?? body);
33549
34524
  if (!parsed.success) {
33550
34525
  throw new LineageReadError(
@@ -33554,7 +34529,7 @@ async function parseLineageGraph(source, response) {
33554
34529
  { issues: parsed.error.issues }
33555
34530
  );
33556
34531
  }
33557
- const proof = isRecord2(envelope?.proof) ? envelope.proof : void 0;
34532
+ const proof = isRecord4(envelope?.proof) ? envelope.proof : void 0;
33558
34533
  return proof === void 0 ? parsed.data : { ...parsed.data, proof };
33559
34534
  }
33560
34535
  async function sendLineageRead(source, fetchFn, url, headers) {
@@ -33575,7 +34550,7 @@ async function sendLineageRead(source, fetchFn, url, headers) {
33575
34550
  return parseLineageGraph(source, response);
33576
34551
  }
33577
34552
  async function getPersonalServerLineage(params) {
33578
- const fetchFn = resolveFetch(params.fetch);
34553
+ const fetchFn = resolveFetch2(params.fetch);
33579
34554
  const baseUrl = normalizeBaseUrl(params.personalServerUrl);
33580
34555
  const audience = params.audience ?? baseUrl;
33581
34556
  const signer = resolveWriteSigner(params.signer, { account: params.account });
@@ -33610,7 +34585,7 @@ async function getGatewayLineage(params) {
33610
34585
  { dataPointId: params.dataPointId }
33611
34586
  );
33612
34587
  }
33613
- const fetchFn = resolveFetch(params.fetch);
34588
+ const fetchFn = resolveFetch2(params.fetch);
33614
34589
  const baseUrl = normalizeBaseUrl(params.gatewayUrl);
33615
34590
  const signer = resolveWriteSigner(params.signer, { account: params.account });
33616
34591
  const uri = gatewayLineagePath(
@@ -33640,7 +34615,7 @@ var TOMBSTONE_METADATA_HASH_PREIMAGE = "vana.data-point.tombstone.metadata.v1";
33640
34615
  var TOMBSTONE_DATA_HASH = "0x30c45ee72fe56d1927701316925ab7ceacd3b6f9267061735d59396f075c6222";
33641
34616
  var TOMBSTONE_METADATA_HASH = "0xc5255a141acd6a2ae55971b62c0a85977c2511989dc114ad2abc2b7644f57d90";
33642
34617
  function computeTombstoneHash(preimage) {
33643
- return (0, import_viem22.keccak256)((0, import_viem22.stringToBytes)(preimage));
34618
+ return (0, import_viem25.keccak256)((0, import_viem25.stringToBytes)(preimage));
33644
34619
  }
33645
34620
  function isTombstoneHashes(dataHash, metadataHash) {
33646
34621
  return typeof dataHash === "string" && typeof metadataHash === "string" && dataHash.toLowerCase() === TOMBSTONE_DATA_HASH && metadataHash.toLowerCase() === TOMBSTONE_METADATA_HASH;
@@ -33659,12 +34634,12 @@ function tombstoneDeletedAt(value) {
33659
34634
  return typeof deletedAt === "string" ? deletedAt : null;
33660
34635
  }
33661
34636
  function assertAddress4(value, name) {
33662
- if (!(0, import_viem22.isAddress)(value)) {
34637
+ if (!(0, import_viem25.isAddress)(value)) {
33663
34638
  throw new Error(`${name} must be a valid EVM address`);
33664
34639
  }
33665
34640
  }
33666
34641
  function assertUint256(value, name) {
33667
- if (value < 0n || value > import_viem22.maxUint256) {
34642
+ if (value < 0n || value > import_viem25.maxUint256) {
33668
34643
  throw new Error(`${name} must fit in uint256, got ${value}`);
33669
34644
  }
33670
34645
  }
@@ -33767,7 +34742,7 @@ async function deleteDataPoint(input) {
33767
34742
  }
33768
34743
  currentVersion = parseExpectedVersion(record.expectedVersion);
33769
34744
  }
33770
- if (currentVersion < 0n || currentVersion >= import_viem22.maxUint256) {
34745
+ if (currentVersion < 0n || currentVersion >= import_viem25.maxUint256) {
33771
34746
  throw new Error(
33772
34747
  `currentVersion ${currentVersion} cannot be incremented to a uint256 tombstone version`
33773
34748
  );
@@ -34074,17 +35049,17 @@ function tryGrantPermissions(scopes) {
34074
35049
  }
34075
35050
 
34076
35051
  // src/protocol/personal-server-write.ts
34077
- var import_sha26 = require("@noble/hashes/sha2");
34078
- var import_viem24 = require("viem");
35052
+ var import_sha27 = require("@noble/hashes/sha2");
35053
+ var import_viem27 = require("viem");
34079
35054
  var import_zod4 = require("zod");
34080
35055
 
34081
35056
  // src/protocol/write-request.ts
34082
- var import_sha25 = require("@noble/hashes/sha2");
34083
- var import_viem23 = require("viem");
35057
+ var import_sha26 = require("@noble/hashes/sha2");
35058
+ var import_viem26 = require("viem");
34084
35059
  function normalizeBaseUrl2(url) {
34085
35060
  return url.replace(/\/+$/, "");
34086
35061
  }
34087
- function resolveFetch2(fetchFn) {
35062
+ function resolveFetch3(fetchFn) {
34088
35063
  const resolved = fetchFn ?? globalThis.fetch;
34089
35064
  if (resolved === void 0) {
34090
35065
  throw new WriteRequestError("No fetch implementation available");
@@ -34097,7 +35072,7 @@ function errorMessage(err) {
34097
35072
  function finiteOr(value, fallback) {
34098
35073
  return typeof value === "number" && Number.isFinite(value) ? value : fallback;
34099
35074
  }
34100
- function sleep2(ms) {
35075
+ function sleep3(ms) {
34101
35076
  return new Promise((resolve) => setTimeout(resolve, ms));
34102
35077
  }
34103
35078
  var issuedProofIats = /* @__PURE__ */ new Map();
@@ -34139,7 +35114,7 @@ function nextProofIat(proofKey) {
34139
35114
  setIssuedProofIat(proofKey, iat, last);
34140
35115
  const waitSec = iat - nowSec - PROOF_IAT_MAX_AHEAD_SECONDS;
34141
35116
  if (waitSec <= 0) return Promise.resolve(iat);
34142
- return sleep2(waitSec * 1e3).then(() => iat);
35117
+ return sleep3(waitSec * 1e3).then(() => iat);
34143
35118
  }
34144
35119
  function freshProofNonce() {
34145
35120
  const webCrypto = globalThis.crypto;
@@ -34147,22 +35122,22 @@ function freshProofNonce() {
34147
35122
  return webCrypto.randomUUID();
34148
35123
  }
34149
35124
  if (typeof webCrypto?.getRandomValues === "function") {
34150
- return (0, import_viem23.bytesToHex)(webCrypto.getRandomValues(new Uint8Array(16)));
35125
+ return (0, import_viem26.bytesToHex)(webCrypto.getRandomValues(new Uint8Array(16)));
34151
35126
  }
34152
35127
  throw new WriteRequestError(
34153
35128
  "No secure random source available to build a proof nonce; provide a crypto global"
34154
35129
  );
34155
35130
  }
34156
35131
  function proofKeyFor(parts) {
34157
- return (0, import_viem23.bytesToHex)(
34158
- (0, import_sha25.sha256)(
35132
+ return (0, import_viem26.bytesToHex)(
35133
+ (0, import_sha26.sha256)(
34159
35134
  new TextEncoder().encode(
34160
35135
  JSON.stringify([
34161
35136
  parts.aud,
34162
35137
  parts.method,
34163
35138
  parts.uri,
34164
35139
  parts.grantId,
34165
- parts.signedBytes ? (0, import_viem23.bytesToHex)((0, import_sha25.sha256)(parts.signedBytes)) : ""
35140
+ parts.signedBytes ? (0, import_viem26.bytesToHex)((0, import_sha26.sha256)(parts.signedBytes)) : ""
34166
35141
  ])
34167
35142
  )
34168
35143
  )
@@ -34180,7 +35155,7 @@ async function sendWithFreshProof(label, fetchFn, options, proofKey, build) {
34180
35155
  lastError = err;
34181
35156
  }
34182
35157
  if (attempt < attempts - 1) {
34183
- await sleep2(delayMs);
35158
+ await sleep3(delayMs);
34184
35159
  delayMs *= 2;
34185
35160
  }
34186
35161
  }
@@ -34219,7 +35194,7 @@ function dataPath(scope) {
34219
35194
  return `/v1/data/${encodeURIComponent(scope)}`;
34220
35195
  }
34221
35196
  async function openWriteSession(params) {
34222
- const fetchFn = resolveFetch2(params.fetch);
35197
+ const fetchFn = resolveFetch3(params.fetch);
34223
35198
  const personalServerUrl = normalizeBaseUrl2(params.personalServerUrl);
34224
35199
  const audience = params.audience ?? personalServerUrl;
34225
35200
  const signer = resolveWriteSigner(params.signer, { account: params.account });
@@ -34299,12 +35274,12 @@ async function openWriteSession(params) {
34299
35274
  };
34300
35275
  }
34301
35276
  function isWriteSession(value) {
34302
- if (!isRecord2(value)) return false;
35277
+ if (!isRecord4(value)) return false;
34303
35278
  const signer = value.signer;
34304
- 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";
35279
+ 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";
34305
35280
  }
34306
35281
  function sessionCoversScope(session, scope) {
34307
- if (!isRecord2(session) || !Array.isArray(session.writeScopes) || !session.writeScopes.every((pattern) => typeof pattern === "string")) {
35282
+ if (!isRecord4(session) || !Array.isArray(session.writeScopes) || !session.writeScopes.every((pattern) => typeof pattern === "string")) {
34308
35283
  throw new WriteRequestError("session must come from openWriteSession");
34309
35284
  }
34310
35285
  return session.writeScopes.some(
@@ -34349,7 +35324,7 @@ function binaryWriteSignedBytes(input) {
34349
35324
  mimeType: normalizeBinaryMimeType(input.contentType),
34350
35325
  ...input.filename ? { filename: input.filename } : {},
34351
35326
  sizeBytes: input.bytes.length,
34352
- contentHash: (0, import_viem24.bytesToHex)((0, import_sha26.sha256)(input.bytes)),
35327
+ contentHash: (0, import_viem27.bytesToHex)((0, import_sha27.sha256)(input.bytes)),
34353
35328
  encoding: "base64",
34354
35329
  content: toBase64(input.bytes),
34355
35330
  ...metadata !== void 0 ? { metadata } : {}
@@ -34378,7 +35353,7 @@ function assertNoReservedKeys(value, where) {
34378
35353
  }
34379
35354
  }
34380
35355
  function isLineagePair(value) {
34381
- return isRecord2(value) && typeof value.ownerAddress === "string" && typeof value.scope === "string";
35356
+ return isRecord4(value) && typeof value.ownerAddress === "string" && typeof value.scope === "string";
34382
35357
  }
34383
35358
  function normalizeLineage(lineage, derivedScope) {
34384
35359
  if (!Array.isArray(lineage)) {
@@ -34397,7 +35372,7 @@ function normalizeLineage(lineage, derivedScope) {
34397
35372
  for (const entry of lineage) {
34398
35373
  let id;
34399
35374
  if (isLineagePair(entry)) {
34400
- if (!(0, import_viem24.isAddress)(entry.ownerAddress, { strict: false })) {
35375
+ if (!(0, import_viem27.isAddress)(entry.ownerAddress, { strict: false })) {
34401
35376
  throw new WriteRequestError(
34402
35377
  "lineage source ownerAddress must be an EVM address",
34403
35378
  { ownerAddress: entry.ownerAddress }
@@ -34446,7 +35421,7 @@ function assertNoLineageField(value, where) {
34446
35421
  }
34447
35422
  function buildMetadataHeader(metadata, sources) {
34448
35423
  if (metadata !== void 0) {
34449
- if (!isRecord2(metadata)) {
35424
+ if (!isRecord4(metadata)) {
34450
35425
  throw new WriteRequestError("metadata must be a plain object");
34451
35426
  }
34452
35427
  assertNoReservedKeys(metadata, "metadata");
@@ -34499,7 +35474,7 @@ function prepareWrite(params) {
34499
35474
  if (params.data === void 0) {
34500
35475
  throw new WriteRequestError("Pass data (a JSON object) or binary");
34501
35476
  }
34502
- if (!isRecord2(params.data)) {
35477
+ if (!isRecord4(params.data)) {
34503
35478
  throw new WriteRequestError("data must be a plain JSON object");
34504
35479
  }
34505
35480
  if (params.metadata !== void 0) {
@@ -34550,7 +35525,7 @@ async function writeData(params) {
34550
35525
  if (!isWriteSession(session)) {
34551
35526
  throw new WriteRequestError("session must come from openWriteSession");
34552
35527
  }
34553
- const fetchFn = resolveFetch2(params.fetch);
35528
+ const fetchFn = resolveFetch3(params.fetch);
34554
35529
  if (typeof params.scope !== "string" || params.scope.length === 0) {
34555
35530
  throw new WriteRequestError("scope is required");
34556
35531
  }
@@ -34662,6 +35637,13 @@ var QUESTION_STATUSES = [
34662
35637
  "failed",
34663
35638
  "stale"
34664
35639
  ];
35640
+ var DERIVATIVE_ERROR_CODES = [
35641
+ "inference_unavailable",
35642
+ "source_missing",
35643
+ "grant_invalid",
35644
+ "internal"
35645
+ ];
35646
+ var DerivativeErrorCodeSchema = import_zod5.z.enum(DERIVATIVE_ERROR_CODES);
34665
35647
  var QuestionStatusSchema = import_zod5.z.enum(QUESTION_STATUSES);
34666
35648
  var QuestionRegisteredBySchema = import_zod5.z.union([
34667
35649
  import_zod5.z.object({ kind: import_zod5.z.literal("owner") }),
@@ -34683,6 +35665,14 @@ var DerivativeQuestionSchema = import_zod5.z.object({
34683
35665
  status: QuestionStatusSchema,
34684
35666
  /** A short reason, set only while `status` is `failed`. */
34685
35667
  error: nullableString,
35668
+ /**
35669
+ * The coarse failure class behind `error`, set only while `status` is
35670
+ * `failed`. `null` from a Personal Server that predates the class
35671
+ * (`personal-server-ts` before the status route).
35672
+ */
35673
+ errorCode: DerivativeErrorCodeSchema.nullish().transform(
35674
+ (value) => value ?? null
35675
+ ),
34686
35676
  createdAt: import_zod5.z.string(),
34687
35677
  updatedAt: nullableString,
34688
35678
  /** When the last compute finished, or `null` while `pending`. */
@@ -34727,7 +35717,7 @@ function resolveRequest(params) {
34727
35717
  "signer must be a viem LocalAccount, a viem WalletClient, or a { signMessage } object"
34728
35718
  );
34729
35719
  }
34730
- const fetchFn = resolveFetch2(params.fetch);
35720
+ const fetchFn = resolveFetch3(params.fetch);
34731
35721
  const baseUrl = normalizeBaseUrl2(params.personalServerUrl);
34732
35722
  const audience = params.audience ?? baseUrl;
34733
35723
  return {
@@ -34815,6 +35805,7 @@ async function questionErrorFromResponse(response, body) {
34815
35805
  );
34816
35806
  }
34817
35807
  }
35808
+ var personalServerErrorFromQuestionResponse = questionErrorFromResponse;
34818
35809
  async function sendOnce(params, resolved, session, spec, bodyBytes) {
34819
35810
  return sendWithFreshProof(
34820
35811
  spec.label,
@@ -35059,7 +36050,7 @@ async function waitForQuestion(params) {
35059
36050
  }
35060
36051
  );
35061
36052
  }
35062
- await sleep2(Math.min(pollIntervalMs, remaining));
36053
+ await sleep3(Math.min(pollIntervalMs, remaining));
35063
36054
  }
35064
36055
  }
35065
36056
  async function askPersonalServer(params) {
@@ -35094,6 +36085,166 @@ async function askPersonalServer(params) {
35094
36085
  return { registration, record };
35095
36086
  }
35096
36087
 
36088
+ // src/protocol/derivative-status.ts
36089
+ var import_zod6 = require("zod");
36090
+ var DERIVATIVE_STATUS_PATH = "/v1/derivatives/status";
36091
+ var DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS = 12e4;
36092
+ var DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS = 2e3;
36093
+ var nullable = (schema) => schema.nullish().transform((value) => value ?? null);
36094
+ var DerivativeStatusSchema = import_zod6.z.object({
36095
+ derivedScope: import_zod6.z.string().min(1),
36096
+ status: QuestionStatusSchema,
36097
+ /** When the last compute finished, or `null` if none ever has. */
36098
+ lastComputedAt: nullable(import_zod6.z.string()),
36099
+ /** Local version of the derived record the last compute wrote. */
36100
+ derivedVersion: nullable(import_zod6.z.number()),
36101
+ derivedCollectedAt: nullable(import_zod6.z.string()),
36102
+ /** The failure class; `null` unless `status` is `failed`. */
36103
+ errorCode: nullable(DerivativeErrorCodeSchema),
36104
+ /**
36105
+ * Seconds until the Personal Server's next automatic retry, or `null` when
36106
+ * none is pending or running — the terminal signature. Poll on this cadence
36107
+ * rather than guessing one.
36108
+ */
36109
+ retryAfterSeconds: nullable(import_zod6.z.number())
36110
+ });
36111
+ function derivativeStatusTarget(derivedScope) {
36112
+ return `${DERIVATIVE_STATUS_PATH}?derivedScope=${encodeURIComponent(derivedScope)}`;
36113
+ }
36114
+ function normalizeBaseUrl3(url) {
36115
+ return url.replace(/\/+$/, "");
36116
+ }
36117
+ function resolveFetch4(fetchFn) {
36118
+ const resolved = fetchFn ?? globalThis.fetch;
36119
+ if (resolved === void 0) {
36120
+ throw new WriteRequestError("No fetch implementation available");
36121
+ }
36122
+ return resolved;
36123
+ }
36124
+ function requireDerivedScope(derivedScope) {
36125
+ if (typeof derivedScope !== "string" || derivedScope.length === 0) {
36126
+ throw new WriteRequestError("derivedScope is required");
36127
+ }
36128
+ return derivedScope;
36129
+ }
36130
+ function sleep4(ms, signal) {
36131
+ if (ms <= 0) return Promise.resolve();
36132
+ return new Promise((resolve, reject) => {
36133
+ const timer = setTimeout(() => {
36134
+ signal?.removeEventListener("abort", onAbort);
36135
+ resolve();
36136
+ }, ms);
36137
+ const onAbort = () => {
36138
+ clearTimeout(timer);
36139
+ reject(abortError2(signal));
36140
+ };
36141
+ signal?.addEventListener("abort", onAbort, { once: true });
36142
+ });
36143
+ }
36144
+ function timeoutError(latest, timeoutMs) {
36145
+ return new DerivativeQuestionTimeoutError(
36146
+ `Derived scope ${latest.derivedScope} was still ${latest.status} after ${timeoutMs}ms`,
36147
+ {
36148
+ derivedScope: latest.derivedScope,
36149
+ status: latest.status,
36150
+ errorCode: latest.errorCode,
36151
+ retryAfterSeconds: latest.retryAfterSeconds,
36152
+ timeoutMs
36153
+ }
36154
+ );
36155
+ }
36156
+ function abortError2(signal) {
36157
+ const reason = signal?.reason;
36158
+ return reason instanceof Error ? reason : new WriteRequestError("Derivative status wait was aborted");
36159
+ }
36160
+ function isDerivativeStatusSettled(status) {
36161
+ if (status.status === "ready") return true;
36162
+ return status.status === "failed" && status.retryAfterSeconds === null;
36163
+ }
36164
+ async function getDerivativeStatus(params) {
36165
+ const derivedScope = requireDerivedScope(params.derivedScope);
36166
+ const fetchFn = resolveFetch4(params.fetch);
36167
+ const baseUrl = normalizeBaseUrl3(params.personalServerUrl);
36168
+ const signer = resolveWriteSigner(params.signer, { account: params.account });
36169
+ const headers = new Headers(params.headers);
36170
+ headers.set(
36171
+ "Authorization",
36172
+ await buildWeb3SignedHeader({
36173
+ signMessage: signer.signMessage,
36174
+ aud: params.audience ?? baseUrl,
36175
+ method: "GET",
36176
+ uri: DERIVATIVE_STATUS_PATH,
36177
+ grantId: params.grantId
36178
+ })
36179
+ );
36180
+ let response;
36181
+ try {
36182
+ response = await fetchFn(
36183
+ `${baseUrl}${derivativeStatusTarget(derivedScope)}`,
36184
+ {
36185
+ method: "GET",
36186
+ headers,
36187
+ ...params.signal ? { signal: params.signal } : {}
36188
+ }
36189
+ );
36190
+ } catch (err) {
36191
+ throw new WriteTransportError(
36192
+ `Derivative status read failed: ${err instanceof Error ? err.message : String(err)}`,
36193
+ 1,
36194
+ err
36195
+ );
36196
+ }
36197
+ if (!response.ok) {
36198
+ throw await personalServerErrorFromQuestionResponse(
36199
+ response
36200
+ );
36201
+ }
36202
+ let body;
36203
+ try {
36204
+ body = await response.json();
36205
+ } catch (err) {
36206
+ throw new DerivativeQuestionRejectedError(
36207
+ "Derivative status response is not JSON",
36208
+ response.status,
36209
+ null,
36210
+ { cause: err instanceof Error ? err.message : String(err) }
36211
+ );
36212
+ }
36213
+ const parsed = DerivativeStatusSchema.safeParse(body);
36214
+ if (!parsed.success) {
36215
+ throw new DerivativeQuestionRejectedError(
36216
+ "Derivative status response is not a status view",
36217
+ response.status,
36218
+ null,
36219
+ { issues: parsed.error.issues }
36220
+ );
36221
+ }
36222
+ return parsed.data;
36223
+ }
36224
+ async function waitForDerivativeStatus(params) {
36225
+ const timeoutMs = Math.max(
36226
+ 0,
36227
+ params.timeoutMs ?? DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS
36228
+ );
36229
+ const pollIntervalMs = Math.max(
36230
+ 0,
36231
+ params.pollIntervalMs ?? DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS
36232
+ );
36233
+ const deadline = Date.now() + timeoutMs;
36234
+ for (; ; ) {
36235
+ if (params.signal?.aborted) throw abortError2(params.signal);
36236
+ const latest = await getDerivativeStatus(params);
36237
+ if (isDerivativeStatusSettled(latest)) return latest;
36238
+ const remaining = deadline - Date.now();
36239
+ if (remaining <= 0) throw timeoutError(latest, timeoutMs);
36240
+ const waitMs = latest.retryAfterSeconds === null ? pollIntervalMs : latest.retryAfterSeconds * 1e3;
36241
+ if (waitMs > remaining) {
36242
+ throw timeoutError(latest, timeoutMs);
36243
+ }
36244
+ await sleep4(waitMs, params.signal);
36245
+ }
36246
+ }
36247
+
35097
36248
  // src/protocol/gateway.ts
35098
36249
  function withGrantPermissions(grant) {
35099
36250
  const stripped = { ...grant };
@@ -36123,7 +37274,7 @@ var KNOWN_CODES = /* @__PURE__ */ new Set([
36123
37274
  "server_not_configured",
36124
37275
  "content_too_large"
36125
37276
  ]);
36126
- function isRecord4(value) {
37277
+ function isRecord5(value) {
36127
37278
  return value !== null && typeof value === "object" && !Array.isArray(value);
36128
37279
  }
36129
37280
  function normalizeCode(value) {
@@ -36134,10 +37285,10 @@ function normalizeCode(value) {
36134
37285
  return KNOWN_CODES.has(code) ? code : null;
36135
37286
  }
36136
37287
  function extractPSErrorBody(body) {
36137
- if (!isRecord4(body)) {
37288
+ if (!isRecord5(body)) {
36138
37289
  return null;
36139
37290
  }
36140
- const nested = isRecord4(body.error) ? body.error : null;
37291
+ const nested = isRecord5(body.error) ? body.error : null;
36141
37292
  const code = normalizeCode(
36142
37293
  nested?.errorCode ?? nested?.code ?? body.errorCode ?? body.code
36143
37294
  );
@@ -36169,15 +37320,23 @@ async function parsePSError(response) {
36169
37320
  BUILDER_REGISTRATION_TYPES,
36170
37321
  BlockchainError,
36171
37322
  BrowserPlatformAdapter,
37323
+ BuilderUnknownError,
37324
+ CLAIM_POLL_FLOOR_MS,
36172
37325
  CONTRACTS,
36173
37326
  CallbackStorage,
36174
37327
  ContractFactory,
36175
37328
  ContractNotFoundError,
36176
37329
  DATA_ACCESS_OP_TYPE,
36177
37330
  DATA_REGISTRY_STATUS_ABI,
37331
+ DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS,
37332
+ DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS,
37333
+ DEFAULT_JOB_DEADLINE_SECONDS,
37334
+ DEFAULT_LEASE_SECONDS,
36178
37335
  DEFAULT_QUESTION_POLL_INTERVAL_MS,
36179
37336
  DEFAULT_QUESTION_TIMEOUT_MS,
37337
+ DERIVATIVE_ERROR_CODES,
36180
37338
  DERIVATIVE_QUESTIONS_PATH,
37339
+ DERIVATIVE_STATUS_PATH,
36181
37340
  DataFileEnvelopeSchema,
36182
37341
  DataPointDeletedError,
36183
37342
  DataPointNotFoundError,
@@ -36186,6 +37345,7 @@ async function parsePSError(response) {
36186
37345
  DerivativeComputeUnavailableError,
36187
37346
  DerivativeCycleError,
36188
37347
  DerivativeDerivedScopeRequiredError,
37348
+ DerivativeErrorCodeSchema,
36189
37349
  DerivativeQuestionFailedError,
36190
37350
  DerivativeQuestionInvalidError,
36191
37351
  DerivativeQuestionNotFoundError,
@@ -36193,8 +37353,12 @@ async function parsePSError(response) {
36193
37353
  DerivativeQuestionSchema,
36194
37354
  DerivativeQuestionTimeoutError,
36195
37355
  DerivativeSourceNotGrantedError,
37356
+ DerivativeStatusSchema,
36196
37357
  DropboxStorage,
36197
37358
  ECIESError,
37359
+ ENCLAVE_IDENTITY_EVIDENCE_VERSION,
37360
+ ENCLAVE_TRUST_ANCHORS,
37361
+ ENCLAVE_WALLET_PURPOSE,
36198
37362
  ESCROW_DEPOSIT_ABI,
36199
37363
  ExpiredTokenError,
36200
37364
  FEE_REGISTRY_ABI,
@@ -36203,12 +37367,24 @@ async function parsePSError(response) {
36203
37367
  GRANT_REGISTRATION_TYPES,
36204
37368
  GRANT_REVOCATION_TYPES,
36205
37369
  GoogleDriveStorage,
37370
+ GrantInvalidError,
36206
37371
  InMemoryTokenStore,
36207
37372
  IngestResponseSchema,
36208
37373
  InvalidConfigurationError,
36209
37374
  InvalidScopeEntryError,
36210
37375
  InvalidSignatureError,
36211
37376
  IpfsStorage,
37377
+ JOB_OPERATIONS,
37378
+ JOB_PROTOCOL_VERSION,
37379
+ JOB_STATES,
37380
+ JobEnvelopeError,
37381
+ JobIdTakenError,
37382
+ JobNotFoundError,
37383
+ JobRejectedError,
37384
+ JobRequestTooLargeError,
37385
+ JobTimeoutError,
37386
+ JobTransportError,
37387
+ JobsClientError,
36212
37388
  LINEAGE_FIELD,
36213
37389
  LINEAGE_KEY,
36214
37390
  LineageEntrySchema,
@@ -36216,10 +37392,17 @@ async function parsePSError(response) {
36216
37392
  LineageNodeSchema,
36217
37393
  LineageReadError,
36218
37394
  MASTER_KEY_MESSAGE,
37395
+ MASTER_SIGNATURE_DELIVERY_MAX_AGE_SECONDS,
37396
+ MASTER_SIGNATURE_DELIVERY_VERSION,
37397
+ MAX_ATTEMPTS,
37398
+ MAX_INLINE_RESULT_BYTES,
37399
+ MAX_JOB_DEADLINE_SECONDS,
37400
+ MAX_LEASE_SECONDS,
36219
37401
  MAX_LINEAGE_SOURCES,
36220
37402
  MAX_QUESTION_CHARS,
36221
37403
  MAX_QUESTION_MODEL_CHARS,
36222
37404
  MAX_QUESTION_SOURCE_SCOPES,
37405
+ MAX_WAIT_SECONDS,
36223
37406
  MissingAuthError,
36224
37407
  NATIVE_ASSET_ADDRESS,
36225
37408
  NATIVE_VANA_ASSET,
@@ -36228,6 +37411,7 @@ async function parsePSError(response) {
36228
37411
  NodePlatformAdapter,
36229
37412
  NonceError,
36230
37413
  OAuthClient,
37414
+ OwnerNotReadyError,
36231
37415
  PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX,
36232
37416
  PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE,
36233
37417
  PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION,
@@ -36253,6 +37437,7 @@ async function parsePSError(response) {
36253
37437
  RedactedLineageNodeSchema,
36254
37438
  RelayerError,
36255
37439
  SCOPE_ACTIONS,
37440
+ SEALED_ENVELOPE_VERSION,
36256
37441
  SERVER_REGISTRATION_TYPES,
36257
37442
  ScopeSchema,
36258
37443
  SerializationError,
@@ -36265,6 +37450,7 @@ async function parsePSError(response) {
36265
37450
  TOMBSTONE_METADATA_HASH,
36266
37451
  TOMBSTONE_METADATA_HASH_PREIMAGE,
36267
37452
  TransactionPendingError,
37453
+ USER_PS_ID_DOMAIN,
36268
37454
  UserRejectedRequestError,
36269
37455
  VanaError,
36270
37456
  VanaStorage,
@@ -36283,6 +37469,7 @@ async function parsePSError(response) {
36283
37469
  WriteSessionExpiredError,
36284
37470
  WriteTransportError,
36285
37471
  WriteUnauthorizedError,
37472
+ appRootPreimage,
36286
37473
  askPersonalServer,
36287
37474
  assertDerivedScopeNaming,
36288
37475
  assertValidPkceVerifier,
@@ -36296,6 +37483,7 @@ async function parsePSError(response) {
36296
37483
  buildEscrowPaymentHeader,
36297
37484
  buildGrantPaymentHeader,
36298
37485
  buildMarkDataPointUnavailableRequest,
37486
+ buildMasterSignatureDelivery,
36299
37487
  buildPersonalServerDataReadRequest,
36300
37488
  buildPersonalServerLiteOwnerBindingMessage,
36301
37489
  buildPersonalServerLiteOwnerBindingSignature,
@@ -36304,6 +37492,7 @@ async function parsePSError(response) {
36304
37492
  buildSetDataPointStatusRequest,
36305
37493
  buildWeb3SignedHeader,
36306
37494
  builderRegistrationDomain,
37495
+ canonicalJobRequestBytes,
36307
37496
  chains,
36308
37497
  clearContractCache,
36309
37498
  computeBodyHash,
@@ -36315,6 +37504,7 @@ async function parsePSError(response) {
36315
37504
  createDefaultNonceSource,
36316
37505
  createEscrowGatewayClient,
36317
37506
  createGatewayClient,
37507
+ createJobsClient,
36318
37508
  createNodePlatformAdapter,
36319
37509
  createPlatformAdapter,
36320
37510
  createPlatformAdapterFor,
@@ -36328,6 +37518,7 @@ async function parsePSError(response) {
36328
37518
  decryptWithPassword,
36329
37519
  deleteDataPoint,
36330
37520
  deleteQuestion,
37521
+ derivativeStatusTarget,
36331
37522
  deriveDataPointId,
36332
37523
  deriveMasterKey,
36333
37524
  deriveScopeKey,
@@ -36338,6 +37529,7 @@ async function parsePSError(response) {
36338
37529
  encodeDepositTokenData,
36339
37530
  encodeSetDataPointStatusData,
36340
37531
  encodeWriteMetadataHeader,
37532
+ encryptMasterSignatureDelivery,
36341
37533
  encryptWithPassword,
36342
37534
  escrowContractAddress,
36343
37535
  escrowPaymentDomain,
@@ -36351,6 +37543,7 @@ async function parsePSError(response) {
36351
37543
  getContractAddress,
36352
37544
  getContractController,
36353
37545
  getContractInfo,
37546
+ getDerivativeStatus,
36354
37547
  getFee,
36355
37548
  getGatewayLineage,
36356
37549
  getLineage,
@@ -36366,16 +37559,20 @@ async function parsePSError(response) {
36366
37559
  isDataPointId,
36367
37560
  isDataPointTombstone,
36368
37561
  isDataPortabilityGatewayConfig,
37562
+ isDerivativeStatusSettled,
36369
37563
  isECIESEncrypted,
36370
37564
  isPlatformSupported,
36371
37565
  isRedactedLineageNode,
36372
37566
  isTombstoneHashes,
37567
+ kmsIssuedPreimage,
36373
37568
  listQuestions,
36374
37569
  mainnetServices,
36375
37570
  moksha,
36376
37571
  mokshaServices,
36377
37572
  mokshaTestnet,
36378
37573
  normalizeBinaryMimeType,
37574
+ openJobRequest,
37575
+ openJobResult,
36379
37576
  openWriteSession,
36380
37577
  parsePSError,
36381
37578
  parsePersonalServerPaymentRequired,
@@ -36399,6 +37596,8 @@ async function parsePSError(response) {
36399
37596
  scopeMatchesPattern,
36400
37597
  scopeNamespace,
36401
37598
  scopeToPathSegments,
37599
+ sealJobRequest,
37600
+ sealJobResult,
36402
37601
  serializeECIES,
36403
37602
  serverRegistrationDomain,
36404
37603
  sessionCoversScope,
@@ -36409,10 +37608,13 @@ async function parsePSError(response) {
36409
37608
  toDirectPaymentReceipt,
36410
37609
  tombstoneDeletedAt,
36411
37610
  tryGrantPermissions,
37611
+ userPsId,
36412
37612
  vanaMainnet,
37613
+ verifyEnclaveIdentityEvidence,
36413
37614
  verifyGrantRegistration,
36414
37615
  verifyPkceChallenge,
36415
37616
  verifyWeb3Signed,
37617
+ waitForDerivativeStatus,
36416
37618
  waitForQuestion,
36417
37619
  writeData,
36418
37620
  writePersonalServerData