@opendatalabs/vana-sdk 3.18.0 → 3.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +129 -3
  2. package/dist/errors.cjs +56 -0
  3. package/dist/errors.cjs.map +1 -1
  4. package/dist/errors.d.ts +98 -2
  5. package/dist/errors.js +48 -0
  6. package/dist/errors.js.map +1 -1
  7. package/dist/index.browser.d.ts +1 -0
  8. package/dist/index.browser.js +542 -33
  9. package/dist/index.browser.js.map +4 -4
  10. package/dist/index.node.cjs +569 -33
  11. package/dist/index.node.cjs.map +4 -4
  12. package/dist/index.node.d.ts +1 -0
  13. package/dist/index.node.js +542 -33
  14. package/dist/index.node.js.map +4 -4
  15. package/dist/protocol/derivative-questions.cjs +501 -0
  16. package/dist/protocol/derivative-questions.cjs.map +1 -0
  17. package/dist/protocol/derivative-questions.d.ts +355 -0
  18. package/dist/protocol/derivative-questions.js +486 -0
  19. package/dist/protocol/derivative-questions.js.map +1 -0
  20. package/dist/protocol/derivative-questions.test.d.ts +1 -0
  21. package/dist/protocol/lineage.cjs +9 -4
  22. package/dist/protocol/lineage.cjs.map +1 -1
  23. package/dist/protocol/lineage.d.ts +21 -12
  24. package/dist/protocol/lineage.js +9 -4
  25. package/dist/protocol/lineage.js.map +1 -1
  26. package/dist/protocol/personal-server-write.cjs +12 -108
  27. package/dist/protocol/personal-server-write.cjs.map +1 -1
  28. package/dist/protocol/personal-server-write.d.ts +2 -17
  29. package/dist/protocol/personal-server-write.js +7 -98
  30. package/dist/protocol/personal-server-write.js.map +1 -1
  31. package/dist/protocol/write-request.cjs +142 -0
  32. package/dist/protocol/write-request.cjs.map +1 -0
  33. package/dist/protocol/write-request.d.ts +63 -0
  34. package/dist/protocol/write-request.js +111 -0
  35. package/dist/protocol/write-request.js.map +1 -0
  36. package/dist/tests/mock-personal-server.d.ts +51 -0
  37. package/package.json +1 -1
