@opendatalabs/vana-sdk 3.23.0-pr.211.7c767d5 → 3.23.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.
@@ -79,9 +79,6 @@ function resultPlaintext(result) {
79
79
  function encryptedBytesToBase64(encrypted) {
80
80
  return (0, import_encoding.toBase64)((0, import_viem.fromHex)(`0x${(0, import_interface.serializeECIES)(encrypted)}`, "bytes"));
81
81
  }
82
- function encryptedToBytes(encrypted) {
83
- return (0, import_viem.fromHex)(`0x${(0, import_interface.serializeECIES)(encrypted)}`, "bytes");
84
- }
85
82
  function base64ToEncrypted(ciphertext) {
86
83
  return (0, import_interface.deserializeECIES)((0, import_viem.toHex)((0, import_encoding.fromBase64)(ciphertext)));
87
84
  }
@@ -227,13 +224,14 @@ async function sealJobResult(result, builderPublicKey, ecies) {
227
224
  (0, import_viem.fromHex)(builderPublicKey, "bytes"),
228
225
  resultPlaintext(result)
229
226
  );
230
- const bytes = encryptedToBytes(encrypted);
231
- return { bytes, hash: (0, import_viem.bytesToHex)((0, import_sha2.sha256)(bytes)), size: bytes.length };
227
+ const ciphertext = encryptedBytesToBase64(encrypted);
228
+ const bytes = (0, import_encoding.fromBase64)(ciphertext);
229
+ return { ciphertext, hash: (0, import_viem.bytesToHex)((0, import_sha2.sha256)(bytes)), size: bytes.length };
232
230
  }
