@opendatalabs/vana-sdk 3.21.0 → 3.22.0-pr.207.e47cd30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -621,6 +621,70 @@ These helpers require `personal-server-ts` main `d91124d` or later, which is
621
621
  where the query-in-the-signed-uri rule, the `nonce` claim, the 404 for an
622
622
  unknown id and the full-view `recompute` answer landed.
623
623
 
624
+ ### Watching a derived scope as the reader
625
+
626
+ The helpers above are the builder's: every one of them needs a write session,
627
+ which an app holding only a bare read entry on the derived scope cannot open.
628
+ That reader sees `GET /v1/data/<derivedScope>` answer 404 whether the compute
629
+ is running, retrying, or finished failing.
630
+
631
+ `getDerivativeStatus` is the reader's view of the same question. It
632
+ authenticates like a data read — a live grant covering the derived scope, or
633
+ the owner — and nothing is charged, so a priced grant raises no 402 here.
634
+
635
+ ```typescript
636
+ import {
637
+ getDerivativeStatus,
638
+ waitForDerivativeStatus,
639
+ } from "@opendatalabs/vana-sdk";
640
+
641
+ const status = await getDerivativeStatus({
642
+ personalServerUrl: "https://ps.example.com",
643
+ derivedScope: "coach.weekly",
644
+ grantId,
645
+ signer,
646
+ });
647
+ // { derivedScope, status, lastComputedAt, derivedVersion,
648
+ // derivedCollectedAt, errorCode, retryAfterSeconds }
649
+
650
+ const settled = await waitForDerivativeStatus({
651
+ personalServerUrl: "https://ps.example.com",
652
+ derivedScope: "coach.weekly",
653
+ grantId,
654
+ signer,
655
+ timeoutMs: 60_000,
656
+ });
657
+ ```
658
+
659
+ The view is lifecycle only: the question text, the source scopes, the question
660
+ id, the registrar and the server's raw `error` string stay owner-only.
661
+ `errorCode` is a closed vocabulary — `inference_unavailable`,
662
+ `source_missing`, `grant_invalid`, `internal` — and is `null` unless `status`
663
+ is `failed`.
664
+
665
+ `retryAfterSeconds` is what separates a failure that is still being worked on
666
+ from one that is over: `inference_unavailable` is the one transient class, and
667
+ the Personal Server retries it on its own schedule. `waitForDerivativeStatus`
668
+ returns as soon as the scope is `ready` or has failed with no retry pending,
669
+ keeps waiting through a retrying failure, and takes the server's
670
+ `retryAfterSeconds` as the cadence in place of `pollIntervalMs`, longer or
671
+ shorter — it is when the next compute actually happens, so asking sooner sees
672
+ nothing new and asking later sits on an answer that already exists. Once the
673
+ remaining budget cannot cover the next cadence it raises the timeout rather
674
+ than spending one more request that cannot carry new data. `signal` aborts
675
+ the wait and the request in flight with it. A failed status is returned, not thrown; branch
676
+ on `errorCode`. `isDerivativeStatusSettled` is the same predicate, exported
677
+ for callers that poll on their own.
678
+
679
+ When several questions write the same derived scope, the most optimistic true
680
+ state answers (`ready`, then `stale`, then `pending`, then `failed`), because
681
+ serving data is registration-agnostic: a duplicate that never wrote anything
682
+ must not report away an answer the scope has.
683
+
684
+ The status route needs a Personal Server that ships it; an older one answers
685
+ 404 for the route itself, which arrives as `DerivativeQuestionNotFoundError`
686
+ — the same error as a covered scope with no question behind it.
687
+
624
688
  ## Networks
625
689
 
626
690
  | Network | Chain ID | RPC URL |