@@ -1186,11 +1186,23 @@ __export(index_node_exports, {
1186
1186
  ContractNotFoundError: () => ContractNotFoundError,
1187
1187
  DATA_ACCESS_OP_TYPE: () => DATA_ACCESS_OP_TYPE,
1188
1188
  DATA_REGISTRY_STATUS_ABI: () => DATA_REGISTRY_STATUS_ABI,
1189
+ DEFAULT_QUESTION_POLL_INTERVAL_MS: () => DEFAULT_QUESTION_POLL_INTERVAL_MS,
1190
+ DEFAULT_QUESTION_TIMEOUT_MS: () => DEFAULT_QUESTION_TIMEOUT_MS,
1191
+ DERIVATIVE_QUESTIONS_PATH: () => DERIVATIVE_QUESTIONS_PATH,
1189
1192
  DataFileEnvelopeSchema: () => DataFileEnvelopeSchema,
1190
1193
  DataPointDeletedError: () => DataPointDeletedError,
1191
1194
  DataPointNotFoundError: () => DataPointNotFoundError,
1192
1195
  DataPointStatus: () => DataPointStatus,
1193
1196
  DataPointVersionConflictError: () => DataPointVersionConflictError,
1197
+ DerivativeComputeUnavailableError: () => DerivativeComputeUnavailableError,
1198
+ DerivativeCycleError: () => DerivativeCycleError,
1199
+ DerivativeQuestionFailedError: () => DerivativeQuestionFailedError,
1200
+ DerivativeQuestionInvalidError: () => DerivativeQuestionInvalidError,
1201
+ DerivativeQuestionNotFoundError: () => DerivativeQuestionNotFoundError,
1202
+ DerivativeQuestionRejectedError: () => DerivativeQuestionRejectedError,
1203
+ DerivativeQuestionSchema: () => DerivativeQuestionSchema,
1204
+ DerivativeQuestionTimeoutError: () => DerivativeQuestionTimeoutError,
1205
+ DerivativeSourceNotGrantedError: () => DerivativeSourceNotGrantedError,
1194
1206
  DropboxStorage: () => DropboxStorage,
1195
1207
  ECIESError: () => ECIESError,
1196
1208
  ESCROW_DEPOSIT_ABI: () => ESCROW_DEPOSIT_ABI2,
@@ -1215,6 +1227,9 @@ __export(index_node_exports, {
1215
1227
  LineageReadError: () => LineageReadError,
1216
1228
  MASTER_KEY_MESSAGE: () => MASTER_KEY_MESSAGE,
1217
1229
  MAX_LINEAGE_SOURCES: () => MAX_LINEAGE_SOURCES,
1230
+ MAX_QUESTION_CHARS: () => MAX_QUESTION_CHARS,
1231
+ MAX_QUESTION_MODEL_CHARS: () => MAX_QUESTION_MODEL_CHARS,
1232
+ MAX_QUESTION_SOURCE_SCOPES: () => MAX_QUESTION_SOURCE_SCOPES,
1218
1233
  MissingAuthError: () => MissingAuthError,
1219
1234
  NATIVE_ASSET_ADDRESS: () => NATIVE_ASSET_ADDRESS,
1220
1235
  NATIVE_VANA_ASSET: () => NATIVE_VANA_ASSET,
@@ -1235,6 +1250,11 @@ __export(index_node_exports, {
1235
1250
  PersonalServerError: () => PersonalServerError,
1236
1251
  PersonalServerWriteError: () => PersonalServerWriteError,
1237
1252
  PinataStorage: () => PinataStorage,
1253
+ QUESTION_STATUSES: () => QUESTION_STATUSES,
1254
+ QuestionDeleteResultSchema: () => QuestionDeleteResultSchema,
1255
+ QuestionRecomputeResultSchema: () => QuestionRecomputeResultSchema,
1256
+ QuestionRegisteredBySchema: () => QuestionRegisteredBySchema,
1257
+ QuestionStatusSchema: () => QuestionStatusSchema,
1238
1258
  R2Storage: () => R2Storage,
1239
1259
  RECORD_DATA_ACCESS_TYPES: () => RECORD_DATA_ACCESS_TYPES,
1240
1260
  REGISTRATION_KIND_FOR_OP: () => REGISTRATION_KIND_FOR_OP,
@@ -1273,6 +1293,7 @@ __export(index_node_exports, {
1273
1293
  WriteSessionExpiredError: () => WriteSessionExpiredError,
1274
1294
  WriteTransportError: () => WriteTransportError,
1275
1295
  WriteUnauthorizedError: () => WriteUnauthorizedError,
1296
+ askPersonalServer: () => askPersonalServer,
1276
1297
  assertDerivedScopeNaming: () => assertDerivedScopeNaming,
1277
1298
  assertValidPkceVerifier: () => assertValidPkceVerifier,
1278
1299
  authorizeEscrowPayment: () => authorizeEscrowPayment,
@@ -1316,6 +1337,7 @@ __export(index_node_exports, {
1316
1337
  dataRegistryDomain: () => dataRegistryDomain,
1317
1338
  decryptWithPassword: () => decryptWithPassword,
1318
1339
  deleteDataPoint: () => deleteDataPoint,
1340
+ deleteQuestion: () => deleteQuestion,
1319
1341
  deriveDataPointId: () => deriveDataPointId,
1320
1342
  deriveMasterKey: () => deriveMasterKey,
1321
1343
  deriveScopeKey: () => deriveScopeKey,
@@ -1345,6 +1367,7 @@ __export(index_node_exports, {
1345
1367
  getOpFee: () => getOpFee,
1346
1368
  getPersonalServerLineage: () => getPersonalServerLineage,
1347
1369
  getPlatformCapabilities: () => getPlatformCapabilities,
1370
+ getQuestion: () => getQuestion,
1348
1371
  getServiceEndpoints: () => getServiceEndpoints,
1349
1372
  grantPermissions: () => grantPermissions,
1350
1373
  grantRegistrationDomain: () => grantRegistrationDomain,
@@ -1357,6 +1380,7 @@ __export(index_node_exports, {
1357
1380
  isPlatformSupported: () => isPlatformSupported,
1358
1381
  isRedactedLineageNode: () => isRedactedLineageNode,
1359
1382
  isTombstoneHashes: () => isTombstoneHashes,
1383
+ listQuestions: () => listQuestions,
1360
1384
  mainnetServices: () => mainnetServices,
1361
1385
  moksha: () => moksha,
1362
1386
  mokshaServices: () => mokshaServices,
@@ -1376,8 +1400,10 @@ __export(index_node_exports, {
1376
1400
  personalServerLineagePath: () => personalServerLineagePath,
1377
1401
  personalServerRegistrationDomain: () => personalServerRegistrationDomain,
1378
1402
  readPersonalServerData: () => readPersonalServerData,
1403
+ recomputeQuestion: () => recomputeQuestion,
1379
1404
  recoverServerOwner: () => recoverServerOwner,
1380
1405
  registerPersonalServerSignature: () => registerPersonalServerSignature,
1406
+ registerQuestion: () => registerQuestion,
1381
1407
  resolveWriteSigner: () => resolveWriteSigner,
1382
1408
  scopeCoveredByGrant: () => scopeCoveredByGrant,
1383
1409
  scopeMatchesPattern: () => scopeMatchesPattern,
@@ -1397,6 +1423,7 @@ __export(index_node_exports, {
1397
1423
  verifyGrantRegistration: () => verifyGrantRegistration,
1398
1424
  verifyPkceChallenge: () => verifyPkceChallenge,
1399
1425
  verifyWeb3Signed: () => verifyWeb3Signed,
1426
+ waitForQuestion: () => waitForQuestion,
1400
1427
  writeData: () => writeData,
1401
1428
  writePersonalServerData: () => writePersonalServerData
1402
1429
  });
@@ -1613,6 +1640,46 @@ var LineageReadError = class extends VanaError {
1613
1640
  errorCode;
1614
1641
  details;
1615
1642
  };
1643
+ var DerivativeQuestionRejectedError = class extends PersonalServerWriteError {
1644
+ constructor(message, status, errorCode = null, details) {
1645
+ super(message, "DERIVATIVE_QUESTION_REJECTED", status, errorCode, details);
1646
+ }
1647
+ };
1648
+ var DerivativeQuestionInvalidError = class extends PersonalServerWriteError {
1649
+ constructor(message, status = 400, errorCode = null, details) {
1650
+ super(message, "DERIVATIVE_QUESTION_INVALID", status, errorCode, details);
1651
+ }
1652
+ };
1653
+ var DerivativeQuestionNotFoundError = class extends PersonalServerWriteError {
1654
+ constructor(message, errorCode = null, details) {
1655
+ super(message, "DERIVATIVE_QUESTION_NOT_FOUND", 404, errorCode, details);
1656
+ }
1657
+ };
1658
+ var DerivativeSourceNotGrantedError = class extends PersonalServerWriteError {
1659
+ constructor(message, errorCode = null, details) {
1660
+ super(message, "DERIVATIVE_SOURCE_NOT_GRANTED", 403, errorCode, details);
1661
+ }
1662
+ };
1663
+ var DerivativeCycleError = class extends PersonalServerWriteError {
1664
+ constructor(message, errorCode = null, details) {
1665
+ super(message, "DERIVATIVE_CYCLE", 409, errorCode, details);
1666
+ }
1667
+ };
1668
+ var DerivativeComputeUnavailableError = class extends PersonalServerWriteError {
1669
+ constructor(message, errorCode = null, details) {
1670
+ super(message, "DERIVATIVE_COMPUTE_UNAVAILABLE", 503, errorCode, details);
1671
+ }
1672
+ };
1673
+ var DerivativeQuestionTimeoutError = class extends PersonalServerWriteError {
1674
+ constructor(message, details) {
1675
+ super(message, "DERIVATIVE_QUESTION_TIMEOUT", void 0, null, details);
1676
+ }
1677
+ };
1678
+ var DerivativeQuestionFailedError = class extends PersonalServerWriteError {
1679
+ constructor(message, details) {
1680
+ super(message, "DERIVATIVE_QUESTION_FAILED", void 0, null, details);
1681
+ }
1682
+ };
1616
1683
  var DataPointDeletedError = class extends VanaError {
1617
1684
  constructor(message, details = {}) {
1618
1685
  super(message, "DATA_POINT_DELETED");
@@ -34006,10 +34073,15 @@ var LineageNodeSchema = import_zod.z.object({
34006
34073
  */
34007
34074
  version: VersionSchema,
34008
34075
  /** The node's tombstone time, or `null` when live. */
34009
- deletedAt: import_zod.z.string().nullable()
34076
+ deletedAt: import_zod.z.string().nullable(),
34077
+ /**
34078
+ * Never present on a visible node. Declared so a node that carries
34079
+ * `redacted: true` next to an id, scope and version cannot slip through
34080
+ * this branch of {@link LineageEntrySchema} with the key stripped.
34081
+ */
34082
+ redacted: import_zod.z.never().optional()
34010
34083
  });
34011
- var RedactedLineageNodeSchema = import_zod.z.object({
34012
- dataPointId: DataPointIdSchema,
34084
+ var RedactedLineageNodeSchema = import_zod.z.strictObject({
34013
34085
  redacted: import_zod.z.literal(true)
34014
34086
  });
34015
34087
  var LineageEntrySchema = import_zod.z.union([
@@ -34034,7 +34106,7 @@ var LineageGraphSchema = import_zod.z.object({
34034
34106
  derivativesTruncated: import_zod.z.boolean().optional()
34035
34107
  });
34036
34108
  function isRedactedLineageNode(entry) {
34037
- return "redacted" in entry && entry.redacted === true;
34109
+ return "redacted" in entry && entry.redacted === true && Object.keys(entry).length === 1;
34038
34110
  }
34039
34111
  function personalServerLineagePath(scope, version) {
34040
34112
  return `/v1/data/${encodeURIComponent(scope)}/lineage${version === void 0 ? "" : `/${String(version)}`}`;
@@ -34616,32 +34688,13 @@ function tryGrantPermissions(scopes) {
34616
34688
  }
34617
34689
 
34618
34690
  // src/protocol/personal-server-write.ts
34691
+ var import_sha26 = require("@noble/hashes/sha2");
34692
+ var import_viem24 = require("viem");
34693
+ var import_zod4 = require("zod");
34694
+
34695
+ // src/protocol/write-request.ts
34619
34696
  var import_sha25 = require("@noble/hashes/sha2");
34620
34697
  var import_viem23 = require("viem");
34621
- var import_zod4 = require("zod");
34622
- var WRITE_SESSION_PATH = "/v1/write/session";
34623
- var WRITE_SIGNATURE_HEADER = "X-Vana-Write-Signature";
34624
- var WRITE_METADATA_HEADER = "X-Vana-Metadata";
34625
- var LINEAGE_FIELD = "lineage";
34626
- var MAX_LINEAGE_SOURCES = 256;
34627
- var WRITE_FILENAME_HEADER = "X-Filename";
34628
- var WRITE_CONTENT_DISPOSITION_HEADER = "Content-Disposition";
34629
- var WRITER_ATTRIBUTION_KEY = "$writtenBy";
34630
- var LINEAGE_KEY = "$lineage";
34631
- var RESERVED_WRITE_KEYS = [
34632
- WRITER_ATTRIBUTION_KEY,
34633
- LINEAGE_KEY
34634
- ];
34635
- var WriteDataResultSchema = IngestResponseSchema.extend({
34636
- // Present when the write carried lineage: the validated, lowercased ids.
34637
- lineage: import_zod4.z.object({ sources: import_zod4.z.array(import_zod4.z.string()) }).optional()
34638
- });
34639
- var WriteSessionResponseSchema = import_zod4.z.object({
34640
- access_token: import_zod4.z.string().min(1),
34641
- token_type: import_zod4.z.string(),
34642
- expires_in: import_zod4.z.number().nonnegative(),
34643
- scope: import_zod4.z.string()
34644
- });
34645
34698
  function normalizeBaseUrl2(url) {
34646
34699
  return url.replace(/\/+$/, "");
34647
34700
  }
@@ -34652,9 +34705,6 @@ function resolveFetch2(fetchFn) {
34652
34705
  }
34653
34706
  return resolved;
34654
34707
  }
34655
- function dataPath(scope) {
34656
- return `/v1/data/${encodeURIComponent(scope)}`;
34657
- }
34658
34708
  function errorMessage(err) {
34659
34709
  return err instanceof Error ? err.message : String(err);
34660
34710
  }
@@ -34742,6 +34792,34 @@ async function sendWithFreshProof(label, fetchFn, options, proofKey, build) {
34742
34792
  lastError
34743
34793
  );
34744
34794
  }
34795
+
34796
+ // src/protocol/personal-server-write.ts
34797
+ var WRITE_SESSION_PATH = "/v1/write/session";
34798
+ var WRITE_SIGNATURE_HEADER = "X-Vana-Write-Signature";
34799
+ var WRITE_METADATA_HEADER = "X-Vana-Metadata";
34800
+ var LINEAGE_FIELD = "lineage";
34801
+ var MAX_LINEAGE_SOURCES = 256;
34802
+ var WRITE_FILENAME_HEADER = "X-Filename";
34803
+ var WRITE_CONTENT_DISPOSITION_HEADER = "Content-Disposition";
34804
+ var WRITER_ATTRIBUTION_KEY = "$writtenBy";
34805
+ var LINEAGE_KEY = "$lineage";
34806
+ var RESERVED_WRITE_KEYS = [
34807
+ WRITER_ATTRIBUTION_KEY,
34808
+ LINEAGE_KEY
34809
+ ];
34810
+ var WriteDataResultSchema = IngestResponseSchema.extend({
34811
+ // Present when the write carried lineage: the validated, lowercased ids.
34812
+ lineage: import_zod4.z.object({ sources: import_zod4.z.array(import_zod4.z.string()) }).optional()
34813
+ });
34814
+ var WriteSessionResponseSchema = import_zod4.z.object({
34815
+ access_token: import_zod4.z.string().min(1),
34816
+ token_type: import_zod4.z.string(),
34817
+ expires_in: import_zod4.z.number().nonnegative(),
34818
+ scope: import_zod4.z.string()
34819
+ });
34820
+ function dataPath(scope) {
34821
+ return `/v1/data/${encodeURIComponent(scope)}`;
34822
+ }
34745
34823
  async function openWriteSession(params) {
34746
34824
  const fetchFn = resolveFetch2(params.fetch);
34747
34825
  const personalServerUrl = normalizeBaseUrl2(params.personalServerUrl);
@@ -34873,7 +34951,7 @@ function binaryWriteSignedBytes(input) {
34873
34951
  mimeType: normalizeBinaryMimeType(input.contentType),
34874
34952
  ...input.filename ? { filename: input.filename } : {},
34875
34953
  sizeBytes: input.bytes.length,
34876
- contentHash: (0, import_viem23.bytesToHex)((0, import_sha25.sha256)(input.bytes)),
34954
+ contentHash: (0, import_viem24.bytesToHex)((0, import_sha26.sha256)(input.bytes)),
34877
34955
  encoding: "base64",
34878
34956
  content: toBase64(input.bytes),
34879
34957
  ...metadata !== void 0 ? { metadata } : {}
@@ -34921,7 +34999,7 @@ function normalizeLineage(lineage, derivedScope) {
34921
34999
  for (const entry of lineage) {
34922
35000
  let id;
34923
35001
  if (isLineagePair(entry)) {
34924
- if (!(0, import_viem23.isAddress)(entry.ownerAddress, { strict: false })) {
35002
+ if (!(0, import_viem24.isAddress)(entry.ownerAddress, { strict: false })) {
34925
35003
  throw new WriteRequestError(
34926
35004
  "lineage source ownerAddress must be an EVM address",
34927
35005
  { ownerAddress: entry.ownerAddress }
@@ -35170,6 +35248,437 @@ async function writePersonalServerData(params) {
35170
35248
  return { ...result, session };
35171
35249
  }
35172
35250
 
35251
+ // src/protocol/derivative-questions.ts
35252
+ var import_zod5 = require("zod");
35253
+ var DERIVATIVE_QUESTIONS_PATH = "/v1/derivatives/questions";
35254
+ var MAX_QUESTION_SOURCE_SCOPES = 16;
35255
+ var MAX_QUESTION_CHARS = 8e3;
35256
+ var MAX_QUESTION_MODEL_CHARS = 128;
35257
+ var MODEL_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
35258
+ var DEFAULT_QUESTION_TIMEOUT_MS = 12e4;
35259
+ var DEFAULT_QUESTION_POLL_INTERVAL_MS = 2e3;
35260
+ var SESSION_REFRESH_SKEW_MS = 3e4;
35261
+ var QUESTION_STATUSES = [
35262
+ "pending",
35263
+ "ready",
35264
+ "failed",
35265
+ "stale"
35266
+ ];
35267
+ var QuestionStatusSchema = import_zod5.z.enum(QUESTION_STATUSES);
35268
+ var QuestionRegisteredBySchema = import_zod5.z.union([
35269
+ import_zod5.z.object({ kind: import_zod5.z.literal("owner") }),
35270
+ import_zod5.z.object({
35271
+ kind: import_zod5.z.literal("builder"),
35272
+ builder: import_zod5.z.string(),
35273
+ grantId: import_zod5.z.string()
35274
+ })
35275
+ ]);
35276
+ var nullableString = import_zod5.z.string().nullish().transform((value) => value ?? null);
35277
+ var DerivativeQuestionSchema = import_zod5.z.object({
35278
+ questionId: import_zod5.z.string().min(1),
35279
+ derivedScope: import_zod5.z.string().min(1),
35280
+ sourceScopes: import_zod5.z.array(import_zod5.z.string()),
35281
+ question: import_zod5.z.string(),
35282
+ /** The model override, or `null` for the server's default. */
35283
+ model: nullableString,
35284
+ registeredBy: QuestionRegisteredBySchema,
35285
+ status: QuestionStatusSchema,
35286
+ /** A short reason, set only while `status` is `failed`. */
35287
+ error: nullableString,
35288
+ createdAt: import_zod5.z.string(),
35289
+ updatedAt: nullableString,
35290
+ /** When the last compute finished, or `null` while `pending`. */
35291
+ lastComputedAt: nullableString,
35292
+ /** Local version of the derived record the last compute wrote. */
35293
+ derivedVersion: import_zod5.z.number().nullish().transform((value) => value ?? null),
35294
+ derivedCollectedAt: nullableString
35295
+ });
35296
+ var QuestionListSchema = import_zod5.z.object({
35297
+ questions: import_zod5.z.array(DerivativeQuestionSchema)
35298
+ });
35299
+ var QuestionRecomputeResultSchema = import_zod5.z.object({
35300
+ questionId: import_zod5.z.string().min(1),
35301
+ derivedScope: import_zod5.z.string().min(1),
35302
+ /** `pending` when the question was never computed, else `stale`. */
35303
+ status: QuestionStatusSchema
35304
+ });
35305
+ var QuestionDeleteResultSchema = import_zod5.z.object({
35306
+ questionId: import_zod5.z.string().min(1),
35307
+ deleted: import_zod5.z.literal(true)
35308
+ });
35309
+ var sessionsBySigner = /* @__PURE__ */ new WeakMap();
35310
+ function sessionCacheKey(personalServerUrl, audience, grantId, fetchFn) {
35311
+ return JSON.stringify([personalServerUrl, audience, grantId]) + fetchIdOf(fetchFn);
35312
+ }
35313
+ var fetchIds = /* @__PURE__ */ new WeakMap();
35314
+ var nextFetchId = 0;
35315
+ function fetchIdOf(fetchFn) {
35316
+ let id = fetchIds.get(fetchFn);
35317
+ if (id === void 0) {
35318
+ id = ++nextFetchId;
35319
+ fetchIds.set(fetchFn, id);
35320
+ }
35321
+ return `#${id}`;
35322
+ }
35323
+ function resolveRequest(params) {
35324
+ if (typeof params.personalServerUrl !== "string" || params.personalServerUrl.length === 0) {
35325
+ throw new WriteRequestError("personalServerUrl is required");
35326
+ }
35327
+ if (typeof params.grantId !== "string" || params.grantId.length === 0) {
35328
+ throw new WriteRequestError(
35329
+ "grantId is required; a question call runs under the grant carrying write:<derivedScope>"
35330
+ );
35331
+ }
35332
+ if (params.signer === null || typeof params.signer !== "object") {
35333
+ throw new WriteRequestError(
35334
+ "signer must be a viem LocalAccount, a viem WalletClient, or a { signMessage } object"
35335
+ );
35336
+ }
35337
+ const fetchFn = resolveFetch2(params.fetch);
35338
+ const baseUrl = normalizeBaseUrl2(params.personalServerUrl);
35339
+ const audience = params.audience ?? baseUrl;
35340
+ return {
35341
+ baseUrl,
35342
+ audience,
35343
+ fetchFn,
35344
+ cacheKey: sessionCacheKey(baseUrl, audience, params.grantId, fetchFn),
35345
+ signerKey: params.signer
35346
+ };
35347
+ }
35348
+ async function resolveSession(params, resolved, force) {
35349
+ let cache = sessionsBySigner.get(resolved.signerKey);
35350
+ if (cache === void 0) {
35351
+ cache = /* @__PURE__ */ new Map();
35352
+ sessionsBySigner.set(resolved.signerKey, cache);
35353
+ }
35354
+ const cached = cache.get(resolved.cacheKey);
35355
+ if (!force && cached !== void 0 && cached.expiresAt > Date.now() + SESSION_REFRESH_SKEW_MS) {
35356
+ return cached;
35357
+ }
35358
+ if (force) cache.delete(resolved.cacheKey);
35359
+ const session = await openWriteSession({
35360
+ personalServerUrl: resolved.baseUrl,
35361
+ signer: params.signer,
35362
+ grantId: params.grantId,
35363
+ account: params.account,
35364
+ audience: resolved.audience,
35365
+ fetch: resolved.fetchFn,
35366
+ headers: params.headers,
35367
+ retry: params.retry
35368
+ });
35369
+ cache.set(resolved.cacheKey, session);
35370
+ return session;
35371
+ }
35372
+ async function questionErrorFromResponse(response) {
35373
+ const { errorCode, message, details } = await readPersonalServerErrorBody(response);
35374
+ const text = message ?? `Derivative question request failed: ${response.status} ${response.statusText}`;
35375
+ switch (errorCode) {
35376
+ case "DERIVATIVE_SOURCE_NOT_GRANTED":
35377
+ return new DerivativeSourceNotGrantedError(text, errorCode, details);
35378
+ case "DERIVATIVE_CYCLE":
35379
+ return new DerivativeCycleError(text, errorCode, details);
35380
+ case "DERIVATIVE_COMPUTE_UNAVAILABLE":
35381
+ return new DerivativeComputeUnavailableError(text, errorCode, details);
35382
+ case "DERIVATIVE_QUESTION_INVALID":
35383
+ case "LINEAGE_SCOPE_UNDER_SOURCE_PREFIX":
35384
+ return new DerivativeQuestionInvalidError(
35385
+ text,
35386
+ response.status,
35387
+ errorCode,
35388
+ details
35389
+ );
35390
+ case "DERIVATIVE_QUESTION_NOT_FOUND":
35391
+ return new DerivativeQuestionNotFoundError(text, errorCode, details);
35392
+ default:
35393
+ break;
35394
+ }
35395
+ switch (response.status) {
35396
+ case 401:
35397
+ return new WriteUnauthorizedError(text, errorCode, details);
35398
+ case 403:
35399
+ return new WriteForbiddenError(text, errorCode, details);
35400
+ case 404:
35401
+ return new DerivativeQuestionNotFoundError(text, errorCode, details);
35402
+ case 409:
35403
+ return new WriteConflictError(text, errorCode, details);
35404
+ default:
35405
+ return new DerivativeQuestionRejectedError(
35406
+ text,
35407
+ response.status,
35408
+ errorCode,
35409
+ details
35410
+ );
35411
+ }
35412
+ }
35413
+ async function sendOnce(params, resolved, session, spec, bodyBytes) {
35414
+ return sendWithFreshProof(
35415
+ spec.label,
35416
+ resolved.fetchFn,
35417
+ params.retry,
35418
+ proofKeyFor({
35419
+ aud: session.audience,
35420
+ method: spec.method,
35421
+ uri: spec.path,
35422
+ grantId: session.grantId,
35423
+ signedBytes: bodyBytes
35424
+ }),
35425
+ async (iat) => {
35426
+ const headers = new Headers(params.headers);
35427
+ headers.set("Accept", "application/json");
35428
+ headers.set("Authorization", `Bearer ${session.accessToken}`);
35429
+ if (bodyBytes !== void 0) {
35430
+ headers.set("Content-Type", "application/json");
35431
+ }
35432
+ headers.set(
35433
+ WRITE_SIGNATURE_HEADER,
35434
+ await buildWeb3SignedHeader({
35435
+ signMessage: session.signer.signMessage,
35436
+ aud: session.audience,
35437
+ // The Personal Server verifies the proof against the request's
35438
+ // path only, so the signed `uri` must not carry the query string.
35439
+ uri: spec.path,
35440
+ method: spec.method,
35441
+ body: bodyBytes,
35442
+ grantId: session.grantId,
35443
+ iat
35444
+ })
35445
+ );
35446
+ return {
35447
+ url: `${resolved.baseUrl}${spec.path}${spec.query ?? ""}`,
35448
+ init: {
35449
+ method: spec.method,
35450
+ headers,
35451
+ ...bodyBytes === void 0 ? {} : { body: bodyBytes },
35452
+ ...params.signal ? { signal: params.signal } : {}
35453
+ }
35454
+ };
35455
+ }
35456
+ );
35457
+ }
35458
+ async function sendQuestionRequest(params, spec, schema) {
35459
+ const resolved = resolveRequest(params);
35460
+ const bodyBytes = spec.body === void 0 ? void 0 : new TextEncoder().encode(JSON.stringify(spec.body));
35461
+ let session = await resolveSession(params, resolved, false);
35462
+ let response = await sendOnce(params, resolved, session, spec, bodyBytes);
35463
+ if (response.status === 401) {
35464
+ session = await resolveSession(params, resolved, true);
35465
+ response = await sendOnce(params, resolved, session, spec, bodyBytes);
35466
+ }
35467
+ if (!response.ok) {
35468
+ throw await questionErrorFromResponse(response);
35469
+ }
35470
+ let body;
35471
+ try {
35472
+ body = await response.json();
35473
+ } catch (err) {
35474
+ throw new DerivativeQuestionRejectedError(
35475
+ `${spec.label} response is not JSON`,
35476
+ response.status,
35477
+ null,
35478
+ { cause: errorMessage(err) }
35479
+ );
35480
+ }
35481
+ const parsed = schema.safeParse(body);
35482
+ if (!parsed.success) {
35483
+ throw new DerivativeQuestionRejectedError(
35484
+ `${spec.label} response is not a derivative question answer`,
35485
+ response.status,
35486
+ null,
35487
+ { issues: parsed.error.issues }
35488
+ );
35489
+ }
35490
+ return parsed.data;
35491
+ }
35492
+ function assertQuestionId(questionId) {
35493
+ if (typeof questionId !== "string" || questionId.length === 0) {
35494
+ throw new WriteRequestError("questionId is required");
35495
+ }
35496
+ return `${DERIVATIVE_QUESTIONS_PATH}/${encodeURIComponent(questionId)}`;
35497
+ }
35498
+ function registrationBody(params) {
35499
+ const { derivedScope, question } = params;
35500
+ if (typeof derivedScope !== "string" || derivedScope.length === 0) {
35501
+ throw new WriteRequestError("derivedScope is required");
35502
+ }
35503
+ if (!Array.isArray(params.sourceScopes) || params.sourceScopes.length === 0) {
35504
+ throw new WriteRequestError(
35505
+ "sourceScopes must be a non-empty array of scopes"
35506
+ );
35507
+ }
35508
+ if (params.sourceScopes.length > MAX_QUESTION_SOURCE_SCOPES) {
35509
+ throw new WriteRequestError(
35510
+ `sourceScopes lists ${params.sourceScopes.length} scopes; the maximum is ${MAX_QUESTION_SOURCE_SCOPES}`,
35511
+ { max: MAX_QUESTION_SOURCE_SCOPES, count: params.sourceScopes.length }
35512
+ );
35513
+ }
35514
+ const sourceScopes = [];
35515
+ for (const scope of params.sourceScopes) {
35516
+ if (typeof scope !== "string" || scope.length === 0) {
35517
+ throw new WriteRequestError("sourceScopes entries must be scope strings");
35518
+ }
35519
+ if (sourceScopes.includes(scope)) {
35520
+ throw new WriteRequestError("sourceScopes must not repeat a scope", {
35521
+ duplicate: scope
35522
+ });
35523
+ }
35524
+ if (scope === derivedScope) {
35525
+ throw new WriteRequestError(
35526
+ "derivedScope cannot be one of its own sources",
35527
+ { scope }
35528
+ );
35529
+ }
35530
+ sourceScopes.push(scope);
35531
+ }
35532
+ if (typeof question !== "string" || question.trim() === "") {
35533
+ throw new WriteRequestError("question must be a non-empty string");
35534
+ }
35535
+ if (question.length > MAX_QUESTION_CHARS) {
35536
+ throw new WriteRequestError(
35537
+ `question is ${question.length} characters; the maximum is ${MAX_QUESTION_CHARS}`,
35538
+ { max: MAX_QUESTION_CHARS, length: question.length }
35539
+ );
35540
+ }
35541
+ if (params.model !== void 0) {
35542
+ if (typeof params.model !== "string" || params.model.length > MAX_QUESTION_MODEL_CHARS || !MODEL_ID_PATTERN.test(params.model)) {
35543
+ throw new WriteRequestError("model must be a provider model id", {
35544
+ model: params.model
35545
+ });
35546
+ }
35547
+ }
35548
+ assertDerivedScopeNaming(derivedScope, sourceScopes);
35549
+ return {
35550
+ derivedScope,
35551
+ sourceScopes,
35552
+ question,
35553
+ ...params.model === void 0 ? {} : { model: params.model }
35554
+ };
35555
+ }
35556
+ async function registerQuestion(params) {
35557
+ const body = registrationBody(params);
35558
+ return sendQuestionRequest(
35559
+ params,
35560
+ {
35561
+ method: "POST",
35562
+ path: DERIVATIVE_QUESTIONS_PATH,
35563
+ body,
35564
+ label: "Register derivative question"
35565
+ },
35566
+ DerivativeQuestionSchema
35567
+ );
35568
+ }
35569
+ async function getQuestion(params) {
35570
+ const path = assertQuestionId(params.questionId);
35571
+ return sendQuestionRequest(
35572
+ params,
35573
+ { method: "GET", path, label: "Read derivative question" },
35574
+ DerivativeQuestionSchema
35575
+ );
35576
+ }
35577
+ async function listQuestions(params) {
35578
+ if (typeof params.derivedScope !== "string" || params.derivedScope.length === 0) {
35579
+ throw new WriteRequestError(
35580
+ "derivedScope is required; a builder may only list its own questions on a scope it may write"
35581
+ );
35582
+ }
35583
+ const { questions } = await sendQuestionRequest(
35584
+ params,
35585
+ {
35586
+ method: "GET",
35587
+ path: DERIVATIVE_QUESTIONS_PATH,
35588
+ query: `?derivedScope=${encodeURIComponent(params.derivedScope)}`,
35589
+ label: "List derivative questions"
35590
+ },
35591
+ QuestionListSchema
35592
+ );
35593
+ return questions;
35594
+ }
35595
+ async function recomputeQuestion(params) {
35596
+ const path = `${assertQuestionId(params.questionId)}/recompute`;
35597
+ return sendQuestionRequest(
35598
+ params,
35599
+ { method: "POST", path, label: "Recompute derivative question" },
35600
+ QuestionRecomputeResultSchema
35601
+ );
35602
+ }
35603
+ async function deleteQuestion(params) {
35604
+ const path = assertQuestionId(params.questionId);
35605
+ return sendQuestionRequest(
35606
+ params,
35607
+ { method: "DELETE", path, label: "Delete derivative question" },
35608
+ QuestionDeleteResultSchema
35609
+ );
35610
+ }
35611
+ function isSettled(status) {
35612
+ return status === "ready" || status === "failed";
35613
+ }
35614
+ function abortError(signal) {
35615
+ const reason = signal.reason;
35616
+ if (reason instanceof Error) return reason;
35617
+ const error = new Error("The operation was aborted");
35618
+ error.name = "AbortError";
35619
+ return error;
35620
+ }
35621
+ async function waitForQuestion(params) {
35622
+ const timeoutMs = Math.max(
35623
+ 0,
35624
+ params.timeoutMs ?? DEFAULT_QUESTION_TIMEOUT_MS
35625
+ );
35626
+ const pollIntervalMs = Math.max(
35627
+ 0,
35628
+ params.pollIntervalMs ?? DEFAULT_QUESTION_POLL_INTERVAL_MS
35629
+ );
35630
+ const deadline = Date.now() + timeoutMs;
35631
+ for (; ; ) {
35632
+ if (params.signal?.aborted) throw abortError(params.signal);
35633
+ const latest = await getQuestion(params);
35634
+ if (isSettled(latest.status)) return latest;
35635
+ const remaining = deadline - Date.now();
35636
+ if (remaining <= 0) {
35637
+ throw new DerivativeQuestionTimeoutError(
35638
+ `Derivative question ${latest.questionId} was still ${latest.status} after ${timeoutMs}ms`,
35639
+ {
35640
+ questionId: latest.questionId,
35641
+ derivedScope: latest.derivedScope,
35642
+ status: latest.status,
35643
+ timeoutMs
35644
+ }
35645
+ );
35646
+ }
35647
+ await sleep2(Math.min(pollIntervalMs, remaining));
35648
+ }
35649
+ }
35650
+ async function askPersonalServer(params) {
35651
+ const registered = await registerQuestion(params);
35652
+ const registration = await waitForQuestion({
35653
+ ...params,
35654
+ questionId: registered.questionId
35655
+ });
35656
+ if (registration.status !== "ready") {
35657
+ throw new DerivativeQuestionFailedError(
35658
+ `Derivative question ${registration.questionId} failed: ${registration.error ?? "no reason given"}`,
35659
+ {
35660
+ questionId: registration.questionId,
35661
+ derivedScope: registration.derivedScope,
35662
+ error: registration.error
35663
+ }
35664
+ );
35665
+ }
35666
+ const signer = resolveWriteSigner(params.signer, {
35667
+ account: params.account
35668
+ });
35669
+ const readParams = {
35670
+ personalServerUrl: normalizeBaseUrl2(params.personalServerUrl),
35671
+ scope: params.derivedScope,
35672
+ grantId: params.grantId,
35673
+ signMessage: signer.signMessage,
35674
+ ...params.audience === void 0 ? {} : { audience: params.audience },
35675
+ ...params.headers === void 0 ? {} : { headers: params.headers },
35676
+ ...params.fetch === void 0 ? {} : { fetch: params.fetch }
35677
+ };
35678
+ const record = await readPersonalServerData(readParams);
35679
+ return { registration, record };
35680
+ }
35681
+
35173
35682
  // src/protocol/gateway.ts
35174
35683
  function withGrantPermissions(grant) {
35175
35684
  const stripped = { ...grant };
@@ -36251,11 +36760,23 @@ async function parsePSError(response) {
36251
36760
  ContractNotFoundError,
36252
36761
  DATA_ACCESS_OP_TYPE,
36253
36762
  DATA_REGISTRY_STATUS_ABI,
36763
+ DEFAULT_QUESTION_POLL_INTERVAL_MS,
36764
+ DEFAULT_QUESTION_TIMEOUT_MS,
36765
+ DERIVATIVE_QUESTIONS_PATH,
36254
36766
  DataFileEnvelopeSchema,
36255
36767
  DataPointDeletedError,
36256
36768
  DataPointNotFoundError,
36257
36769
  DataPointStatus,
36258
36770
  DataPointVersionConflictError,
36771
+ DerivativeComputeUnavailableError,
36772
+ DerivativeCycleError,
36773
+ DerivativeQuestionFailedError,
36774
+ DerivativeQuestionInvalidError,
36775
+ DerivativeQuestionNotFoundError,
36776
+ DerivativeQuestionRejectedError,
36777
+ DerivativeQuestionSchema,
36778
+ DerivativeQuestionTimeoutError,
36779
+ DerivativeSourceNotGrantedError,
36259
36780
  DropboxStorage,
36260
36781
  ECIESError,
36261
36782
  ESCROW_DEPOSIT_ABI,
@@ -36280,6 +36801,9 @@ async function parsePSError(response) {
36280
36801
  LineageReadError,
36281
36802
  MASTER_KEY_MESSAGE,
36282
36803
  MAX_LINEAGE_SOURCES,
36804
+ MAX_QUESTION_CHARS,
36805
+ MAX_QUESTION_MODEL_CHARS,
36806
+ MAX_QUESTION_SOURCE_SCOPES,
36283
36807
  MissingAuthError,
36284
36808
  NATIVE_ASSET_ADDRESS,
36285
36809
  NATIVE_VANA_ASSET,
@@ -36300,6 +36824,11 @@ async function parsePSError(response) {
36300
36824
  PersonalServerError,
36301
36825
  PersonalServerWriteError,
36302
36826
  PinataStorage,
36827
+ QUESTION_STATUSES,
36828
+ QuestionDeleteResultSchema,
36829
+ QuestionRecomputeResultSchema,
36830
+ QuestionRegisteredBySchema,
36831
+ QuestionStatusSchema,
36303
36832
  R2Storage,
36304
36833
  RECORD_DATA_ACCESS_TYPES,
36305
36834
  REGISTRATION_KIND_FOR_OP,
@@ -36338,6 +36867,7 @@ async function parsePSError(response) {
36338
36867
  WriteSessionExpiredError,
36339
36868
  WriteTransportError,
36340
36869
  WriteUnauthorizedError,
36870
+ askPersonalServer,
36341
36871
  assertDerivedScopeNaming,
36342
36872
  assertValidPkceVerifier,
36343
36873
  authorizeEscrowPayment,
@@ -36381,6 +36911,7 @@ async function parsePSError(response) {
36381
36911
  dataRegistryDomain,
36382
36912
  decryptWithPassword,
36383
36913
  deleteDataPoint,
36914
+ deleteQuestion,
36384
36915
  deriveDataPointId,
36385
36916
  deriveMasterKey,
36386
36917
  deriveScopeKey,
@@ -36410,6 +36941,7 @@ async function parsePSError(response) {
36410
36941
  getOpFee,
36411
36942
  getPersonalServerLineage,
36412
36943
  getPlatformCapabilities,
36944
+ getQuestion,
36413
36945
  getServiceEndpoints,
36414
36946
  grantPermissions,
36415
36947
  grantRegistrationDomain,
@@ -36422,6 +36954,7 @@ async function parsePSError(response) {
36422
36954
  isPlatformSupported,
36423
36955
  isRedactedLineageNode,
36424
36956
  isTombstoneHashes,
36957
+ listQuestions,
36425
36958
  mainnetServices,
36426
36959
  moksha,
36427
36960
  mokshaServices,
@@ -36441,8 +36974,10 @@ async function parsePSError(response) {
36441
36974
  personalServerLineagePath,
36442
36975
  personalServerRegistrationDomain,
36443
36976
  readPersonalServerData,
36977
+ recomputeQuestion,
36444
36978
  recoverServerOwner,
36445
36979
  registerPersonalServerSignature,
36980
+ registerQuestion,
36446
36981
  resolveWriteSigner,
36447
36982
  scopeCoveredByGrant,
36448
36983
  scopeMatchesPattern,
@@ -36462,6 +36997,7 @@ async function parsePSError(response) {
36462
36997
  verifyGrantRegistration,
36463
36998
  verifyPkceChallenge,
36464
36999
  verifyWeb3Signed,
37000
+ waitForQuestion,
36465
37001
  writeData,
36466
37002
  writePersonalServerData
36467
37003
  });