233
- async function openJobResult(sealedBytes, builderPrivateKey, ecies, expect) {
231
+ async function openJobResult(ciphertext, builderPrivateKey, ecies, expect) {
234
232
  const plaintext = await ecies.decrypt(
235
233
  (0, import_viem.fromHex)(builderPrivateKey, "bytes"),
236
- (0, import_interface.deserializeECIES)((0, import_viem.toHex)(sealedBytes))
234
+ base64ToEncrypted(ciphertext)
237
235
  );
238
236
  const result = validateResult(parseObject(plaintext, "job result"));
239
237
  if (result.jobId !== expect.jobId) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/crypto/envelope/job.ts"],"sourcesContent":["/**\n * ECIES envelopes for encrypted job requests and results.\n *\n * Request plaintext is UTF-8 JSON with object keys sorted recursively and\n * array order preserved. Result properties follow their interface order. The\n * Request ciphertext is base64 of `iv || ephemPub || ct || mac`, as specified\n * by the ECIES provider interface. Result ciphertext is the raw concatenated\n * byte sequence stored in object storage. The Gateway hashes raw ciphertext\n * bytes, not plaintext.\n * The builder verifies the decrypted result's job ID, scope, and version\n * bindings. The PS worker verifies\n * `auth.bodyHash === sha256(canonicalJobRequestBytes(request))`; the Gateway\n * never sees the plaintext. Flow: personal-server-ts\n * `docs/260903-jobs-contract.md`, section 1.\n *\n * @category Cryptography\n */\n\nimport { sha256 } from \"@noble/hashes/sha2\";\nimport { bytesToHex, fromHex, isAddress, isHex, toHex, type Hex } from \"viem\";\nimport {\n deserializeECIES,\n serializeECIES,\n type ECIESProvider,\n} from \"../ecies/interface\";\nimport {\n JOB_OPERATIONS,\n JOB_PROTOCOL_VERSION,\n type JobOperation,\n type JobRequest,\n type JobRequestEnvelope,\n type JobResult,\n} from \"../../protocol/jobs\";\nimport { fromBase64, toBase64 } from \"../../utils/encoding\";\n\nconst textDecoder = new TextDecoder();\nconst textEncoder = new TextEncoder();\n\n/** A job envelope or result did not match the jobs protocol. */\nexport class JobEnvelopeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"JobEnvelopeError\";\n }\n}\n\nfunction sortJsonKeys(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortJsonKeys);\n }\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.keys(value)\n .sort()\n .map((key) => [\n key,\n sortJsonKeys((value as Record<string, unknown>)[key]),\n ]),\n );\n }\n return value;\n}\n\nfunction canonicalJsonBytes(value: unknown): Uint8Array {\n return textEncoder.encode(JSON.stringify(sortJsonKeys(value)));\n}\n\n/**\n * Returns the canonical UTF-8 JSON bytes committed to by the auth body hash.\n *\n * @param request - Job request to validate and serialize canonically.\n * @returns Recursively key-sorted, whitespace-free UTF-8 JSON bytes.\n * @throws {JobEnvelopeError} If the request does not match the protocol schema.\n */\nexport function canonicalJobRequestBytes(request: JobRequest): Uint8Array {\n validateJobRequest(request);\n return canonicalJsonBytes(request);\n}\n\nfunction requestPlaintext(envelope: JobRequestEnvelope): Uint8Array {\n validateRequestEnvelope(envelope);\n return canonicalJsonBytes(envelope);\n}\n\nfunction resultPlaintext(result: JobResult): Uint8Array {\n return textEncoder.encode(\n JSON.stringify({\n v: result.v,\n jobId: result.jobId,\n scope: result.scope,\n version: result.version,\n contentType: result.contentType,\n body: result.body,\n }),\n );\n}\n\nfunction encryptedBytesToBase64(\n encrypted: Awaited<ReturnType<ECIESProvider[\"encrypt\"]>>,\n): string {\n return toBase64(fromHex(`0x${serializeECIES(encrypted)}`, \"bytes\"));\n}\n\nfunction encryptedToBytes(\n encrypted: Awaited<ReturnType<ECIESProvider[\"encrypt\"]>>,\n): Uint8Array {\n return fromHex(`0x${serializeECIES(encrypted)}`, \"bytes\");\n}\n\nfunction base64ToEncrypted(ciphertext: string) {\n return deserializeECIES(toHex(fromBase64(ciphertext)));\n}\n\nfunction parseObject(\n plaintext: Uint8Array,\n kind: string,\n): Record<string, unknown> {\n try {\n const value: unknown = JSON.parse(textDecoder.decode(plaintext));\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new JobEnvelopeError(`Invalid ${kind}: expected an object`);\n }\n return value as Record<string, unknown>;\n } catch (error) {\n if (error instanceof JobEnvelopeError) throw error;\n throw new JobEnvelopeError(`Invalid ${kind}: malformed JSON`);\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction requirePlainObject(\n value: unknown,\n field: string,\n kind: string,\n): asserts value is Record<string, unknown> {\n if (!isPlainObject(value)) {\n throw new JobEnvelopeError(`Invalid ${kind}: invalid ${field}`);\n }\n}\n\nfunction requireExactKeys(\n value: Record<string, unknown>,\n expectedKeys: readonly string[],\n kind: string,\n): void {\n for (const key of expectedKeys) {\n if (!Object.hasOwn(value, key) || value[key] === undefined) {\n throw new JobEnvelopeError(`Invalid ${kind}: missing ${key}`);\n }\n }\n const expected = new Set<PropertyKey>(expectedKeys);\n for (const key of Reflect.ownKeys(value)) {\n if (!expected.has(key)) {\n throw new JobEnvelopeError(\n `Invalid ${kind}: unknown field ${String(key)}`,\n );\n }\n }\n}\n\nfunction requireString(\n value: unknown,\n field: string,\n kind: string,\n): asserts value is string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new JobEnvelopeError(`Invalid ${kind}: missing ${field}`);\n }\n}\n\nfunction validateJobRequest(value: unknown): JobRequest {\n requirePlainObject(value, \"request\", \"job request\");\n requireExactKeys(\n value,\n [\n \"v\",\n \"jobId\",\n \"owner\",\n \"builder\",\n \"builderPublicKey\",\n \"grantId\",\n \"scope\",\n \"operation\",\n \"pinnedVersion\",\n \"deadline\",\n ],\n \"job request\",\n );\n if (value.v !== JOB_PROTOCOL_VERSION) {\n throw new JobEnvelopeError(\n `Unsupported job request version: ${String(value.v)}`,\n );\n }\n requireString(value.jobId, \"jobId\", \"job request\");\n if (typeof value.owner !== \"string\" || !isAddress(value.owner)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid owner\");\n }\n if (typeof value.builder !== \"string\" || !isAddress(value.builder)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid builder\");\n }\n if (\n typeof value.builderPublicKey !== \"string\" ||\n !isHex(value.builderPublicKey)\n ) {\n throw new JobEnvelopeError(\"Invalid job request: invalid builderPublicKey\");\n }\n if (typeof value.grantId !== \"string\" || !isHex(value.grantId)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid grantId\");\n }\n requireString(value.scope, \"scope\", \"job request\");\n if (!JOB_OPERATIONS.includes(value.operation as JobOperation)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid operation\");\n }\n if (value.pinnedVersion !== null && typeof value.pinnedVersion !== \"string\") {\n throw new JobEnvelopeError(\"Invalid job request: missing pinnedVersion\");\n }\n if (\n typeof value.deadline !== \"string\" ||\n !Number.isFinite(Date.parse(value.deadline))\n ) {\n throw new JobEnvelopeError(\"Invalid job request: invalid deadline\");\n }\n return value as unknown as JobRequest;\n}\n\nfunction validateRequestEnvelope(value: unknown): JobRequestEnvelope {\n requirePlainObject(value, \"envelope\", \"job request envelope\");\n requireExactKeys(value, [\"request\", \"auth\"], \"job request envelope\");\n validateJobRequest(value.request);\n requireString(value.auth, \"auth\", \"job request envelope\");\n return value as unknown as JobRequestEnvelope;\n}\n\nfunction validateResult(value: unknown): JobResult {\n requirePlainObject(value, \"result\", \"job result\");\n requireExactKeys(\n value,\n [\"v\", \"jobId\", \"scope\", \"version\", \"contentType\", \"body\"],\n \"job result\",\n );\n if (value.v !== JOB_PROTOCOL_VERSION) {\n throw new JobEnvelopeError(\n `Unsupported job result version: ${String(value.v)}`,\n );\n }\n for (const field of [\"jobId\", \"scope\", \"contentType\"]) {\n requireString(value[field], field, \"job result\");\n }\n if (typeof value.body !== \"string\") {\n throw new JobEnvelopeError(\"Invalid job result: missing body\");\n }\n if (value.version !== null && typeof value.version !== \"string\") {\n throw new JobEnvelopeError(\"Invalid job result: missing version\");\n }\n return value as unknown as JobResult;\n}\n\n/**\n * Encrypts a validated job request envelope for a Personal Server enclave.\n *\n * The PS worker verifies\n * `auth.bodyHash === sha256(canonicalJobRequestBytes(request))`; the Gateway\n * never sees the plaintext.\n *\n * @param envelope - Request and builder Web3Signed authorization to encrypt.\n * @param enclavePublicKey - Public key returned by `GET /v1/identity?owner=`.\n * @param ecies - Injected ECIES implementation.\n * @returns Base64 ciphertext encoded as `iv || ephemPub || ct || mac`.\n * @throws {JobEnvelopeError} If the envelope or request is invalid.\n * @throws If ECIES encryption fails or the enclave public key is invalid.\n *\n * @example\n * ```ts\n * const identity = await fetch(`/v1/identity?owner=${owner}`).then((response) =>\n * response.json(),\n * );\n * const requestCiphertext = await sealJobRequest(\n * requestEnvelope,\n * identity.publicKey,\n * ecies,\n * );\n * await fetch(\"/v1/jobs\", {\n * method: \"POST\",\n * body: JSON.stringify({ ...submission, requestCiphertext }),\n * });\n * ```\n */\nexport async function sealJobRequest(\n envelope: JobRequestEnvelope,\n enclavePublicKey: Hex,\n ecies: ECIESProvider,\n): Promise<string> {\n const encrypted = await ecies.encrypt(\n fromHex(enclavePublicKey, \"bytes\"),\n requestPlaintext(envelope),\n );\n return encryptedBytesToBase64(encrypted);\n}\n\n/**\n * Decrypts and validates a job request envelope inside the enclave.\n *\n * @param ciphertext - Base64 `iv || ephemPub || ct || mac` ciphertext.\n * @param privateKey - Enclave key bytes, supplied as `Uint8Array` so the agent can zero them after use.\n * @param ecies - Injected ECIES implementation.\n * @returns The validated request envelope exactly as parsed from plaintext.\n * @throws {JobEnvelopeError} If plaintext is malformed or fails schema validation.\n * @throws If ciphertext decoding or ECIES decryption fails.\n */\nexport async function openJobRequest(\n ciphertext: string,\n privateKey: Uint8Array,\n ecies: ECIESProvider,\n): Promise<JobRequestEnvelope> {\n const plaintext = await ecies.decrypt(\n privateKey,\n base64ToEncrypted(ciphertext),\n );\n return validateRequestEnvelope(\n parseObject(plaintext, \"job request envelope\"),\n );\n}\n\n/**\n * Encrypts a validated job result for its builder and describes the ciphertext.\n *\n * `hash` is lowercase `0x` SHA-256 of the raw sealed bytes, not the `sha256:`\n * prefix used by Web3Signed `bodyHash`. `size` is the sealed byte length. They\n * equal the Gateway's `resultHash` and `resultSize`.\n *\n * @param result - Job result to validate and encrypt.\n * @param builderPublicKey - Builder wallet public key recorded in the request.\n * @param ecies - Injected ECIES implementation.\n * @returns Raw sealed bytes plus their Gateway-compatible hash and size.\n * @throws {JobEnvelopeError} If the result does not match the protocol schema.\n * @throws If ECIES encryption fails or the builder public key is invalid.\n */\nexport async function sealJobResult(\n result: JobResult,\n builderPublicKey: Hex,\n ecies: ECIESProvider,\n): Promise<{ bytes: Uint8Array; hash: Hex; size: number }> {\n validateResult(result);\n const encrypted = await ecies.encrypt(\n fromHex(builderPublicKey, \"bytes\"),\n resultPlaintext(result),\n );\n const bytes = encryptedToBytes(encrypted);\n return { bytes, hash: bytesToHex(sha256(bytes)), size: bytes.length };\n}\n\n/**\n * Decrypts a job result and verifies its builder-visible protocol bindings.\n *\n * The builder private key is a `Hex` wallet key. For `expect.version`,\n * `undefined` skips the check while `null` requires a null result version.\n *\n * @param sealedBytes - Raw `iv || ephemPub || ct || mac` bytes.\n * @param builderPrivateKey - Builder's wallet private key as hex.\n * @param ecies - Injected ECIES implementation.\n * @param expect - Required job ID and optional scope and version bindings.\n * @returns The validated result when every supplied binding matches.\n * @throws {JobEnvelopeError} If plaintext is malformed, invalid, or a binding differs.\n * @throws If ciphertext decoding or ECIES decryption fails.\n *\n * @example\n * ```ts\n * const sealedBytes = new Uint8Array(await response.arrayBuffer());\n * const result = await openJobResult(sealedBytes, key, ecies, {\n * jobId,\n * scope,\n * });\n * const body = fromBase64(result.body);\n * ```\n */\nexport async function openJobResult(\n sealedBytes: Uint8Array,\n builderPrivateKey: Hex,\n ecies: ECIESProvider,\n expect: { jobId: string; scope?: string; version?: string | null },\n): Promise<JobResult> {\n const plaintext = await ecies.decrypt(\n fromHex(builderPrivateKey, \"bytes\"),\n deserializeECIES(toHex(sealedBytes)),\n );\n const result = validateResult(parseObject(plaintext, \"job result\"));\n if (result.jobId !== expect.jobId) {\n throw new JobEnvelopeError(\n `Job result ID ${result.jobId} does not match expected job ID ${expect.jobId}`,\n );\n }\n if (expect.scope !== undefined && result.scope !== expect.scope) {\n throw new JobEnvelopeError(\n `Job result scope ${result.scope} does not match expected scope ${expect.scope}`,\n );\n }\n if (expect.version !== undefined && result.version !== expect.version) {\n throw new JobEnvelopeError(\n `Job result version ${String(result.version)} does not match expected version ${String(expect.version)}`,\n );\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkBA,kBAAuB;AACvB,kBAAuE;A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AgBA,eAAsB,cACpB,QACA,kBACA,OACyD;AACzD,iBAAe,MAAM;AACrB,QAAM,YAAY,MAAM,MAAM;AAAA,QAC5B,qBAAQ,kBAAkB,OAAO;AAAA,IACjC,gBAAgB,MAAM;AAAA,EACxB;AACA,QAAM,QAAQ,iBAAiB,SAAS;AACxC,SAAO,EAAE,OAAO,UAAM,4BAAW,oBAAO,KAAK,CAAC,GAAG,MAAM,MAAM,OAAO;AACtE;AA0BA,eAAsB,cACpB,aACA,mBACA,OACA,QACoB;AACpB,QAAM,YAAY,MAAM,MAAM;AAAA,QAC5B,qBAAQ,mBAAmB,OAAO;AAAA,QAClC,uCAAiB,mBAAM,WAAW,CAAC;AAAA,EACrC;AACA,QAAM,SAAS,eAAe,YAAY,WAAW,YAAY,CAAC;AAClE,MAAI,OAAO,UAAU,OAAO,OAAO;AACjC,UAAM,IAAI;AAAA,MACR,iBAAiB,OAAO,KAAK,mCAAmC,OAAO,KAAK;AAAA,IAC9E;AAAA,EACF;AACA,MAAI,OAAO,UAAU,UAAa,OAAO,UAAU,OAAO,OAAO;AAC/D,UAAM,IAAI;AAAA,MACR,oBAAoB,OAAO,KAAK,kCAAkC,OAAO,KAAK;AAAA,IAChF;AAAA,EACF;AACA,MAAI,OAAO,YAAY,UAAa,OAAO,YAAY,OAAO,SAAS;AACrE,UAAM,IAAI;AAAA,MACR,sBAAsB,OAAO,OAAO,OAAO,CAAC,oCAAoC,OAAO,OAAO,OAAO,CAAC;AAAA,IACxG;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../../src/crypto/envelope/job.ts"],"sourcesContent":["/**\n * ECIES envelopes for encrypted job requests and results.\n *\n * Request plaintext is UTF-8 JSON with object keys sorted recursively and\n * array order preserved. Result properties follow their interface order. The\n * wire ciphertext is base64 of `iv || ephemPub || ct || mac`, as specified by\n * the ECIES provider interface. The Gateway hashes raw ciphertext bytes, not\n * plaintext.\n * The builder verifies the decrypted result's job ID, scope, and version\n * bindings. The PS worker verifies\n * `auth.bodyHash === sha256(canonicalJobRequestBytes(request))`; the Gateway\n * never sees the plaintext. Flow: personal-server-ts\n * `docs/260903-jobs-contract.md`, section 1.\n *\n * @category Cryptography\n */\n\nimport { sha256 } from \"@noble/hashes/sha2\";\nimport { bytesToHex, fromHex, isAddress, isHex, toHex, type Hex } from \"viem\";\nimport {\n deserializeECIES,\n serializeECIES,\n type ECIESProvider,\n} from \"../ecies/interface\";\nimport {\n JOB_OPERATIONS,\n JOB_PROTOCOL_VERSION,\n type JobOperation,\n type JobRequest,\n type JobRequestEnvelope,\n type JobResult,\n} from \"../../protocol/jobs\";\nimport { fromBase64, toBase64 } from \"../../utils/encoding\";\n\nconst textDecoder = new TextDecoder();\nconst textEncoder = new TextEncoder();\n\n/** A job envelope or result did not match the jobs protocol. */\nexport class JobEnvelopeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"JobEnvelopeError\";\n }\n}\n\nfunction sortJsonKeys(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortJsonKeys);\n }\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.keys(value)\n .sort()\n .map((key) => [\n key,\n sortJsonKeys((value as Record<string, unknown>)[key]),\n ]),\n );\n }\n return value;\n}\n\nfunction canonicalJsonBytes(value: unknown): Uint8Array {\n return textEncoder.encode(JSON.stringify(sortJsonKeys(value)));\n}\n\n/**\n * Returns the canonical UTF-8 JSON bytes committed to by the auth body hash.\n *\n * @param request - Job request to validate and serialize canonically.\n * @returns Recursively key-sorted, whitespace-free UTF-8 JSON bytes.\n * @throws {JobEnvelopeError} If the request does not match the protocol schema.\n */\nexport function canonicalJobRequestBytes(request: JobRequest): Uint8Array {\n validateJobRequest(request);\n return canonicalJsonBytes(request);\n}\n\nfunction requestPlaintext(envelope: JobRequestEnvelope): Uint8Array {\n validateRequestEnvelope(envelope);\n return canonicalJsonBytes(envelope);\n}\n\nfunction resultPlaintext(result: JobResult): Uint8Array {\n return textEncoder.encode(\n JSON.stringify({\n v: result.v,\n jobId: result.jobId,\n scope: result.scope,\n version: result.version,\n contentType: result.contentType,\n body: result.body,\n }),\n );\n}\n\nfunction encryptedBytesToBase64(\n encrypted: Awaited<ReturnType<ECIESProvider[\"encrypt\"]>>,\n): string {\n return toBase64(fromHex(`0x${serializeECIES(encrypted)}`, \"bytes\"));\n}\n\nfunction base64ToEncrypted(ciphertext: string) {\n return deserializeECIES(toHex(fromBase64(ciphertext)));\n}\n\nfunction parseObject(\n plaintext: Uint8Array,\n kind: string,\n): Record<string, unknown> {\n try {\n const value: unknown = JSON.parse(textDecoder.decode(plaintext));\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new JobEnvelopeError(`Invalid ${kind}: expected an object`);\n }\n return value as Record<string, unknown>;\n } catch (error) {\n if (error instanceof JobEnvelopeError) throw error;\n throw new JobEnvelopeError(`Invalid ${kind}: malformed JSON`);\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction requirePlainObject(\n value: unknown,\n field: string,\n kind: string,\n): asserts value is Record<string, unknown> {\n if (!isPlainObject(value)) {\n throw new JobEnvelopeError(`Invalid ${kind}: invalid ${field}`);\n }\n}\n\nfunction requireExactKeys(\n value: Record<string, unknown>,\n expectedKeys: readonly string[],\n kind: string,\n): void {\n for (const key of expectedKeys) {\n if (!Object.hasOwn(value, key) || value[key] === undefined) {\n throw new JobEnvelopeError(`Invalid ${kind}: missing ${key}`);\n }\n }\n const expected = new Set<PropertyKey>(expectedKeys);\n for (const key of Reflect.ownKeys(value)) {\n if (!expected.has(key)) {\n throw new JobEnvelopeError(\n `Invalid ${kind}: unknown field ${String(key)}`,\n );\n }\n }\n}\n\nfunction requireString(\n value: unknown,\n field: string,\n kind: string,\n): asserts value is string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new JobEnvelopeError(`Invalid ${kind}: missing ${field}`);\n }\n}\n\nfunction validateJobRequest(value: unknown): JobRequest {\n requirePlainObject(value, \"request\", \"job request\");\n requireExactKeys(\n value,\n [\n \"v\",\n \"jobId\",\n \"owner\",\n \"builder\",\n \"builderPublicKey\",\n \"grantId\",\n \"scope\",\n \"operation\",\n \"pinnedVersion\",\n \"deadline\",\n ],\n \"job request\",\n );\n if (value.v !== JOB_PROTOCOL_VERSION) {\n throw new JobEnvelopeError(\n `Unsupported job request version: ${String(value.v)}`,\n );\n }\n requireString(value.jobId, \"jobId\", \"job request\");\n if (typeof value.owner !== \"string\" || !isAddress(value.owner)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid owner\");\n }\n if (typeof value.builder !== \"string\" || !isAddress(value.builder)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid builder\");\n }\n if (\n typeof value.builderPublicKey !== \"string\" ||\n !isHex(value.builderPublicKey)\n ) {\n throw new JobEnvelopeError(\"Invalid job request: invalid builderPublicKey\");\n }\n if (typeof value.grantId !== \"string\" || !isHex(value.grantId)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid grantId\");\n }\n requireString(value.scope, \"scope\", \"job request\");\n if (!JOB_OPERATIONS.includes(value.operation as JobOperation)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid operation\");\n }\n if (value.pinnedVersion !== null && typeof value.pinnedVersion !== \"string\") {\n throw new JobEnvelopeError(\"Invalid job request: missing pinnedVersion\");\n }\n if (\n typeof value.deadline !== \"string\" ||\n !Number.isFinite(Date.parse(value.deadline))\n ) {\n throw new JobEnvelopeError(\"Invalid job request: invalid deadline\");\n }\n return value as unknown as JobRequest;\n}\n\nfunction validateRequestEnvelope(value: unknown): JobRequestEnvelope {\n requirePlainObject(value, \"envelope\", \"job request envelope\");\n requireExactKeys(value, [\"request\", \"auth\"], \"job request envelope\");\n validateJobRequest(value.request);\n requireString(value.auth, \"auth\", \"job request envelope\");\n return value as unknown as JobRequestEnvelope;\n}\n\nfunction validateResult(value: unknown): JobResult {\n requirePlainObject(value, \"result\", \"job result\");\n requireExactKeys(\n value,\n [\"v\", \"jobId\", \"scope\", \"version\", \"contentType\", \"body\"],\n \"job result\",\n );\n if (value.v !== JOB_PROTOCOL_VERSION) {\n throw new JobEnvelopeError(\n `Unsupported job result version: ${String(value.v)}`,\n );\n }\n for (const field of [\"jobId\", \"scope\", \"contentType\"]) {\n requireString(value[field], field, \"job result\");\n }\n if (typeof value.body !== \"string\") {\n throw new JobEnvelopeError(\"Invalid job result: missing body\");\n }\n if (value.version !== null && typeof value.version !== \"string\") {\n throw new JobEnvelopeError(\"Invalid job result: missing version\");\n }\n return value as unknown as JobResult;\n}\n\n/**\n * Encrypts a validated job request envelope for a Personal Server enclave.\n *\n * The PS worker verifies\n * `auth.bodyHash === sha256(canonicalJobRequestBytes(request))`; the Gateway\n * never sees the plaintext.\n *\n * @param envelope - Request and builder Web3Signed authorization to encrypt.\n * @param enclavePublicKey - Public key returned by `GET /v1/identity?owner=`.\n * @param ecies - Injected ECIES implementation.\n * @returns Base64 ciphertext encoded as `iv || ephemPub || ct || mac`.\n * @throws {JobEnvelopeError} If the envelope or request is invalid.\n * @throws If ECIES encryption fails or the enclave public key is invalid.\n *\n * @example\n * ```ts\n * const identity = await fetch(`/v1/identity?owner=${owner}`).then((response) =>\n * response.json(),\n * );\n * const requestCiphertext = await sealJobRequest(\n * requestEnvelope,\n * identity.publicKey,\n * ecies,\n * );\n * await fetch(\"/v1/jobs\", {\n * method: \"POST\",\n * body: JSON.stringify({ ...submission, requestCiphertext }),\n * });\n * ```\n */\nexport async function sealJobRequest(\n envelope: JobRequestEnvelope,\n enclavePublicKey: Hex,\n ecies: ECIESProvider,\n): Promise<string> {\n const encrypted = await ecies.encrypt(\n fromHex(enclavePublicKey, \"bytes\"),\n requestPlaintext(envelope),\n );\n return encryptedBytesToBase64(encrypted);\n}\n\n/**\n * Decrypts and validates a job request envelope inside the enclave.\n *\n * @param ciphertext - Base64 `iv || ephemPub || ct || mac` ciphertext.\n * @param privateKey - Enclave key bytes, supplied as `Uint8Array` so the agent can zero them after use.\n * @param ecies - Injected ECIES implementation.\n * @returns The validated request envelope exactly as parsed from plaintext.\n * @throws {JobEnvelopeError} If plaintext is malformed or fails schema validation.\n * @throws If ciphertext decoding or ECIES decryption fails.\n */\nexport async function openJobRequest(\n ciphertext: string,\n privateKey: Uint8Array,\n ecies: ECIESProvider,\n): Promise<JobRequestEnvelope> {\n const plaintext = await ecies.decrypt(\n privateKey,\n base64ToEncrypted(ciphertext),\n );\n return validateRequestEnvelope(\n parseObject(plaintext, \"job request envelope\"),\n );\n}\n\n/**\n * Encrypts a validated job result for its builder and describes the ciphertext.\n *\n * `hash` is lowercase `0x` SHA-256 of decoded ciphertext bytes, not the\n * `sha256:` prefix used by Web3Signed `bodyHash`. `size` is that decoded byte\n * length. They equal the Gateway's `resultHash` and `resultSize`.\n *\n * @param result - Job result to validate and encrypt.\n * @param builderPublicKey - Builder wallet public key recorded in the request.\n * @param ecies - Injected ECIES implementation.\n * @returns Base64 ciphertext plus its Gateway-compatible hash and size.\n * @throws {JobEnvelopeError} If the result does not match the protocol schema.\n * @throws If ECIES encryption fails or the builder public key is invalid.\n */\nexport async function sealJobResult(\n result: JobResult,\n builderPublicKey: Hex,\n ecies: ECIESProvider,\n): Promise<{ ciphertext: string; hash: Hex; size: number }> {\n validateResult(result);\n const encrypted = await ecies.encrypt(\n fromHex(builderPublicKey, \"bytes\"),\n resultPlaintext(result),\n );\n const ciphertext = encryptedBytesToBase64(encrypted);\n const bytes = fromBase64(ciphertext);\n return { ciphertext, hash: bytesToHex(sha256(bytes)), size: bytes.length };\n}\n\n/**\n * Decrypts a job result and verifies its builder-visible protocol bindings.\n *\n * The builder private key is a `Hex` wallet key. For `expect.version`,\n * `undefined` skips the check while `null` requires a null result version.\n *\n * @param ciphertext - Base64 `iv || ephemPub || ct || mac` ciphertext.\n * @param builderPrivateKey - Builder's wallet private key as hex.\n * @param ecies - Injected ECIES implementation.\n * @param expect - Required job ID and optional scope and version bindings.\n * @returns The validated result when every supplied binding matches.\n * @throws {JobEnvelopeError} If plaintext is malformed, invalid, or a binding differs.\n * @throws If ciphertext decoding or ECIES decryption fails.\n *\n * @example\n * ```ts\n * const result = await openJobResult(\n * status.resultCiphertext,\n * key,\n * ecies,\n * { jobId, scope },\n * );\n * const body = fromBase64(result.body);\n * ```\n */\nexport async function openJobResult(\n ciphertext: string,\n builderPrivateKey: Hex,\n ecies: ECIESProvider,\n expect: { jobId: string; scope?: string; version?: string | null },\n): Promise<JobResult> {\n const plaintext = await ecies.decrypt(\n fromHex(builderPrivateKey, \"bytes\"),\n base64ToEncrypted(ciphertext),\n );\n const result = validateResult(parseObject(plaintext, \"job result\"));\n if (result.jobId !== expect.jobId) {\n throw new JobEnvelopeError(\n `Job result ID ${result.jobId} does not match expected job ID ${expect.jobId}`,\n );\n }\n if (expect.scope !== undefined && result.scope !== expect.scope) {\n throw new JobEnvelopeError(\n `Job result scope ${result.scope} does not match expected scope ${expect.scope}`,\n );\n }\n if (expect.version !== undefined && result.version !== expect.version) {\n throw new JobEnvelopeError(\n `Job result version ${String(result.version)} does not match expected version ${String(expect.version)}`,\n );\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBA,kBAAuB;AACvB,kBAAuE;AACvE,uBAIO;AACP,kBAOO;AACP,sBAAqC;AAErC,MAAM,cAAc,IAAI,YAAY;AACpC,MAAM,cAAc,IAAI,YAAY;AAG7B,MAAM,yBAAyB,MAAM;AAAA,EAC1C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEA,SAAS,aAAa,OAAyB;AAC7C,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,MAAM,IAAI,YAAY;AAAA,EAC/B;AACA,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAC/C,WAAO,OAA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C9B;AACA,QAAM,SAAS,eAAe,YAAY,WAAW,YAAY,CAAC;AAClE,MAAI,OAAO,UAAU,OAAO,OAAO;AACjC,UAAM,IAAI;AAAA,MACR,iBAAiB,OAAO,KAAK,mCAAmC,OAAO,KAAK;AAAA,IAC9E;AAAA,EACF;AACA,MAAI,OAAO,UAAU,UAAa,OAAO,UAAU,OAAO,OAAO;AAC/D,UAAM,IAAI;AAAA,MACR,oBAAoB,OAAO,KAAK,kCAAkC,OAAO,KAAK;AAAA,IAChF;AAAA,EACF;AACA,MAAI,OAAO,YAAY,UAAa,OAAO,YAAY,OAAO,SAAS;AACrE,UAAM,IAAI;AAAA,MACR,sBAAsB,OAAO,OAAO,OAAO,CAAC,oCAAoC,OAAO,OAAO,OAAO,CAAC;AAAA,IACxG;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
@@ -3,10 +3,9 @@
3
3
  *
4
4
  * Request plaintext is UTF-8 JSON with object keys sorted recursively and
5
5
  * array order preserved. Result properties follow their interface order. The
6
- * Request ciphertext is base64 of `iv || ephemPub || ct || mac`, as specified
7
- * by the ECIES provider interface. Result ciphertext is the raw concatenated
8
- * byte sequence stored in object storage. The Gateway hashes raw ciphertext
9
- * bytes, not plaintext.
6
+ * wire ciphertext is base64 of `iv || ephemPub || ct || mac`, as specified by
7
+ * the ECIES provider interface. The Gateway hashes raw ciphertext bytes, not
8
+ * plaintext.
10
9
  * The builder verifies the decrypted result's job ID, scope, and version
11
10
  * bindings. The PS worker verifies
12
11
  * `auth.bodyHash === sha256(canonicalJobRequestBytes(request))`; the Gateway
@@ -75,19 +74,19 @@ export declare function openJobRequest(ciphertext: string, privateKey: Uint8Arra
75
74
  /**
76
75
  * Encrypts a validated job result for its builder and describes the ciphertext.
77
76
  *
78
- * `hash` is lowercase `0x` SHA-256 of the raw sealed bytes, not the `sha256:`
79
- * prefix used by Web3Signed `bodyHash`. `size` is the sealed byte length. They
80
- * equal the Gateway's `resultHash` and `resultSize`.
77
+ * `hash` is lowercase `0x` SHA-256 of decoded ciphertext bytes, not the
78
+ * `sha256:` prefix used by Web3Signed `bodyHash`. `size` is that decoded byte
79
+ * length. They equal the Gateway's `resultHash` and `resultSize`.
81
80
  *
82
81
  * @param result - Job result to validate and encrypt.
83
82
  * @param builderPublicKey - Builder wallet public key recorded in the request.
84
83
  * @param ecies - Injected ECIES implementation.
85
- * @returns Raw sealed bytes plus their Gateway-compatible hash and size.
84
+ * @returns Base64 ciphertext plus its Gateway-compatible hash and size.
86
85
  * @throws {JobEnvelopeError} If the result does not match the protocol schema.
87
86
  * @throws If ECIES encryption fails or the builder public key is invalid.
88
87
  */
89
88
  export declare function sealJobResult(result: JobResult, builderPublicKey: Hex, ecies: ECIESProvider): Promise<{
90
- bytes: Uint8Array;
89
+ ciphertext: string;
91
90
  hash: Hex;
92
91
  size: number;
93
92
  }>;
@@ -97,7 +96,7 @@ export declare function sealJobResult(result: JobResult, builderPublicKey: Hex,
97
96
  * The builder private key is a `Hex` wallet key. For `expect.version`,
98
97
  * `undefined` skips the check while `null` requires a null result version.
99
98
  *
100
- * @param sealedBytes - Raw `iv || ephemPub || ct || mac` bytes.
99
+ * @param ciphertext - Base64 `iv || ephemPub || ct || mac` ciphertext.
101
100
  * @param builderPrivateKey - Builder's wallet private key as hex.
102
101
  * @param ecies - Injected ECIES implementation.
103
102
  * @param expect - Required job ID and optional scope and version bindings.
@@ -107,15 +106,16 @@ export declare function sealJobResult(result: JobResult, builderPublicKey: Hex,
107
106
  *
108
107
  * @example
109
108
  * ```ts
110
- * const sealedBytes = new Uint8Array(await response.arrayBuffer());
111
- * const result = await openJobResult(sealedBytes, key, ecies, {
112
- * jobId,
113
- * scope,
114
- * });
109
+ * const result = await openJobResult(
110
+ * status.resultCiphertext,
111
+ * key,
112
+ * ecies,
113
+ * { jobId, scope },
114
+ * );
115
115
  * const body = fromBase64(result.body);
116
116
  * ```
117
117
  */
118
- export declare function openJobResult(sealedBytes: Uint8Array, builderPrivateKey: Hex, ecies: ECIESProvider, expect: {
118
+ export declare function openJobResult(ciphertext: string, builderPrivateKey: Hex, ecies: ECIESProvider, expect: {
119
119
  jobId: string;
120
120
  scope?: string;
121
121
  version?: string | null;
@@ -57,9 +57,6 @@ function resultPlaintext(result) {
57
57
  function encryptedBytesToBase64(encrypted) {
58
58
  return toBase64(fromHex(`0x${serializeECIES(encrypted)}`, "bytes"));
59
59
  }
60
- function encryptedToBytes(encrypted) {
61
- return fromHex(`0x${serializeECIES(encrypted)}`, "bytes");
62
- }
63
60
  function base64ToEncrypted(ciphertext) {
64
61
  return deserializeECIES(toHex(fromBase64(ciphertext)));
65
62
  }
@@ -205,13 +202,14 @@ async function sealJobResult(result, builderPublicKey, ecies) {
205
202
  fromHex(builderPublicKey, "bytes"),
206
203
  resultPlaintext(result)
207
204
  );
208
- const bytes = encryptedToBytes(encrypted);
209
- return { bytes, hash: bytesToHex(sha256(bytes)), size: bytes.length };
205
+ const ciphertext = encryptedBytesToBase64(encrypted);
206
+ const bytes = fromBase64(ciphertext);
207
+ return { ciphertext, hash: bytesToHex(sha256(bytes)), size: bytes.length };
210
208
  }
211
- async function openJobResult(sealedBytes, builderPrivateKey, ecies, expect) {
209
+ async function openJobResult(ciphertext, builderPrivateKey, ecies, expect) {
212
210
  const plaintext = await ecies.decrypt(
213
211
  fromHex(builderPrivateKey, "bytes"),
214
- deserializeECIES(toHex(sealedBytes))
212
+ base64ToEncrypted(ciphertext)
215
213
  );
216
214
  const result = validateResult(parseObject(plaintext, "job result"));
217
215
  if (result.jobId !== expect.jobId) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/crypto/envelope/job.ts"],"sourcesContent":["/**\n * ECIES envelopes for encrypted job requests and results.\n *\n * Request plaintext is UTF-8 JSON with object keys sorted recursively and\n * array order preserved. Result properties follow their interface order. The\n * Request ciphertext is base64 of `iv || ephemPub || ct || mac`, as specified\n * by the ECIES provider interface. Result ciphertext is the raw concatenated\n * byte sequence stored in object storage. The Gateway hashes raw ciphertext\n * bytes, not plaintext.\n * The builder verifies the decrypted result's job ID, scope, and version\n * bindings. The PS worker verifies\n * `auth.bodyHash === sha256(canonicalJobRequestBytes(request))`; the Gateway\n * never sees the plaintext. Flow: personal-server-ts\n * `docs/260903-jobs-contract.md`, section 1.\n *\n * @category Cryptography\n */\n\nimport { sha256 } from \"@noble/hashes/sha2\";\nimport { bytesToHex, fromHex, isAddress, isHex, toHex, type Hex } from \"viem\";\nimport {\n deserializeECIES,\n serializeECIES,\n type ECIESProvider,\n} from \"../ecies/interface\";\nimport {\n JOB_OPERATIONS,\n JOB_PROTOCOL_VERSION,\n type JobOperation,\n type JobRequest,\n type JobRequestEnvelope,\n type JobResult,\n} from \"../../protocol/jobs\";\nimport { fromBase64, toBase64 } from \"../../utils/encoding\";\n\nconst textDecoder = new TextDecoder();\nconst textEncoder = new TextEncoder();\n\n/** A job envelope or result did not match the jobs protocol. */\nexport class JobEnvelopeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"JobEnvelopeError\";\n }\n}\n\nfunction sortJsonKeys(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortJsonKeys);\n }\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.keys(value)\n .sort()\n .map((key) => [\n key,\n sortJsonKeys((value as Record<string, unknown>)[key]),\n ]),\n );\n }\n return value;\n}\n\nfunction canonicalJsonBytes(value: unknown): Uint8Array {\n return textEncoder.encode(JSON.stringify(sortJsonKeys(value)));\n}\n\n/**\n * Returns the canonical UTF-8 JSON bytes committed to by the auth body hash.\n *\n * @param request - Job request to validate and serialize canonically.\n * @returns Recursively key-sorted, whitespace-free UTF-8 JSON bytes.\n * @throws {JobEnvelopeError} If the request does not match the protocol schema.\n */\nexport function canonicalJobRequestBytes(request: JobRequest): Uint8Array {\n validateJobRequest(request);\n return canonicalJsonBytes(request);\n}\n\nfunction requestPlaintext(envelope: JobRequestEnvelope): Uint8Array {\n validateRequestEnvelope(envelope);\n return canonicalJsonBytes(envelope);\n}\n\nfunction resultPlaintext(result: JobResult): Uint8Array {\n return textEncoder.encode(\n JSON.stringify({\n v: result.v,\n jobId: result.jobId,\n scope: result.scope,\n version: result.version,\n contentType: result.contentType,\n body: result.body,\n }),\n );\n}\n\nfunction encryptedBytesToBase64(\n encrypted: Awaited<ReturnType<ECIESProvider[\"encrypt\"]>>,\n): string {\n return toBase64(fromHex(`0x${serializeECIES(encrypted)}`, \"bytes\"));\n}\n\nfunction encryptedToBytes(\n encrypted: Awaited<ReturnType<ECIESProvider[\"encrypt\"]>>,\n): Uint8Array {\n return fromHex(`0x${serializeECIES(encrypted)}`, \"bytes\");\n}\n\nfunction base64ToEncrypted(ciphertext: string) {\n return deserializeECIES(toHex(fromBase64(ciphertext)));\n}\n\nfunction parseObject(\n plaintext: Uint8Array,\n kind: string,\n): Record<string, unknown> {\n try {\n const value: unknown = JSON.parse(textDecoder.decode(plaintext));\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new JobEnvelopeError(`Invalid ${kind}: expected an object`);\n }\n return value as Record<string, unknown>;\n } catch (error) {\n if (error instanceof JobEnvelopeError) throw error;\n throw new JobEnvelopeError(`Invalid ${kind}: malformed JSON`);\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction requirePlainObject(\n value: unknown,\n field: string,\n kind: string,\n): asserts value is Record<string, unknown> {\n if (!isPlainObject(value)) {\n throw new JobEnvelopeError(`Invalid ${kind}: invalid ${field}`);\n }\n}\n\nfunction requireExactKeys(\n value: Record<string, unknown>,\n expectedKeys: readonly string[],\n kind: string,\n): void {\n for (const key of expectedKeys) {\n if (!Object.hasOwn(value, key) || value[key] === undefined) {\n throw new JobEnvelopeError(`Invalid ${kind}: missing ${key}`);\n }\n }\n const expected = new Set<PropertyKey>(expectedKeys);\n for (const key of Reflect.ownKeys(value)) {\n if (!expected.has(key)) {\n throw new JobEnvelopeError(\n `Invalid ${kind}: unknown field ${String(key)}`,\n );\n }\n }\n}\n\nfunction requireString(\n value: unknown,\n field: string,\n kind: string,\n): asserts value is string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new JobEnvelopeError(`Invalid ${kind}: missing ${field}`);\n }\n}\n\nfunction validateJobRequest(value: unknown): JobRequest {\n requirePlainObject(value, \"request\", \"job request\");\n requireExactKeys(\n value,\n [\n \"v\",\n \"jobId\",\n \"owner\",\n \"builder\",\n \"builderPublicKey\",\n \"grantId\",\n \"scope\",\n \"operation\",\n \"pinnedVersion\",\n \"deadline\",\n ],\n \"job request\",\n );\n if (value.v !== JOB_PROTOCOL_VERSION) {\n throw new JobEnvelopeError(\n `Unsupported job request version: ${String(value.v)}`,\n );\n }\n requireString(value.jobId, \"jobId\", \"job request\");\n if (typeof value.owner !== \"string\" || !isAddress(value.owner)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid owner\");\n }\n if (typeof value.builder !== \"string\" || !isAddress(value.builder)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid builder\");\n }\n if (\n typeof value.builderPublicKey !== \"string\" ||\n !isHex(value.builderPublicKey)\n ) {\n throw new JobEnvelopeError(\"Invalid job request: invalid builderPublicKey\");\n }\n if (typeof value.grantId !== \"string\" || !isHex(value.grantId)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid grantId\");\n }\n requireString(value.scope, \"scope\", \"job request\");\n if (!JOB_OPERATIONS.includes(value.operation as JobOperation)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid operation\");\n }\n if (value.pinnedVersion !== null && typeof value.pinnedVersion !== \"string\") {\n throw new JobEnvelopeError(\"Invalid job request: missing pinnedVersion\");\n }\n if (\n typeof value.deadline !== \"string\" ||\n !Number.isFinite(Date.parse(value.deadline))\n ) {\n throw new JobEnvelopeError(\"Invalid job request: invalid deadline\");\n }\n return value as unknown as JobRequest;\n}\n\nfunction validateRequestEnvelope(value: unknown): JobRequestEnvelope {\n requirePlainObject(value, \"envelope\", \"job request envelope\");\n requireExactKeys(value, [\"request\", \"auth\"], \"job request envelope\");\n validateJobRequest(value.request);\n requireString(value.auth, \"auth\", \"job request envelope\");\n return value as unknown as JobRequestEnvelope;\n}\n\nfunction validateResult(value: unknown): JobResult {\n requirePlainObject(value, \"result\", \"job result\");\n requireExactKeys(\n value,\n [\"v\", \"jobId\", \"scope\", \"version\", \"contentType\", \"body\"],\n \"job result\",\n );\n if (value.v !== JOB_PROTOCOL_VERSION) {\n throw new JobEnvelopeError(\n `Unsupported job result version: ${String(value.v)}`,\n );\n }\n for (const field of [\"jobId\", \"scope\", \"contentType\"]) {\n requireString(value[field], field, \"job result\");\n }\n if (typeof value.body !== \"string\") {\n throw new JobEnvelopeError(\"Invalid job result: missing body\");\n }\n if (value.version !== null && typeof value.version !== \"string\") {\n throw new JobEnvelopeError(\"Invalid job result: missing version\");\n }\n return value as unknown as JobResult;\n}\n\n/**\n * Encrypts a validated job request envelope for a Personal Server enclave.\n *\n * The PS worker verifies\n * `auth.bodyHash === sha256(canonicalJobRequestBytes(request))`; the Gateway\n * never sees the plaintext.\n *\n * @param envelope - Request and builder Web3Signed authorization to encrypt.\n * @param enclavePublicKey - Public key returned by `GET /v1/identity?owner=`.\n * @param ecies - Injected ECIES implementation.\n * @returns Base64 ciphertext encoded as `iv || ephemPub || ct || mac`.\n * @throws {JobEnvelopeError} If the envelope or request is invalid.\n * @throws If ECIES encryption fails or the enclave public key is invalid.\n *\n * @example\n * ```ts\n * const identity = await fetch(`/v1/identity?owner=${owner}`).then((response) =>\n * response.json(),\n * );\n * const requestCiphertext = await sealJobRequest(\n * requestEnvelope,\n * identity.publicKey,\n * ecies,\n * );\n * await fetch(\"/v1/jobs\", {\n * method: \"POST\",\n * body: JSON.stringify({ ...submission, requestCiphertext }),\n * });\n * ```\n */\nexport async function sealJobRequest(\n envelope: JobRequestEnvelope,\n enclavePublicKey: Hex,\n ecies: ECIESProvider,\n): Promise<string> {\n const encrypted = await ecies.encrypt(\n fromHex(enclavePublicKey, \"bytes\"),\n requestPlaintext(envelope),\n );\n return encryptedBytesToBase64(encrypted);\n}\n\n/**\n * Decrypts and validates a job request envelope inside the enclave.\n *\n * @param ciphertext - Base64 `iv || ephemPub || ct || mac` ciphertext.\n * @param privateKey - Enclave key bytes, supplied as `Uint8Array` so the agent can zero them after use.\n * @param ecies - Injected ECIES implementation.\n * @returns The validated request envelope exactly as parsed from plaintext.\n * @throws {JobEnvelopeError} If plaintext is malformed or fails schema validation.\n * @throws If ciphertext decoding or ECIES decryption fails.\n */\nexport async function openJobRequest(\n ciphertext: string,\n privateKey: Uint8Array,\n ecies: ECIESProvider,\n): Promise<JobRequestEnvelope> {\n const plaintext = await ecies.decrypt(\n privateKey,\n base64ToEncrypted(ciphertext),\n );\n return validateRequestEnvelope(\n parseObject(plaintext, \"job request envelope\"),\n );\n}\n\n/**\n * Encrypts a validated job result for its builder and describes the ciphertext.\n *\n * `hash` is lowercase `0x` SHA-256 of the raw sealed bytes, not the `sha256:`\n * prefix used by Web3Signed `bodyHash`. `size` is the sealed byte length. They\n * equal the Gateway's `resultHash` and `resultSize`.\n *\n * @param result - Job result to validate and encrypt.\n * @param builderPublicKey - Builder wallet public key recorded in the request.\n * @param ecies - Injected ECIES implementation.\n * @returns Raw sealed bytes plus their Gateway-compatible hash and size.\n * @throws {JobEnvelopeError} If the result does not match the protocol schema.\n * @throws If ECIES encryption fails or the builder public key is invalid.\n */\nexport async function sealJobResult(\n result: JobResult,\n builderPublicKey: Hex,\n ecies: ECIESProvider,\n): Promise<{ bytes: Uint8Array; hash: Hex; size: number }> {\n validateResult(result);\n const encrypted = await ecies.encrypt(\n fromHex(builderPublicKey, \"bytes\"),\n resultPlaintext(result),\n );\n const bytes = encryptedToBytes(encrypted);\n return { bytes, hash: bytesToHex(sha256(bytes)), size: bytes.length };\n}\n\n/**\n * Decrypts a job result and verifies its builder-visible protocol bindings.\n *\n * The builder private key is a `Hex` wallet key. For `expect.version`,\n * `undefined` skips the check while `null` requires a null result version.\n *\n * @param sealedBytes - Raw `iv || ephemPub || ct || mac` bytes.\n * @param builderPrivateKey - Builder's wallet private key as hex.\n * @param ecies - Injected ECIES implementation.\n * @param expect - Required job ID and optional scope and version bindings.\n * @returns The validated result when every supplied binding matches.\n * @throws {JobEnvelopeError} If plaintext is malformed, invalid, or a binding differs.\n * @throws If ciphertext decoding or ECIES decryption fails.\n *\n * @example\n * ```ts\n * const sealedBytes = new Uint8Array(await response.arrayBuffer());\n * const result = await openJobResult(sealedBytes, key, ecies, {\n * jobId,\n * scope,\n * });\n * const body = fromBase64(result.body);\n * ```\n */\nexport async function openJobResult(\n sealedBytes: Uint8Array,\n builderPrivateKey: Hex,\n ecies: ECIESProvider,\n expect: { jobId: string; scope?: string; version?: string | null },\n): Promise<JobResult> {\n const plaintext = await ecies.decrypt(\n fromHex(builderPrivateKey, \"bytes\"),\n deserializeECIES(toHex(sealedBytes)),\n );\n const result = validateResult(parseObject(plaintext, \"job result\"));\n if (result.jobId !== expect.jobId) {\n throw new JobEnvelopeError(\n `Job result ID ${result.jobId} does not match expected job ID ${expect.jobId}`,\n );\n }\n if (expect.scope !== undefined && result.scope !== expect.scope) {\n throw new JobEnvelopeError(\n `Job result scope ${result.scope} does not match expected scope ${expect.scope}`,\n );\n }\n if (expect.version !== undefined && result.version !== expect.version) {\n throw new JobEnvelopeError(\n `Job result version ${String(result.version)} does not match expected version ${String(expect.version)}`,\n );\n }\n return result;\n}\n"],"mappings":"AAkBA,SAAS,cAAc;AACvB,SAAS,YAAY,SAAS,WAAW,OAAO,aAAuB;AACvE;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OAKK;AACP,SAAS,YAAY,gBAAgB;AAErC,MAAM,cAAc,IAAI,YAAY;AACpC,MAAM,cAAc,IAAI,YAAY;AAG7B,MAAM,yBAAyB,MAAM;AAAA,EAC1C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,O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AAO,EAAE,OAAO,MAAM,WAAW,OAAO,KAAK,CAAC,GAAG,MAAM,MAAM,OAAO;AACtE;AA0BA,eAAsB,cACpB,aACA,mBACA,OACA,QACoB;AACpB,QAAM,YAAY,MAAM,MAAM;AAAA,IAC5B,QAAQ,mBAAmB,OAAO;AAAA,IAClC,iBAAiB,MAAM,WAAW,CAAC;AAAA,EACrC;AACA,QAAM,SAAS,eAAe,YAAY,WAAW,YAAY,CAAC;AAClE,MAAI,OAAO,UAAU,OAAO,OAAO;AACjC,UAAM,IAAI;AAAA,MACR,iBAAiB,OAAO,KAAK,mCAAmC,OAAO,KAAK;AAAA,IAC9E;AAAA,EACF;AACA,MAAI,OAAO,UAAU,UAAa,OAAO,UAAU,OAAO,OAAO;AAC/D,UAAM,IAAI;AAAA,MACR,oBAAoB,OAAO,KAAK,kCAAkC,OAAO,KAAK;AAAA,IAChF;AAAA,EACF;AACA,MAAI,OAAO,YAAY,UAAa,OAAO,YAAY,OAAO,SAAS;AACrE,UAAM,IAAI;AAAA,MACR,sBAAsB,OAAO,OAAO,OAAO,CAAC,oCAAoC,OAAO,OAAO,OAAO,CAAC;AAAA,IACxG;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../../src/crypto/envelope/job.ts"],"sourcesContent":["/**\n * ECIES envelopes for encrypted job requests and results.\n *\n * Request plaintext is UTF-8 JSON with object keys sorted recursively and\n * array order preserved. Result properties follow their interface order. The\n * wire ciphertext is base64 of `iv || ephemPub || ct || mac`, as specified by\n * the ECIES provider interface. The Gateway hashes raw ciphertext bytes, not\n * plaintext.\n * The builder verifies the decrypted result's job ID, scope, and version\n * bindings. The PS worker verifies\n * `auth.bodyHash === sha256(canonicalJobRequestBytes(request))`; the Gateway\n * never sees the plaintext. Flow: personal-server-ts\n * `docs/260903-jobs-contract.md`, section 1.\n *\n * @category Cryptography\n */\n\nimport { sha256 } from \"@noble/hashes/sha2\";\nimport { bytesToHex, fromHex, isAddress, isHex, toHex, type Hex } from \"viem\";\nimport {\n deserializeECIES,\n serializeECIES,\n type ECIESProvider,\n} from \"../ecies/interface\";\nimport {\n JOB_OPERATIONS,\n JOB_PROTOCOL_VERSION,\n type JobOperation,\n type JobRequest,\n type JobRequestEnvelope,\n type JobResult,\n} from \"../../protocol/jobs\";\nimport { fromBase64, toBase64 } from \"../../utils/encoding\";\n\nconst textDecoder = new TextDecoder();\nconst textEncoder = new TextEncoder();\n\n/** A job envelope or result did not match the jobs protocol. */\nexport class JobEnvelopeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"JobEnvelopeError\";\n }\n}\n\nfunction sortJsonKeys(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortJsonKeys);\n }\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.keys(value)\n .sort()\n .map((key) => [\n key,\n sortJsonKeys((value as Record<string, unknown>)[key]),\n ]),\n );\n }\n return value;\n}\n\nfunction canonicalJsonBytes(value: unknown): Uint8Array {\n return textEncoder.encode(JSON.stringify(sortJsonKeys(value)));\n}\n\n/**\n * Returns the canonical UTF-8 JSON bytes committed to by the auth body hash.\n *\n * @param request - Job request to validate and serialize canonically.\n * @returns Recursively key-sorted, whitespace-free UTF-8 JSON bytes.\n * @throws {JobEnvelopeError} If the request does not match the protocol schema.\n */\nexport function canonicalJobRequestBytes(request: JobRequest): Uint8Array {\n validateJobRequest(request);\n return canonicalJsonBytes(request);\n}\n\nfunction requestPlaintext(envelope: JobRequestEnvelope): Uint8Array {\n validateRequestEnvelope(envelope);\n return canonicalJsonBytes(envelope);\n}\n\nfunction resultPlaintext(result: JobResult): Uint8Array {\n return textEncoder.encode(\n JSON.stringify({\n v: result.v,\n jobId: result.jobId,\n scope: result.scope,\n version: result.version,\n contentType: result.contentType,\n body: result.body,\n }),\n );\n}\n\nfunction encryptedBytesToBase64(\n encrypted: Awaited<ReturnType<ECIESProvider[\"encrypt\"]>>,\n): string {\n return toBase64(fromHex(`0x${serializeECIES(encrypted)}`, \"bytes\"));\n}\n\nfunction base64ToEncrypted(ciphertext: string) {\n return deserializeECIES(toHex(fromBase64(ciphertext)));\n}\n\nfunction parseObject(\n plaintext: Uint8Array,\n kind: string,\n): Record<string, unknown> {\n try {\n const value: unknown = JSON.parse(textDecoder.decode(plaintext));\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new JobEnvelopeError(`Invalid ${kind}: expected an object`);\n }\n return value as Record<string, unknown>;\n } catch (error) {\n if (error instanceof JobEnvelopeError) throw error;\n throw new JobEnvelopeError(`Invalid ${kind}: malformed JSON`);\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction requirePlainObject(\n value: unknown,\n field: string,\n kind: string,\n): asserts value is Record<string, unknown> {\n if (!isPlainObject(value)) {\n throw new JobEnvelopeError(`Invalid ${kind}: invalid ${field}`);\n }\n}\n\nfunction requireExactKeys(\n value: Record<string, unknown>,\n expectedKeys: readonly string[],\n kind: string,\n): void {\n for (const key of expectedKeys) {\n if (!Object.hasOwn(value, key) || value[key] === undefined) {\n throw new JobEnvelopeError(`Invalid ${kind}: missing ${key}`);\n }\n }\n const expected = new Set<PropertyKey>(expectedKeys);\n for (const key of Reflect.ownKeys(value)) {\n if (!expected.has(key)) {\n throw new JobEnvelopeError(\n `Invalid ${kind}: unknown field ${String(key)}`,\n );\n }\n }\n}\n\nfunction requireString(\n value: unknown,\n field: string,\n kind: string,\n): asserts value is string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new JobEnvelopeError(`Invalid ${kind}: missing ${field}`);\n }\n}\n\nfunction validateJobRequest(value: unknown): JobRequest {\n requirePlainObject(value, \"request\", \"job request\");\n requireExactKeys(\n value,\n [\n \"v\",\n \"jobId\",\n \"owner\",\n \"builder\",\n \"builderPublicKey\",\n \"grantId\",\n \"scope\",\n \"operation\",\n \"pinnedVersion\",\n \"deadline\",\n ],\n \"job request\",\n );\n if (value.v !== JOB_PROTOCOL_VERSION) {\n throw new JobEnvelopeError(\n `Unsupported job request version: ${String(value.v)}`,\n );\n }\n requireString(value.jobId, \"jobId\", \"job request\");\n if (typeof value.owner !== \"string\" || !isAddress(value.owner)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid owner\");\n }\n if (typeof value.builder !== \"string\" || !isAddress(value.builder)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid builder\");\n }\n if (\n typeof value.builderPublicKey !== \"string\" ||\n !isHex(value.builderPublicKey)\n ) {\n throw new JobEnvelopeError(\"Invalid job request: invalid builderPublicKey\");\n }\n if (typeof value.grantId !== \"string\" || !isHex(value.grantId)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid grantId\");\n }\n requireString(value.scope, \"scope\", \"job request\");\n if (!JOB_OPERATIONS.includes(value.operation as JobOperation)) {\n throw new JobEnvelopeError(\"Invalid job request: invalid operation\");\n }\n if (value.pinnedVersion !== null && typeof value.pinnedVersion !== \"string\") {\n throw new JobEnvelopeError(\"Invalid job request: missing pinnedVersion\");\n }\n if (\n typeof value.deadline !== \"string\" ||\n !Number.isFinite(Date.parse(value.deadline))\n ) {\n throw new JobEnvelopeError(\"Invalid job request: invalid deadline\");\n }\n return value as unknown as JobRequest;\n}\n\nfunction validateRequestEnvelope(value: unknown): JobRequestEnvelope {\n requirePlainObject(value, \"envelope\", \"job request envelope\");\n requireExactKeys(value, [\"request\", \"auth\"], \"job request envelope\");\n validateJobRequest(value.request);\n requireString(value.auth, \"auth\", \"job request envelope\");\n return value as unknown as JobRequestEnvelope;\n}\n\nfunction validateResult(value: unknown): JobResult {\n requirePlainObject(value, \"result\", \"job result\");\n requireExactKeys(\n value,\n [\"v\", \"jobId\", \"scope\", \"version\", \"contentType\", \"body\"],\n \"job result\",\n );\n if (value.v !== JOB_PROTOCOL_VERSION) {\n throw new JobEnvelopeError(\n `Unsupported job result version: ${String(value.v)}`,\n );\n }\n for (const field of [\"jobId\", \"scope\", \"contentType\"]) {\n requireString(value[field], field, \"job result\");\n }\n if (typeof value.body !== \"string\") {\n throw new JobEnvelopeError(\"Invalid job result: missing body\");\n }\n if (value.version !== null && typeof value.version !== \"string\") {\n throw new JobEnvelopeError(\"Invalid job result: missing version\");\n }\n return value as unknown as JobResult;\n}\n\n/**\n * Encrypts a validated job request envelope for a Personal Server enclave.\n *\n * The PS worker verifies\n * `auth.bodyHash === sha256(canonicalJobRequestBytes(request))`; the Gateway\n * never sees the plaintext.\n *\n * @param envelope - Request and builder Web3Signed authorization to encrypt.\n * @param enclavePublicKey - Public key returned by `GET /v1/identity?owner=`.\n * @param ecies - Injected ECIES implementation.\n * @returns Base64 ciphertext encoded as `iv || ephemPub || ct || mac`.\n * @throws {JobEnvelopeError} If the envelope or request is invalid.\n * @throws If ECIES encryption fails or the enclave public key is invalid.\n *\n * @example\n * ```ts\n * const identity = await fetch(`/v1/identity?owner=${owner}`).then((response) =>\n * response.json(),\n * );\n * const requestCiphertext = await sealJobRequest(\n * requestEnvelope,\n * identity.publicKey,\n * ecies,\n * );\n * await fetch(\"/v1/jobs\", {\n * method: \"POST\",\n * body: JSON.stringify({ ...submission, requestCiphertext }),\n * });\n * ```\n */\nexport async function sealJobRequest(\n envelope: JobRequestEnvelope,\n enclavePublicKey: Hex,\n ecies: ECIESProvider,\n): Promise<string> {\n const encrypted = await ecies.encrypt(\n fromHex(enclavePublicKey, \"bytes\"),\n requestPlaintext(envelope),\n );\n return encryptedBytesToBase64(encrypted);\n}\n\n/**\n * Decrypts and validates a job request envelope inside the enclave.\n *\n * @param ciphertext - Base64 `iv || ephemPub || ct || mac` ciphertext.\n * @param privateKey - Enclave key bytes, supplied as `Uint8Array` so the agent can zero them after use.\n * @param ecies - Injected ECIES implementation.\n * @returns The validated request envelope exactly as parsed from plaintext.\n * @throws {JobEnvelopeError} If plaintext is malformed or fails schema validation.\n * @throws If ciphertext decoding or ECIES decryption fails.\n */\nexport async function openJobRequest(\n ciphertext: string,\n privateKey: Uint8Array,\n ecies: ECIESProvider,\n): Promise<JobRequestEnvelope> {\n const plaintext = await ecies.decrypt(\n privateKey,\n base64ToEncrypted(ciphertext),\n );\n return validateRequestEnvelope(\n parseObject(plaintext, \"job request envelope\"),\n );\n}\n\n/**\n * Encrypts a validated job result for its builder and describes the ciphertext.\n *\n * `hash` is lowercase `0x` SHA-256 of decoded ciphertext bytes, not the\n * `sha256:` prefix used by Web3Signed `bodyHash`. `size` is that decoded byte\n * length. They equal the Gateway's `resultHash` and `resultSize`.\n *\n * @param result - Job result to validate and encrypt.\n * @param builderPublicKey - Builder wallet public key recorded in the request.\n * @param ecies - Injected ECIES implementation.\n * @returns Base64 ciphertext plus its Gateway-compatible hash and size.\n * @throws {JobEnvelopeError} If the result does not match the protocol schema.\n * @throws If ECIES encryption fails or the builder public key is invalid.\n */\nexport async function sealJobResult(\n result: JobResult,\n builderPublicKey: Hex,\n ecies: ECIESProvider,\n): Promise<{ ciphertext: string; hash: Hex; size: number }> {\n validateResult(result);\n const encrypted = await ecies.encrypt(\n fromHex(builderPublicKey, \"bytes\"),\n resultPlaintext(result),\n );\n const ciphertext = encryptedBytesToBase64(encrypted);\n const bytes = fromBase64(ciphertext);\n return { ciphertext, hash: bytesToHex(sha256(bytes)), size: bytes.length };\n}\n\n/**\n * Decrypts a job result and verifies its builder-visible protocol bindings.\n *\n * The builder private key is a `Hex` wallet key. For `expect.version`,\n * `undefined` skips the check while `null` requires a null result version.\n *\n * @param ciphertext - Base64 `iv || ephemPub || ct || mac` ciphertext.\n * @param builderPrivateKey - Builder's wallet private key as hex.\n * @param ecies - Injected ECIES implementation.\n * @param expect - Required job ID and optional scope and version bindings.\n * @returns The validated result when every supplied binding matches.\n * @throws {JobEnvelopeError} If plaintext is malformed, invalid, or a binding differs.\n * @throws If ciphertext decoding or ECIES decryption fails.\n *\n * @example\n * ```ts\n * const result = await openJobResult(\n * status.resultCiphertext,\n * key,\n * ecies,\n * { jobId, scope },\n * );\n * const body = fromBase64(result.body);\n * ```\n */\nexport async function openJobResult(\n ciphertext: string,\n builderPrivateKey: Hex,\n ecies: ECIESProvider,\n expect: { jobId: string; scope?: string; version?: string | null },\n): Promise<JobResult> {\n const plaintext = await ecies.decrypt(\n fromHex(builderPrivateKey, \"bytes\"),\n base64ToEncrypted(ciphertext),\n );\n const result = validateResult(parseObject(plaintext, \"job result\"));\n if (result.jobId !== expect.jobId) {\n throw new JobEnvelopeError(\n `Job result ID ${result.jobId} does not match expected job ID ${expect.jobId}`,\n );\n }\n if (expect.scope !== undefined && result.scope !== expect.scope) {\n throw new JobEnvelopeError(\n `Job result scope ${result.scope} does not match expected scope ${expect.scope}`,\n );\n }\n if (expect.version !== undefined && result.version !== expect.version) {\n throw new JobEnvelopeError(\n `Job result version ${String(result.version)} does not match expected version ${String(expect.version)}`,\n );\n }\n return result;\n}\n"],"mappings":"AAiBA,SAAS,cAAc;AACvB,SAAS,YAAY,SAAS,WAAW,OAAO,aAAuB;AACvE;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OAKK;AACP,SAAS,YAAY,gBAAgB;AAErC,MAAM,cAAc,IAAI,YAAY;AACpC,MAAM,cAAc,IAAI,YAAY;AAG7B,MAAM,yBAAyB,MAAM;AAAA,EAC1C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEA,SAAS,aAAa,OAAyB;AAC7C,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,MAAM,IAAI,YAAY;AAAA,EAC/B;AACA,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAC/C,WAAO,OAAO;AAAA,MACZ,OAAO,KAAK,KAAK,EACd,KAAK,EACL,IAAI,CAAC,QAAQ;AAAA,QACZ;AAAA,QACA,aAAc,MAAkC,GAAG,CAAC;AAAA,MACtD,CAAC;AAAA,IACL;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,mBAA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Aa,OAAO,UAAU,OAAO,OAAO;AAC/D,UAAM,IAAI;AAAA,MACR,oBAAoB,OAAO,KAAK,kCAAkC,OAAO,KAAK;AAAA,IAChF;AAAA,EACF;AACA,MAAI,OAAO,YAAY,UAAa,OAAO,YAAY,OAAO,SAAS;AACrE,UAAM,IAAI;AAAA,MACR,sBAAsB,OAAO,OAAO,OAAO,CAAC,oCAAoC,OAAO,OAAO,OAAO,CAAC;AAAA,IACxG;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
package/dist/errors.cjs CHANGED
@@ -39,7 +39,6 @@ __export(errors_exports, {
39
39
  JobNotFoundError: () => JobNotFoundError,
40
40
  JobRejectedError: () => JobRejectedError,
41
41
  JobRequestTooLargeError: () => JobRequestTooLargeError,
42
- JobResultIntegrityError: () => JobResultIntegrityError,
43
42
  JobTimeoutError: () => JobTimeoutError,
44
43
  JobTransportError: () => JobTransportError,
45
44
  JobsClientError: () => JobsClientError,
@@ -314,11 +313,6 @@ class JobTimeoutError extends JobsClientError {
314
313
  super(message, "JOB_TIMEOUT", void 0, null, details);
315
314
  }
316
315
  }
317
- class JobResultIntegrityError extends JobsClientError {
318
- constructor(message, details) {
319
- super(message, "JOB_RESULT_INTEGRITY", void 0, null, details);
320
- }
321
- }
322
316
  class JobRejectedError extends JobsClientError {
323
317
  constructor(message, status, errorCode = null, details) {
324
318
  super(message, "JOB_REJECTED", status, errorCode, details);
@@ -436,7 +430,6 @@ class DataPointVersionConflictError extends VanaError {
436
430
  JobNotFoundError,
437
431
  JobRejectedError,
438
432
  JobRequestTooLargeError,
439
- JobResultIntegrityError,
440
433
  JobTimeoutError,
441
434
  JobTransportError,
442
435
  JobsClientError,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Base error class for all Vana SDK errors with structured error codes.\n *\n * @remarks\n * This abstract base class provides a foundation for all SDK-specific errors with\n * consistent error codes and stack trace handling. All Vana SDK errors extend this\n * class to provide structured error information that applications can handle\n * programmatically. The error code enables differentiation between error types\n * without relying on string matching.\n * @category Error Handling\n */\nexport class VanaError extends Error {\n constructor(\n message: string,\n public readonly code?: string,\n ) {\n super(message);\n this.name = this.constructor.name;\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n}\n\n/**\n * Thrown when gasless transaction submission via relayer fails.\n *\n * @remarks\n * This error occurs when the relayer service is unavailable, returns an error,\n * or fails to process a gasless transaction. It includes the HTTP status code\n * and response details when available to help with debugging relayer issues.\n * @category Error Handling\n */\nexport class RelayerError extends VanaError {\n constructor(\n message: string,\n public readonly statusCode?: number,\n public readonly response?: unknown,\n ) {\n super(message, \"RELAYER_ERROR\");\n }\n}\n\n/**\n * Thrown when the user rejects a wallet signature request.\n *\n * @remarks\n * This error occurs when users decline to sign transactions or typed data through\n * their wallet interface. It's a normal part of user interaction and should be\n * handled gracefully by applications without treating it as a system error.\n * @category Error Handling\n */\nexport class UserRejectedRequestError extends VanaError {\n constructor(message: string = \"User rejected the signature request\") {\n super(message, \"USER_REJECTED_REQUEST\");\n }\n}\n\n/**\n * Thrown when the SDK configuration contains invalid or missing parameters.\n *\n * @remarks\n * This error occurs during SDK initialization when required configuration\n * parameters are missing, invalid, or incompatible. Common causes include\n * missing wallet clients, invalid chain IDs, malformed storage provider\n * configurations, or incompatible parameter combinations.\n *\n * Applications should catch this error during initialization and provide\n * clear feedback to users about configuration requirements.\n *\n * @example\n * ```typescript\n * try {\n * const vana = Vana({\n * chainId: 999999, // Invalid chain ID\n * account: null // Missing account\n * });\n * } catch (error) {\n * if (error instanceof InvalidConfigurationError) {\n * console.error('Configuration error:', error.message);\n * // Show user-friendly configuration help\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class InvalidConfigurationError extends VanaError {\n constructor(message: string) {\n super(message, \"INVALID_CONFIGURATION\");\n }\n}\n\n/**\n * Thrown when a required Vana protocol contract is not deployed on the current chain.\n *\n * @remarks\n * This error occurs when attempting to interact with contracts that are not\n * available on the connected blockchain network. It includes the contract name\n * and chain ID to help identify deployment issues or incorrect network configuration.\n * @category Error Handling\n */\nexport class ContractNotFoundError extends VanaError {\n constructor(contractName: string, chainId: number) {\n super(\n `Contract ${contractName} not found on chain ${chainId}`,\n \"CONTRACT_NOT_FOUND\",\n );\n }\n}\n\n/**\n * Thrown when blockchain operations fail due to network, contract, or transaction issues.\n *\n * @remarks\n * This error encompasses various blockchain-related failures including network\n * connectivity issues, contract execution failures, insufficient gas, invalid\n * transaction parameters, or smart contract reverts. The original error is\n * preserved to provide detailed debugging information while maintaining a\n * consistent SDK error interface.\n *\n * Common causes:\n * - Network connectivity problems\n * - Insufficient gas or gas price too low\n * - Contract function reverts\n * - Invalid transaction parameters\n * - Blockchain congestion or downtime\n *\n * @example\n * ```typescript\n * try {\n * await vana.permissions.grant({\n * grantee: '0x742d35...',\n * operation: 'read'\n * });\n * } catch (error) {\n * if (error instanceof BlockchainError) {\n * console.error('Blockchain operation failed:', error.message);\n *\n * // Check if it's a network issue\n * if (error.originalError?.message.includes('network')) {\n * // Retry with exponential backoff\n * await retryOperation();\n * }\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class BlockchainError extends VanaError {\n constructor(\n message: string,\n public readonly originalError?: Error,\n ) {\n super(message, \"BLOCKCHAIN_ERROR\");\n }\n}\n\n/**\n * Thrown when data serialization or deserialization operations fail.\n *\n * @remarks\n * This error occurs when the SDK cannot properly serialize parameters for\n * blockchain transactions, IPFS storage, or API calls. Common causes include\n * circular references in objects, unsupported data types, or malformed JSON.\n * It's typically encountered during grant file creation, storage operations,\n * or when preparing transaction data.\n *\n * @example\n * ```typescript\n * try {\n * // Object with circular reference causes serialization error\n * const obj = { name: 'test' };\n * obj.self = obj; // Circular reference\n *\n * await vana.data.upload({\n * content: obj,\n * filename: 'data.json'\n * });\n * } catch (error) {\n * if (error instanceof SerializationError) {\n * console.error('Data serialization failed:', error.message);\n * // Clean data before retry\n * const cleanedData = removeCircularReferences(obj);\n * await vana.data.upload({\n * content: cleanedData,\n * filename: 'data.json'\n * });\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class SerializationError extends VanaError {\n constructor(message: string) {\n super(message, \"SERIALIZATION_ERROR\");\n }\n}\n\n/**\n * Thrown when a signature operation fails or cannot be completed.\n *\n * @remarks\n * This error occurs when wallet signature operations fail due to disconnection,\n * locked accounts, or other wallet-related issues. It preserves the original\n * error for debugging while providing consistent error handling across the SDK.\n *\n * Recovery strategies:\n * - Check wallet connection and account unlock status\n * - Retry operation with explicit user interaction\n * - For gasless operations, consider switching to direct transactions\n *\n * @example\n * ```typescript\n * try {\n * await vana.permissions.grant({ grantee: '0x...' });\n * } catch (error) {\n * if (error instanceof SignatureError) {\n * // Prompt user to unlock wallet\n * await promptWalletUnlock();\n * // Retry operation\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class SignatureError extends VanaError {\n constructor(\n message: string,\n public readonly originalError?: Error,\n ) {\n super(message, \"SIGNATURE_ERROR\");\n }\n}\n\n/**\n * Thrown when network communication fails during API calls or blockchain interactions.\n *\n * @remarks\n * This error encompasses network connectivity issues, API unavailability,\n * timeout errors, and CORS restrictions. It's commonly encountered during\n * IPFS operations, subgraph queries, or RPC calls.\n *\n * Recovery strategies:\n * - Check network connectivity\n * - Retry with exponential backoff\n * - Verify API endpoints are accessible\n * - Switch to alternative network providers or gateways\n *\n * @example\n * ```typescript\n * try {\n * const files = await vana.data.getUserFiles({ owner: '0x...' });\n * } catch (error) {\n * if (error instanceof NetworkError) {\n * // Implement retry with exponential backoff\n * await retryWithBackoff(() => vana.data.getUserFiles({ owner: '0x...' }));\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class NetworkError extends VanaError {\n constructor(\n message: string,\n public readonly originalError?: Error,\n ) {\n super(message, \"NETWORK_ERROR\");\n }\n}\n\n/**\n * Thrown when transaction nonce retrieval fails during gasless operations.\n *\n * @remarks\n * This error occurs when the SDK cannot retrieve the user's current nonce from\n * smart contracts, preventing gasless transaction submission. Nonces are critical\n * for preventing replay attacks in signed transactions.\n *\n * Recovery strategies:\n * - Retry nonce retrieval after brief delay\n * - Check wallet connection and account status\n * - Use manual nonce specification if supported by the operation\n * - Switch to direct transactions as fallback\n *\n * @example\n * ```typescript\n * try {\n * await vana.permissions.grant({ grantee: '0x...' });\n * } catch (error) {\n * if (error instanceof NonceError) {\n * // Wait and retry\n * await delay(1000);\n * await vana.permissions.grant({ grantee: '0x...' });\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class NonceError extends VanaError {\n constructor(message: string) {\n super(message, \"NONCE_ERROR\");\n }\n}\n\n/**\n * Thrown when personal server operations fail or cannot be completed.\n *\n * @remarks\n * This error occurs during interactions with personal servers for computation\n * requests, identity retrieval, or operation status checks. Common causes include\n * server unavailability, untrusted server status, or invalid permission grants.\n *\n * Recovery strategies:\n * - Verify server URL accessibility\n * - Check server trust status via `vana.permissions.getTrustedServers()`\n * - Ensure valid permissions exist for the operation\n * - Retry after server becomes available\n *\n * @example\n * ```typescript\n * try {\n * const result = await vana.server.createOperation({ permissionId: 123 });\n * } catch (error) {\n * if (error instanceof PersonalServerError) {\n * // Check if server is trusted\n * const trustedServers = await vana.permissions.getTrustedServers();\n * if (!trustedServers.includes(serverId)) {\n * await vana.permissions.trustServer({ serverId });\n * }\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class PersonalServerError extends VanaError {\n constructor(\n message: string,\n public readonly originalError?: Error,\n ) {\n super(message, \"PERSONAL_SERVER_ERROR\");\n }\n}\n\n/**\n * Thrown when attempting to register a server with a URL different from its existing registration.\n *\n * @remarks\n * This error occurs when trying to add or trust a server that's already registered\n * on-chain with a different URL. Server URLs are immutable once registered to\n * maintain consistency and security. Applications should use the existing URL\n * or register a new server with a different ID.\n *\n * @example\n * ```typescript\n * try {\n * await vana.permissions.addAndTrustServer({\n * serverId: 1,\n * serverUrl: 'https://new-url.com',\n * publicKey: '0x...'\n * });\n * } catch (error) {\n * if (error instanceof ServerUrlMismatchError) {\n * console.log(`Server already registered with: ${error.existingUrl}`);\n * // Use existing URL or register new server\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class ServerUrlMismatchError extends VanaError {\n constructor(existingUrl: string, providedUrl: string, serverId: string) {\n super(\n `Server ${serverId} is already registered with URL \"${existingUrl}\". Cannot change to \"${providedUrl}\".`,\n \"SERVER_URL_MISMATCH\",\n );\n this.existingUrl = existingUrl;\n this.providedUrl = providedUrl;\n this.serverId = serverId;\n }\n\n public readonly existingUrl: string;\n public readonly providedUrl: string;\n public readonly serverId: string;\n}\n\n/**\n * Thrown when permission grant, revoke, or validation operations fail.\n *\n * @remarks\n * This error occurs during permission management operations including grants,\n * revocations, and permission validation checks. Common causes include invalid\n * grantee addresses, expired permissions, or insufficient privileges.\n *\n * @example\n * ```typescript\n * try {\n * await vana.permissions.revoke({ permissionId: 999999 });\n * } catch (error) {\n * if (error instanceof PermissionError) {\n * console.error('Permission operation failed:', error.message);\n * // Permission may not exist or user may not be owner\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class PermissionError extends VanaError {\n constructor(\n message: string,\n public readonly originalError?: Error,\n ) {\n super(message, \"PERMISSION_ERROR\");\n }\n}\n\n/**\n * Thrown when attempting to perform write operations without a wallet client.\n *\n * @remarks\n * This error occurs when trying to execute operations that require wallet\n * interaction (signing, encrypting, or submitting transactions) while the SDK\n * is initialized in read-only mode without a wallet client. To perform write\n * operations, the SDK must be initialized with a wallet client.\n *\n * Common operations that require a wallet:\n * - Signing transactions or typed data\n * - Encrypting or decrypting files\n * - Granting or revoking permissions\n * - Uploading data to IPFS\n * - Submitting blockchain transactions\n *\n * @example\n * ```typescript\n * try {\n * // This will throw if no wallet client is provided\n * await vana.data.decryptFile({ fileId: 'abc123' });\n * } catch (error) {\n * if (error instanceof ReadOnlyError) {\n * console.error(`Cannot ${error.operation}: ${error.message}`);\n * // Initialize with wallet client to enable write operations\n * const vanaWithWallet = Vana({\n * walletClient: createWalletClient(...)\n * });\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class ReadOnlyError extends VanaError {\n constructor(\n operation: string,\n suggestion: string = \"Initialize the SDK with a walletClient to perform this operation\",\n ) {\n super(\n `Operation '${operation}' requires a wallet client. ${suggestion}`,\n \"READ_ONLY_ERROR\",\n );\n this.operation = operation;\n this.suggestion = suggestion;\n }\n\n /** The operation that was attempted */\n public readonly operation: string;\n /** Suggested solution for fixing the error */\n public readonly suggestion: string;\n}\n\n/**\n * Thrown when a long-running transaction operation times out or fails during polling.\n *\n * @remarks\n * This error occurs when asynchronous relayer operations exceed the configured timeout\n * or encounter non-recoverable errors during status polling. It preserves the operation ID\n * to allow recovery and status checking at a later time.\n *\n * The error includes:\n * - Operation ID for recovery and status checking\n * - Last known status before failure\n * - Original error details\n *\n * Recovery strategies:\n * - Save the operation ID for later status checking\n * - Implement manual recovery flow using the operation ID\n * - Check transaction status through alternative means\n * - Contact support if operation remains stuck\n *\n * @example\n * ```typescript\n * try {\n * const result = await vana.permissions.grant({\n * grantee: '0x...',\n * files: [1, 2, 3]\n * });\n * } catch (error) {\n * if (error instanceof TransactionPendingError) {\n * // Save operation ID for recovery\n * localStorage.setItem('pending_operation', error.operationId);\n *\n * // Show recovery UI\n * showRecoveryDialog({\n * operationId: error.operationId,\n * lastStatus: error.lastKnownStatus\n * });\n *\n * // Attempt recovery later\n * const status = await vana.checkOperationStatus(error.operationId);\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class TransactionPendingError extends VanaError {\n constructor(\n /** The operation ID that can be used for status checking */\n public readonly operationId: string,\n message: string,\n /** The last known status of the operation before failure */\n public readonly lastKnownStatus?: unknown,\n ) {\n super(\n `Transaction operation pending: ${message} (operationId: ${operationId})`,\n \"TRANSACTION_PENDING\",\n );\n }\n\n /**\n * Converts the error to a JSON-serializable format.\n *\n * @remarks\n * Useful for logging, storage, or transmission of error details.\n *\n * @returns JSON representation of the error\n */\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n operationId: this.operationId,\n lastKnownStatus: this.lastKnownStatus,\n };\n }\n}\n\n/**\n * Personal Server error codes a Write API call can surface in\n * {@link PersonalServerWriteError.errorCode}.\n *\n * @remarks\n * The `WRITE_*` and `LINEAGE_*` codes are specific to the Write API; the\n * rest are the shared protocol codes the write policy reuses. The string\n * escape hatch keeps codes introduced by a newer Personal Server readable.\n * @category Error Handling\n */\nexport type PersonalServerWriteErrorCode =\n | \"WRITE_SESSION_AUTH_FAILED\"\n | \"WRITE_SESSION_PROOF_REQUIRED\"\n | \"WRITE_SESSION_PROOF_REPLAY\"\n | \"GRANT_ID_REQUIRED\"\n | \"WRITE_ATTRIBUTION_REQUIRED\"\n | \"WRITE_ATTRIBUTION_INVALID\"\n | \"WRITE_ATTRIBUTION_SIGNER_MISMATCH\"\n | \"WRITE_ATTRIBUTION_GRANT_MISMATCH\"\n | \"WRITE_ATTRIBUTION_REPLAY\"\n | \"WRITE_BODY_NOT_CANONICAL\"\n | \"LINEAGE_INVALID\"\n | \"LINEAGE_SCOPE_UNDER_SOURCE_PREFIX\"\n | \"LINEAGE_SOURCE_UNKNOWN\"\n | \"LINEAGE_SOURCE_LOOKUP_FAILED\"\n | \"LINEAGE_FORBIDDEN\"\n | \"LINEAGE_GATEWAY_ERROR\"\n | \"LINEAGE_UNAVAILABLE\"\n | \"LINEAGE_CASCADE_UNAVAILABLE\"\n | \"LINEAGE_SIGNATURE_REQUIRED\"\n | \"LINEAGE_SIGNATURE_INVALID\"\n | \"INVALID_CASCADE\"\n | \"INVALID_VERSION\"\n | \"NOT_FOUND\"\n | \"MISSING_AUTH\"\n | \"INVALID_SIGNATURE\"\n | \"UNREGISTERED_BUILDER\"\n | \"GRANT_REQUIRED\"\n | \"GRANT_REVOKED\"\n | \"GRANT_EXPIRED\"\n | \"GRANT_OWNER_MISMATCH\"\n | \"SCOPE_MISMATCH\"\n | \"INVALID_BODY\"\n | \"CONTENT_TOO_LARGE\"\n | \"PS_UNAVAILABLE\"\n | \"SERVER_NOT_CONFIGURED\"\n | \"INTERNAL_ERROR\"\n | \"DERIVATIVE_QUESTION_INVALID\"\n | \"DERIVATIVE_QUESTION_NOT_FOUND\"\n | \"DERIVATIVE_DERIVED_SCOPE_REQUIRED\"\n | \"DERIVATIVE_CYCLE\"\n | \"DERIVATIVE_SOURCE_NOT_GRANTED\"\n | \"DERIVATIVE_COMPUTE_UNAVAILABLE\"\n | \"METHOD_NOT_ALLOWED\"\n | (string & {});\n\n/**\n * Base class for every Personal Server Write API failure, including the\n * derivative question routes that authenticate with the same credential.\n *\n * @remarks\n * `status` is the HTTP status the Personal Server answered with (absent for\n * failures raised before a request was sent or when no response arrived),\n * `errorCode` is the Personal Server's protocol error code when the body\n * carried one, and `details` is the server-supplied detail object.\n * @category Error Handling\n */\nexport class PersonalServerWriteError extends VanaError {\n constructor(\n message: string,\n code: string,\n public readonly status?: number,\n public readonly errorCode: PersonalServerWriteErrorCode | null = null,\n public readonly details?: Record<string, unknown>,\n ) {\n super(message, code);\n }\n}\n\n/**\n * Thrown before any request is sent when the write input is invalid: no\n * payload, a payload that is not a JSON object, a reserved `$writtenBy` /\n * `$lineage` key, a malformed lineage source id, or an unusable signer.\n * @category Error Handling\n */\nexport class WriteRequestError extends PersonalServerWriteError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"WRITE_INVALID_REQUEST\", undefined, null, details);\n }\n}\n\n/**\n * Thrown when the transport failed (fetch threw) on every attempt.\n *\n * @remarks\n * A write whose response was lost may still have been stored: the Personal\n * Server commits before answering. Check the scope before re-sending the\n * same record.\n * @category Error Handling\n */\nexport class WriteTransportError extends PersonalServerWriteError {\n constructor(\n message: string,\n public readonly attempts: number,\n cause?: unknown,\n ) {\n super(message, \"WRITE_TRANSPORT_ERROR\", undefined, null, { attempts });\n this.cause = cause;\n }\n}\n\n/**\n * Thrown when `POST /v1/write/session` refused the handshake (any non-2xx),\n * or answered with a body the SDK cannot read.\n * @category Error Handling\n */\nexport class WriteSessionError extends PersonalServerWriteError {\n constructor(\n message: string,\n status?: number,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"WRITE_SESSION_REJECTED\", status, errorCode, details);\n }\n}\n\n/**\n * Thrown by {@link writeData} when the session's bearer token has passed its\n * `expires_in` lifetime. Open a new session; nothing was sent.\n * @category Error Handling\n */\nexport class WriteSessionExpiredError extends PersonalServerWriteError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"WRITE_SESSION_EXPIRED\", undefined, null, details);\n }\n}\n\n/**\n * Thrown when a write answered 401.\n *\n * @remarks\n * `WRITE_ATTRIBUTION_*` codes describe the per-write proof. A plain\n * `INVALID_SIGNATURE` or `MISSING_AUTH` on a write usually means the session\n * token is no longer known to the Personal Server (expired, or the server\n * restarted and dropped its in-memory sessions): open a new session.\n * @category Error Handling\n */\nexport class WriteUnauthorizedError extends PersonalServerWriteError {\n constructor(\n message: string,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"WRITE_UNAUTHORIZED\", 401, errorCode, details);\n }\n}\n\n/**\n * Thrown when a write answered 403: the live grant no longer authorizes it\n * (revoked, expired, wrong owner) or the scope is outside its write patterns.\n * @category Error Handling\n */\nexport class WriteForbiddenError extends PersonalServerWriteError {\n constructor(\n message: string,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"WRITE_FORBIDDEN\", 403, errorCode, details);\n }\n}\n\n/**\n * Thrown when a write answered 409 (the record conflicts with server state).\n * @category Error Handling\n */\nexport class WriteConflictError extends PersonalServerWriteError {\n constructor(\n message: string,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"WRITE_CONFLICT\", 409, errorCode, details);\n }\n}\n\n/**\n * Thrown when the Personal Server rejected the write's lineage: 422\n * `LINEAGE_SOURCE_UNKNOWN` (`details.unknown` lists the offending ids), 400\n * `LINEAGE_INVALID` / `LINEAGE_SCOPE_UNDER_SOURCE_PREFIX`, or 502\n * `LINEAGE_SOURCE_LOOKUP_FAILED`.\n * @category Error Handling\n */\nexport class WriteLineageError extends PersonalServerWriteError {\n constructor(\n message: string,\n status = 422,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"WRITE_LINEAGE_REJECTED\", status, errorCode, details);\n }\n}\n\n/**\n * Thrown when a write answered any other non-2xx status (400 for a body the\n * server cannot store, 413 for an oversized payload, 5xx).\n * @category Error Handling\n */\nexport class WriteRejectedError extends PersonalServerWriteError {\n constructor(\n message: string,\n status: number,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"WRITE_REJECTED\", status, errorCode, details);\n }\n}\n\n/** Gateway error codes surfaced by the builder jobs client. */\nexport type JobGatewayErrorCode =\n | \"INVALID_WAIT\"\n | \"INVALID_BODY\"\n | \"BUILDER_UNKNOWN\"\n | \"GRANT_INVALID\"\n | \"OWNER_NOT_READY\"\n | \"BODY_TOO_LARGE\"\n | \"JOB_ID_MISMATCH\"\n | \"JOB_ID_TAKEN\"\n | \"JOB_NOT_FOUND\"\n | (string & {});\n\n/**\n * Base class for failures raised by the builder jobs client.\n *\n * @remarks\n * `status` is the Gateway HTTP status when a response arrived, `errorCode`\n * is the Gateway protocol code when one was supplied, and `details` retains\n * structured response or client context for diagnostics.\n *\n * @param message - Human-readable failure description.\n * @param code - Stable SDK error code.\n * @param status - Gateway HTTP status, when available.\n * @param errorCode - Gateway protocol error code, when available.\n * @param details - Additional structured context.\n * @category Error Handling\n */\nexport class JobsClientError extends VanaError {\n constructor(\n message: string,\n code: string,\n public readonly status?: number,\n public readonly errorCode: JobGatewayErrorCode | null = null,\n public readonly details?: Record<string, unknown>,\n ) {\n super(message, code);\n }\n}\n\n/**\n * Thrown when the Gateway does not recognize the signing builder (403\n * `BUILDER_UNKNOWN`).\n *\n * @param message - Gateway failure description.\n * @param details - Additional structured Gateway context.\n * @category Error Handling\n */\nexport class BuilderUnknownError extends JobsClientError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"JOB_BUILDER_UNKNOWN\", 403, \"BUILDER_UNKNOWN\", details);\n }\n}\n\n/**\n * Thrown when the supplied grant does not authorize the requested raw read\n * (403 `GRANT_INVALID`).\n *\n * @param message - Gateway failure description.\n * @param details - Additional structured Gateway context.\n * @category Error Handling\n */\nexport class GrantInvalidError extends JobsClientError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"JOB_GRANT_INVALID\", 403, \"GRANT_INVALID\", details);\n }\n}\n\n/**\n * Thrown when the owner's enclave identity is not ready to accept encrypted\n * jobs, either locally after the identity lookup or as a 403 Gateway answer.\n *\n * @param message - Identity readiness failure description.\n * @param details - Additional identity or Gateway context.\n * @category Error Handling\n */\nexport class OwnerNotReadyError extends JobsClientError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"JOB_OWNER_NOT_READY\", 403, \"OWNER_NOT_READY\", details);\n }\n}\n\n/**\n * Thrown when a freshly generated job id already exists at the Gateway (409\n * `JOB_ID_TAKEN`).\n *\n * @param message - Gateway conflict description.\n * @param details - Additional structured Gateway context.\n * @category Error Handling\n */\nexport class JobIdTakenError extends JobsClientError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"JOB_ID_TAKEN\", 409, \"JOB_ID_TAKEN\", details);\n }\n}\n\n/**\n * Thrown when a job is unknown or belongs to another builder (404\n * `JOB_NOT_FOUND`).\n *\n * @param message - Gateway not-found description.\n * @param details - Additional structured Gateway context.\n * @category Error Handling\n */\nexport class JobNotFoundError extends JobsClientError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"JOB_NOT_FOUND\", 404, \"JOB_NOT_FOUND\", details);\n }\n}\n\n/**\n * Thrown when a job submission exceeds the Gateway request limit (413).\n *\n * @param message - Gateway size-limit description.\n * @param errorCode - Gateway protocol error code.\n * @param details - Additional structured Gateway context.\n * @category Error Handling\n */\nexport class JobRequestTooLargeError extends JobsClientError {\n constructor(\n message: string,\n errorCode: JobGatewayErrorCode | null = \"BODY_TOO_LARGE\",\n details?: Record<string, unknown>,\n ) {\n super(message, \"JOB_REQUEST_TOO_LARGE\", 413, errorCode, details);\n }\n}\n\n/**\n * Thrown when a job does not reach a terminal state within the caller's wait\n * budget or before the job's own deadline.\n *\n * @param message - Timeout description.\n * @param details - Last known job state and timing context.\n * @category Error Handling\n */\nexport class JobTimeoutError extends JobsClientError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"JOB_TIMEOUT\", undefined, null, details);\n }\n}\n\n/**\n * Thrown when fetched job-result bytes do not match their object handle.\n *\n * @param message - Integrity failure description.\n * @param details - Expected and actual result metadata.\n * @category Error Handling\n */\nexport class JobResultIntegrityError extends JobsClientError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"JOB_RESULT_INTEGRITY\", undefined, null, details);\n }\n}\n\n/**\n * Thrown when the Gateway rejects a jobs request, returns an undocumented\n * response, or client input cannot form a valid jobs request.\n *\n * @param message - Rejection description.\n * @param status - Gateway HTTP status, when available.\n * @param errorCode - Gateway protocol error code, when available.\n * @param details - Additional structured context.\n * @category Error Handling\n */\nexport class JobRejectedError extends JobsClientError {\n constructor(\n message: string,\n status?: number,\n errorCode: JobGatewayErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"JOB_REJECTED\", status, errorCode, details);\n }\n}\n\n/**\n * Thrown when a jobs client HTTP request fails before a response arrives.\n *\n * @param message - Human-readable transport failure.\n * @param cause - Original value thrown by `fetch`.\n * @category Error Handling\n */\nexport class JobTransportError extends JobsClientError {\n constructor(message: string, cause?: unknown) {\n super(message, \"JOB_TRANSPORT_ERROR\");\n this.cause = cause;\n }\n}\n\n/**\n * Thrown when a lineage read (Personal Server or gateway) fails: a non-2xx\n * answer, a body that is not a lineage graph, a malformed data point id, or\n * a transport failure.\n * @category Error Handling\n */\nexport class LineageReadError extends VanaError {\n constructor(\n message: string,\n public readonly status?: number,\n public readonly errorCode: PersonalServerWriteErrorCode | null = null,\n public readonly details?: Record<string, unknown>,\n ) {\n super(message, \"LINEAGE_READ_ERROR\");\n }\n}\n\n/**\n * Thrown when the Personal Server rejected a derivative question with a\n * status the more specific errors do not claim (405, 413\n * `CONTENT_TOO_LARGE`, 5xx), or answered a body the SDK cannot read.\n *\n * @remarks\n * The question routes share the Write API's credential, so their\n * authentication failures are the write errors: {@link WriteUnauthorizedError}\n * (401), {@link WriteForbiddenError} (403 on the derived scope),\n * {@link WriteConflictError} (409 that is not a cycle),\n * {@link WriteRequestError} (refused before sending),\n * {@link WriteTransportError} (`fetch` threw).\n * @category Error Handling\n */\nexport class DerivativeQuestionRejectedError extends PersonalServerWriteError {\n constructor(\n message: string,\n status: number,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"DERIVATIVE_QUESTION_REJECTED\", status, errorCode, details);\n }\n}\n\n/**\n * Thrown when the Personal Server refused a question registration as\n * invalid: 400 `DERIVATIVE_QUESTION_INVALID` (body shape, the scope grammar,\n * 1 to 16 distinct source scopes, an 8000 character question, a model id) or\n * 400 `LINEAGE_SCOPE_UNDER_SOURCE_PREFIX` (the derived scope shares its first\n * dot-segment with a source scope). `details.field` names the offending\n * field when the server sent one.\n * @category Error Handling\n */\nexport class DerivativeQuestionInvalidError extends PersonalServerWriteError {\n constructor(\n message: string,\n status = 400,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"DERIVATIVE_QUESTION_INVALID\", status, errorCode, details);\n }\n}\n\n/**\n * Thrown when a question id is unknown (404\n * `DERIVATIVE_QUESTION_NOT_FOUND`).\n *\n * @remarks\n * A builder only ever sees the questions it registered itself, so a question\n * another builder (or the owner) registered on the same derived scope is a\n * 404 too, not a 403. An id no Personal Server ever held is a 404 as well\n * for any authenticated caller (`personal-server-ts` d91124d and later),\n * where it used to fall through to the owner gate's 401.\n * @category Error Handling\n */\nexport class DerivativeQuestionNotFoundError extends PersonalServerWriteError {\n constructor(\n message: string,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"DERIVATIVE_QUESTION_NOT_FOUND\", 404, errorCode, details);\n }\n}\n\n/**\n * Thrown when a builder listed questions without naming a derived scope (400\n * `DERIVATIVE_DERIVED_SCOPE_REQUIRED`).\n *\n * @remarks\n * The unfiltered list is the owner's; a builder may only see its own\n * questions on a scope it may write, so `?derivedScope=` is what the call is\n * authorized against. The SDK refuses an empty `derivedScope` before\n * signing anything ({@link WriteRequestError}), so this is what a hand-built\n * request gets. It is a 400, not the 401 older servers answered, so a client\n * with a re-handshake-on-401 policy does not go through a pointless\n * handshake and then report an authentication problem it does not have.\n * @category Error Handling\n */\nexport class DerivativeDerivedScopeRequiredError extends PersonalServerWriteError {\n constructor(\n message: string,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(\n message,\n \"DERIVATIVE_DERIVED_SCOPE_REQUIRED\",\n 400,\n errorCode,\n details,\n );\n }\n}\n\n/**\n * Thrown when a source scope of the question is not read-granted to the\n * builder (403 `DERIVATIVE_SOURCE_NOT_GRANTED`).\n *\n * @remarks\n * The answer exposes the sources to whoever may read the derived scope, so\n * the grant must carry a **bare** read entry for every source scope;\n * `write:` entries confer nothing. `details.scopes` lists the uncovered\n * ones.\n * @category Error Handling\n */\nexport class DerivativeSourceNotGrantedError extends PersonalServerWriteError {\n constructor(\n message: string,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"DERIVATIVE_SOURCE_NOT_GRANTED\", 403, errorCode, details);\n }\n}\n\n/**\n * Thrown when the registration would make the derived scope a transitive\n * source of itself through other registrations (409 `DERIVATIVE_CYCLE`), so\n * recompute would never settle. `details.path` is the offending chain.\n * @category Error Handling\n */\nexport class DerivativeCycleError extends PersonalServerWriteError {\n constructor(\n message: string,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"DERIVATIVE_CYCLE\", 409, errorCode, details);\n }\n}\n\n/**\n * Thrown when the Personal Server has no compute layer wired (503\n * `DERIVATIVE_COMPUTE_UNAVAILABLE`): it cannot answer questions at all.\n * @category Error Handling\n */\nexport class DerivativeComputeUnavailableError extends PersonalServerWriteError {\n constructor(\n message: string,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"DERIVATIVE_COMPUTE_UNAVAILABLE\", 503, errorCode, details);\n }\n}\n\n/**\n * Thrown when a question did not reach `ready` or `failed` within the\n * caller's budget. The question keeps computing on the server; poll it\n * again. `details.status` is the last status seen.\n * @category Error Handling\n */\nexport class DerivativeQuestionTimeoutError extends PersonalServerWriteError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"DERIVATIVE_QUESTION_TIMEOUT\", undefined, null, details);\n }\n}\n\n/**\n * Thrown when a question settled as `failed`.\n *\n * @remarks\n * `details.error` is the Personal Server's short failure reason (a status\n * code, a scope name, an error class); the prompt and the data are never\n * part of it. A failed question is recomputed on the next source change or\n * an explicit recompute.\n * @category Error Handling\n */\nexport class DerivativeQuestionFailedError extends PersonalServerWriteError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"DERIVATIVE_QUESTION_FAILED\", undefined, null, details);\n }\n}\n\n/**\n * Thrown when a DataRegistryV2 data point has been deleted (tombstoned).\n *\n * @remarks\n * Raised by gateway reads that hit HTTP 410, by Personal Server reads of a\n * deleted scope, and by any SDK read helper that would otherwise hand a\n * tombstone back to the caller as if it were data. Pass\n * `includeDeleted: true` to the gateway read helpers to opt in to seeing the\n * tombstone row (with its `deletedAt`) instead of this error.\n * @category Error Handling\n */\nexport class DataPointDeletedError extends VanaError {\n constructor(\n message: string,\n public readonly details: {\n dataPointId?: string;\n scope?: string;\n ownerAddress?: string;\n deletedAt?: string | null;\n } = {},\n ) {\n super(message, \"DATA_POINT_DELETED\");\n }\n}\n\n/**\n * Thrown when a data point operation targets a (owner, scope) the gateway\n * has no record of.\n * @category Error Handling\n */\nexport class DataPointNotFoundError extends VanaError {\n constructor(\n message: string,\n public readonly details: {\n dataPointId?: string;\n scope?: string;\n ownerAddress?: string;\n } = {},\n ) {\n super(message, \"DATA_POINT_NOT_FOUND\");\n }\n}\n\n/**\n * Thrown when the gateway rejects a data point write with HTTP 409 because\n * the signed `expectedVersion` is stale.\n *\n * @remarks\n * `currentExpectedVersion` is the version the gateway currently holds (when\n * the gateway surfaced it); re-sign against `currentExpectedVersion + 1`.\n * @category Error Handling\n */\nexport class DataPointVersionConflictError extends VanaError {\n constructor(\n message: string,\n public readonly details: {\n dataPointId?: string;\n scope?: string;\n ownerAddress?: string;\n expectedVersion?: string;\n currentExpectedVersion?: string;\n } = {},\n ) {\n super(message, \"DATA_POINT_VERSION_CONFLICT\");\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWO,MAAM,kBAAkB,MAAM;AAAA,EACnC,YACE,SACgB,MAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO,KAAK,YAAY;AAG7B,QAAI,MAAM,mBAAmB;AAC3B,YAAM,kBAAkB,MAAM,KAAK,WAAW;AAAA,IAChD;AAAA,EACF;AAAA,EATkB;AAUpB;AAWO,MAAM,qBAAqB,UAAU;AAAA,EAC1C,YACE,SACgB,YACA,UAChB;AACA,UAAM,SAAS,eAAe;AAHd;AACA;AAAA,EAGl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xE;AACF;AAYO,MAAM,sCAAsC,yBAAyB;AAAA,EAC1E,YAAY,SAAiB,SAAmC;AAC9D,UAAM,SAAS,8BAA8B,QAAW,MAAM,OAAO;AAAA,EACvE;AACF;AAaO,MAAM,8BAA8B,UAAU;AAAA,EACnD,YACE,SACgB,UAKZ,CAAC,GACL;AACA,UAAM,SAAS,oBAAoB;AAPnB;AAAA,EAQlB;AAAA,EARkB;AASpB;AAOO,MAAM,+BAA+B,UAAU;AAAA,EACpD,YACE,SACgB,UAIZ,CAAC,GACL;AACA,UAAM,SAAS,sBAAsB;AANrB;AAAA,EAOlB;AAAA,EAPkB;AAQpB;AAWO,MAAM,sCAAsC,UAAU;AAAA,EAC3D,YACE,SACgB,UAMZ,CAAC,GACL;AACA,UAAM,SAAS,6BAA6B;AAR5B;AAAA,EASlB;AAAA,EATkB;AAUpB;","names":[]}
1
+ {"version":3,"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Base error class for all Vana SDK errors with structured error codes.\n *\n * @remarks\n * This abstract base class provides a foundation for all SDK-specific errors with\n * consistent error codes and stack trace handling. All Vana SDK errors extend this\n * class to provide structured error information that applications can handle\n * programmatically. The error code enables differentiation between error types\n * without relying on string matching.\n * @category Error Handling\n */\nexport class VanaError extends Error {\n constructor(\n message: string,\n public readonly code?: string,\n ) {\n super(message);\n this.name = this.constructor.name;\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n}\n\n/**\n * Thrown when gasless transaction submission via relayer fails.\n *\n * @remarks\n * This error occurs when the relayer service is unavailable, returns an error,\n * or fails to process a gasless transaction. It includes the HTTP status code\n * and response details when available to help with debugging relayer issues.\n * @category Error Handling\n */\nexport class RelayerError extends VanaError {\n constructor(\n message: string,\n public readonly statusCode?: number,\n public readonly response?: unknown,\n ) {\n super(message, \"RELAYER_ERROR\");\n }\n}\n\n/**\n * Thrown when the user rejects a wallet signature request.\n *\n * @remarks\n * This error occurs when users decline to sign transactions or typed data through\n * their wallet interface. It's a normal part of user interaction and should be\n * handled gracefully by applications without treating it as a system error.\n * @category Error Handling\n */\nexport class UserRejectedRequestError extends VanaError {\n constructor(message: string = \"User rejected the signature request\") {\n super(message, \"USER_REJECTED_REQUEST\");\n }\n}\n\n/**\n * Thrown when the SDK configuration contains invalid or missing parameters.\n *\n * @remarks\n * This error occurs during SDK initialization when required configuration\n * parameters are missing, invalid, or incompatible. Common causes include\n * missing wallet clients, invalid chain IDs, malformed storage provider\n * configurations, or incompatible parameter combinations.\n *\n * Applications should catch this error during initialization and provide\n * clear feedback to users about configuration requirements.\n *\n * @example\n * ```typescript\n * try {\n * const vana = Vana({\n * chainId: 999999, // Invalid chain ID\n * account: null // Missing account\n * });\n * } catch (error) {\n * if (error instanceof InvalidConfigurationError) {\n * console.error('Configuration error:', error.message);\n * // Show user-friendly configuration help\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class InvalidConfigurationError extends VanaError {\n constructor(message: string) {\n super(message, \"INVALID_CONFIGURATION\");\n }\n}\n\n/**\n * Thrown when a required Vana protocol contract is not deployed on the current chain.\n *\n * @remarks\n * This error occurs when attempting to interact with contracts that are not\n * available on the connected blockchain network. It includes the contract name\n * and chain ID to help identify deployment issues or incorrect network configuration.\n * @category Error Handling\n */\nexport class ContractNotFoundError extends VanaError {\n constructor(contractName: string, chainId: number) {\n super(\n `Contract ${contractName} not found on chain ${chainId}`,\n \"CONTRACT_NOT_FOUND\",\n );\n }\n}\n\n/**\n * Thrown when blockchain operations fail due to network, contract, or transaction issues.\n *\n * @remarks\n * This error encompasses various blockchain-related failures including network\n * connectivity issues, contract execution failures, insufficient gas, invalid\n * transaction parameters, or smart contract reverts. The original error is\n * preserved to provide detailed debugging information while maintaining a\n * consistent SDK error interface.\n *\n * Common causes:\n * - Network connectivity problems\n * - Insufficient gas or gas price too low\n * - Contract function reverts\n * - Invalid transaction parameters\n * - Blockchain congestion or downtime\n *\n * @example\n * ```typescript\n * try {\n * await vana.permissions.grant({\n * grantee: '0x742d35...',\n * operation: 'read'\n * });\n * } catch (error) {\n * if (error instanceof BlockchainError) {\n * console.error('Blockchain operation failed:', error.message);\n *\n * // Check if it's a network issue\n * if (error.originalError?.message.includes('network')) {\n * // Retry with exponential backoff\n * await retryOperation();\n * }\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class BlockchainError extends VanaError {\n constructor(\n message: string,\n public readonly originalError?: Error,\n ) {\n super(message, \"BLOCKCHAIN_ERROR\");\n }\n}\n\n/**\n * Thrown when data serialization or deserialization operations fail.\n *\n * @remarks\n * This error occurs when the SDK cannot properly serialize parameters for\n * blockchain transactions, IPFS storage, or API calls. Common causes include\n * circular references in objects, unsupported data types, or malformed JSON.\n * It's typically encountered during grant file creation, storage operations,\n * or when preparing transaction data.\n *\n * @example\n * ```typescript\n * try {\n * // Object with circular reference causes serialization error\n * const obj = { name: 'test' };\n * obj.self = obj; // Circular reference\n *\n * await vana.data.upload({\n * content: obj,\n * filename: 'data.json'\n * });\n * } catch (error) {\n * if (error instanceof SerializationError) {\n * console.error('Data serialization failed:', error.message);\n * // Clean data before retry\n * const cleanedData = removeCircularReferences(obj);\n * await vana.data.upload({\n * content: cleanedData,\n * filename: 'data.json'\n * });\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class SerializationError extends VanaError {\n constructor(message: string) {\n super(message, \"SERIALIZATION_ERROR\");\n }\n}\n\n/**\n * Thrown when a signature operation fails or cannot be completed.\n *\n * @remarks\n * This error occurs when wallet signature operations fail due to disconnection,\n * locked accounts, or other wallet-related issues. It preserves the original\n * error for debugging while providing consistent error handling across the SDK.\n *\n * Recovery strategies:\n * - Check wallet connection and account unlock status\n * - Retry operation with explicit user interaction\n * - For gasless operations, consider switching to direct transactions\n *\n * @example\n * ```typescript\n * try {\n * await vana.permissions.grant({ grantee: '0x...' });\n * } catch (error) {\n * if (error instanceof SignatureError) {\n * // Prompt user to unlock wallet\n * await promptWalletUnlock();\n * // Retry operation\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class SignatureError extends VanaError {\n constructor(\n message: string,\n public readonly originalError?: Error,\n ) {\n super(message, \"SIGNATURE_ERROR\");\n }\n}\n\n/**\n * Thrown when network communication fails during API calls or blockchain interactions.\n *\n * @remarks\n * This error encompasses network connectivity issues, API unavailability,\n * timeout errors, and CORS restrictions. It's commonly encountered during\n * IPFS operations, subgraph queries, or RPC calls.\n *\n * Recovery strategies:\n * - Check network connectivity\n * - Retry with exponential backoff\n * - Verify API endpoints are accessible\n * - Switch to alternative network providers or gateways\n *\n * @example\n * ```typescript\n * try {\n * const files = await vana.data.getUserFiles({ owner: '0x...' });\n * } catch (error) {\n * if (error instanceof NetworkError) {\n * // Implement retry with exponential backoff\n * await retryWithBackoff(() => vana.data.getUserFiles({ owner: '0x...' }));\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class NetworkError extends VanaError {\n constructor(\n message: string,\n public readonly originalError?: Error,\n ) {\n super(message, \"NETWORK_ERROR\");\n }\n}\n\n/**\n * Thrown when transaction nonce retrieval fails during gasless operations.\n *\n * @remarks\n * This error occurs when the SDK cannot retrieve the user's current nonce from\n * smart contracts, preventing gasless transaction submission. Nonces are critical\n * for preventing replay attacks in signed transactions.\n *\n * Recovery strategies:\n * - Retry nonce retrieval after brief delay\n * - Check wallet connection and account status\n * - Use manual nonce specification if supported by the operation\n * - Switch to direct transactions as fallback\n *\n * @example\n * ```typescript\n * try {\n * await vana.permissions.grant({ grantee: '0x...' });\n * } catch (error) {\n * if (error instanceof NonceError) {\n * // Wait and retry\n * await delay(1000);\n * await vana.permissions.grant({ grantee: '0x...' });\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class NonceError extends VanaError {\n constructor(message: string) {\n super(message, \"NONCE_ERROR\");\n }\n}\n\n/**\n * Thrown when personal server operations fail or cannot be completed.\n *\n * @remarks\n * This error occurs during interactions with personal servers for computation\n * requests, identity retrieval, or operation status checks. Common causes include\n * server unavailability, untrusted server status, or invalid permission grants.\n *\n * Recovery strategies:\n * - Verify server URL accessibility\n * - Check server trust status via `vana.permissions.getTrustedServers()`\n * - Ensure valid permissions exist for the operation\n * - Retry after server becomes available\n *\n * @example\n * ```typescript\n * try {\n * const result = await vana.server.createOperation({ permissionId: 123 });\n * } catch (error) {\n * if (error instanceof PersonalServerError) {\n * // Check if server is trusted\n * const trustedServers = await vana.permissions.getTrustedServers();\n * if (!trustedServers.includes(serverId)) {\n * await vana.permissions.trustServer({ serverId });\n * }\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class PersonalServerError extends VanaError {\n constructor(\n message: string,\n public readonly originalError?: Error,\n ) {\n super(message, \"PERSONAL_SERVER_ERROR\");\n }\n}\n\n/**\n * Thrown when attempting to register a server with a URL different from its existing registration.\n *\n * @remarks\n * This error occurs when trying to add or trust a server that's already registered\n * on-chain with a different URL. Server URLs are immutable once registered to\n * maintain consistency and security. Applications should use the existing URL\n * or register a new server with a different ID.\n *\n * @example\n * ```typescript\n * try {\n * await vana.permissions.addAndTrustServer({\n * serverId: 1,\n * serverUrl: 'https://new-url.com',\n * publicKey: '0x...'\n * });\n * } catch (error) {\n * if (error instanceof ServerUrlMismatchError) {\n * console.log(`Server already registered with: ${error.existingUrl}`);\n * // Use existing URL or register new server\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class ServerUrlMismatchError extends VanaError {\n constructor(existingUrl: string, providedUrl: string, serverId: string) {\n super(\n `Server ${serverId} is already registered with URL \"${existingUrl}\". Cannot change to \"${providedUrl}\".`,\n \"SERVER_URL_MISMATCH\",\n );\n this.existingUrl = existingUrl;\n this.providedUrl = providedUrl;\n this.serverId = serverId;\n }\n\n public readonly existingUrl: string;\n public readonly providedUrl: string;\n public readonly serverId: string;\n}\n\n/**\n * Thrown when permission grant, revoke, or validation operations fail.\n *\n * @remarks\n * This error occurs during permission management operations including grants,\n * revocations, and permission validation checks. Common causes include invalid\n * grantee addresses, expired permissions, or insufficient privileges.\n *\n * @example\n * ```typescript\n * try {\n * await vana.permissions.revoke({ permissionId: 999999 });\n * } catch (error) {\n * if (error instanceof PermissionError) {\n * console.error('Permission operation failed:', error.message);\n * // Permission may not exist or user may not be owner\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class PermissionError extends VanaError {\n constructor(\n message: string,\n public readonly originalError?: Error,\n ) {\n super(message, \"PERMISSION_ERROR\");\n }\n}\n\n/**\n * Thrown when attempting to perform write operations without a wallet client.\n *\n * @remarks\n * This error occurs when trying to execute operations that require wallet\n * interaction (signing, encrypting, or submitting transactions) while the SDK\n * is initialized in read-only mode without a wallet client. To perform write\n * operations, the SDK must be initialized with a wallet client.\n *\n * Common operations that require a wallet:\n * - Signing transactions or typed data\n * - Encrypting or decrypting files\n * - Granting or revoking permissions\n * - Uploading data to IPFS\n * - Submitting blockchain transactions\n *\n * @example\n * ```typescript\n * try {\n * // This will throw if no wallet client is provided\n * await vana.data.decryptFile({ fileId: 'abc123' });\n * } catch (error) {\n * if (error instanceof ReadOnlyError) {\n * console.error(`Cannot ${error.operation}: ${error.message}`);\n * // Initialize with wallet client to enable write operations\n * const vanaWithWallet = Vana({\n * walletClient: createWalletClient(...)\n * });\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class ReadOnlyError extends VanaError {\n constructor(\n operation: string,\n suggestion: string = \"Initialize the SDK with a walletClient to perform this operation\",\n ) {\n super(\n `Operation '${operation}' requires a wallet client. ${suggestion}`,\n \"READ_ONLY_ERROR\",\n );\n this.operation = operation;\n this.suggestion = suggestion;\n }\n\n /** The operation that was attempted */\n public readonly operation: string;\n /** Suggested solution for fixing the error */\n public readonly suggestion: string;\n}\n\n/**\n * Thrown when a long-running transaction operation times out or fails during polling.\n *\n * @remarks\n * This error occurs when asynchronous relayer operations exceed the configured timeout\n * or encounter non-recoverable errors during status polling. It preserves the operation ID\n * to allow recovery and status checking at a later time.\n *\n * The error includes:\n * - Operation ID for recovery and status checking\n * - Last known status before failure\n * - Original error details\n *\n * Recovery strategies:\n * - Save the operation ID for later status checking\n * - Implement manual recovery flow using the operation ID\n * - Check transaction status through alternative means\n * - Contact support if operation remains stuck\n *\n * @example\n * ```typescript\n * try {\n * const result = await vana.permissions.grant({\n * grantee: '0x...',\n * files: [1, 2, 3]\n * });\n * } catch (error) {\n * if (error instanceof TransactionPendingError) {\n * // Save operation ID for recovery\n * localStorage.setItem('pending_operation', error.operationId);\n *\n * // Show recovery UI\n * showRecoveryDialog({\n * operationId: error.operationId,\n * lastStatus: error.lastKnownStatus\n * });\n *\n * // Attempt recovery later\n * const status = await vana.checkOperationStatus(error.operationId);\n * }\n * }\n * ```\n * @category Error Handling\n */\nexport class TransactionPendingError extends VanaError {\n constructor(\n /** The operation ID that can be used for status checking */\n public readonly operationId: string,\n message: string,\n /** The last known status of the operation before failure */\n public readonly lastKnownStatus?: unknown,\n ) {\n super(\n `Transaction operation pending: ${message} (operationId: ${operationId})`,\n \"TRANSACTION_PENDING\",\n );\n }\n\n /**\n * Converts the error to a JSON-serializable format.\n *\n * @remarks\n * Useful for logging, storage, or transmission of error details.\n *\n * @returns JSON representation of the error\n */\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n operationId: this.operationId,\n lastKnownStatus: this.lastKnownStatus,\n };\n }\n}\n\n/**\n * Personal Server error codes a Write API call can surface in\n * {@link PersonalServerWriteError.errorCode}.\n *\n * @remarks\n * The `WRITE_*` and `LINEAGE_*` codes are specific to the Write API; the\n * rest are the shared protocol codes the write policy reuses. The string\n * escape hatch keeps codes introduced by a newer Personal Server readable.\n * @category Error Handling\n */\nexport type PersonalServerWriteErrorCode =\n | \"WRITE_SESSION_AUTH_FAILED\"\n | \"WRITE_SESSION_PROOF_REQUIRED\"\n | \"WRITE_SESSION_PROOF_REPLAY\"\n | \"GRANT_ID_REQUIRED\"\n | \"WRITE_ATTRIBUTION_REQUIRED\"\n | \"WRITE_ATTRIBUTION_INVALID\"\n | \"WRITE_ATTRIBUTION_SIGNER_MISMATCH\"\n | \"WRITE_ATTRIBUTION_GRANT_MISMATCH\"\n | \"WRITE_ATTRIBUTION_REPLAY\"\n | \"WRITE_BODY_NOT_CANONICAL\"\n | \"LINEAGE_INVALID\"\n | \"LINEAGE_SCOPE_UNDER_SOURCE_PREFIX\"\n | \"LINEAGE_SOURCE_UNKNOWN\"\n | \"LINEAGE_SOURCE_LOOKUP_FAILED\"\n | \"LINEAGE_FORBIDDEN\"\n | \"LINEAGE_GATEWAY_ERROR\"\n | \"LINEAGE_UNAVAILABLE\"\n | \"LINEAGE_CASCADE_UNAVAILABLE\"\n | \"LINEAGE_SIGNATURE_REQUIRED\"\n | \"LINEAGE_SIGNATURE_INVALID\"\n | \"INVALID_CASCADE\"\n | \"INVALID_VERSION\"\n | \"NOT_FOUND\"\n | \"MISSING_AUTH\"\n | \"INVALID_SIGNATURE\"\n | \"UNREGISTERED_BUILDER\"\n | \"GRANT_REQUIRED\"\n | \"GRANT_REVOKED\"\n | \"GRANT_EXPIRED\"\n | \"GRANT_OWNER_MISMATCH\"\n | \"SCOPE_MISMATCH\"\n | \"INVALID_BODY\"\n | \"CONTENT_TOO_LARGE\"\n | \"PS_UNAVAILABLE\"\n | \"SERVER_NOT_CONFIGURED\"\n | \"INTERNAL_ERROR\"\n | \"DERIVATIVE_QUESTION_INVALID\"\n | \"DERIVATIVE_QUESTION_NOT_FOUND\"\n | \"DERIVATIVE_DERIVED_SCOPE_REQUIRED\"\n | \"DERIVATIVE_CYCLE\"\n | \"DERIVATIVE_SOURCE_NOT_GRANTED\"\n | \"DERIVATIVE_COMPUTE_UNAVAILABLE\"\n | \"METHOD_NOT_ALLOWED\"\n | (string & {});\n\n/**\n * Base class for every Personal Server Write API failure, including the\n * derivative question routes that authenticate with the same credential.\n *\n * @remarks\n * `status` is the HTTP status the Personal Server answered with (absent for\n * failures raised before a request was sent or when no response arrived),\n * `errorCode` is the Personal Server's protocol error code when the body\n * carried one, and `details` is the server-supplied detail object.\n * @category Error Handling\n */\nexport class PersonalServerWriteError extends VanaError {\n constructor(\n message: string,\n code: string,\n public readonly status?: number,\n public readonly errorCode: PersonalServerWriteErrorCode | null = null,\n public readonly details?: Record<string, unknown>,\n ) {\n super(message, code);\n }\n}\n\n/**\n * Thrown before any request is sent when the write input is invalid: no\n * payload, a payload that is not a JSON object, a reserved `$writtenBy` /\n * `$lineage` key, a malformed lineage source id, or an unusable signer.\n * @category Error Handling\n */\nexport class WriteRequestError extends PersonalServerWriteError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"WRITE_INVALID_REQUEST\", undefined, null, details);\n }\n}\n\n/**\n * Thrown when the transport failed (fetch threw) on every attempt.\n *\n * @remarks\n * A write whose response was lost may still have been stored: the Personal\n * Server commits before answering. Check the scope before re-sending the\n * same record.\n * @category Error Handling\n */\nexport class WriteTransportError extends PersonalServerWriteError {\n constructor(\n message: string,\n public readonly attempts: number,\n cause?: unknown,\n ) {\n super(message, \"WRITE_TRANSPORT_ERROR\", undefined, null, { attempts });\n this.cause = cause;\n }\n}\n\n/**\n * Thrown when `POST /v1/write/session` refused the handshake (any non-2xx),\n * or answered with a body the SDK cannot read.\n * @category Error Handling\n */\nexport class WriteSessionError extends PersonalServerWriteError {\n constructor(\n message: string,\n status?: number,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"WRITE_SESSION_REJECTED\", status, errorCode, details);\n }\n}\n\n/**\n * Thrown by {@link writeData} when the session's bearer token has passed its\n * `expires_in` lifetime. Open a new session; nothing was sent.\n * @category Error Handling\n */\nexport class WriteSessionExpiredError extends PersonalServerWriteError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"WRITE_SESSION_EXPIRED\", undefined, null, details);\n }\n}\n\n/**\n * Thrown when a write answered 401.\n *\n * @remarks\n * `WRITE_ATTRIBUTION_*` codes describe the per-write proof. A plain\n * `INVALID_SIGNATURE` or `MISSING_AUTH` on a write usually means the session\n * token is no longer known to the Personal Server (expired, or the server\n * restarted and dropped its in-memory sessions): open a new session.\n * @category Error Handling\n */\nexport class WriteUnauthorizedError extends PersonalServerWriteError {\n constructor(\n message: string,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"WRITE_UNAUTHORIZED\", 401, errorCode, details);\n }\n}\n\n/**\n * Thrown when a write answered 403: the live grant no longer authorizes it\n * (revoked, expired, wrong owner) or the scope is outside its write patterns.\n * @category Error Handling\n */\nexport class WriteForbiddenError extends PersonalServerWriteError {\n constructor(\n message: string,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"WRITE_FORBIDDEN\", 403, errorCode, details);\n }\n}\n\n/**\n * Thrown when a write answered 409 (the record conflicts with server state).\n * @category Error Handling\n */\nexport class WriteConflictError extends PersonalServerWriteError {\n constructor(\n message: string,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"WRITE_CONFLICT\", 409, errorCode, details);\n }\n}\n\n/**\n * Thrown when the Personal Server rejected the write's lineage: 422\n * `LINEAGE_SOURCE_UNKNOWN` (`details.unknown` lists the offending ids), 400\n * `LINEAGE_INVALID` / `LINEAGE_SCOPE_UNDER_SOURCE_PREFIX`, or 502\n * `LINEAGE_SOURCE_LOOKUP_FAILED`.\n * @category Error Handling\n */\nexport class WriteLineageError extends PersonalServerWriteError {\n constructor(\n message: string,\n status = 422,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"WRITE_LINEAGE_REJECTED\", status, errorCode, details);\n }\n}\n\n/**\n * Thrown when a write answered any other non-2xx status (400 for a body the\n * server cannot store, 413 for an oversized payload, 5xx).\n * @category Error Handling\n */\nexport class WriteRejectedError extends PersonalServerWriteError {\n constructor(\n message: string,\n status: number,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"WRITE_REJECTED\", status, errorCode, details);\n }\n}\n\n/** Gateway error codes surfaced by the builder jobs client. */\nexport type JobGatewayErrorCode =\n | \"INVALID_WAIT\"\n | \"INVALID_BODY\"\n | \"BUILDER_UNKNOWN\"\n | \"GRANT_INVALID\"\n | \"OWNER_NOT_READY\"\n | \"BODY_TOO_LARGE\"\n | \"JOB_ID_MISMATCH\"\n | \"JOB_ID_TAKEN\"\n | \"JOB_NOT_FOUND\"\n | (string & {});\n\n/**\n * Base class for failures raised by the builder jobs client.\n *\n * @remarks\n * `status` is the Gateway HTTP status when a response arrived, `errorCode`\n * is the Gateway protocol code when one was supplied, and `details` retains\n * structured response or client context for diagnostics.\n *\n * @param message - Human-readable failure description.\n * @param code - Stable SDK error code.\n * @param status - Gateway HTTP status, when available.\n * @param errorCode - Gateway protocol error code, when available.\n * @param details - Additional structured context.\n * @category Error Handling\n */\nexport class JobsClientError extends VanaError {\n constructor(\n message: string,\n code: string,\n public readonly status?: number,\n public readonly errorCode: JobGatewayErrorCode | null = null,\n public readonly details?: Record<string, unknown>,\n ) {\n super(message, code);\n }\n}\n\n/**\n * Thrown when the Gateway does not recognize the signing builder (403\n * `BUILDER_UNKNOWN`).\n *\n * @param message - Gateway failure description.\n * @param details - Additional structured Gateway context.\n * @category Error Handling\n */\nexport class BuilderUnknownError extends JobsClientError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"JOB_BUILDER_UNKNOWN\", 403, \"BUILDER_UNKNOWN\", details);\n }\n}\n\n/**\n * Thrown when the supplied grant does not authorize the requested raw read\n * (403 `GRANT_INVALID`).\n *\n * @param message - Gateway failure description.\n * @param details - Additional structured Gateway context.\n * @category Error Handling\n */\nexport class GrantInvalidError extends JobsClientError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"JOB_GRANT_INVALID\", 403, \"GRANT_INVALID\", details);\n }\n}\n\n/**\n * Thrown when the owner's enclave identity is not ready to accept encrypted\n * jobs, either locally after the identity lookup or as a 403 Gateway answer.\n *\n * @param message - Identity readiness failure description.\n * @param details - Additional identity or Gateway context.\n * @category Error Handling\n */\nexport class OwnerNotReadyError extends JobsClientError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"JOB_OWNER_NOT_READY\", 403, \"OWNER_NOT_READY\", details);\n }\n}\n\n/**\n * Thrown when a freshly generated job id already exists at the Gateway (409\n * `JOB_ID_TAKEN`).\n *\n * @param message - Gateway conflict description.\n * @param details - Additional structured Gateway context.\n * @category Error Handling\n */\nexport class JobIdTakenError extends JobsClientError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"JOB_ID_TAKEN\", 409, \"JOB_ID_TAKEN\", details);\n }\n}\n\n/**\n * Thrown when a job is unknown or belongs to another builder (404\n * `JOB_NOT_FOUND`).\n *\n * @param message - Gateway not-found description.\n * @param details - Additional structured Gateway context.\n * @category Error Handling\n */\nexport class JobNotFoundError extends JobsClientError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"JOB_NOT_FOUND\", 404, \"JOB_NOT_FOUND\", details);\n }\n}\n\n/**\n * Thrown when a job submission exceeds the Gateway request limit (413).\n *\n * @param message - Gateway size-limit description.\n * @param errorCode - Gateway protocol error code.\n * @param details - Additional structured Gateway context.\n * @category Error Handling\n */\nexport class JobRequestTooLargeError extends JobsClientError {\n constructor(\n message: string,\n errorCode: JobGatewayErrorCode | null = \"BODY_TOO_LARGE\",\n details?: Record<string, unknown>,\n ) {\n super(message, \"JOB_REQUEST_TOO_LARGE\", 413, errorCode, details);\n }\n}\n\n/**\n * Thrown when a job does not reach a terminal state within the caller's wait\n * budget or before the job's own deadline.\n *\n * @param message - Timeout description.\n * @param details - Last known job state and timing context.\n * @category Error Handling\n */\nexport class JobTimeoutError extends JobsClientError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"JOB_TIMEOUT\", undefined, null, details);\n }\n}\n\n/**\n * Thrown when the Gateway rejects a jobs request, returns an undocumented\n * response, or client input cannot form a valid jobs request.\n *\n * @param message - Rejection description.\n * @param status - Gateway HTTP status, when available.\n * @param errorCode - Gateway protocol error code, when available.\n * @param details - Additional structured context.\n * @category Error Handling\n */\nexport class JobRejectedError extends JobsClientError {\n constructor(\n message: string,\n status?: number,\n errorCode: JobGatewayErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"JOB_REJECTED\", status, errorCode, details);\n }\n}\n\n/**\n * Thrown when a jobs client HTTP request fails before a response arrives.\n *\n * @param message - Human-readable transport failure.\n * @param cause - Original value thrown by `fetch`.\n * @category Error Handling\n */\nexport class JobTransportError extends JobsClientError {\n constructor(message: string, cause?: unknown) {\n super(message, \"JOB_TRANSPORT_ERROR\");\n this.cause = cause;\n }\n}\n\n/**\n * Thrown when a lineage read (Personal Server or gateway) fails: a non-2xx\n * answer, a body that is not a lineage graph, a malformed data point id, or\n * a transport failure.\n * @category Error Handling\n */\nexport class LineageReadError extends VanaError {\n constructor(\n message: string,\n public readonly status?: number,\n public readonly errorCode: PersonalServerWriteErrorCode | null = null,\n public readonly details?: Record<string, unknown>,\n ) {\n super(message, \"LINEAGE_READ_ERROR\");\n }\n}\n\n/**\n * Thrown when the Personal Server rejected a derivative question with a\n * status the more specific errors do not claim (405, 413\n * `CONTENT_TOO_LARGE`, 5xx), or answered a body the SDK cannot read.\n *\n * @remarks\n * The question routes share the Write API's credential, so their\n * authentication failures are the write errors: {@link WriteUnauthorizedError}\n * (401), {@link WriteForbiddenError} (403 on the derived scope),\n * {@link WriteConflictError} (409 that is not a cycle),\n * {@link WriteRequestError} (refused before sending),\n * {@link WriteTransportError} (`fetch` threw).\n * @category Error Handling\n */\nexport class DerivativeQuestionRejectedError extends PersonalServerWriteError {\n constructor(\n message: string,\n status: number,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"DERIVATIVE_QUESTION_REJECTED\", status, errorCode, details);\n }\n}\n\n/**\n * Thrown when the Personal Server refused a question registration as\n * invalid: 400 `DERIVATIVE_QUESTION_INVALID` (body shape, the scope grammar,\n * 1 to 16 distinct source scopes, an 8000 character question, a model id) or\n * 400 `LINEAGE_SCOPE_UNDER_SOURCE_PREFIX` (the derived scope shares its first\n * dot-segment with a source scope). `details.field` names the offending\n * field when the server sent one.\n * @category Error Handling\n */\nexport class DerivativeQuestionInvalidError extends PersonalServerWriteError {\n constructor(\n message: string,\n status = 400,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"DERIVATIVE_QUESTION_INVALID\", status, errorCode, details);\n }\n}\n\n/**\n * Thrown when a question id is unknown (404\n * `DERIVATIVE_QUESTION_NOT_FOUND`).\n *\n * @remarks\n * A builder only ever sees the questions it registered itself, so a question\n * another builder (or the owner) registered on the same derived scope is a\n * 404 too, not a 403. An id no Personal Server ever held is a 404 as well\n * for any authenticated caller (`personal-server-ts` d91124d and later),\n * where it used to fall through to the owner gate's 401.\n * @category Error Handling\n */\nexport class DerivativeQuestionNotFoundError extends PersonalServerWriteError {\n constructor(\n message: string,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"DERIVATIVE_QUESTION_NOT_FOUND\", 404, errorCode, details);\n }\n}\n\n/**\n * Thrown when a builder listed questions without naming a derived scope (400\n * `DERIVATIVE_DERIVED_SCOPE_REQUIRED`).\n *\n * @remarks\n * The unfiltered list is the owner's; a builder may only see its own\n * questions on a scope it may write, so `?derivedScope=` is what the call is\n * authorized against. The SDK refuses an empty `derivedScope` before\n * signing anything ({@link WriteRequestError}), so this is what a hand-built\n * request gets. It is a 400, not the 401 older servers answered, so a client\n * with a re-handshake-on-401 policy does not go through a pointless\n * handshake and then report an authentication problem it does not have.\n * @category Error Handling\n */\nexport class DerivativeDerivedScopeRequiredError extends PersonalServerWriteError {\n constructor(\n message: string,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(\n message,\n \"DERIVATIVE_DERIVED_SCOPE_REQUIRED\",\n 400,\n errorCode,\n details,\n );\n }\n}\n\n/**\n * Thrown when a source scope of the question is not read-granted to the\n * builder (403 `DERIVATIVE_SOURCE_NOT_GRANTED`).\n *\n * @remarks\n * The answer exposes the sources to whoever may read the derived scope, so\n * the grant must carry a **bare** read entry for every source scope;\n * `write:` entries confer nothing. `details.scopes` lists the uncovered\n * ones.\n * @category Error Handling\n */\nexport class DerivativeSourceNotGrantedError extends PersonalServerWriteError {\n constructor(\n message: string,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"DERIVATIVE_SOURCE_NOT_GRANTED\", 403, errorCode, details);\n }\n}\n\n/**\n * Thrown when the registration would make the derived scope a transitive\n * source of itself through other registrations (409 `DERIVATIVE_CYCLE`), so\n * recompute would never settle. `details.path` is the offending chain.\n * @category Error Handling\n */\nexport class DerivativeCycleError extends PersonalServerWriteError {\n constructor(\n message: string,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"DERIVATIVE_CYCLE\", 409, errorCode, details);\n }\n}\n\n/**\n * Thrown when the Personal Server has no compute layer wired (503\n * `DERIVATIVE_COMPUTE_UNAVAILABLE`): it cannot answer questions at all.\n * @category Error Handling\n */\nexport class DerivativeComputeUnavailableError extends PersonalServerWriteError {\n constructor(\n message: string,\n errorCode: PersonalServerWriteErrorCode | null = null,\n details?: Record<string, unknown>,\n ) {\n super(message, \"DERIVATIVE_COMPUTE_UNAVAILABLE\", 503, errorCode, details);\n }\n}\n\n/**\n * Thrown when a question did not reach `ready` or `failed` within the\n * caller's budget. The question keeps computing on the server; poll it\n * again. `details.status` is the last status seen.\n * @category Error Handling\n */\nexport class DerivativeQuestionTimeoutError extends PersonalServerWriteError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"DERIVATIVE_QUESTION_TIMEOUT\", undefined, null, details);\n }\n}\n\n/**\n * Thrown when a question settled as `failed`.\n *\n * @remarks\n * `details.error` is the Personal Server's short failure reason (a status\n * code, a scope name, an error class); the prompt and the data are never\n * part of it. A failed question is recomputed on the next source change or\n * an explicit recompute.\n * @category Error Handling\n */\nexport class DerivativeQuestionFailedError extends PersonalServerWriteError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, \"DERIVATIVE_QUESTION_FAILED\", undefined, null, details);\n }\n}\n\n/**\n * Thrown when a DataRegistryV2 data point has been deleted (tombstoned).\n *\n * @remarks\n * Raised by gateway reads that hit HTTP 410, by Personal Server reads of a\n * deleted scope, and by any SDK read helper that would otherwise hand a\n * tombstone back to the caller as if it were data. Pass\n * `includeDeleted: true` to the gateway read helpers to opt in to seeing the\n * tombstone row (with its `deletedAt`) instead of this error.\n * @category Error Handling\n */\nexport class DataPointDeletedError extends VanaError {\n constructor(\n message: string,\n public readonly details: {\n dataPointId?: string;\n scope?: string;\n ownerAddress?: string;\n deletedAt?: string | null;\n } = {},\n ) {\n super(message, \"DATA_POINT_DELETED\");\n }\n}\n\n/**\n * Thrown when a data point operation targets a (owner, scope) the gateway\n * has no record of.\n * @category Error Handling\n */\nexport class DataPointNotFoundError extends VanaError {\n constructor(\n message: string,\n public readonly details: {\n dataPointId?: string;\n scope?: string;\n ownerAddress?: string;\n } = {},\n ) {\n super(message, \"DATA_POINT_NOT_FOUND\");\n }\n}\n\n/**\n * Thrown when the gateway rejects a data point write with HTTP 409 because\n * the signed `expectedVersion` is stale.\n *\n * @remarks\n * `currentExpectedVersion` is the version the gateway currently holds (when\n * the gateway surfaced it); re-sign against `currentExpectedVersion + 1`.\n * @category Error Handling\n */\nexport class DataPointVersionConflictError extends VanaError {\n constructor(\n message: string,\n public readonly details: {\n dataPointId?: string;\n scope?: string;\n ownerAddress?: string;\n expectedVersion?: string;\n currentExpectedVersion?: string;\n } = {},\n ) {\n super(message, \"DATA_POINT_VERSION_CONFLICT\");\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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zE;AACF;AAQO,MAAM,6BAA6B,yBAAyB;AAAA,EACjE,YACE,SACA,YAAiD,MACjD,SACA;AACA,UAAM,SAAS,oBAAoB,KAAK,WAAW,OAAO;AAAA,EAC5D;AACF;AAOO,MAAM,0CAA0C,yBAAyB;AAAA,EAC9E,YACE,SACA,YAAiD,MACjD,SACA;AACA,UAAM,SAAS,kCAAkC,KAAK,WAAW,OAAO;AAAA,EAC1E;AACF;AAQO,MAAM,uCAAuC,yBAAyB;AAAA,EAC3E,YAAY,SAAiB,SAAmC;AAC9D,UAAM,SAAS,+BAA+B,QAAW,MAAM,OAAO;AAAA,EACxE;AACF;AAYO,MAAM,sCAAsC,yBAAyB;AAAA,EAC1E,YAAY,SAAiB,SAAmC;AAC9D,UAAM,SAAS,8BAA8B,QAAW,MAAM,OAAO;AAAA,EACvE;AACF;AAaO,MAAM,8BAA8B,UAAU;AAAA,EACnD,YACE,SACgB,UAKZ,CAAC,GACL;AACA,UAAM,SAAS,oBAAoB;AAPnB;AAAA,EAQlB;AAAA,EARkB;AASpB;AAOO,MAAM,+BAA+B,UAAU;AAAA,EACpD,YACE,SACgB,UAIZ,CAAC,GACL;AACA,UAAM,SAAS,sBAAsB;AANrB;AAAA,EAOlB;AAAA,EAPkB;AAQpB;AAWO,MAAM,sCAAsC,UAAU;AAAA,EAC3D,YACE,SACgB,UAMZ,CAAC,GACL;AACA,UAAM,SAAS,6BAA6B;AAR5B;AAAA,EASlB;AAAA,EATkB;AAUpB;","names":[]}
package/dist/errors.d.ts CHANGED
@@ -662,16 +662,6 @@ export declare class JobRequestTooLargeError extends JobsClientError {
662
662
  export declare class JobTimeoutError extends JobsClientError {
663
663
  constructor(message: string, details?: Record<string, unknown>);
664
664
  }
665
- /**
666
- * Thrown when fetched job-result bytes do not match their object handle.
667
- *
668
- * @param message - Integrity failure description.
669
- * @param details - Expected and actual result metadata.
670
- * @category Error Handling
671
- */
672
- export declare class JobResultIntegrityError extends JobsClientError {
673
- constructor(message: string, details?: Record<string, unknown>);
674
- }
675
665
  /**
676
666
  * Thrown when the Gateway rejects a jobs request, returns an undocumented
677
667
  * response, or client input cannot form a valid jobs request.