@opendatalabs/vana-sdk 3.18.1 → 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.
@@ -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");
@@ -34621,32 +34688,13 @@ function tryGrantPermissions(scopes) {
34621
34688
  }
34622
34689
 
34623
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
34624
34696
  var import_sha25 = require("@noble/hashes/sha2");
34625
34697
  var import_viem23 = require("viem");
34626
- var import_zod4 = require("zod");
34627
- var WRITE_SESSION_PATH = "/v1/write/session";
34628
- var WRITE_SIGNATURE_HEADER = "X-Vana-Write-Signature";
34629
- var WRITE_METADATA_HEADER = "X-Vana-Metadata";
34630
- var LINEAGE_FIELD = "lineage";
34631
- var MAX_LINEAGE_SOURCES = 256;
34632
- var WRITE_FILENAME_HEADER = "X-Filename";
34633
- var WRITE_CONTENT_DISPOSITION_HEADER = "Content-Disposition";
34634
- var WRITER_ATTRIBUTION_KEY = "$writtenBy";
34635
- var LINEAGE_KEY = "$lineage";
34636
- var RESERVED_WRITE_KEYS = [
34637
- WRITER_ATTRIBUTION_KEY,
34638
- LINEAGE_KEY
34639
- ];
34640
- var WriteDataResultSchema = IngestResponseSchema.extend({
34641
- // Present when the write carried lineage: the validated, lowercased ids.
34642
- lineage: import_zod4.z.object({ sources: import_zod4.z.array(import_zod4.z.string()) }).optional()
34643
- });
34644
- var WriteSessionResponseSchema = import_zod4.z.object({
34645
- access_token: import_zod4.z.string().min(1),
34646
- token_type: import_zod4.z.string(),
34647
- expires_in: import_zod4.z.number().nonnegative(),
34648
- scope: import_zod4.z.string()
34649
- });
34650
34698
  function normalizeBaseUrl2(url) {
34651
34699
  return url.replace(/\/+$/, "");
34652
34700
  }
@@ -34657,9 +34705,6 @@ function resolveFetch2(fetchFn) {
34657
34705
  }
34658
34706
  return resolved;
34659
34707
  }
34660
- function dataPath(scope) {
34661
- return `/v1/data/${encodeURIComponent(scope)}`;
34662
- }
34663
34708
  function errorMessage(err) {
34664
34709
  return err instanceof Error ? err.message : String(err);
34665
34710
  }
@@ -34747,6 +34792,34 @@ async function sendWithFreshProof(label, fetchFn, options, proofKey, build) {
34747
34792
  lastError
34748
34793
  );