@@ -37,6 +37,7 @@ export { parseWeb3SignedHeader, verifyWeb3Signed, type Web3SignedPayload, type V
37
37
  export { buildWeb3SignedHeader, computeBodyHash, type Web3SignedSignFn, } from "./auth/web3-signed-builder.js";
38
38
  export { MissingAuthError, InvalidSignatureError, ExpiredTokenError, } from "./auth/errors.js";
39
39
  export { NATIVE_VANA_ASSET, dataRegistryDomain, grantRegistrationDomain, grantRevocationDomain, serverRegistrationDomain, builderRegistrationDomain, escrowPaymentDomain, GRANT_REGISTRATION_TYPES, GRANT_REVOCATION_TYPES, SERVER_REGISTRATION_TYPES, BUILDER_REGISTRATION_TYPES, ADD_DATA_TYPES, RECORD_DATA_ACCESS_TYPES, type DataPortabilityContracts, type DataPortabilityGatewayConfig, type GrantRegistrationMessage, type GrantRevocationMessage, type ServerRegistrationMessage, type BuilderRegistrationMessage, type AddDataMessage, type RecordDataAccessMessage, } from "./protocol/eip712.js";
40
+ export { ENCLAVE_IDENTITY_EVIDENCE_VERSION, USER_PS_ID_DOMAIN, ENCLAVE_WALLET_PURPOSE, MASTER_SIGNATURE_DELIVERY_VERSION, SEALED_ENVELOPE_VERSION, ENCLAVE_TRUST_ANCHORS, userPsId, appRootPreimage, kmsIssuedPreimage, verifyEnclaveIdentityEvidence, buildMasterSignatureDelivery, encryptMasterSignatureDelivery, type UserPsId, type EnclaveIdentityEvidence, type IdentityRequest, type IdentityState, type IdentityResponse, type IdentityRegistrationRequest, type IdentityRegistrationResponse, type MasterSignatureDelivery, type SealedSecretSubmission, type SealedSecretResponse, type AesGcmBox, type SealedEnvelope, type EnclaveTrustAnchors, } from "./protocol/identity.js";
40
41
  export { PERSONAL_SERVER_REGISTRATION_DEFAULT_CHAIN_ID, PERSONAL_SERVER_REGISTRATION_DEFAULT_VERIFYING_CONTRACT, personalServerRegistrationDomain, createViemPersonalServerRegistrationSigner, buildPersonalServerRegistrationTypedData, buildPersonalServerRegistrationSignature, registerPersonalServerSignature, type PersonalServerRegistrationTypedData, type PersonalServerRegistrationSigner, type PersonalServerRegistrationDomainInput, type ViemPersonalServerRegistrationWalletClient, type ViemPersonalServerRegistrationSignerSource, type BuildPersonalServerRegistrationTypedDataInput, type BuildPersonalServerRegistrationSignatureInput, type PersonalServerRegistrationSignature, } from "./protocol/personal-server-registration.js";
41
42
  export { PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION, PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE, PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX, buildPersonalServerLiteOwnerBindingMessage, createViemPersonalServerLiteOwnerBindingSigner, buildPersonalServerLiteOwnerBindingSignature, signPersonalServerLiteOwnerBinding, type PersonalServerLiteOwnerBindingPurpose, type PersonalServerLiteOwnerBindingMessage, type PersonalServerLiteOwnerBindingSigner, type ViemPersonalServerLiteOwnerBindingWalletClient, type ViemPersonalServerLiteOwnerBindingSignerSource, type BuildPersonalServerLiteOwnerBindingSignatureInput, type PersonalServerLiteOwnerBindingSignature, } from "./personal-server-lite/owner-binding.js";
42
43
  export { ACCOUNT_PERSONAL_SERVER_REGISTRATION_INTENT, AccountPersonalServerRegistrationError, signPersonalServerRegistrationWithAccount, type AccountPersonalServerRegistrationIntent, type AccountPersonalServerRegistrationSignature, type AccountPersonalServerRegistrationStatus, type AccountPersonalServerRegistrationRequest, type AccountPersonalServerRegistrationConfig, type AccountSignedPersonalServerRegistration, type AccountConfirmationRequiredPersonalServerRegistration, type AccountFallbackSignedPersonalServerRegistration, type AccountPersonalServerRegistrationResult, } from "./account/personal-server-registration.js";
@@ -51,7 +52,8 @@ export { ScopeSchema, parseScope, scopeToPathSegments, scopeMatchesPattern, scop
51
52
  export { SCOPE_ACTIONS, InvalidScopeEntryError, parseScopeEntry, formatScopeEntry, grantPermissions, permissionsToScopes, tryGrantPermissions, hasAction, type ScopeAction, type ParsedScopeEntry, type GrantPermission, } from "./protocol/scope-actions.js";
52
53
  export { WRITE_SESSION_PATH, WRITE_SIGNATURE_HEADER, WRITE_METADATA_HEADER, WRITE_FILENAME_HEADER, WRITE_CONTENT_DISPOSITION_HEADER, WRITER_ATTRIBUTION_KEY, LINEAGE_KEY, LINEAGE_FIELD, MAX_LINEAGE_SOURCES, RESERVED_WRITE_KEYS, openWriteSession, writeData, writePersonalServerData, sessionCoversScope, binaryWriteSignedBytes, normalizeBinaryMimeType, parseWriteMetadataHeader, encodeWriteMetadataHeader, type WriteTransportRetryOptions, type WriteSession, type OpenWriteSessionParams, type WriteBinaryPayload, type LineageSource, type WriteJsonDataParams, type WriteBinaryDataParams, type WriteDataParams, type WriteDataResult, type WritePersonalServerDataParams, type WritePersonalServerDataResult, type BinaryWriteSignedBytesInput, } from "./protocol/personal-server-write.js";
53
54
  export { resolveWriteSigner, type WriteSigner, type WriteSignerSource, type ViemWriteAccount, type ViemWriteWalletClient, type ResolveWriteSignerOptions, } from "./protocol/write-signer.js";
54
- export { DERIVATIVE_QUESTIONS_PATH, MAX_QUESTION_SOURCE_SCOPES, MAX_QUESTION_CHARS, MAX_QUESTION_MODEL_CHARS, DEFAULT_QUESTION_TIMEOUT_MS, DEFAULT_QUESTION_POLL_INTERVAL_MS, QUESTION_STATUSES, registerQuestion, getQuestion, listQuestions, recomputeQuestion, deleteQuestion, waitForQuestion, askPersonalServer, QuestionStatusSchema, QuestionRegisteredBySchema, DerivativeQuestionSchema, QuestionRecomputeResultSchema, QuestionDeleteResultSchema, type QuestionStatus, type QuestionRegisteredBy, type DerivativeQuestion, type QuestionRecomputeResult, type QuestionDeleteResult, type DerivativeQuestionAuthParams, type RegisterQuestionParams, type GetQuestionParams, type ListQuestionsParams, type RecomputeQuestionParams, type DeleteQuestionParams, type WaitForQuestionParams, type AskPersonalServerParams, type AskPersonalServerResult, } from "./protocol/derivative-questions.js";
55
+ export { DERIVATIVE_QUESTIONS_PATH, MAX_QUESTION_SOURCE_SCOPES, MAX_QUESTION_CHARS, MAX_QUESTION_MODEL_CHARS, DEFAULT_QUESTION_TIMEOUT_MS, DEFAULT_QUESTION_POLL_INTERVAL_MS, QUESTION_STATUSES, DERIVATIVE_ERROR_CODES, DerivativeErrorCodeSchema, type DerivativeErrorCode, registerQuestion, getQuestion, listQuestions, recomputeQuestion, deleteQuestion, waitForQuestion, askPersonalServer, QuestionStatusSchema, QuestionRegisteredBySchema, DerivativeQuestionSchema, QuestionRecomputeResultSchema, QuestionDeleteResultSchema, type QuestionStatus, type QuestionRegisteredBy, type DerivativeQuestion, type QuestionRecomputeResult, type QuestionDeleteResult, type DerivativeQuestionAuthParams, type RegisterQuestionParams, type GetQuestionParams, type ListQuestionsParams, type RecomputeQuestionParams, type DeleteQuestionParams, type WaitForQuestionParams, type AskPersonalServerParams, type AskPersonalServerResult, } from "./protocol/derivative-questions.js";
56
+ export { DERIVATIVE_STATUS_PATH, DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS, DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS, derivativeStatusTarget, getDerivativeStatus, waitForDerivativeStatus, isDerivativeStatusSettled, DerivativeStatusSchema, type DerivativeStatus, type GetDerivativeStatusParams, type WaitForDerivativeStatusParams, } from "./protocol/derivative-status.js";
55
57
  export { deriveDataPointId, isDataPointId, scopeNamespace, derivedScopeViolatesNaming, assertDerivedScopeNaming, isRedactedLineageNode, personalServerLineagePath, gatewayLineagePath, getLineage, getPersonalServerLineage, getGatewayLineage, LineageNodeSchema, RedactedLineageNodeSchema, LineageEntrySchema, LineageGraphSchema, type LineageNode, type RedactedLineageNode, type LineageEntry, type LineageGraph, type LineageReadResult, type PersonalServerLineageParams, type GatewayLineageParams, type GetLineageParams, } from "./protocol/lineage.js";
56
58
  export { DataFileEnvelopeSchema, createDataFileEnvelope, IngestResponseSchema, type DataFileEnvelope, type IngestResponse, } from "./protocol/data-file.js";
57
59
  export { createGatewayClient, type GatewayEnvelope, type GatewayProof, type Builder, type Schema, type ServerInfo, type OwnerServerRecord, type OwnerServersResult, type GatewayGrantFee, type GatewayGrantStatus, type GatewayGrantResponse, type GrantListItem, type DataPointRecord, type DataPointListResult, type ListDataPointsOptions, type RegisterServerParams, type RegisterServerResult, type RegisterBuilderParams, type RegisterBuilderResult, type RegisterDataPointParams, type RegisterDataPointResult, type GetDataPointOptions, type DeleteDataPointParams, type DeleteDataPointResult, type CreateGrantParams, type RevokeGrantParams, type AccessRecord, type PayForOperationParams, type PayForOperationResult, type SettleOpType, type SettleItem, type SettlePromoteResult, type SettleReconcileItem, type SettleParams, type SettleResult, type GatewayClient, } from "./protocol/gateway.js";
@@ -31736,6 +31736,124 @@ var RECORD_DATA_ACCESS_TYPES = {
31736
31736
  ]
31737
31737
  };
31738
31738
 
31739
+ // src/protocol/identity.ts
31740
+ init_interface();
31741
+ import * as secp256k13 from "@noble/secp256k1";
31742
+ import {
31743
+ concat as concat4,
31744
+ encodePacked,
31745
+ fromHex as fromHex5,
31746
+ getAddress,
31747
+ keccak256,
31748
+ recoverPublicKey,
31749
+ toBytes
31750
+ } from "viem";
31751
+ import { publicKeyToAddress } from "viem/accounts";
31752
+ var ENCLAVE_IDENTITY_EVIDENCE_VERSION = 1;
31753
+ var USER_PS_ID_DOMAIN = "vana.ps-enclave.v1";
31754
+ var ENCLAVE_WALLET_PURPOSE = "vana.ps-enclave.wallet.v1";
31755
+ var MASTER_SIGNATURE_DELIVERY_VERSION = "vana.ps-enclave.delivery.v1";
31756
+ var SEALED_ENVELOPE_VERSION = 1;
31757
+ var VANA_MAINNET_CHAIN_ID = 1480;
31758
+ var MOKSHA_CHAIN_ID = 14800;
31759
+ var KMS_ISSUED_PREFIX = "dstack-kms-issued";
31760
+ var PREIMAGE_SEPARATOR = ":";
31761
+ var UNCOMPRESSED_PUBLIC_KEY_BYTES = 65;
31762
+ var UNCOMPRESSED_PUBLIC_KEY_PREFIX = "04";
31763
+ var ENCLAVE_TRUST_ANCHORS = {
31764
+ // filled at fleet provisioning; verify fails closed while empty
31765
+ [VANA_MAINNET_CHAIN_ID]: { kmsRootPubkey: "0x", appIds: [] },
31766
+ // filled at fleet provisioning; verify fails closed while empty
31767
+ [MOKSHA_CHAIN_ID]: { kmsRootPubkey: "0x", appIds: [] }
31768
+ };
31769
+ function userPsId(chainId, ownerAddress) {
31770
+ const packed = encodePacked(
31771
+ ["string", "uint256", "address"],
31772
+ [USER_PS_ID_DOMAIN, BigInt(chainId), getAddress(ownerAddress)]
31773
+ );
31774
+ return keccak256(packed);
31775
+ }
31776
+ function appRootPreimage(purpose, publicKey) {
31777
+ const keyHex = publicKey.slice(2).toLowerCase();
31778
+ return keccak256(toBytes(`${purpose}${PREIMAGE_SEPARATOR}${keyHex}`));
31779
+ }
31780
+ function kmsIssuedPreimage(appId, appRootPublicKey) {
31781
+ const appIdHex = appId.slice(2).toLowerCase();
31782
+ const prefix = toBytes(
31783
+ `${KMS_ISSUED_PREFIX}${PREIMAGE_SEPARATOR}${appIdHex}`
31784
+ );
31785
+ const compressed = secp256k13.ProjectivePoint.fromHex(
31786
+ fromHex5(appRootPublicKey, "bytes")
31787
+ ).toRawBytes(true);
31788
+ return keccak256(concat4([prefix, compressed]));
31789
+ }
31790
+ async function recoverChainKey(hash, signature, link) {
31791
+ try {
31792
+ return (await recoverPublicKey({ hash, signature })).toLowerCase();
31793
+ } catch {
31794
+ throw new Error(`Invalid enclave signature chain link ${link}`);
31795
+ }
31796
+ }
31797
+ async function verifyEnclaveIdentityEvidence(evidence, anchors) {
31798
+ if (evidence.v !== ENCLAVE_IDENTITY_EVIDENCE_VERSION) {
31799
+ throw new Error("Unsupported enclave identity evidence version");
31800
+ }
31801
+ if (!Number.isInteger(evidence.epoch) || evidence.epoch < 1) {
31802
+ throw new Error("Invalid enclave identity epoch");
31803
+ }
31804
+ const derivedAddress = publicKeyToAddress(evidence.publicKey);
31805
+ if (getAddress(derivedAddress) !== getAddress(evidence.address)) {
31806
+ throw new Error("Enclave public key does not match its address");
31807
+ }
31808
+ const appRootPublicKey = await recoverChainKey(
31809
+ appRootPreimage(evidence.purpose, evidence.publicKey),
31810
+ evidence.signatureChain[0],
31811
+ 0
31812
+ );
31813
+ const kmsRootPublicKey = await recoverChainKey(
31814
+ kmsIssuedPreimage(evidence.appId, appRootPublicKey),
31815
+ evidence.signatureChain[1],
31816
+ 1
31817
+ );
31818
+ if (anchors.kmsRootPubkey === "0x") {
31819
+ throw new Error("KMS root trust anchor is not provisioned");
31820
+ }
31821
+ if (kmsRootPublicKey !== anchors.kmsRootPubkey.toLowerCase()) {
31822
+ throw new Error("KMS root public key does not match the trust anchor");
31823
+ }
31824
+ if (keccak256(kmsRootPublicKey) !== evidence.kmsRootFingerprint.toLowerCase()) {
31825
+ throw new Error("KMS root fingerprint does not match the evidence");
31826
+ }
31827
+ const appId = evidence.appId.toLowerCase();
31828
+ if (!anchors.appIds.some((allowedAppId) => allowedAppId.toLowerCase() === appId)) {
31829
+ throw new Error("Enclave app ID is not trusted");
31830
+ }
31831
+ }
31832
+ function buildMasterSignatureDelivery(evidence, masterSignature, now = Math.floor(Date.now() / 1e3)) {
31833
+ deriveMasterKey(masterSignature);
31834
+ return {
31835
+ v: MASTER_SIGNATURE_DELIVERY_VERSION,
31836
+ userPsId: evidence.userPsId,
31837
+ epoch: evidence.epoch,
31838
+ enclaveAddress: evidence.address,
31839
+ ownerAddress: evidence.ownerAddress,
31840
+ masterSignature,
31841
+ issuedAt: now
31842
+ };
31843
+ }
31844
+ function assertUncompressedKey(publicKey) {
31845
+ const hex = publicKey.slice(2);
31846
+ if (hex.length !== UNCOMPRESSED_PUBLIC_KEY_BYTES * 2 || !hex.startsWith(UNCOMPRESSED_PUBLIC_KEY_PREFIX) || !/^[0-9a-fA-F]+$/.test(hex)) {
31847
+ throw new Error("Public key must be a 65-byte uncompressed secp256k1 key");
31848
+ }
31849
+ }
31850
+ async function encryptMasterSignatureDelivery(delivery, publicKey, ecies) {
31851
+ assertUncompressedKey(publicKey);
31852
+ const plaintext = toBytes(JSON.stringify(delivery));
31853
+ const encrypted = await ecies.encrypt(fromHex5(publicKey, "bytes"), plaintext);
31854
+ return `0x${serializeECIES(encrypted)}`;
31855
+ }
31856
+
31739
31857
  // src/protocol/personal-server-registration.ts
31740
31858
  import {
31741
31859
  isAddress
@@ -32435,7 +32553,7 @@ function buildMarkDataPointUnavailableRequest(config, input) {
32435
32553
  // src/protocol/data-point-deletion.ts
32436
32554
  import {
32437
32555
  isAddress as isAddress5,
32438
- keccak256 as keccak2562,
32556
+ keccak256 as keccak2563,
32439
32557
  maxUint256,
32440
32558
  stringToBytes as stringToBytes3
32441
32559
  } from "viem";
@@ -32444,7 +32562,7 @@ import {
32444
32562
  import {
32445
32563
  encodeAbiParameters,
32446
32564
  isAddress as isAddress4,
32447
- keccak256
32565
+ keccak256 as keccak2562
32448
32566
  } from "viem";
32449
32567
  import { z } from "zod";
32450
32568
 
@@ -32528,7 +32646,7 @@ function deriveDataPointId(ownerAddress, scope) {
32528
32646
  `ownerAddress is not an EVM address: ${String(ownerAddress)}`
32529
32647
  );
32530
32648
  }
32531
- return keccak256(
32649
+ return keccak2562(
32532
32650
  encodeAbiParameters(
32533
32651
  [
32534
32652
  { name: "ownerAddress", type: "address" },
@@ -32755,7 +32873,7 @@ var TOMBSTONE_METADATA_HASH_PREIMAGE = "vana.data-point.tombstone.metadata.v1";
32755
32873
  var TOMBSTONE_DATA_HASH = "0x30c45ee72fe56d1927701316925ab7ceacd3b6f9267061735d59396f075c6222";
32756
32874
  var TOMBSTONE_METADATA_HASH = "0xc5255a141acd6a2ae55971b62c0a85977c2511989dc114ad2abc2b7644f57d90";
32757
32875
  function computeTombstoneHash(preimage) {
32758
- return keccak2562(stringToBytes3(preimage));
32876
+ return keccak2563(stringToBytes3(preimage));
32759
32877
  }
32760
32878
  function isTombstoneHashes(dataHash, metadataHash) {
32761
32879
  return typeof dataHash === "string" && typeof metadataHash === "string" && dataHash.toLowerCase() === TOMBSTONE_DATA_HASH && metadataHash.toLowerCase() === TOMBSTONE_METADATA_HASH;
@@ -33777,6 +33895,13 @@ var QUESTION_STATUSES = [
33777
33895
  "failed",
33778
33896
  "stale"
33779
33897
  ];
33898
+ var DERIVATIVE_ERROR_CODES = [
33899
+ "inference_unavailable",
33900
+ "source_missing",
33901
+ "grant_invalid",
33902
+ "internal"
33903
+ ];
33904
+ var DerivativeErrorCodeSchema = z5.enum(DERIVATIVE_ERROR_CODES);
33780
33905
  var QuestionStatusSchema = z5.enum(QUESTION_STATUSES);
33781
33906
  var QuestionRegisteredBySchema = z5.union([
33782
33907
  z5.object({ kind: z5.literal("owner") }),
@@ -33798,6 +33923,14 @@ var DerivativeQuestionSchema = z5.object({
33798
33923
  status: QuestionStatusSchema,
33799
33924
  /** A short reason, set only while `status` is `failed`. */
33800
33925
  error: nullableString,
33926
+ /**
33927
+ * The coarse failure class behind `error`, set only while `status` is
33928
+ * `failed`. `null` from a Personal Server that predates the class
33929
+ * (`personal-server-ts` before the status route).
33930
+ */
33931
+ errorCode: DerivativeErrorCodeSchema.nullish().transform(
33932
+ (value) => value ?? null
33933
+ ),
33801
33934
  createdAt: z5.string(),
33802
33935
  updatedAt: nullableString,
33803
33936
  /** When the last compute finished, or `null` while `pending`. */
@@ -33930,6 +34063,7 @@ async function questionErrorFromResponse(response, body) {
33930
34063
  );
33931
34064
  }
33932
34065
  }
34066
+ var personalServerErrorFromQuestionResponse = questionErrorFromResponse;
33933
34067
  async function sendOnce(params, resolved, session, spec, bodyBytes) {
33934
34068
  return sendWithFreshProof(
33935
34069
  spec.label,
@@ -34209,6 +34343,166 @@ async function askPersonalServer(params) {
34209
34343
  return { registration, record };
34210
34344
  }
34211
34345
 
34346
+ // src/protocol/derivative-status.ts
34347
+ import { z as z6 } from "zod";
34348
+ var DERIVATIVE_STATUS_PATH = "/v1/derivatives/status";
34349
+ var DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS = 12e4;
34350
+ var DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS = 2e3;
34351
+ var nullable = (schema) => schema.nullish().transform((value) => value ?? null);
34352
+ var DerivativeStatusSchema = z6.object({
34353
+ derivedScope: z6.string().min(1),
34354
+ status: QuestionStatusSchema,
34355
+ /** When the last compute finished, or `null` if none ever has. */
34356
+ lastComputedAt: nullable(z6.string()),
34357
+ /** Local version of the derived record the last compute wrote. */
34358
+ derivedVersion: nullable(z6.number()),
34359
+ derivedCollectedAt: nullable(z6.string()),
34360
+ /** The failure class; `null` unless `status` is `failed`. */
34361
+ errorCode: nullable(DerivativeErrorCodeSchema),
34362
+ /**
34363
+ * Seconds until the Personal Server's next automatic retry, or `null` when
34364
+ * none is pending or running — the terminal signature. Poll on this cadence
34365
+ * rather than guessing one.
34366
+ */
34367
+ retryAfterSeconds: nullable(z6.number())
34368
+ });
34369
+ function derivativeStatusTarget(derivedScope) {
34370
+ return `${DERIVATIVE_STATUS_PATH}?derivedScope=${encodeURIComponent(derivedScope)}`;
34371
+ }
34372
+ function normalizeBaseUrl3(url) {
34373
+ return url.replace(/\/+$/, "");
34374
+ }
34375
+ function resolveFetch3(fetchFn) {
34376
+ const resolved = fetchFn ?? globalThis.fetch;
34377
+ if (resolved === void 0) {
34378
+ throw new WriteRequestError("No fetch implementation available");
34379
+ }
34380
+ return resolved;
34381
+ }
34382
+ function requireDerivedScope(derivedScope) {
34383
+ if (typeof derivedScope !== "string" || derivedScope.length === 0) {
34384
+ throw new WriteRequestError("derivedScope is required");
34385
+ }
34386
+ return derivedScope;
34387
+ }
34388
+ function sleep3(ms, signal) {
34389
+ if (ms <= 0) return Promise.resolve();
34390
+ return new Promise((resolve, reject) => {
34391
+ const timer = setTimeout(() => {
34392
+ signal?.removeEventListener("abort", onAbort);
34393
+ resolve();
34394
+ }, ms);
34395
+ const onAbort = () => {
34396
+ clearTimeout(timer);
34397
+ reject(abortError2(signal));
34398
+ };
34399
+ signal?.addEventListener("abort", onAbort, { once: true });
34400
+ });
34401
+ }
34402
+ function timeoutError(latest, timeoutMs) {
34403
+ return new DerivativeQuestionTimeoutError(
34404
+ `Derived scope ${latest.derivedScope} was still ${latest.status} after ${timeoutMs}ms`,
34405
+ {
34406
+ derivedScope: latest.derivedScope,
34407
+ status: latest.status,
34408
+ errorCode: latest.errorCode,
34409
+ retryAfterSeconds: latest.retryAfterSeconds,
34410
+ timeoutMs
34411
+ }
34412
+ );
34413
+ }
34414
+ function abortError2(signal) {
34415
+ const reason = signal?.reason;
34416
+ return reason instanceof Error ? reason : new WriteRequestError("Derivative status wait was aborted");
34417
+ }
34418
+ function isDerivativeStatusSettled(status) {
34419
+ if (status.status === "ready") return true;
34420
+ return status.status === "failed" && status.retryAfterSeconds === null;
34421
+ }
34422
+ async function getDerivativeStatus(params) {
34423
+ const derivedScope = requireDerivedScope(params.derivedScope);
34424
+ const fetchFn = resolveFetch3(params.fetch);
34425
+ const baseUrl = normalizeBaseUrl3(params.personalServerUrl);
34426
+ const signer = resolveWriteSigner(params.signer, { account: params.account });
34427
+ const headers = new Headers(params.headers);
34428
+ headers.set(
34429
+ "Authorization",
34430
+ await buildWeb3SignedHeader({
34431
+ signMessage: signer.signMessage,
34432
+ aud: params.audience ?? baseUrl,
34433
+ method: "GET",
34434
+ uri: DERIVATIVE_STATUS_PATH,
34435
+ grantId: params.grantId
34436
+ })
34437
+ );
34438
+ let response;
34439
+ try {
34440
+ response = await fetchFn(
34441
+ `${baseUrl}${derivativeStatusTarget(derivedScope)}`,
34442
+ {
34443
+ method: "GET",
34444
+ headers,
34445
+ ...params.signal ? { signal: params.signal } : {}
34446
+ }
34447
+ );
34448
+ } catch (err) {
34449
+ throw new WriteTransportError(
34450
+ `Derivative status read failed: ${err instanceof Error ? err.message : String(err)}`,
34451
+ 1,
34452
+ err
34453
+ );
34454
+ }
34455
+ if (!response.ok) {
34456
+ throw await personalServerErrorFromQuestionResponse(
34457
+ response
34458
+ );
34459
+ }
34460
+ let body;
34461
+ try {
34462
+ body = await response.json();
34463
+ } catch (err) {
34464
+ throw new DerivativeQuestionRejectedError(
34465
+ "Derivative status response is not JSON",
34466
+ response.status,
34467
+ null,
34468
+ { cause: err instanceof Error ? err.message : String(err) }
34469
+ );
34470
+ }
34471
+ const parsed = DerivativeStatusSchema.safeParse(body);
34472
+ if (!parsed.success) {
34473
+ throw new DerivativeQuestionRejectedError(
34474
+ "Derivative status response is not a status view",
34475
+ response.status,
34476
+ null,
34477
+ { issues: parsed.error.issues }
34478
+ );
34479
+ }
34480
+ return parsed.data;
34481
+ }
34482
+ async function waitForDerivativeStatus(params) {
34483
+ const timeoutMs = Math.max(
34484
+ 0,
34485
+ params.timeoutMs ?? DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS
34486
+ );
34487
+ const pollIntervalMs = Math.max(
34488
+ 0,
34489
+ params.pollIntervalMs ?? DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS
34490
+ );
34491
+ const deadline = Date.now() + timeoutMs;
34492
+ for (; ; ) {
34493
+ if (params.signal?.aborted) throw abortError2(params.signal);
34494
+ const latest = await getDerivativeStatus(params);
34495
+ if (isDerivativeStatusSettled(latest)) return latest;
34496
+ const remaining = deadline - Date.now();
34497
+ if (remaining <= 0) throw timeoutError(latest, timeoutMs);
34498
+ const waitMs = latest.retryAfterSeconds === null ? pollIntervalMs : latest.retryAfterSeconds * 1e3;
34499
+ if (waitMs > remaining) {
34500
+ throw timeoutError(latest, timeoutMs);
34501
+ }
34502
+ await sleep3(waitMs, params.signal);
34503
+ }
34504
+ }
34505
+
34212
34506
  // src/protocol/gateway.ts
34213
34507
  function withGrantPermissions(grant) {
34214
34508
  const stripped = { ...grant };
@@ -34821,9 +35115,13 @@ export {
34821
35115
  ContractFactory,
34822
35116
  ContractNotFoundError,
34823
35117
  DATA_REGISTRY_STATUS_ABI,
35118
+ DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS,
35119
+ DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS,
34824
35120
  DEFAULT_QUESTION_POLL_INTERVAL_MS,
34825
35121
  DEFAULT_QUESTION_TIMEOUT_MS,
35122
+ DERIVATIVE_ERROR_CODES,
34826
35123
  DERIVATIVE_QUESTIONS_PATH,
35124
+ DERIVATIVE_STATUS_PATH,
34827
35125
  DataFileEnvelopeSchema,
34828
35126
  DataPointDeletedError,
34829
35127
  DataPointNotFoundError,
@@ -34832,6 +35130,7 @@ export {
34832
35130
  DerivativeComputeUnavailableError,
34833
35131
  DerivativeCycleError,
34834
35132
  DerivativeDerivedScopeRequiredError,
35133
+ DerivativeErrorCodeSchema,
34835
35134
  DerivativeQuestionFailedError,
34836
35135
  DerivativeQuestionInvalidError,
34837
35136
  DerivativeQuestionNotFoundError,
@@ -34839,8 +35138,12 @@ export {
34839
35138
  DerivativeQuestionSchema,
34840
35139
  DerivativeQuestionTimeoutError,
34841
35140
  DerivativeSourceNotGrantedError,
35141
+ DerivativeStatusSchema,
34842
35142
  DropboxStorage,
34843
35143
  ECIESError,
35144
+ ENCLAVE_IDENTITY_EVIDENCE_VERSION,
35145
+ ENCLAVE_TRUST_ANCHORS,
35146
+ ENCLAVE_WALLET_PURPOSE,
34844
35147
  ESCROW_DEPOSIT_ABI2 as ESCROW_DEPOSIT_ABI,
34845
35148
  ExpiredTokenError,
34846
35149
  FEE_REGISTRY_ABI,
@@ -34861,6 +35164,7 @@ export {
34861
35164
  LineageNodeSchema,
34862
35165
  LineageReadError,
34863
35166
  MASTER_KEY_MESSAGE,
35167
+ MASTER_SIGNATURE_DELIVERY_VERSION,
34864
35168
  MAX_LINEAGE_SOURCES,
34865
35169
  MAX_QUESTION_CHARS,
34866
35170
  MAX_QUESTION_MODEL_CHARS,
@@ -34896,6 +35200,7 @@ export {
34896
35200
  RedactedLineageNodeSchema,
34897
35201
  RelayerError,
34898
35202
  SCOPE_ACTIONS,
35203
+ SEALED_ENVELOPE_VERSION,
34899
35204
  SERVER_REGISTRATION_TYPES,
34900
35205
  ScopeSchema,
34901
35206
  SerializationError,
@@ -34908,6 +35213,7 @@ export {
34908
35213
  TOMBSTONE_METADATA_HASH,
34909
35214
  TOMBSTONE_METADATA_HASH_PREIMAGE,
34910
35215
  TransactionPendingError,
35216
+ USER_PS_ID_DOMAIN,
34911
35217
  UserRejectedRequestError,
34912
35218
  VanaError,
34913
35219
  VanaStorage,
@@ -34926,6 +35232,7 @@ export {
34926
35232
  WriteSessionExpiredError,
34927
35233
  WriteTransportError,
34928
35234
  WriteUnauthorizedError,
35235
+ appRootPreimage,
34929
35236
  askPersonalServer,
34930
35237
  assertDerivedScopeNaming,
34931
35238
  assertValidPkceVerifier,
@@ -34935,6 +35242,7 @@ export {
34935
35242
  buildDepositNativeRequest,
34936
35243
  buildDepositTokenRequest,
34937
35244
  buildMarkDataPointUnavailableRequest,
35245
+ buildMasterSignatureDelivery,
34938
35246
  buildPersonalServerDataReadRequest,
34939
35247
  buildPersonalServerLiteOwnerBindingMessage,
34940
35248
  buildPersonalServerLiteOwnerBindingSignature,
@@ -34963,6 +35271,7 @@ export {
34963
35271
  decryptWithPassword,
34964
35272
  deleteDataPoint,
34965
35273
  deleteQuestion,
35274
+ derivativeStatusTarget,
34966
35275
  deriveDataPointId,
34967
35276
  deriveMasterKey,
34968
35277
  deriveScopeKey,
@@ -34973,6 +35282,7 @@ export {
34973
35282
  encodeDepositTokenData,
34974
35283
  encodeSetDataPointStatusData,
34975
35284
  encodeWriteMetadataHeader,
35285
+ encryptMasterSignatureDelivery,
34976
35286
  encryptWithPassword,
34977
35287
  escrowContractAddress,
34978
35288
  escrowPaymentDomain,
@@ -34986,6 +35296,7 @@ export {
34986
35296
  getContractAddress,
34987
35297
  getContractController,
34988
35298
  getContractInfo,
35299
+ getDerivativeStatus,
34989
35300
  getFee,
34990
35301
  getGatewayLineage,
34991
35302
  getLineage,
@@ -35001,10 +35312,12 @@ export {
35001
35312
  isDataPointId,
35002
35313
  isDataPointTombstone,
35003
35314
  isDataPortabilityGatewayConfig,
35315
+ isDerivativeStatusSettled,
35004
35316
  isECIESEncrypted,
35005
35317
  isPlatformSupported,
35006
35318
  isRedactedLineageNode,
35007
35319
  isTombstoneHashes,
35320
+ kmsIssuedPreimage,
35008
35321
  listQuestions,
35009
35322
  mainnetServices,
35010
35323
  moksha,
@@ -35039,10 +35352,13 @@ export {
35039
35352
  signPersonalServerRegistrationWithAccount,
35040
35353
  tombstoneDeletedAt,
35041
35354
  tryGrantPermissions,
35355
+ userPsId,
35042
35356
  vanaMainnet2 as vanaMainnet,
35357
+ verifyEnclaveIdentityEvidence,
35043
35358
  verifyGrantRegistration,
35044
35359
  verifyPkceChallenge,
35045
35360
  verifyWeb3Signed,
35361
+ waitForDerivativeStatus,
35046
35362
  waitForQuestion,
35047
35363
  writeData,
35048
35364
  writePersonalServerData