34749
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
+ }
34750
34823
  async function openWriteSession(params) {
34751
34824
  const fetchFn = resolveFetch2(params.fetch);
34752
34825
  const personalServerUrl = normalizeBaseUrl2(params.personalServerUrl);
@@ -34878,7 +34951,7 @@ function binaryWriteSignedBytes(input) {
34878
34951
  mimeType: normalizeBinaryMimeType(input.contentType),
34879
34952
  ...input.filename ? { filename: input.filename } : {},
34880
34953
  sizeBytes: input.bytes.length,
34881
- contentHash: (0, import_viem23.bytesToHex)((0, import_sha25.sha256)(input.bytes)),
34954
+ contentHash: (0, import_viem24.bytesToHex)((0, import_sha26.sha256)(input.bytes)),
34882
34955
  encoding: "base64",
34883
34956
  content: toBase64(input.bytes),
34884
34957
  ...metadata !== void 0 ? { metadata } : {}
@@ -34926,7 +34999,7 @@ function normalizeLineage(lineage, derivedScope) {
34926
34999
  for (const entry of lineage) {
34927
35000
  let id;
34928
35001
  if (isLineagePair(entry)) {
34929
- if (!(0, import_viem23.isAddress)(entry.ownerAddress, { strict: false })) {
35002
+ if (!(0, import_viem24.isAddress)(entry.ownerAddress, { strict: false })) {
34930
35003
  throw new WriteRequestError(
34931
35004
  "lineage source ownerAddress must be an EVM address",
34932
35005
  { ownerAddress: entry.ownerAddress }
@@ -35175,6 +35248,437 @@ async function writePersonalServerData(params) {
35175
35248
  return { ...result, session };
35176
35249
  }
35177
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
+
35178
35682
  // src/protocol/gateway.ts
35179
35683
  function withGrantPermissions(grant) {
35180
35684
  const stripped = { ...grant };
@@ -36256,11 +36760,23 @@ async function parsePSError(response) {
36256
36760
  ContractNotFoundError,
36257
36761
  DATA_ACCESS_OP_TYPE,
36258
36762
  DATA_REGISTRY_STATUS_ABI,
36763
+ DEFAULT_QUESTION_POLL_INTERVAL_MS,
36764
+ DEFAULT_QUESTION_TIMEOUT_MS,
36765
+ DERIVATIVE_QUESTIONS_PATH,
36259
36766
  DataFileEnvelopeSchema,
36260
36767
  DataPointDeletedError,
36261
36768
  DataPointNotFoundError,
36262
36769
  DataPointStatus,
36263
36770
  DataPointVersionConflictError,
36771
+ DerivativeComputeUnavailableError,
36772
+ DerivativeCycleError,
36773
+ DerivativeQuestionFailedError,
36774
+ DerivativeQuestionInvalidError,
36775
+ DerivativeQuestionNotFoundError,
36776
+ DerivativeQuestionRejectedError,
36777
+ DerivativeQuestionSchema,
36778
+ DerivativeQuestionTimeoutError,
36779
+ DerivativeSourceNotGrantedError,
36264
36780
  DropboxStorage,
36265
36781
  ECIESError,
36266
36782
  ESCROW_DEPOSIT_ABI,
@@ -36285,6 +36801,9 @@ async function parsePSError(response) {
36285
36801
  LineageReadError,
36286
36802
  MASTER_KEY_MESSAGE,
36287
36803
  MAX_LINEAGE_SOURCES,
36804
+ MAX_QUESTION_CHARS,
36805
+ MAX_QUESTION_MODEL_CHARS,
36806
+ MAX_QUESTION_SOURCE_SCOPES,
36288
36807
  MissingAuthError,
36289
36808
  NATIVE_ASSET_ADDRESS,
36290
36809
  NATIVE_VANA_ASSET,
@@ -36305,6 +36824,11 @@ async function parsePSError(response) {
36305
36824
  PersonalServerError,
36306
36825
  PersonalServerWriteError,
36307
36826
  PinataStorage,
36827
+ QUESTION_STATUSES,
36828
+ QuestionDeleteResultSchema,
36829
+ QuestionRecomputeResultSchema,
36830
+ QuestionRegisteredBySchema,
36831
+ QuestionStatusSchema,
36308
36832
  R2Storage,
36309
36833
  RECORD_DATA_ACCESS_TYPES,
36310
36834
  REGISTRATION_KIND_FOR_OP,
@@ -36343,6 +36867,7 @@ async function parsePSError(response) {
36343
36867
  WriteSessionExpiredError,
36344
36868
  WriteTransportError,
36345
36869
  WriteUnauthorizedError,
36870
+ askPersonalServer,
36346
36871
  assertDerivedScopeNaming,
36347
36872
  assertValidPkceVerifier,
36348
36873
  authorizeEscrowPayment,
@@ -36386,6 +36911,7 @@ async function parsePSError(response) {
36386
36911
  dataRegistryDomain,
36387
36912
  decryptWithPassword,
36388
36913
  deleteDataPoint,
36914
+ deleteQuestion,
36389
36915
  deriveDataPointId,
36390
36916
  deriveMasterKey,
36391
36917
  deriveScopeKey,
@@ -36415,6 +36941,7 @@ async function parsePSError(response) {
36415
36941
  getOpFee,
36416
36942
  getPersonalServerLineage,
36417
36943
  getPlatformCapabilities,
36944
+ getQuestion,
36418
36945
  getServiceEndpoints,
36419
36946
  grantPermissions,
36420
36947
  grantRegistrationDomain,
@@ -36427,6 +36954,7 @@ async function parsePSError(response) {
36427
36954
  isPlatformSupported,
36428
36955
  isRedactedLineageNode,
36429
36956
  isTombstoneHashes,
36957
+ listQuestions,
36430
36958
  mainnetServices,
36431
36959
  moksha,
36432
36960
  mokshaServices,
@@ -36446,8 +36974,10 @@ async function parsePSError(response) {
36446
36974
  personalServerLineagePath,
36447
36975
  personalServerRegistrationDomain,
36448
36976
  readPersonalServerData,
36977
+ recomputeQuestion,
36449
36978
  recoverServerOwner,
36450
36979
  registerPersonalServerSignature,
36980
+ registerQuestion,
36451
36981
  resolveWriteSigner,
36452
36982
  scopeCoveredByGrant,
36453
36983
  scopeMatchesPattern,
@@ -36467,6 +36997,7 @@ async function parsePSError(response) {
36467
36997
  verifyGrantRegistration,
36468
36998
  verifyPkceChallenge,
36469
36999
  verifyWeb3Signed,
37000
+ waitForQuestion,
36470
37001
  writeData,
36471
37002
  writePersonalServerData
36472
37003
  });