pendra 0.18.0 → 0.18.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +9 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/_privateInference.ts","../src/_hpke.ts","../src/_parsing.ts","../src/_placement.ts","../src/_privateInferenceEngine.ts","../src/resources/audio/speech.ts","../src/resources/audio/transcriptions.ts","../src/resources/audio/index.ts","../src/_sse.ts","../src/streaming.ts","../src/_privateStreaming.ts","../src/resources/chat/completions.ts","../src/resources/chat/index.ts","../src/resources/embeddings.ts","../src/resources/images/generations.ts","../src/resources/images/index.ts","../src/resources/models.ts","../src/resources/moderations.ts","../src/resources/rerank.ts","../src/version.ts","../src/client.ts","../src/index.ts"],"sourcesContent":["export class APIError extends Error {\n readonly status: number | undefined;\n\n constructor(message: string, status?: number) {\n super(message);\n this.name = \"APIError\";\n this.status = status;\n }\n}\n\nexport class APIConnectionError extends APIError {\n constructor(message = \"Failed to connect to the Pendra API\") {\n super(message);\n this.name = \"APIConnectionError\";\n }\n}\n\nexport interface APIStatusErrorOptions {\n /** The parsed JSON body, or the raw text when it wasn't JSON. */\n body?: unknown;\n /** The body's `detail` field as the API sent it (string, array or object). */\n detail?: unknown;\n}\n\n/**\n * Raised when the API returns a non-2xx response.\n *\n * `message` is always a readable string. The response stays available for\n * callers that want to act on its structure: `body` is the parsed JSON body (or\n * the raw text when it wasn't JSON), and `detail` is the body's `detail` field\n * as sent — an array or object for validation and structured errors.\n */\nexport class APIStatusError extends APIError {\n override readonly status: number;\n readonly body: unknown;\n readonly detail: unknown;\n\n constructor(message: string, status: number, options: APIStatusErrorOptions = {}) {\n super(message, status);\n this.name = \"APIStatusError\";\n this.status = status;\n this.body = options.body;\n this.detail = options.detail;\n }\n}\n\nexport class AuthenticationError extends APIStatusError {\n constructor(\n message = \"Invalid API key — check your PENDRA_API_KEY\",\n options: APIStatusErrorOptions = {},\n ) {\n super(message, 401, options);\n this.name = \"AuthenticationError\";\n }\n}\n\nexport class RateLimitError extends APIStatusError {\n constructor(message = \"Rate limit exceeded\", options: APIStatusErrorOptions = {}) {\n super(message, 429, options);\n this.name = \"RateLimitError\";\n }\n}\n\n/**\n * Raised when a response arrives but isn't the shape the SDK expects.\n *\n * A server or proxy problem, not a transport one: the request reached Pendra\n * and came back, but the body could not be read as the documented type — a 200\n * missing a required field, a captive-portal HTML page from a corporate proxy,\n * a truncated body.\n *\n * Deliberately NOT an `APIConnectionError`: retrying a response that will never\n * parse just burns the retry budget, so callers that retry on connection\n * failures should let this one through. `body` holds a short excerpt of what\n * actually came back.\n */\nexport class APIResponseValidationError extends APIError {\n /** How much of the offending body to keep in the message. */\n static readonly BODY_EXCERPT_CHARS = 200;\n\n readonly body: string | undefined;\n\n constructor(message: string, options: { status?: number; body?: string } = {}) {\n const { status, body } = options;\n let text = message;\n if (body) {\n const max = APIResponseValidationError.BODY_EXCERPT_CHARS;\n text = `${message} (body: ${body.slice(0, max)}${body.length > max ? \"…\" : \"\"})`;\n }\n super(text, status);\n this.name = \"APIResponseValidationError\";\n this.body = body;\n }\n}\n\n/**\n * Raised when a stream reports a failure in-band, after HTTP 200.\n *\n * A streaming response commits its status line before the worker has done any\n * work, so anything that goes wrong afterwards — the worker crashing, the\n * request timing out, the fleet being at capacity — can only be described in\n * the body. The API sends `data: {\"error\": {…}}` followed by `data: [DONE]`,\n * and this error is how the SDK surfaces that instead of ending the stream as\n * though it had succeeded.\n *\n * `requestId` and `workerId` identify the failed inference to Pendra support.\n *\n * Note this extends `APIError`, not `APIStatusError`, because the API omits\n * `code` on some frames (the timeout and the generic catch-all) — so `status`\n * is genuinely optional here, which `APIStatusError`'s always-present `status`\n * cannot express. Check `status` for undefined before comparing it.\n */\nexport class APIStreamError extends APIError {\n readonly type: string | undefined;\n readonly code: number | undefined;\n readonly requestId: string | undefined;\n readonly workerId: string | undefined;\n readonly workerName: string | undefined;\n\n constructor(\n message: string,\n options: {\n type?: string;\n code?: number;\n requestId?: string;\n workerId?: string;\n workerName?: string;\n } = {},\n ) {\n super(message, typeof options.code === \"number\" ? options.code : undefined);\n this.name = \"APIStreamError\";\n this.type = options.type;\n this.code = options.code;\n this.requestId = options.requestId;\n this.workerId = options.workerId;\n this.workerName = options.workerName;\n }\n}\n\n/** Pydantic `loc` segments naming where FastAPI looked, not a caller field. */\nconst LOC_SOURCES = new Set([\"body\", \"query\", \"path\", \"header\", \"cookie\"]);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === \"string\" && value ? value : undefined;\n}\n\nfunction compactJson(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nfunction messageFromItem(item: unknown): string | undefined {\n if (isRecord(item)) {\n const msg = nonEmptyString(item.msg) ?? nonEmptyString(item.message);\n if (msg) {\n let field = typeof item.field === \"string\" ? item.field : undefined;\n if (field === undefined) {\n const loc = Array.isArray(item.loc) ? [...item.loc] : [];\n if (loc.length && LOC_SOURCES.has(String(loc[0]))) loc.shift();\n field = loc.map(String).join(\".\");\n }\n return field ? `${field}: ${msg}` : msg;\n }\n }\n return messageFromDetail(item);\n}\n\n/**\n * Render a FastAPI `detail` of any shape as a readable string: a validation\n * error list becomes `field: problem; …`, an object its `error.message` /\n * `message` / `msg`. `undefined` when there is nothing worth showing.\n * @internal\n */\nexport function messageFromDetail(detail: unknown): string | undefined {\n if (detail === undefined || detail === null) return undefined;\n if (typeof detail === \"string\") return detail || undefined;\n if (Array.isArray(detail)) {\n const parts = detail.map(messageFromItem).filter((p): p is string => !!p);\n return parts.length ? parts.join(\"; \") : undefined;\n }\n if (isRecord(detail)) {\n const err = detail.error;\n const nested = isRecord(err) ? nonEmptyString(err.message) : undefined;\n const msg = nested ?? nonEmptyString(detail.message) ?? nonEmptyString(detail.msg);\n if (msg) return msg;\n return Object.keys(detail).length ? compactJson(detail) : undefined;\n }\n return compactJson(detail);\n}\n\n/**\n * Read an error response's body once: parsed JSON, else the raw text, else\n * `undefined` (empty or unreadable). Never throws.\n * @internal\n */\nexport async function readErrorBody(response: Response): Promise<unknown> {\n let raw: string;\n try {\n raw = await response.text();\n } catch {\n return undefined;\n }\n if (!raw) return undefined;\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n return raw;\n }\n}\n\n/**\n * Build the error for a non-2xx response from its already-read `body` (see\n * `readErrorBody`). The one place every request path turns an error response\n * into an exception, so they agree. The message follows the order the API\n * errors page documents: the OpenAI-style `error.message`, then `detail` (a\n * string as-is; an array or object rendered as text), then a top-level\n * `message`, then the raw body, then `fallback`.\n * @internal\n */\nexport function statusErrorFromBody(\n status: number,\n body: unknown,\n fallback: string,\n): APIStatusError {\n const detail = isRecord(body) ? body.detail : undefined;\n const err = isRecord(body) ? body.error : undefined;\n let message =\n (isRecord(err) ? nonEmptyString(err.message) : undefined) ??\n messageFromDetail(detail) ??\n (isRecord(body) ? nonEmptyString(body.message) : undefined);\n if (message === undefined) {\n if (typeof body === \"string\") message = body || fallback;\n else if (Array.isArray(body) ? body.length : isRecord(body) && Object.keys(body).length) {\n message = compactJson(body);\n } else message = fallback;\n }\n const options = { body, detail };\n if (status === 401) return new AuthenticationError(message, options);\n if (status === 429) return new RateLimitError(message, options);\n return new APIStatusError(message, status, options);\n}\n","/**\n * Client-side Private Inference wire format (byte-for-byte port of the Python\n * SDK's `pendra._private_inference`, itself a mirror of the worker's\n * internal/privinf). Seals a request body to the org workload key, decrypts the\n * worker's sealed response, and computes the opaque conversation-affinity token.\n *\n * The API only ever relays ciphertext + routing metadata; see docs/PRIVATE_INFERENCE.md.\n */\n\nimport { chacha20poly1305 } from \"@noble/ciphers/chacha.js\";\nimport { extract, expand } from \"@noble/hashes/hkdf.js\";\nimport * as hpke from \"./_hpke\";\n\nexport const ENVELOPE_KEY = \"pendra_encrypted\";\n// v2: the response key is exported from the request's own HPKE context, so only\n// a worker holding the workload key can produce a reply this client opens. v1\n// sealed replies to a cleartext response_pk the relay could seal to as well\n// (#2142); this client never sends v1 and refuses v1 replies.\nexport const ENVELOPE_VERSION = 2;\n\nconst TEXT_ENCODER = new TextEncoder();\nconst TEXT_DECODER = new TextDecoder();\n\nconst SUITE_INFO = TEXT_ENCODER.encode(\"pendra-pi-v1\");\nconst RESPONSE_EXPORT_CTX = TEXT_ENCODER.encode(\"pendra-pi-v1:rdek\");\nconst AFFINITY_SALT_INFO = TEXT_ENCODER.encode(\"pendra-affinity-salt-v1\");\n\nfunction utf8(s: string): Uint8Array {\n return TEXT_ENCODER.encode(s);\n}\n\nfunction b64(b: Uint8Array): string {\n // Node/browser-safe base64 of raw bytes (standard alphabet, padded).\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(b).toString(\"base64\");\n }\n let binary = \"\";\n for (let i = 0; i < b.length; i++) binary += String.fromCharCode(b[i]);\n // eslint-disable-next-line no-undef\n return btoa(binary);\n}\n\nfunction b64d(s: string): Uint8Array {\n if (typeof Buffer !== \"undefined\") {\n return new Uint8Array(Buffer.from(s, \"base64\"));\n }\n // eslint-disable-next-line no-undef\n const binary = atob(s);\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);\n return out;\n}\n\nfunction toHex(b: Uint8Array): string {\n return Array.from(b)\n .map((x) => x.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/** Hex SHA-256 of a raw 32-byte X25519 public key (the recipient `kid`). */\nexport function fingerprint(pub: Uint8Array): string {\n return hpke.sha256Hex(pub);\n}\n\n/**\n * Routing-metadata AAD bound to the request ciphertext (matches the worker):\n * `pendra-pi-v1 \\x00 model \\x00 stream-bit \\x00 task_type \\x00` — v1's layout\n * with its response_pk slot left empty, which v2 has no value for.\n */\nexport function buildAad(model: string, stream: boolean, taskType: string): Uint8Array {\n const streamBit = stream ? utf8(\"1\") : utf8(\"0\");\n const sep = new Uint8Array([0x00]);\n const parts = [utf8(\"pendra-pi-v1\"), utf8(model), streamBit, utf8(taskType), new Uint8Array(0)];\n let total = 0;\n for (let i = 0; i < parts.length; i++) {\n if (i > 0) total += 1;\n total += parts[i].length;\n }\n const out = new Uint8Array(total);\n let off = 0;\n for (let i = 0; i < parts.length; i++) {\n if (i > 0) {\n out.set(sep, off);\n off += 1;\n }\n out.set(parts[i], off);\n off += parts[i].length;\n }\n return out;\n}\n\n/**\n * 12-byte ChaCha20-Poly1305 nonce with a big-endian seq counter in the low\n * 8 bytes — matches the worker's response chunk framing.\n */\nexport function seqNonce(seq: number): Uint8Array {\n const nonce = new Uint8Array(12);\n // Big-endian uint64 in the low 8 bytes (bytes 4..11).\n let n = BigInt(seq);\n for (let i = 11; i >= 4; i--) {\n nonce[i] = Number(n & 0xffn);\n n >>= 8n;\n }\n return nonce;\n}\n\nexport interface Recipient {\n kid: string;\n enc: string;\n sealed_dek: string;\n}\n\nexport interface Envelope {\n v: number;\n recipients: Recipient[];\n nonce: string;\n ciphertext: string;\n affinity_key?: string;\n binary_nonce?: string;\n binary_ciphertext?: string;\n}\n\nexport interface SealOptions {\n model: string;\n stream: boolean;\n taskType: string;\n affinityKey?: string | null;\n binary?: Uint8Array | null;\n}\n\n/**\n * Seal a full request body to one or more org workload public keys.\n *\n * `orgPubs` is a single 32-byte X25519 public key, or a list of them (the org\n * may register up to a few distinct worker keys). The request body is encrypted\n * **once** under a fresh data key (DEK); that DEK is then HPKE-sealed separately\n * to each public key, producing one `recipients` entry per key. Any worker\n * holding **any** of those keys can open its matching recipient and decrypt the\n * shared DEK.\n *\n * Returns `{ envelope, responseKeys }`. `responseKeys` maps each recipient `kid`\n * to the response key exported from that recipient's HPKE context; hand it to\n * {@link ResponseDecryptor}. Place the envelope under `pendra_encrypted`\n * alongside cleartext model/stream.\n */\nexport function sealRequest(\n orgPubs: Uint8Array | Uint8Array[],\n body: Uint8Array,\n opts: SealOptions,\n): { envelope: Envelope; responseKeys: Map<string, Uint8Array> } {\n const pubs = Array.isArray(orgPubs) ? orgPubs : [orgPubs];\n if (pubs.length === 0) {\n throw new Error(\"sealRequest: no org public keys to seal to\");\n }\n // Dedupe by fingerprint, preserving order — a duplicate recipient would be\n // dead weight (the worker opens the first match either way).\n const seen = new Set<string>();\n const uniquePubs: Uint8Array[] = [];\n for (const p of pubs) {\n const fp = fingerprint(p);\n if (!seen.has(fp)) {\n seen.add(fp);\n uniquePubs.push(p);\n }\n }\n\n const dek = hpke.randomBytes(32);\n const nonce = hpke.randomBytes(12);\n const aad = buildAad(opts.model, opts.stream, opts.taskType);\n const ciphertext = chacha20poly1305(dek, nonce, aad).encrypt(body);\n\n const recipients: Recipient[] = [];\n const responseKeys = new Map<string, Uint8Array>();\n for (const pub of uniquePubs) {\n const { enc, ctx: sealer } = hpke.setupBaseS(pub, SUITE_INFO);\n const sealedDek = sealer.seal(new Uint8Array(0), dek);\n const kid = fingerprint(pub);\n responseKeys.set(kid, sealer.export(RESPONSE_EXPORT_CTX, 32));\n recipients.push({ kid, enc: b64(enc), sealed_dek: b64(sealedDek) });\n }\n\n const envelope: Envelope = {\n v: ENVELOPE_VERSION,\n recipients,\n nonce: b64(nonce),\n ciphertext: b64(ciphertext),\n };\n if (opts.affinityKey != null) {\n envelope.affinity_key = opts.affinityKey;\n }\n if (opts.binary != null) {\n const binaryNonce = hpke.randomBytes(12);\n envelope.binary_nonce = b64(binaryNonce);\n envelope.binary_ciphertext = b64(chacha20poly1305(dek, binaryNonce, aad).encrypt(opts.binary));\n }\n return { envelope, responseKeys };\n}\n\nexport interface ResponseInner {\n v?: number;\n /** Legacy v1 encapsulated key. A v2 client refuses any frame carrying it. */\n enc?: string;\n kid?: string;\n seq: number;\n ciphertext: string;\n}\n\nconst API_TRAILER_CHUNK_KEYS = new Set([\"id\", \"object\", \"created\", \"model\", \"choices\", \"pendra\"]);\nconst API_TRAILER_PENDRA_KEYS = new Set([\"timing\", \"worker\", \"request_id\"]);\n\n/**\n * Whether an unsealed frame on an encrypted stream is the API's trailer chunk:\n * empty `choices`, and under `pendra` only what the API itself knows about the\n * request — `timing`, the serving `worker` and the `request_id` — with none of\n * the fields that carry model output. The API appends it after the worker's\n * sealed chunks, so it is the one chunk that legitimately arrives unsealed.\n *\n * The placement keys are there only because the request sent\n * `X-Pendra-Placement: 1`; SDKs that don't send it get a timing-only trailer.\n * They are still checked for shape, so a relay cannot pass off something that\n * isn't placement under their names.\n */\nexport function isApiTrailerChunk(frame: unknown): boolean {\n if (frame === null || typeof frame !== \"object\" || Array.isArray(frame)) return false;\n const obj = frame as Record<string, unknown>;\n const pendra = obj.pendra;\n if (\n !Object.keys(obj).every((k) => API_TRAILER_CHUNK_KEYS.has(k)) ||\n !Array.isArray(obj.choices) ||\n obj.choices.length !== 0 ||\n pendra === null ||\n typeof pendra !== \"object\" ||\n Array.isArray(pendra)\n ) {\n return false;\n }\n const block = pendra as Record<string, unknown>;\n const keys = Object.keys(block);\n if (keys.length === 0 || !keys.every((k) => API_TRAILER_PENDRA_KEYS.has(k))) return false;\n if (\n \"worker\" in block &&\n (block.worker === null || typeof block.worker !== \"object\" || Array.isArray(block.worker))\n ) {\n return false;\n }\n if (\"request_id\" in block && typeof block.request_id !== \"string\") return false;\n return true;\n}\n\n/**\n * The error for a reply to an encrypted request that arrived without an\n * envelope. Only a worker can seal a reply, so an unsealed one could have come\n * from anyone on the path (#2142) and is refused rather than returned.\n */\nexport function unsealedReplyError(): Error {\n return new Error(\n \"private_inference: refusing an unencrypted reply to an encrypted request (it could have been forged in transit)\",\n );\n}\n\n/**\n * Request-body key, inside the sealed body, asking the worker to seal the end\n * of a private-inference stream (#2157). The relay can neither add nor strip it.\n */\nexport const STREAM_TERMINATOR_KEY = \"pendra_stream_terminator\";\n\n/**\n * Whether a decrypted frame is the worker's declaration that it will seal the\n * end of this stream. Only the first sealed frame (seq 0) may carry it.\n */\nexport function isStreamTerminatorDeclaration(plaintext: string): boolean {\n try {\n const obj = JSON.parse(plaintext) as unknown;\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n !Array.isArray(obj) &&\n Object.keys(obj).length === 1 &&\n (obj as Record<string, unknown>)[STREAM_TERMINATOR_KEY] === 1\n );\n } catch {\n return false;\n }\n}\n\n/**\n * The error for a stream the server ended before the worker's sealed `[DONE]`,\n * after the worker declared it would send one: the relay may have cut the\n * reply short (#2157).\n */\nexport function truncatedStreamError(): Error {\n return new Error(\n \"private_inference: the stream ended before the worker's sealed end-of-stream marker; the response may have been truncated in transit\",\n );\n}\n\n/**\n * Decrypts a worker's sealed response. The first frame names the `kid` the\n * worker opened; its response key (from {@link sealRequest}) decrypts every\n * frame. Refuses any frame not in v2 form and enforces a monotonic `seq` across\n * streaming chunks.\n */\nexport class ResponseDecryptor {\n private keys: Map<string, Uint8Array>;\n private dek: Uint8Array | null = null;\n private nextSeq = 0;\n\n constructor(responseKeys: Map<string, Uint8Array>) {\n this.keys = responseKeys;\n }\n\n private ensureDek(inner: ResponseInner): void {\n // A v1 reply (sealed to a key carried in the request) is exactly what a\n // relay can forge (#2142). This client sealed a v2 request, so a genuine\n // worker never sends one — refuse it rather than fall back.\n if (inner.v !== ENVELOPE_VERSION || inner.enc !== undefined) {\n throw new Error(\n \"private_inference: refusing a response that is not in v2 form (it could have been forged in transit)\",\n );\n }\n if (this.dek !== null) return;\n const dek = inner.kid === undefined ? undefined : this.keys.get(inner.kid);\n if (dek === undefined) {\n throw new Error(\"private_inference: first response frame names no key this request was sealed to\");\n }\n this.dek = dek;\n }\n\n /** Decrypt a non-streaming result envelope `{v, kid, seq, ciphertext}`. */\n openResult(inner: ResponseInner): Uint8Array {\n this.ensureDek(inner);\n return chacha20poly1305(this.dek as Uint8Array, seqNonce(Number(inner.seq))).decrypt(b64d(inner.ciphertext));\n }\n\n /** Decrypt one streaming chunk envelope, enforcing monotonic `seq`. */\n openChunk(inner: ResponseInner): Uint8Array {\n const seq = Number(inner.seq);\n if (seq !== this.nextSeq) {\n throw new Error(\n `private_inference: out-of-order response chunk (seq ${seq}, expected ${this.nextSeq})`,\n );\n }\n this.ensureDek(inner);\n // Advance seq only after a successful decrypt: a transient decrypt failure\n // then leaves the counter unchanged so a retry of the same (correct) chunk\n // isn't wrongly rejected as out-of-order.\n const pt = chacha20poly1305(this.dek as Uint8Array, seqNonce(seq)).decrypt(b64d(inner.ciphertext));\n this.nextSeq += 1;\n return pt;\n }\n}\n\n/** salt = HKDF-SHA256(ikm=utf8(apiKey), salt='', info='pendra-affinity-salt-v1', L=32). */\nexport function deriveSalt(rawApiKey: string): Uint8Array {\n // Mirror Python's HKDF (which uses an empty salt → HMAC treats it as NH zeros).\n const prk = extract(hpke.sha256, utf8(rawApiKey), new Uint8Array(32));\n return expand(hpke.sha256, prk, AFFINITY_SALT_INFO, 32);\n}\n\n/**\n * Canonical JSON matching Python's\n * `json.dumps(value, sort_keys=True, separators=(\",\",\":\"), ensure_ascii=True)`:\n * recursively sort object keys, no whitespace, and escape ALL non-ASCII code\n * units as `\\uXXXX` (per UTF-16 code unit) plus the standard escapes.\n * `JSON.stringify` does NOT match this (it emits raw non-ASCII), so we serialize\n * by hand.\n */\nexport function canonicalJson(value: unknown): string {\n if (value === null) return \"null\";\n const t = typeof value;\n if (t === \"boolean\") return value ? \"true\" : \"false\";\n if (t === \"number\") {\n // Python's json emits Infinity/NaN unquoted; mirror JSON.stringify's finite\n // handling which is what any realistic message content will carry.\n return String(value);\n }\n if (t === \"string\") return encodeString(value as string);\n if (Array.isArray(value)) {\n return \"[\" + value.map((v) => canonicalJson(v)).join(\",\") + \"]\";\n }\n if (t === \"object\") {\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n const items = keys.map((k) => encodeString(k) + \":\" + canonicalJson(obj[k]));\n return \"{\" + items.join(\",\") + \"}\";\n }\n // undefined / function / symbol shouldn't appear in message content; be safe.\n return \"null\";\n}\n\nfunction encodeString(s: string): string {\n let out = '\"';\n for (let i = 0; i < s.length; i++) {\n const code = s.charCodeAt(i); // UTF-16 code unit\n switch (code) {\n case 0x22:\n out += '\\\\\"';\n break;\n case 0x5c:\n out += \"\\\\\\\\\";\n break;\n case 0x08:\n out += \"\\\\b\";\n break;\n case 0x09:\n out += \"\\\\t\";\n break;\n case 0x0a:\n out += \"\\\\n\";\n break;\n case 0x0c:\n out += \"\\\\f\";\n break;\n case 0x0d:\n out += \"\\\\r\";\n break;\n default:\n if (code < 0x20 || code > 0x7e) {\n // Control chars and all non-ASCII (incl. each surrogate half of an\n // astral char) as \\uXXXX — matches Python's ensure_ascii=True.\n out += \"\\\\u\" + code.toString(16).padStart(4, \"0\");\n } else {\n out += s[i];\n }\n }\n }\n return out + '\"';\n}\n\nfunction flattenContent(content: unknown): string {\n if (typeof content === \"string\") return content;\n return canonicalJson(content);\n}\n\nexport interface AffinityMessage {\n role?: string;\n content?: unknown;\n}\n\n/**\n * Compute the opaque conversation-affinity token (chat only). Canonicalises\n * model + roles/content up to and including the first `user` message, then\n * HMAC-SHA256s it under a salt derived from the API key (or an explicit\n * override). Returns null when there is no user message.\n *\n * Stable across the Python and Node SDKs so KV-cache affinity survives a client\n * switching SDKs; the API treats it as opaque (no server-side recompute).\n */\nexport function affinityKey(\n rawApiKey: string,\n model: string,\n messages: AffinityMessage[] | null | undefined,\n saltOverride?: Uint8Array | null,\n): string | null {\n const parts: string[] = [\"model=\" + model];\n let sawUser = false;\n for (const m of messages ?? []) {\n const role = m.role ?? \"\";\n parts.push(role + \":\" + flattenContent(m.content));\n if (role === \"user\") {\n sawUser = true;\n break;\n }\n }\n if (!sawUser) return null;\n const salt = saltOverride != null ? saltOverride : deriveSalt(rawApiKey);\n const mac = hpke.hmac(hpke.sha256, salt, utf8(parts.join(\"\\x00\")));\n return toHex(mac);\n}\n\n/** Internal helpers exported for the resources / tests. */\nexport const _internal = { b64, b64d, utf8, TEXT_DECODER };\n","/**\n * Minimal RFC 9180 HPKE — base mode, single fixed suite:\n * DHKEM(X25519, HKDF-SHA256) + HKDF-SHA256 + ChaCha20-Poly1305.\n *\n * This is the byte-for-byte port of the Python SDK's `pendra._hpke`, itself the\n * client mirror of the worker's github.com/cloudflare/circl/hpke usage (see\n * packages/worker/internal/privinf). It implements exactly what Pendra Private\n * Inference needs — Setup(Base){S,R}, Seal/Open, and Export — and nothing else.\n * Validated against the RFC 9180 Appendix A.2 known-answer vector (see the\n * __tests__ suite), which guarantees byte-for-byte interop with circl.\n *\n * Depends on @noble/curves, @noble/ciphers, and @noble/hashes.\n */\n\nimport { x25519 } from \"@noble/curves/ed25519.js\";\nimport { chacha20poly1305 } from \"@noble/ciphers/chacha.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { hmac } from \"@noble/hashes/hmac.js\";\nimport { extract, expand } from \"@noble/hashes/hkdf.js\";\nimport { randomBytes as nobleRandomBytes } from \"@noble/hashes/utils.js\";\n\n// Fixed suite identifiers (RFC 9180 §7).\nconst KEM_ID = 0x0020; // DHKEM(X25519, HKDF-SHA256)\nconst KDF_ID = 0x0001; // HKDF-SHA256\nconst AEAD_ID = 0x0003; // ChaCha20Poly1305\n\nconst NH = 32; // HKDF-SHA256 output / exporter secret size\nconst NK = 32; // ChaCha20 key size\nconst NN = 12; // ChaCha20 nonce size\nconst NSECRET = 32; // DHKEM(X25519) shared-secret size\n\nfunction i2osp(n: number, len: number): Uint8Array {\n const out = new Uint8Array(len);\n for (let i = len - 1; i >= 0; i--) {\n out[i] = n & 0xff;\n n = Math.floor(n / 256);\n }\n return out;\n}\n\nconst TEXT_ENCODER = new TextEncoder();\n\nfunction bytes(s: string): Uint8Array {\n return TEXT_ENCODER.encode(s);\n}\n\nfunction concat(...parts: Uint8Array[]): Uint8Array {\n let total = 0;\n for (const p of parts) total += p.length;\n const out = new Uint8Array(total);\n let off = 0;\n for (const p of parts) {\n out.set(p, off);\n off += p.length;\n }\n return out;\n}\n\n// \"HPKE\" ‖ I2OSP(kem,2) ‖ I2OSP(kdf,2) ‖ I2OSP(aead,2)\nconst SUITE_ID = concat(bytes(\"HPKE\"), i2osp(KEM_ID, 2), i2osp(KDF_ID, 2), i2osp(AEAD_ID, 2));\n// \"KEM\" ‖ I2OSP(kem,2)\nconst KEM_SUITE_ID = concat(bytes(\"KEM\"), i2osp(KEM_ID, 2));\nconst HPKE_VERSION = bytes(\"HPKE-v1\");\n\nfunction hkdfExtract(salt: Uint8Array, ikm: Uint8Array): Uint8Array {\n // Mirror Python's _hkdf_extract: an empty salt becomes NH zero bytes.\n const effectiveSalt = salt.length === 0 ? new Uint8Array(NH) : salt;\n return extract(sha256, ikm, effectiveSalt);\n}\n\nfunction hkdfExpand(prk: Uint8Array, info: Uint8Array, length: number): Uint8Array {\n return expand(sha256, prk, info, length);\n}\n\nfunction labeledExtract(salt: Uint8Array, label: Uint8Array, ikm: Uint8Array, suiteId: Uint8Array): Uint8Array {\n return hkdfExtract(salt, concat(HPKE_VERSION, suiteId, label, ikm));\n}\n\nfunction labeledExpand(\n prk: Uint8Array,\n label: Uint8Array,\n info: Uint8Array,\n length: number,\n suiteId: Uint8Array,\n): Uint8Array {\n const labeledInfo = concat(i2osp(length, 2), HPKE_VERSION, suiteId, label, info);\n return hkdfExpand(prk, labeledInfo, length);\n}\n\nfunction extractAndExpand(dh: Uint8Array, kemContext: Uint8Array): Uint8Array {\n const eaePrk = labeledExtract(new Uint8Array(0), bytes(\"eae_prk\"), dh, KEM_SUITE_ID);\n return labeledExpand(eaePrk, bytes(\"shared_secret\"), kemContext, NSECRET, KEM_SUITE_ID);\n}\n\n/** DHKEM Encap → [shared_secret, enc]. `skE` injectable for known-answer tests. */\nfunction encap(pkR: Uint8Array, skE?: Uint8Array): [Uint8Array, Uint8Array] {\n const skEObj = skE ?? x25519.utils.randomSecretKey();\n const enc = x25519.getPublicKey(skEObj);\n const dh = x25519.getSharedSecret(skEObj, pkR);\n const kemContext = concat(enc, pkR);\n return [extractAndExpand(dh, kemContext), enc];\n}\n\n/** DHKEM Decap → shared_secret. */\nfunction decap(enc: Uint8Array, skR: Uint8Array): Uint8Array {\n const dh = x25519.getSharedSecret(skR, enc);\n const pkRm = x25519.getPublicKey(skR);\n const kemContext = concat(enc, pkRm);\n return extractAndExpand(dh, kemContext);\n}\n\n/**\n * An HPKE encryption context (RFC 9180 §5.2): AEAD key + base nonce +\n * monotonic sequence, plus the exporter secret.\n */\nexport class Context {\n readonly key: Uint8Array;\n readonly baseNonce: Uint8Array;\n readonly exporterSecret: Uint8Array;\n private seq = 0;\n\n constructor(key: Uint8Array, baseNonce: Uint8Array, exporterSecret: Uint8Array) {\n this.key = key;\n this.baseNonce = baseNonce;\n this.exporterSecret = exporterSecret;\n }\n\n private computeNonce(): Uint8Array {\n const seqBytes = i2osp(this.seq, NN);\n const nonce = new Uint8Array(NN);\n for (let i = 0; i < NN; i++) {\n nonce[i] = this.baseNonce[i] ^ seqBytes[i];\n }\n return nonce;\n }\n\n seal(aad: Uint8Array, pt: Uint8Array): Uint8Array {\n const ct = chacha20poly1305(this.key, this.computeNonce(), aad).encrypt(pt);\n this.seq += 1;\n return ct;\n }\n\n open(aad: Uint8Array, ct: Uint8Array): Uint8Array {\n const pt = chacha20poly1305(this.key, this.computeNonce(), aad).decrypt(ct);\n this.seq += 1;\n return pt;\n }\n\n export(exporterContext: Uint8Array, length: number): Uint8Array {\n return labeledExpand(this.exporterSecret, bytes(\"sec\"), exporterContext, length, SUITE_ID);\n }\n}\n\nfunction keySchedule(sharedSecret: Uint8Array, info: Uint8Array): Context {\n // Base mode (mode_id = 0x00), empty PSK / PSK id.\n const empty = new Uint8Array(0);\n const pskIdHash = labeledExtract(empty, bytes(\"psk_id_hash\"), empty, SUITE_ID);\n const infoHash = labeledExtract(empty, bytes(\"info_hash\"), info, SUITE_ID);\n const keyScheduleContext = concat(new Uint8Array([0x00]), pskIdHash, infoHash);\n const secret = labeledExtract(sharedSecret, bytes(\"secret\"), empty, SUITE_ID);\n const key = labeledExpand(secret, bytes(\"key\"), keyScheduleContext, NK, SUITE_ID);\n const baseNonce = labeledExpand(secret, bytes(\"base_nonce\"), keyScheduleContext, NN, SUITE_ID);\n const exporterSecret = labeledExpand(secret, bytes(\"exp\"), keyScheduleContext, NH, SUITE_ID);\n return new Context(key, baseNonce, exporterSecret);\n}\n\n/**\n * Sender setup (RFC 9180 §5.1.1). Returns { enc, ctx }. `skE` is only for\n * deterministic tests; production callers omit it for a random ephemeral key.\n */\nexport function setupBaseS(pkR: Uint8Array, info: Uint8Array, skE?: Uint8Array): { enc: Uint8Array; ctx: Context } {\n const [sharedSecret, enc] = encap(pkR, skE);\n return { enc, ctx: keySchedule(sharedSecret, info) };\n}\n\n/** Receiver setup (RFC 9180 §5.1.1). */\nexport function setupBaseR(skR: Uint8Array, enc: Uint8Array, info: Uint8Array): Context {\n const sharedSecret = decap(enc, skR);\n return keySchedule(sharedSecret, info);\n}\n\n/** Return { priv, pub } — raw 32-byte X25519 keypair. */\nexport function generateX25519Keypair(): { priv: Uint8Array; pub: Uint8Array } {\n const priv = x25519.utils.randomSecretKey();\n return { priv, pub: x25519.getPublicKey(priv) };\n}\n\nexport function x25519PublicFromPrivate(sk: Uint8Array): Uint8Array {\n return x25519.getPublicKey(sk);\n}\n\nexport function randomBytes(n: number): Uint8Array {\n return nobleRandomBytes(n);\n}\n\n/** Lowercase hex SHA-256 of the given bytes (fingerprint / TOFU identity). */\nexport function sha256Hex(data: Uint8Array): string {\n return Array.from(sha256(data))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nexport { hmac, sha256 };\n","/**\n * Turning API responses into SDK types — and failures into SDK errors.\n *\n * Both parsers live here rather than beside either consumer so the plaintext\n * and private-inference paths cannot drift apart in what they throw. They used\n * to: a stream frame that wasn't a chunk was either skipped (malformed JSON) or\n * yielded *as if it were a chunk* (an in-band `{\"error\": …}` report), and a\n * non-streaming body was cast to `ChatCompletion` without being looked at.\n *\n * Mirrors `packages/sdk-python/pendra/_parsing.py` (issues #2252, #2253).\n */\n\nimport { APIResponseValidationError, APIStreamError } from \"./errors\";\nimport { unsealedReplyError, type ResponseInner } from \"./_privateInference\";\nimport type { ChatCompletion, ChatCompletionChunk } from \"./types/chat\";\n\ninterface InBandError {\n message?: unknown;\n type?: unknown;\n code?: unknown;\n request_id?: unknown;\n worker_id?: unknown;\n worker_name?: unknown;\n}\n\nfunction asString(v: unknown): string | undefined {\n return typeof v === \"string\" ? v : undefined;\n}\n\n/**\n * Throw if `parsed` is the API reporting a failure in-band rather than a chunk.\n *\n * A streaming response commits HTTP 200 before inference starts, so a worker\n * crash, a timeout or an at-capacity rejection arrives as\n * `data: {\"error\": {…}}` and then `data: [DONE]`. `JSON.parse` succeeds on\n * that, so without this check the frame was yielded as a `ChatCompletionChunk`\n * and the caller blew up on `chunk.choices[0]` — or, with `[DONE]` right\n * behind it, simply saw the reply stop.\n */\nexport function throwIfInBandError(\n parsed: unknown,\n fallback = \"The server reported an error mid-stream\",\n): void {\n if (typeof parsed !== \"object\" || parsed === null) return;\n const err = (parsed as { error?: unknown }).error;\n if (typeof err !== \"object\" || err === null || Array.isArray(err)) return;\n const e = err as InBandError;\n throw new APIStreamError(\n asString(e.message) ?? fallback,\n {\n type: asString(e.type),\n code: typeof e.code === \"number\" ? e.code : undefined,\n requestId: asString(e.request_id),\n workerId: asString(e.worker_id),\n workerName: asString(e.worker_name),\n },\n );\n}\n\n/**\n * A chunk must carry `id`, `model` and a `choices` array.\n *\n * The API sets all three on every frame it emits, including the synthesised\n * timing, usage and notice chunks — those use `\"\"` and `[]` rather than\n * omitting the fields — so requiring them cannot reject a real chunk. The\n * Python SDK has required `id` and `model` in production for many versions,\n * which is live proof the API never omits them.\n *\n * `choices` is the one callers actually index, so checking it here is what\n * turns a would-be `TypeError` on `chunk.choices[0]` — thrown from inside the\n * caller's own loop, naming nothing useful — into an error that quotes the\n * offending frame.\n */\nfunction isChunkShaped(parsed: unknown): parsed is ChatCompletionChunk {\n if (typeof parsed !== \"object\" || parsed === null) return false;\n const c = parsed as Record<string, unknown>;\n return typeof c.id === \"string\" && typeof c.model === \"string\" && Array.isArray(c.choices);\n}\n\n/**\n * Turn one SSE `data:` payload into a chunk, or throw.\n *\n * `label` distinguishes a plaintext frame from one a private-inference stream\n * decrypted to, so the error says which stage produced the bad payload.\n */\nexport function parseStreamFrame(\n data: string,\n label: \"Stream frame\" | \"Decrypted stream frame\" = \"Stream frame\",\n): ChatCompletionChunk {\n let parsed: unknown;\n try {\n parsed = JSON.parse(data);\n } catch {\n throw new APIResponseValidationError(`${label} was not valid JSON`, { body: data });\n }\n throwIfInBandError(parsed);\n if (!isChunkShaped(parsed)) {\n throw new APIResponseValidationError(`${label} was not a chat completion chunk`, {\n body: data,\n });\n }\n return parsed;\n}\n\nfunction completionFrom(parsed: unknown, body: string, status?: number): ChatCompletion {\n if (typeof parsed !== \"object\" || parsed === null) {\n throw new APIResponseValidationError(\"Response was not a chat completion\", { status, body });\n }\n const c = parsed as Record<string, unknown>;\n if (typeof c.id !== \"string\" || typeof c.model !== \"string\" || !Array.isArray(c.choices)) {\n throw new APIResponseValidationError(\"Response was not a chat completion\", { status, body });\n }\n return parsed as ChatCompletion;\n}\n\n/**\n * Read a non-streaming completion body, or throw `APIResponseValidationError`.\n *\n * Reads the body as text first so the raw response is available for the error\n * excerpt — `response.json()` consumes the body, leaving nothing to quote when\n * it throws a bare `SyntaxError` (e.g. an HTML error page from a proxy).\n */\nexport async function parseCompletion(response: Response): Promise<ChatCompletion> {\n const body = await response.text();\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n throw new APIResponseValidationError(\"Response was not valid JSON\", {\n status: response.status,\n body,\n });\n }\n // A late failure on a slow reply, reported in-band (see readJsonReply).\n throwIfInBandError(parsed, \"The server reported an error\");\n return completionFrom(parsed, body, response.status);\n}\n\n/**\n * Read a non-streaming JSON reply, throwing the API's in-band error if it is one.\n *\n * A request that runs past the API's keep-alive threshold has its 200\n * committed before the worker finishes, so a late failure (worker error,\n * timeout, capacity) arrives as a 200 `{\"error\": {…}}` body. Resources used to\n * cast that straight to their response type and hand the caller the error\n * object as if it were a result (issue #2582). A body that isn't JSON still\n * throws the `SyntaxError` `response.json()` always did.\n */\nexport async function readJsonReply(response: Response): Promise<unknown> {\n const parsed: unknown = await response.json();\n throwIfInBandError(parsed, \"The server reported an error\");\n return parsed;\n}\n\n/** Parse the plaintext a private-inference reply decrypted to, or throw. */\nexport function parseDecryptedCompletion(json: string, status?: number): ChatCompletion {\n let parsed: unknown;\n try {\n parsed = JSON.parse(json);\n } catch {\n throw new APIResponseValidationError(\"Decrypted response was not valid JSON\", {\n status,\n body: json,\n });\n }\n try {\n return completionFrom(parsed, json, status);\n } catch {\n throw new APIResponseValidationError(\"Decrypted response was not a chat completion\", {\n status,\n body: json,\n });\n }\n}\n\n/**\n * Read a private-inference reply and return its sealed envelope, or throw —\n * along with the unsealed `pendra` block the API sets beside the envelope to\n * say which worker served the request (see `withPlacement`).\n *\n * A request that runs past the API's keep-alive threshold has its 200\n * committed before the worker finishes, so a late failure (worker error,\n * timeout, capacity) arrives as a 200 `{\"error\": {…}}` body. That is reported\n * as the API error it is rather than as a forgery: an unauthenticated error\n * carries no content, so at worst a forged one fails a request that could be\n * dropped in transit anyway. Anything else without an envelope is refused.\n */\nexport async function readSealedReply(\n response: Response,\n): Promise<{ inner: ResponseInner; placement: unknown }> {\n const body = await response.text();\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n throw new APIResponseValidationError(\"Response was not valid JSON\", {\n status: response.status,\n body,\n });\n }\n throwIfInBandError(parsed, \"The server reported an error\");\n const wrapper =\n typeof parsed === \"object\" && parsed !== null\n ? (parsed as { pendra_encrypted?: ResponseInner; pendra?: unknown })\n : undefined;\n const inner = wrapper?.pendra_encrypted;\n if (!inner) throw unsealedReplyError();\n return { inner, placement: wrapper.pendra };\n}\n\n/** Parse the JSON a private-inference reply decrypted to, or throw. */\nexport function parseDecryptedJson(json: string, status?: number): unknown {\n try {\n return JSON.parse(json);\n } catch {\n throw new APIResponseValidationError(\"Decrypted response was not valid JSON\", {\n status,\n body: json,\n });\n }\n}\n","/**\n * Which worker served a request (\"placement\"), read off an API response.\n *\n * The API reports it two ways. Every JSON body carries it in the `pendra`\n * extension block — `{\"worker\": {\"id\", \"name\"}, \"request_id\"}` — and a\n * non-streaming reply also sends the `X-Worker-Id` / `X-Worker-Name` /\n * `X-Request-Id` headers. The body is the one to trust: a request slower than\n * the API's keep-alive threshold commits its headers before any worker is\n * known, so they are missing exactly when a caller is most likely to want\n * them. The headers are only a fallback for an API older than this SDK.\n *\n * A stream reports it on its trailer chunk instead (see `Stream`), since its\n * headers go out before the request is dispatched.\n *\n * @internal\n */\n\nimport type { PendraExtension, PendraWorker } from \"./types/chat\";\n\ninterface Placement {\n worker: PendraWorker;\n request_id?: string;\n}\n\nconst UTF8_EXT_PREFIX = \"utf-8''\";\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/** A `{id, name}` worker, or `undefined` when `v` isn't one. */\nexport function parseWorker(v: unknown): PendraWorker | undefined {\n if (!isPlainObject(v) || typeof v.id !== \"string\" || !v.id) return undefined;\n return {\n id: v.id,\n name: typeof v.name === \"string\" && v.name ? v.name : null,\n version: typeof v.version === \"string\" && v.version ? v.version : null,\n };\n}\n\nfunction placementFromBlock(block: unknown): Placement | undefined {\n if (!isPlainObject(block)) return undefined;\n const worker = parseWorker(block.worker);\n if (!worker) return undefined;\n const requestId = block.request_id;\n return typeof requestId === \"string\" && requestId\n ? { worker, request_id: requestId }\n : { worker };\n}\n\n/**\n * Decode `X-Worker-Name`: plain ASCII, or RFC 8187 `UTF-8''<percent-encoded>`\n * for a name that isn't. A malformed encoding is kept as sent rather than lost.\n */\nexport function decodeWorkerNameHeader(raw: string): string {\n if (raw.slice(0, UTF8_EXT_PREFIX.length).toLowerCase() !== UTF8_EXT_PREFIX) return raw;\n try {\n return decodeURIComponent(raw.slice(UTF8_EXT_PREFIX.length));\n } catch {\n return raw;\n }\n}\n\nfunction header(headers: Headers | undefined, name: string): string | undefined {\n // Tolerate a response without real Headers (a hand-built mock, a fetch shim).\n if (!headers || typeof headers.get !== \"function\") return undefined;\n return headers.get(name) || undefined;\n}\n\n/**\n * Placement from the response headers. Needs `X-Worker-Id`: the API stamps an\n * `X-Request-Id` on every response, served by a worker or not, so on its own\n * it names no worker.\n */\nfunction placementFromHeaders(headers: Headers | undefined): Placement | undefined {\n const id = header(headers, \"X-Worker-Id\");\n if (!id) return undefined;\n const rawName = header(headers, \"X-Worker-Name\");\n const requestId = header(headers, \"X-Request-Id\");\n // There is no version header: the body block is the only place it rides.\n const worker: PendraWorker = {\n id,\n name: rawName ? decodeWorkerNameHeader(rawName) : null,\n version: null,\n };\n return requestId ? { worker, request_id: requestId } : { worker };\n}\n\n/**\n * Drop a malformed `worker` / `request_id` from a `pendra` block in place, so\n * the typed fields never hold something other than what they declare.\n */\nfunction sanitise(block: Record<string, unknown>): void {\n if (\"worker\" in block && block.worker !== null) {\n const worker = parseWorker(block.worker);\n if (worker) block.worker = worker;\n else delete block.worker;\n }\n if (\"request_id\" in block && block.request_id !== null && typeof block.request_id !== \"string\") {\n delete block.request_id;\n }\n}\n\n/**\n * Set `result.pendra.worker` / `.request_id` from the first of `blocks` that\n * names a worker, else from the response headers. Everything else already in\n * `result.pendra` (a notice, web-tool steps) is kept, and `result` is returned\n * for chaining. Non-objects pass through untouched.\n *\n * Only the placement keys are ever taken from `blocks`. On a private-inference\n * reply one of them is the unsealed sibling of the envelope, which anyone on\n * the path could have written, so it must not be able to add a notice or\n * web-tool steps to the sealed reply — only say which worker served it, which\n * the headers could claim just as well.\n */\nexport function withPlacement<T>(result: T, headers: Headers | undefined, ...blocks: unknown[]): T {\n if (!isPlainObject(result)) return result;\n const own = isPlainObject(result.pendra) ? result.pendra : undefined;\n if (own) sanitise(own);\n\n let placement: Placement | undefined;\n for (const block of blocks) {\n placement = placementFromBlock(block);\n if (placement) break;\n }\n placement ??= placementFromHeaders(headers);\n if (!placement) return result;\n\n const merged: Record<string, unknown> = { ...(own ?? {}), worker: placement.worker };\n if (placement.request_id) merged.request_id = placement.request_id;\n else delete merged.request_id;\n (result as Record<string, unknown>).pendra = merged;\n return result;\n}\n\n/**\n * The placement a stream chunk carries, if any, after dropping a malformed\n * `worker` / `request_id` from it in place.\n */\nexport function chunkPlacement(\n chunk: { pendra?: PendraExtension | null },\n): { worker?: PendraWorker; requestId?: string } {\n const block: unknown = chunk.pendra;\n if (!isPlainObject(block)) return {};\n sanitise(block);\n const worker = block.worker as PendraWorker | null | undefined;\n const requestId = block.request_id as string | null | undefined;\n return { worker: worker ?? undefined, requestId: requestId || undefined };\n}\n\n/** Request header asking for placement on a private-inference stream's trailer. */\nexport const PLACEMENT_OPT_IN_HEADER = \"X-Pendra-Placement\";\n","/**\n * Private Inference engine: resolves and caches the org workload public key\n * (TOFU by default, or an explicit pinned fingerprint), then seals requests to\n * it. Byte-for-byte port of the Python SDK's `_private_inference_engine`.\n *\n * Deliberately HTTP-agnostic — the calling resource performs the key-fetch GET\n * and hands the returned keys to `resolveOrgKey`, so all the trust logic lives\n * here in one place and is unit-testable without a network. TOFU file I/O uses a\n * dynamic `import(\"node:fs\")` so browser bundles (which require a pinned\n * fingerprint) never need it.\n */\n\nimport * as hpke from \"./_hpke\";\nimport * as pi from \"./_privateInference\";\n\nexport class PrivateInferenceError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PrivateInferenceError\";\n }\n}\n\nconst FINGERPRINT_RE = /^[0-9a-f]{64}$/;\n\n/**\n * Parse a pin (one fingerprint or a comma-separated allowlist) into a set.\n * Fails closed: a pin that names no fingerprint (`\",\"`, a blank string) or holds\n * anything other than 64-hex-char fingerprints throws, instead of silently\n * leaving the client unpinned or pinned to a value that can never match.\n */\nexport function parsePinnedFingerprints(pin: unknown): Set<string> {\n if (typeof pin !== \"string\") {\n throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);\n }\n const fps = pin\n .split(\",\")\n .map((f) => f.trim().toLowerCase())\n .filter((f) => f.length > 0);\n if (fps.length === 0) {\n throw new PrivateInferenceError(\n \"pinnedFingerprint was set but contains no fingerprint. Pass the 64-character \" +\n \"fingerprint shown in the console, or leave it unset to use automatic trust.\",\n );\n }\n const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();\n if (bad.length > 0) {\n throw new PrivateInferenceError(\n `pinnedFingerprint \"${bad[0]}\" is not a valid fingerprint: expected 64 ` +\n \"hexadecimal characters, as shown in the console.\",\n );\n }\n return new Set(fps);\n}\n\nexport interface FetchedKey {\n public_key: string;\n fingerprint?: string;\n}\n\nfunction defaultTofuPath(): string {\n const env = typeof process !== \"undefined\" ? process.env : undefined;\n if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;\n const home = env?.HOME || env?.USERPROFILE || \".\";\n // Join with \"/\" — path.join would require importing node:path eagerly.\n return `${home.replace(/\\/$/, \"\")}/.pendra/known_org_keys.json`;\n}\n\nfunction b64d(s: string): Uint8Array {\n if (typeof Buffer !== \"undefined\") return new Uint8Array(Buffer.from(s, \"base64\"));\n // eslint-disable-next-line no-undef\n const binary = atob(s);\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);\n return out;\n}\n\nexport interface EngineOptions {\n baseUrl: string;\n apiKey: string;\n pinnedFingerprint?: string | null;\n affinitySalt?: Uint8Array | null;\n tofuPath?: string | null;\n}\n\nexport class PrivateInferenceEngine {\n private baseUrl: string;\n private apiKey: string;\n // A pin is an allowlist: accept one fingerprint or a comma-separated set.\n // The client seals only to fetched keys whose fingerprint is pinned.\n private pinnedFingerprints: Set<string> | null;\n private affinitySalt: Uint8Array | null;\n private tofuPath: string;\n private orgPubs: Uint8Array[] | null = null;\n\n constructor(opts: EngineOptions) {\n this.baseUrl = opts.baseUrl.replace(/\\/$/, \"\");\n this.apiKey = opts.apiKey;\n // null / undefined mean \"not pinned\"; anything else (even \"\") must parse\n // to a valid, non-empty set (a pin must never silently turn itself off).\n const pin = opts.pinnedFingerprint;\n this.pinnedFingerprints = pin === null || pin === undefined ? null : parsePinnedFingerprints(pin);\n this.affinitySalt = opts.affinitySalt ?? null;\n this.tofuPath = opts.tofuPath || defaultTofuPath();\n }\n\n // --- key resolution ---\n\n cachedOrgPublicKeys(): Uint8Array[] | null {\n return this.orgPubs;\n }\n\n cachedOrgPublicKey(): Uint8Array | null {\n // Back-compat scalar accessor — the first resolved key, or null.\n return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;\n }\n\n private tofuIdentity(): string {\n // Key the TOFU record by (base_url, api-key hash). We never store the raw\n // key; the hash just distinguishes orgs sharing a base URL.\n const digest = hpke.sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);\n return `${this.baseUrl}|${digest}`;\n }\n\n /**\n * Drop the cached key set so the next call re-fetches it.\n *\n * The cache is otherwise held for the whole process lifetime, which is\n * correct while a fleet keeps one key but fatal when it re-keys: a\n * long-running server would go on sealing to a fingerprint no worker holds\n * and fail EVERY request until someone restarted it. The API signals a re-key\n * with `X-Pendra-Error-Code: no_private_inference_worker`, and this is what\n * lets the client recover on its own.\n *\n * Pinned clients are deliberately NOT re-fetched on that signal — a pin is an\n * allowlist, so a fetch could only return fingerprints the pin already\n * rejects. They surface the error instead, which is what pinning means.\n */\n invalidateOrgKey(): void {\n this.orgPubs = null;\n }\n\n /** Whether this client seals only to an explicit fingerprint allowlist. */\n get isPinned(): boolean {\n return this.pinnedFingerprints !== null;\n }\n\n /**\n * Validate the key(s) returned by GET /v1/private-inference/key, apply the pin\n * allowlist (or auto-trust TOFU), cache the accepted public keys, and return\n * them (newest-seen first). The client seals to **all** of the returned keys\n * so any worker holding any of them can serve the request. Throws\n * PrivateInferenceError on absence, a malformed key, or (when pinned) an empty\n * intersection with the pin set.\n */\n async resolveOrgKey(fetchedKeys: FetchedKey[]): Promise<Uint8Array[]> {\n if (this.orgPubs !== null) return this.orgPubs;\n if (!fetchedKeys || fetchedKeys.length === 0) {\n throw new PrivateInferenceError(\n \"No encryption key is registered for this organisation. Start a worker \" +\n \"and it will be issued one automatically.\",\n );\n }\n // Validate EVERY key before any trust write: recompute each fingerprint from\n // its bytes (never trust the server's claimed value), and reject a\n // wrong-length key up front so a bad key can't be persisted to TOFU and only\n // fail later inside HPKE.\n const pubs: Uint8Array[] = [];\n const fps: string[] = [];\n for (const entry of fetchedKeys) {\n let pub: Uint8Array;\n try {\n pub = b64d(entry.public_key);\n } catch (e) {\n throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);\n }\n if (pub.length !== 32) {\n throw new PrivateInferenceError(\n `Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`,\n );\n }\n pubs.push(pub);\n fps.push(pi.fingerprint(pub));\n }\n\n let accepted: Uint8Array[];\n if (this.pinnedFingerprints !== null) {\n // Pin = allowlist. Seal only to fetched keys whose fingerprint is pinned;\n // error if none of them are (nothing we're allowed to use).\n accepted = pubs.filter((_p, i) => this.pinnedFingerprints!.has(fps[i]));\n if (accepted.length === 0) {\n const pinned = Array.from(this.pinnedFingerprints).sort().join(\", \");\n throw new PrivateInferenceError(\n `None of the org's workload key fingerprints (${fps.join(\", \")}) match your ` +\n `pinned fingerprint(s) (${pinned}). Refusing to seal (possible man-in-the-middle). ` +\n \"If your fleet re-keyed — which happens when every worker goes offline at \" +\n \"once — update the pin to a current fingerprint from the console.\",\n );\n }\n } else {\n // TOFU, auto-add: trust every fingerprint the server returns, adding any\n // new ones to the store. New worker keys \"just work\"; the pin is the\n // opt-in strict path for callers who want an allowlist instead.\n await this.tofuTrust(fps);\n accepted = pubs;\n }\n\n this.orgPubs = accepted;\n return accepted;\n }\n\n private async tofuTrust(fps: string[]): Promise<void> {\n // Record every fingerprint as trusted for this identity (auto-add). No\n // rejection — a caller who wants to gate on an allowlist uses a pin.\n const store = await this.loadTofu();\n const identity = this.tofuIdentity();\n const known = store[identity];\n // Backward-compat: earlier versions stored a single fingerprint string.\n const trusted = new Set<string>();\n if (typeof known === \"string\") {\n trusted.add(known);\n } else if (Array.isArray(known)) {\n for (const f of known) if (typeof f === \"string\") trusted.add(f);\n }\n const before = trusted.size;\n for (const f of fps) trusted.add(f);\n if (trusted.size !== before || !Array.isArray(known)) {\n store[identity] = Array.from(trusted).sort();\n await this.saveTofu(store);\n }\n }\n\n private async loadTofu(): Promise<Record<string, string | string[]>> {\n try {\n const fs = await import(\"node:fs\");\n const raw = fs.readFileSync(this.tofuPath, \"utf-8\");\n const data = JSON.parse(raw);\n return data && typeof data === \"object\" && !Array.isArray(data)\n ? (data as Record<string, string | string[]>)\n : {};\n } catch {\n return {};\n }\n }\n\n private async saveTofu(store: Record<string, string | string[]>): Promise<void> {\n const fs = await import(\"node:fs\");\n const path = await import(\"node:path\");\n const directory = path.dirname(this.tofuPath) || \".\";\n fs.mkdirSync(directory, { recursive: true });\n // Write-then-rename so a crash can't leave a truncated store; 0600 since it\n // records the fingerprints a client trusts.\n const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);\n try {\n fs.writeFileSync(tmp, JSON.stringify(store), { mode: 0o600 });\n // writeFileSync's `mode` only applies when it creates the file; enforce it\n // explicitly so the final store is always 0600 regardless of prior state.\n try {\n fs.chmodSync(tmp, 0o600);\n } catch {\n /* best effort — some platforms (Windows) don't honour POSIX modes */\n }\n fs.renameSync(tmp, this.tofuPath);\n } catch (e) {\n try {\n fs.unlinkSync(tmp);\n } catch {\n /* ignore */\n }\n throw e;\n }\n }\n\n // --- sealing ---\n\n /**\n * Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.\n * `messages` (chat only) drives the affinity token; pass undefined for non-chat.\n * `binary` (audio only) is sealed under the same data key as the body.\n */\n seal(args: {\n model: string;\n stream: boolean;\n taskType: string;\n body: Uint8Array;\n messages?: pi.AffinityMessage[] | null;\n binary?: Uint8Array | null;\n }): { topLevel: Record<string, unknown>; decryptor: pi.ResponseDecryptor } {\n if (this.orgPubs === null || this.orgPubs.length === 0) {\n throw new PrivateInferenceError(\n \"private inference: org key not resolved yet (call resolveOrgKey first)\",\n );\n }\n let affinity: string | null = null;\n if (args.messages != null) {\n affinity = pi.affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);\n }\n const { envelope, responseKeys } = pi.sealRequest(this.orgPubs, args.body, {\n model: args.model,\n stream: args.stream,\n taskType: args.taskType,\n affinityKey: affinity,\n binary: args.binary ?? null,\n });\n const topLevel: Record<string, unknown> = {\n model: args.model,\n stream: args.stream,\n pendra_encrypted: envelope,\n };\n return { topLevel, decryptor: new pi.ResponseDecryptor(responseKeys) };\n }\n\n get keyFetchUrl(): string {\n return `${this.baseUrl}/v1/private-inference/key`;\n }\n}\n","import type { Pendra } from \"../../client\";\nimport { APIResponseValidationError } from \"../../errors\";\nimport type { SpeechCreateParams, SpeechResponse } from \"../../types/audio\";\nimport type { PendraExtension } from \"../../types/chat\";\nimport { throwIfInBandError } from \"../../_parsing\";\nimport { withPlacement } from \"../../_placement\";\nimport { _internal } from \"../../_privateInference\";\nimport { PrivateInferenceError } from \"../../_privateInferenceEngine\";\n\n// Standard-alphabet base64, padding optional. Checked before decoding because\n// both `Buffer.from(s, \"base64\")` and some `atob` shims skip characters they\n// don't recognise, which would turn a corrupt body into a truncated WAV rather\n// than an error.\nconst BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;\n\nfunction decodeAudio(value: unknown): Uint8Array | undefined {\n if (typeof value !== \"string\") return undefined;\n const s = value.replace(/\\s+/g, \"\");\n if (!s || !BASE64_RE.test(s) || s.replace(/=+$/, \"\").length % 4 === 1) return undefined;\n if (s.includes(\"=\") && s.length % 4 !== 0) return undefined;\n let bytes: Uint8Array;\n try {\n bytes = _internal.b64d(s);\n } catch {\n return undefined;\n }\n return bytes.length > 0 ? bytes : undefined;\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nexport class Speech {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n /**\n * Turn text into spoken audio (OpenAI-compatible).\n *\n * @example\n * ```ts\n * import { writeFileSync } from \"node:fs\";\n *\n * const speech = await client.audio.speech.create({\n * model: \"qwen3-tts\",\n * input: \"Hello from Pendra.\",\n * });\n * writeFileSync(\"speech.wav\", speech.audio);\n * ```\n */\n async create(params: SpeechCreateParams): Promise<SpeechResponse> {\n if (!params.model || typeof params.model !== \"string\") {\n throw new Error(\"model must be a non-empty string\");\n }\n if (typeof params.input !== \"string\" || !params.input.trim()) {\n throw new Error(\"input must be a non-empty string\");\n }\n\n // Refuse rather than send the text in plaintext: a caller who turned\n // private inference on expects nothing to leave the machine unencrypted.\n if (this.client.privateInferenceEnabled) {\n throw new PrivateInferenceError(\"Private inference does not support speech synthesis yet.\");\n }\n\n const body: Record<string, unknown> = { model: params.model, input: params.input };\n if (params.voice != null) body.voice = params.voice;\n if (params.response_format != null) body.response_format = params.response_format;\n\n // Asking for JSON lets the API keep a long generation alive through the\n // edge proxy, and puts the placement in the body where it always arrives.\n const headers: Record<string, string> = { Accept: \"application/json\" };\n if (params.worker_id) headers[\"X-Pendra-Worker-Id\"] = params.worker_id;\n\n // Generation time grows with the length of the input, so give it the same\n // floor as transcription; a larger client `timeout` still wins.\n const timeout = Math.max(this.client.timeout ?? 0, 300_000);\n\n const { response } = await this.client._fetch(\"/api/v1/audio/speech\", {\n method: \"POST\",\n body,\n headers,\n timeout,\n });\n\n const text = await response.text();\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new APIResponseValidationError(\"Response was not valid JSON\", {\n status: response.status,\n body: text,\n });\n }\n // A request slower than the API's keep-alive threshold has its 200\n // committed before the worker finishes, so a late failure arrives in-band.\n throwIfInBandError(parsed, \"The server reported an error\");\n if (!isRecord(parsed)) {\n throw new APIResponseValidationError(\"Response was not a speech result\", {\n status: response.status,\n body: text,\n });\n }\n\n const audio = decodeAudio(parsed.audio);\n if (!audio) {\n throw new APIResponseValidationError(\"Response did not contain decodable audio\", {\n status: response.status,\n body: text,\n });\n }\n\n const result: SpeechResponse = {\n audio,\n format:\n typeof parsed.format === \"string\" && parsed.format\n ? parsed.format\n : (params.response_format ?? \"wav\"),\n duration_ms:\n typeof parsed.duration_ms === \"number\" && Number.isFinite(parsed.duration_ms)\n ? parsed.duration_ms\n : null,\n arrayBuffer: async () => audio.slice().buffer as ArrayBuffer,\n };\n if (isRecord(parsed.pendra)) result.pendra = parsed.pendra as PendraExtension;\n return withPlacement(result, response.headers, result.pendra);\n }\n}\n","import type { Pendra } from \"../../client\";\nimport {\n APIConnectionError,\n APIResponseValidationError,\n readErrorBody,\n statusErrorFromBody,\n} from \"../../errors\";\nimport type { AudioFileInput, TranscriptionCreateParams, TranscriptionResponse } from \"../../types/audio\";\nimport { parseDecryptedJson, readJsonReply, readSealedReply } from \"../../_parsing\";\nimport { withPlacement } from \"../../_placement\";\n\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\n\n// Mirrors the API's hard cap (25MB). It also bounds the encrypted path, where\n// sealing base64-inflates the audio by ~4/3 inside a JSON body.\nconst MAX_FILE_SIZE = 25 * 1024 * 1024;\n\n// Map common audio MIME types to file extensions so multipart uploads\n// without an explicit filename still carry an extension the API can use\n// for format detection.\nconst MIME_EXT: Record<string, string> = {\n \"audio/mpeg\": \"mp3\",\n \"audio/mp3\": \"mp3\",\n \"audio/mp4\": \"m4a\",\n \"audio/x-m4a\": \"m4a\",\n \"audio/wav\": \"wav\",\n \"audio/wave\": \"wav\",\n \"audio/x-wav\": \"wav\",\n \"audio/webm\": \"webm\",\n \"audio/ogg\": \"ogg\",\n \"audio/flac\": \"flac\",\n \"audio/x-flac\": \"flac\",\n};\n\nfunction extFromMime(type: string | undefined): string | undefined {\n if (!type) return undefined;\n // Strip codec parameters (e.g. `audio/webm;codecs=opus`).\n const base = type.split(\";\")[0].trim().toLowerCase();\n return MIME_EXT[base];\n}\n\n// Name the container from the file's own header: the three the API accepts\n// (WAV, FLAC, and MP3 by its ID3 tag or first frame). Anything else has no\n// extension we can honestly give it.\nasync function extFromHeader(blob: Blob): Promise<string | undefined> {\n const head = new Uint8Array(await blob.slice(0, 12).arrayBuffer());\n const ascii = (from: number, to: number) => String.fromCharCode(...head.subarray(from, to));\n if (head.length >= 12 && ascii(0, 4) === \"RIFF\" && ascii(8, 12) === \"WAVE\") return \"wav\";\n if (head.length >= 4 && ascii(0, 4) === \"fLaC\") return \"flac\";\n if (head.length >= 3 && ascii(0, 3) === \"ID3\") return \"mp3\";\n if (head.length >= 2 && head[0] === 0xff && (head[1] & 0xe0) === 0xe0) return \"mp3\";\n return undefined;\n}\n\nasync function asBlob(file: AudioFileInput): Promise<{ blob: Blob; filename: string }> {\n if (file instanceof Blob) {\n // Browser `File` extends Blob and carries a .name. For plain Blobs\n // we derive an extension from blob.type, or failing that from the\n // file's header, so the multipart upload still carries enough info\n // for server-side format detection. A blob that is neither typed nor\n // recognisable is sent without an extension rather than called an MP3:\n // the API then answers with a clear \"unsupported format\" error.\n const asFile = file as File;\n if (asFile.name) {\n return { blob: file, filename: asFile.name };\n }\n const ext = extFromMime(file.type) ?? (await extFromHeader(file));\n return { blob: file, filename: ext ? `audio.${ext}` : \"audio\" };\n }\n const { filename, content } = file;\n if (content instanceof Blob) {\n return { blob: content, filename };\n }\n // ArrayBuffer and Uint8Array both satisfy BlobPart at runtime; the\n // explicit cast keeps strict TS dts builds happy where Uint8Array's\n // generic ArrayBufferLike parameter doesn't unify cleanly with the\n // BlobPart union.\n return { blob: new Blob([content as BlobPart]), filename };\n}\n\nexport class Transcriptions {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n async create(params: TranscriptionCreateParams): Promise<TranscriptionResponse> {\n if (!params.model) {\n throw new Error(\"model is required\");\n }\n\n // The API rejects an out-of-range beam on a plaintext upload, but can't see\n // one inside a sealed body, so check here to reject both paths alike.\n if (\n params.beam_size != null &&\n !(Number.isInteger(params.beam_size) && params.beam_size >= 1 && params.beam_size <= 8)\n ) {\n throw new Error(`beam_size must be an integer between 1 and 8 (got ${params.beam_size})`);\n }\n\n const { blob, filename } = await asBlob(params.file);\n if (blob.size === 0) {\n throw new Error(\"audio file is empty\");\n }\n if (blob.size > MAX_FILE_SIZE) {\n throw new Error(`audio file exceeds ${MAX_FILE_SIZE / (1024 * 1024)}MB limit`);\n }\n\n // Audio uploads need a higher floor than the default client timeout\n // (long files routinely take >2 min server-side), but callers who\n // explicitly pass a larger `timeout` to the client should still win.\n const timeout = Math.max(this.client.timeout ?? 0, 300_000);\n\n if (this.client.privateInferenceEnabled) {\n return this.createEncrypted(params, blob, timeout);\n }\n\n const form = new FormData();\n form.append(\"file\", blob, filename);\n form.append(\"model\", params.model);\n if (params.language) form.append(\"language\", params.language);\n if (params.prompt) form.append(\"prompt\", params.prompt);\n if (params.response_format) form.append(\"response_format\", params.response_format);\n if (params.temperature != null) form.append(\"temperature\", String(params.temperature));\n if (params.beam_size != null) form.append(\"beam_size\", String(params.beam_size));\n if (params.timestamp_granularities) {\n // FastAPI's Form(list[str]) expects repeated `field[]=value` per the\n // OpenAI convention. Each granularity is appended as its own entry.\n for (const g of params.timestamp_granularities) {\n form.append(\"timestamp_granularities[]\", g);\n }\n }\n\n // Bypass client._fetch (which JSON-stringifies) and hit fetch() directly\n // — the multipart boundary needs to live on Content-Type, which fetch\n // sets automatically when given a FormData body. Manually setting any\n // Content-Type header here would clobber that.\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n let response: Response;\n try {\n response = await fetch(`${this.client.baseURL}/api/v1/audio/transcriptions`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.client.apiKey}`,\n ...(params.worker_id ? { \"X-Pendra-Worker-Id\": params.worker_id } : {}),\n },\n body: form,\n signal: controller.signal,\n });\n } catch (err) {\n clearTimeout(timeoutId);\n if (err instanceof DOMException && err.name === \"AbortError\") {\n throw new APIConnectionError(\"Transcription request timed out\");\n }\n throw new APIConnectionError(String(err));\n }\n clearTimeout(timeoutId);\n\n if (response.status >= 400) {\n const body = await readErrorBody(response);\n throw statusErrorFromBody(response.status, body, response.statusText);\n }\n\n // Non-JSON response formats (text/srt/vtt) come back as raw text. Wrap\n // them in the response envelope so the return type stays consistent. With\n // no JSON body to carry it, their placement comes from the headers alone.\n const format = params.response_format;\n if (format === \"text\" || format === \"srt\" || format === \"vtt\") {\n const text = await response.text();\n return withPlacement({ text } as TranscriptionResponse, response.headers);\n }\n\n const result = (await readJsonReply(response)) as TranscriptionResponse;\n return withPlacement(result, response.headers, result.pendra);\n }\n\n /**\n * Private-inference transcription. There is no multipart upload: the audio\n * bytes ride inside the envelope (sealed under the request's data key) and\n * the request options are the sealed JSON body, POSTed as JSON to the same\n * route.\n */\n private async createEncrypted(\n params: TranscriptionCreateParams,\n blob: Blob,\n timeout: number,\n ): Promise<TranscriptionResponse> {\n const body: Record<string, unknown> = { model: params.model };\n if (params.language) body.language = params.language;\n if (params.prompt) body.prompt = params.prompt;\n if (params.response_format) body.response_format = params.response_format;\n if (params.temperature != null) body.temperature = params.temperature;\n if (params.beam_size != null) body.beam_size = params.beam_size;\n if (params.timestamp_granularities) {\n body.timestamp_granularities = params.timestamp_granularities;\n }\n\n const engine = await this.client._privateEngine();\n const { topLevel, decryptor } = engine.seal({\n model: params.model,\n stream: false,\n taskType: \"transcription\",\n body: ENCODER.encode(JSON.stringify(body)),\n binary: new Uint8Array(await blob.arrayBuffer()),\n });\n const { response } = await this.client._fetch(\n \"/api/v1/audio/transcriptions\",\n {\n method: \"POST\",\n body: topLevel,\n headers: params.worker_id ? { \"X-Pendra-Worker-Id\": params.worker_id } : undefined,\n timeout,\n },\n );\n // The worker JSON-encodes the sealed result: json/verbose_json decrypt to\n // an object, text/srt/vtt to a JSON string. Wrap the string in the same\n // `{ text }` envelope the plaintext path returns.\n const { inner, placement } = await readSealedReply(response);\n const raw = DECODER.decode(decryptor.openResult(inner));\n const parsed = parseDecryptedJson(raw, response.status);\n const place = (r: TranscriptionResponse) =>\n withPlacement(r, response.headers, r.pendra, placement);\n if (typeof parsed === \"string\") return place({ text: parsed });\n if (typeof parsed === \"object\" && parsed !== null) {\n if (typeof (parsed as TranscriptionResponse).text !== \"string\") {\n throw new APIResponseValidationError(\"Decrypted response was not a transcription\", {\n status: response.status,\n body: raw,\n });\n }\n return place(parsed as TranscriptionResponse);\n }\n // A plain-text transcript that happens to be valid JSON on its own (e.g.\n // \"42\\n\") reaches us unwrapped, so fall back to the raw plaintext.\n return place({ text: raw });\n }\n}\n","import type { Pendra } from \"../../client\";\nimport { Speech } from \"./speech\";\nimport { Transcriptions } from \"./transcriptions\";\n\nexport class Audio {\n transcriptions: Transcriptions;\n speech: Speech;\n\n constructor(client: Pendra) {\n this.transcriptions = new Transcriptions(client);\n this.speech = new Speech(client);\n }\n}\n","/**\n * Minimal server-sent-events frame decoder.\n *\n * Streaming responses are a sequence of *frames*, not a sequence of lines: a\n * frame is one or more field lines terminated by a blank line, and a `data:`\n * line belongs to whichever `event:` precedes it in the same frame.\n *\n * Reading line-by-line instead — filtering for `data:` and treating every hit\n * as a chat chunk — silently mis-parses any named event the server sends: the\n * `event:` line is skipped and *its* `data:` line is then parsed as a chunk.\n * That is the bug this module exists to prevent (Pendra issue #1398).\n *\n * Only frames belonging to the default event are emitted: no `event:` field, or\n * `event: message`. Anything else is a named event this SDK doesn't model, and\n * is dropped whole.\n */\n\n/** Field value for the default event type. */\nconst DEFAULT_EVENT = \"message\";\n\n/**\n * Strip a field name and its separator off a line.\n *\n * Per the spec the separator is a colon optionally followed by a *single*\n * space, so both `data: {…}` and `data:{…}` are valid and carry the same value.\n * Further leading spaces are part of the value and are preserved.\n */\nfunction fieldValue(line: string, name: string): string {\n const value = line.slice(name.length + 1);\n return value.startsWith(\" \") ? value.slice(1) : value;\n}\n\n/**\n * Incremental SSE decoder. Feed it decoded text with `push()` and it returns\n * the data payload of every complete default-event frame, in order.\n */\nexport class SseDecoder {\n private buffer = \"\";\n private event = \"\";\n private data: string[] = [];\n\n /** Feed a chunk of decoded text; returns the payloads it completed. */\n push(text: string): string[] {\n this.buffer += text;\n const lines = this.buffer.split(\"\\n\");\n // The trailing element is whatever follows the last newline — an\n // incomplete line, held back until more bytes arrive.\n this.buffer = lines.pop() ?? \"\";\n\n const out: string[] = [];\n for (const line of lines) {\n const payload = this.pushLine(line);\n if (payload !== null) out.push(payload);\n }\n return out;\n }\n\n /**\n * Release what the stream ended without terminating: the held-back partial\n * line, plus any frame that never got its blank line.\n *\n * The spec discards an unterminated final block; we keep it, so a connection\n * that drops after the last `data:` line but before its blank line still\n * delivers that payload rather than silently losing it.\n */\n flush(): string[] {\n const out: string[] = [];\n if (this.buffer !== \"\") {\n const payload = this.pushLine(this.buffer);\n this.buffer = \"\";\n if (payload !== null) out.push(payload);\n }\n const tail = this.endFrame();\n if (tail !== null) out.push(tail);\n return out;\n }\n\n private pushLine(rawLine: string): string | null {\n const line = rawLine.endsWith(\"\\r\") ? rawLine.slice(0, -1) : rawLine;\n if (line === \"\") return this.endFrame();\n if (line.startsWith(\":\")) return null; // comment / keep-alive\n if (line.startsWith(\"event:\")) {\n this.event = fieldValue(line, \"event\");\n return null;\n }\n if (line.startsWith(\"data:\")) {\n this.data.push(fieldValue(line, \"data\"));\n return null;\n }\n // Any other field (`id:`, `retry:`, or an unknown one) is ignored per the\n // spec — but it must not reset the frame being accumulated.\n return null;\n }\n\n private endFrame(): string | null {\n const { data, event } = this;\n this.data = [];\n this.event = \"\";\n if (data.length === 0) return null;\n if (event !== \"\" && event !== DEFAULT_EVENT) return null;\n // Multiple data lines in one frame join with a newline.\n return data.join(\"\\n\");\n }\n}\n","import { APIConnectionError } from \"./errors\";\nimport { parseStreamFrame } from \"./_parsing\";\nimport { SseDecoder } from \"./_sse\";\nimport { chunkPlacement } from \"./_placement\";\nimport type { ChatCompletionChunk, PendraWorker } from \"./types/chat\";\n\n/**\n * Async-iterable reader for a streaming chat completion.\n *\n * Framing is handled by {@link SseDecoder}, which assembles whole SSE frames\n * rather than filtering lines — so a frame the server tags with a named\n * `event:` is dropped in one piece instead of having its `data:` line mistaken\n * for a chat chunk (issue #1398).\n *\n * Each surviving frame goes through {@link parseStreamFrame}, which throws on\n * the API's in-band `{\"error\": …}` failure reports and on a frame that isn't a\n * chunk. The error frames used to be yielded *as* chunks (`JSON.parse` succeeds\n * on them), so a worker crash surfaced as a `TypeError` on `chunk.choices[0]`\n * rather than as something a caller could catch and read (issue #2252).\n *\n * `idleTimeoutMs` bounds the gap between reads, not the whole stream: the API\n * sends a keep-alive comment every 15 s, so a healthy stream never goes quiet\n * for long however long it runs, while a stalled one fails with an\n * `APIConnectionError` rather than hanging (#2185). Leaving the loop before the\n * stream ends — a `break`, or a frame that throws — aborts the request, so the\n * connection is released and the worker stops generating tokens nobody will\n * read (#2216).\n *\n * The worker that served the stream is reported on its trailer chunk, the last\n * one before `[DONE]` — `stream.worker` and `stream.requestId` hold it once\n * that chunk has been iterated.\n */\nexport class Stream implements AsyncIterable<ChatCompletionChunk> {\n private reader: ReadableStreamDefaultReader<Uint8Array>;\n private decoder = new TextDecoder();\n private sse = new SseDecoder();\n private done = false;\n private controller: AbortController;\n private placement = new PlacementTracker();\n\n private idleTimeoutMs: number | undefined;\n\n constructor(response: Response, controller: AbortController, idleTimeoutMs?: number) {\n if (!response.body) {\n throw new Error(\"Response body is null — streaming not supported\");\n }\n this.reader = response.body.getReader();\n this.controller = controller;\n this.idleTimeoutMs = idleTimeoutMs;\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk> {\n try {\n while (!this.done) {\n const { value, done: readerDone } = await readWithIdleTimeout(\n this.reader,\n this.idleTimeoutMs,\n );\n\n const payloads = readerDone\n ? this.sse.flush()\n : this.sse.push(this.decoder.decode(value, { stream: true }));\n\n for (const data of payloads) {\n if (data === \"[DONE]\") {\n this.done = true;\n return;\n }\n yield this.placement.observe(parseStreamFrame(data));\n }\n\n if (readerDone) {\n this.done = true;\n break;\n }\n }\n } finally {\n releaseReader(this.reader, this.controller, this.done);\n }\n }\n\n /**\n * The worker that served this stream, or `null` until the chunk reporting it\n * — the trailer, just before `[DONE]` — has been iterated (and on an API too\n * old to report it). Same as that chunk's `pendra.worker`.\n */\n get worker(): PendraWorker | null {\n return this.placement.worker;\n }\n\n /**\n * Pendra's id for this request, reported alongside {@link Stream.worker};\n * `null` until then.\n */\n get requestId(): string | null {\n return this.placement.requestId;\n }\n\n abort(): void {\n this.done = true;\n this.controller.abort();\n }\n}\n\n/**\n * Remembers the placement a stream's chunks report, for the `worker` /\n * `requestId` getters. Shared with the private-inference stream.\n *\n * @internal\n */\nexport class PlacementTracker {\n worker: PendraWorker | null = null;\n requestId: string | null = null;\n\n /** Record `chunk`'s placement, if it carries any, and hand it back. */\n observe(chunk: ChatCompletionChunk): ChatCompletionChunk {\n const { worker, requestId } = chunkPlacement(chunk);\n if (worker) this.worker = worker;\n if (requestId) this.requestId = requestId;\n return chunk;\n }\n}\n\n/**\n * `reader.read()`, failing with an `APIConnectionError` if nothing arrives\n * within `idleTimeoutMs`. The caller's `finally` then aborts the request.\n *\n * @internal\n */\nexport async function readWithIdleTimeout(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n idleTimeoutMs: number | undefined,\n): ReturnType<ReadableStreamDefaultReader<Uint8Array>[\"read\"]> {\n if (!idleTimeoutMs) return reader.read();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const idle = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new APIConnectionError(`Stream received no data for ${idleTimeoutMs}ms`)),\n idleTimeoutMs,\n );\n });\n try {\n return await Promise.race([reader.read(), idle]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * End a stream's read loop. One that stopped before the server finished — the\n * consumer broke out, or a frame threw — aborts the request and cancels the\n * body rather than leaving the connection open.\n *\n * @internal\n */\nexport function releaseReader(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n controller: AbortController,\n finished: boolean,\n): void {\n if (!finished) {\n controller.abort();\n reader.cancel().catch(() => {});\n }\n reader.releaseLock();\n}\n","import { APIResponseValidationError } from \"./errors\";\nimport { parseStreamFrame } from \"./_parsing\";\nimport { SseDecoder } from \"./_sse\";\nimport { PlacementTracker, readWithIdleTimeout, releaseReader } from \"./streaming\";\nimport type { ChatCompletionChunk, PendraWorker } from \"./types/chat\";\nimport {\n isApiTrailerChunk,\n isStreamTerminatorDeclaration,\n truncatedStreamError,\n unsealedReplyError,\n type ResponseDecryptor,\n type ResponseInner,\n} from \"./_privateInference\";\n\nconst DECODER = new TextDecoder();\n\n/**\n * A private-inference variant of `Stream` for encrypted chat streaming. Each\n * SSE `data:` payload carries `{\"pendra_encrypted\":{…,\"seq\":N,\"ciphertext\":\"…\"}}`;\n * we decrypt it (enforcing monotonic seq) back to the original chunk JSON and\n * yield the parsed chunk.\n *\n * Framing is {@link SseDecoder}'s job, shared with the plaintext `Stream`. The\n * worker seals only the payload after `data: ` and leaves the framing intact,\n * so a sealed stream is framed exactly like a plaintext one — including that a\n * named `event:` frame is dropped whole rather than mistaken for a chunk\n * (issue #1398). The idle timeout and early-exit abort also match `Stream`\n * (#2185, #2216).\n *\n * The request asks the worker to seal the end of the stream (#2157). A worker\n * that does so declares it in its first sealed frame and seals `[DONE]` as its\n * last. Once the declaration has been seen, a stream the server ends without\n * the sealed `[DONE]` — a plaintext `[DONE]` or the body closing — throws, since\n * the relay may have cut the reply short. After the sealed `[DONE]` only the\n * API's trailer chunk may follow, and a stall is a clean end: the reply is\n * already known to be complete. A worker too old to declare it leaves the\n * stream checked as before, except that a stream with no sealed frame at all\n * is refused either way: every worker seals at least one frame on a chat reply\n * that succeeds, so an empty one could only mean the relay dropped them all.\n * Stopping early (`break`, `abort()`) never throws this error.\n */\nexport class EncryptedStream implements AsyncIterable<ChatCompletionChunk> {\n private reader: ReadableStreamDefaultReader<Uint8Array>;\n private decoder = new TextDecoder();\n private sse = new SseDecoder();\n private done = false;\n private controller: AbortController;\n private decryptor: ResponseDecryptor;\n private aborted = false;\n private openedAny = false;\n private declared = false;\n private terminated = false;\n private placement = new PlacementTracker();\n\n private idleTimeoutMs: number | undefined;\n\n constructor(\n response: Response,\n controller: AbortController,\n decryptor: ResponseDecryptor,\n idleTimeoutMs?: number,\n ) {\n if (!response.body) {\n throw new Error(\"Response body is null — streaming not supported\");\n }\n this.reader = response.body.getReader();\n this.controller = controller;\n this.decryptor = decryptor;\n this.idleTimeoutMs = idleTimeoutMs;\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk> {\n try {\n while (!this.done) {\n let read: Awaited<ReturnType<typeof readWithIdleTimeout>>;\n try {\n read = await readWithIdleTimeout(this.reader, this.idleTimeoutMs);\n } catch (e) {\n // The reply is already complete; a relay holding the connection open\n // after it is not a failure. Returning with `done` unset still aborts\n // the request in `finally`.\n if (this.terminated) return;\n throw e;\n }\n const { value, done: readerDone } = read;\n\n const payloads = readerDone\n ? this.sse.flush()\n : this.sse.push(this.decoder.decode(value, { stream: true }));\n\n for (const data of payloads) {\n if (data === \"[DONE]\") {\n this.checkEnded();\n this.done = true;\n return;\n }\n\n // A frame that isn't an encrypted envelope is legitimate only when the\n // API added it, after the worker was already out of the picture: an\n // in-band failure report, which parseStreamFrame throws on (issue\n // #2252), or the trailer chunk carrying timings and placement. Anything else unsealed on an\n // encrypted stream is content nobody can vouch for — a relay could\n // inject it (#2142) — so it is refused, never yielded.\n let frame: { pendra_encrypted?: ResponseInner };\n try {\n frame = JSON.parse(data) as { pendra_encrypted?: ResponseInner };\n } catch {\n // A partial last line released at EOF: the connection was cut\n // mid-frame. After the sealed [DONE] the reply is complete anyway;\n // before it, that is a truncation, not a parse error to retry.\n // The consumer already left via abort(): nothing it will read.\n if (this.aborted) continue;\n if (readerDone) {\n if (this.terminated) continue;\n this.checkEnded();\n }\n throw new APIResponseValidationError(\"Stream frame was not valid JSON\", {\n body: data,\n });\n }\n const inner = frame?.pendra_encrypted;\n if (!inner) {\n if (isApiTrailerChunk(frame)) {\n // The API sends it only once the worker's stream has ended, so\n // the same end-of-stream check applies here.\n this.checkEnded();\n yield this.placement.observe(parseStreamFrame(data));\n continue;\n }\n parseStreamFrame(data);\n // An integrity failure, like a chunk that fails to decrypt — not a\n // parse error that invites a blind retry.\n throw unsealedReplyError();\n }\n if (this.terminated) {\n throw new Error(\n \"private_inference: refusing a frame after the worker's sealed end of stream\",\n );\n }\n const plain = this.decryptor.openChunk(inner);\n const chunkJson = DECODER.decode(plain).trim();\n const first = !this.openedAny;\n this.openedAny = true;\n if (first && isStreamTerminatorDeclaration(chunkJson)) {\n this.declared = true;\n continue;\n }\n if (chunkJson === \"[DONE]\") {\n if (this.declared) {\n // Keep reading: the API's trailer chunk and its [DONE] follow.\n this.terminated = true;\n continue;\n }\n this.done = true;\n return;\n }\n if (!chunkJson) continue;\n yield this.placement.observe(parseStreamFrame(chunkJson, \"Decrypted stream frame\"));\n }\n\n if (readerDone) {\n this.checkEnded();\n this.done = true;\n break;\n }\n }\n } finally {\n releaseReader(this.reader, this.controller, this.done);\n }\n }\n\n /**\n * The server ended the stream: it must have carried a sealed frame, and after\n * a declaration, it must have ended on the sealed `[DONE]`.\n */\n private checkEnded(): void {\n if (this.aborted) return;\n if (!this.openedAny || (this.declared && !this.terminated)) {\n throw truncatedStreamError();\n }\n }\n\n /** Same as `Stream.worker`: set once the trailer chunk has been iterated. */\n get worker(): PendraWorker | null {\n return this.placement.worker;\n }\n\n /** Same as `Stream.requestId`. */\n get requestId(): string | null {\n return this.placement.requestId;\n }\n\n abort(): void {\n this.aborted = true;\n this.done = true;\n this.controller.abort();\n }\n}\n","import type { Pendra } from \"../../client\";\nimport type {\n ChatCompletion,\n ChatCompletionCreateParams,\n} from \"../../types/chat\";\nimport { parseCompletion, parseDecryptedCompletion, readSealedReply } from \"../../_parsing\";\nimport { Stream } from \"../../streaming\";\nimport { EncryptedStream } from \"../../_privateStreaming\";\nimport { STREAM_TERMINATOR_KEY } from \"../../_privateInference\";\nimport { PLACEMENT_OPT_IN_HEADER, withPlacement } from \"../../_placement\";\n\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\n\nexport class Completions {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n create(\n params: ChatCompletionCreateParams & { stream: true },\n ): Promise<Stream>;\n create(\n params: ChatCompletionCreateParams & { stream?: false },\n ): Promise<ChatCompletion>;\n create(\n params: ChatCompletionCreateParams,\n ): Promise<ChatCompletion | Stream>;\n async create(\n params: ChatCompletionCreateParams,\n ): Promise<ChatCompletion | Stream> {\n // Forward everything the caller passed rather than copying a fixed list of\n // fields. The API models chat with `extra=\"allow\"` and hands anything it\n // doesn't recognise to the worker, so an allowlist here meant a documented\n // parameter the SDK hadn't caught up with (enable_thinking,\n // reasoning_effort, response_format, ...) was silently dropped on the floor\n // — a request that quietly did something else instead of failing (#1865).\n // `worker_id` is the one exception: it's a routing directive we send as a\n // header, not a body field. Null/undefined values are omitted so an\n // explicitly-unset option doesn't reach the API as a null it would reject.\n const { worker_id: _workerId, ...rest } = params;\n const body: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rest)) {\n if (value != null) body[key] = value;\n }\n\n const headers: Record<string, string> = {};\n if (params.worker_id) headers[\"X-Pendra-Worker-Id\"] = params.worker_id;\n // A stream reports its worker on the trailer chunk. The API always adds it\n // to a plaintext stream, but on a private-inference one only when asked:\n // SDKs that predate it refuse any unsealed trailer carrying more than\n // timings. Sent on both, so the two paths build the same request.\n if (params.stream) headers[PLACEMENT_OPT_IN_HEADER] = \"1\";\n\n if (this.client.privateInferenceEnabled) {\n return this.createEncrypted(params, body, headers);\n }\n\n if (params.stream) {\n const { response, controller } = await this.client._fetch(\n \"/api/v1/chat/completions\",\n { method: \"POST\", body, headers },\n );\n return new Stream(response, controller, this.client.timeout);\n }\n\n const { response } = await this.client._fetch(\n \"/api/v1/chat/completions\",\n { method: \"POST\", body, headers },\n );\n // Not a bare cast: a 200 whose body is missing `id` — or an HTML error page\n // from a proxy — used to sail through as a `ChatCompletion` with undefined\n // fields, or throw a raw `SyntaxError` with nothing to quote (issue #2253).\n const completion = await parseCompletion(response);\n return withPlacement(completion, response.headers, completion.pendra);\n }\n\n private async createEncrypted(\n params: ChatCompletionCreateParams,\n body: Record<string, unknown>,\n headers: Record<string, string>,\n ): Promise<ChatCompletion | Stream> {\n const engine = await this.client._privateEngine();\n const stream = Boolean(params.stream);\n const { topLevel, decryptor } = engine.seal({\n model: params.model,\n stream,\n taskType: \"chat\",\n // The terminator request rides inside the sealed body, so the relay can\n // neither strip nor add it: it asks the worker to seal the end of the\n // stream (#2157).\n body: ENCODER.encode(JSON.stringify(stream ? { ...body, [STREAM_TERMINATOR_KEY]: 1 } : body)),\n messages: params.messages,\n });\n\n if (stream) {\n const { response, controller } = await this.client._fetch(\n \"/api/v1/chat/completions\",\n { method: \"POST\", body: topLevel, headers },\n );\n // EncryptedStream is a drop-in AsyncIterable<ChatCompletionChunk>, same as Stream.\n return new EncryptedStream(response, controller, decryptor, this.client.timeout) as unknown as Stream;\n }\n\n const { response } = await this.client._fetch(\n \"/api/v1/chat/completions\",\n { method: \"POST\", body: topLevel, headers },\n );\n // A late failure arrives in-band, unsealed; readSealedReply raises it.\n const { inner, placement } = await readSealedReply(response);\n // The decrypt stays outside the parsing helpers: a ciphertext-integrity\n // failure must keep propagating distinctly rather than being flattened into\n // a parse error that invites a blind retry.\n const plain = decryptor.openResult(inner);\n const completion = parseDecryptedCompletion(DECODER.decode(plain), response.status);\n // Placement is the API's to report, so it rides beside the envelope rather\n // than inside it; the sealed reply keeps its own notice.\n return withPlacement(completion, response.headers, completion.pendra, placement);\n }\n}\n","import type { Pendra } from \"../../client\";\nimport { Completions } from \"./completions\";\n\nexport class Chat {\n completions: Completions;\n\n constructor(client: Pendra) {\n this.completions = new Completions(client);\n }\n}\n","import type { Pendra } from \"../client\";\nimport type {\n CreateEmbeddingResponse,\n EmbeddingCreateParams,\n} from \"../types/embeddings\";\nimport { readJsonReply, readSealedReply } from \"../_parsing\";\nimport { withPlacement } from \"../_placement\";\n\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\n\nfunction validateParams(params: EmbeddingCreateParams): void {\n if (!params.model || typeof params.model !== \"string\") {\n throw new Error(\"model must be a non-empty string\");\n }\n const { input } = params;\n if (typeof input === \"string\") {\n if (input.length === 0) {\n throw new Error(\"input must be a non-empty string or non-empty array of strings\");\n }\n return;\n }\n if (Array.isArray(input)) {\n if (input.length === 0) {\n throw new Error(\"input must be a non-empty string or non-empty array of strings\");\n }\n if (!input.every((s) => typeof s === \"string\" && s.length > 0)) {\n throw new Error(\"input array entries must all be non-empty strings\");\n }\n return;\n }\n throw new Error(\"input must be a string or an array of strings\");\n}\n\nexport class Embeddings {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n /**\n * Create embeddings for the given input.\n *\n * @example\n * ```ts\n * const result = await client.embeddings.create({\n * model: \"nomic-embed-text:latest\",\n * input: \"Hello world\",\n * });\n * console.log(result.data[0].embedding);\n * ```\n */\n async create(params: EmbeddingCreateParams): Promise<CreateEmbeddingResponse> {\n validateParams(params);\n\n const body: Record<string, unknown> = {\n model: params.model,\n input: params.input,\n };\n if (params.encoding_format != null) body.encoding_format = params.encoding_format;\n if (params.dimensions != null) body.dimensions = params.dimensions;\n if (params.user != null) body.user = params.user;\n\n const headers = params.worker_id ? { \"X-Pendra-Worker-Id\": params.worker_id } : undefined;\n\n if (this.client.privateInferenceEnabled) {\n return this.createEncrypted(params.model, body, headers);\n }\n\n const { response } = await this.client._fetch(\n \"/api/v1/embeddings\",\n { method: \"POST\", body, headers },\n );\n const result = (await readJsonReply(response)) as CreateEmbeddingResponse;\n return withPlacement(result, response.headers, result.pendra);\n }\n\n private async createEncrypted(\n model: string,\n body: Record<string, unknown>,\n headers: Record<string, string> | undefined,\n ): Promise<CreateEmbeddingResponse> {\n const engine = await this.client._privateEngine();\n // Embeddings are never streamed and carry no affinity messages.\n const { topLevel, decryptor } = engine.seal({\n model,\n stream: false,\n taskType: \"embeddings\",\n body: ENCODER.encode(JSON.stringify(body)),\n });\n const { response } = await this.client._fetch(\n \"/api/v1/embeddings\",\n { method: \"POST\", body: topLevel, headers },\n );\n // A late failure arrives in-band, unsealed; readSealedReply raises it.\n const { inner, placement } = await readSealedReply(response);\n const plain = decryptor.openResult(inner);\n const result = JSON.parse(DECODER.decode(plain)) as CreateEmbeddingResponse;\n // Placement rides unsealed beside the envelope (see withPlacement).\n return withPlacement(result, response.headers, result.pendra, placement);\n }\n}\n","import type { Pendra } from \"../../client\";\nimport { APIResponseValidationError } from \"../../errors\";\nimport type { ImageGenerationCreateParams, ImageResponse } from \"../../types/images\";\nimport { parseDecryptedJson, readJsonReply, readSealedReply } from \"../../_parsing\";\nimport { withPlacement } from \"../../_placement\";\n\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\n\nconst SIZE_RE = /^\\d+x\\d+$/;\n\nfunction validateParams(params: ImageGenerationCreateParams): void {\n if (!params.prompt || !params.prompt.trim()) {\n throw new Error(\"prompt must be a non-empty string\");\n }\n if (params.n != null && (params.n < 1 || params.n > 4)) {\n throw new Error(\"n must be between 1 and 4\");\n }\n if (params.size != null && !SIZE_RE.test(params.size)) {\n throw new Error(\"size must be in the form WIDTHxHEIGHT (e.g. '1024x1024')\");\n }\n}\n\nexport class Generations {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n async create(params: ImageGenerationCreateParams): Promise<ImageResponse> {\n validateParams(params);\n\n const body: Record<string, unknown> = {\n model: params.model,\n prompt: params.prompt,\n };\n\n if (params.n != null) body.n = params.n;\n if (params.size != null) body.size = params.size;\n if (params.response_format != null) body.response_format = params.response_format;\n if (params.num_inference_steps != null) body.num_inference_steps = params.num_inference_steps;\n if (params.seed != null) body.seed = params.seed;\n if (params.negative_prompt != null) body.negative_prompt = params.negative_prompt;\n\n const headers = params.worker_id ? { \"X-Pendra-Worker-Id\": params.worker_id } : undefined;\n\n if (this.client.privateInferenceEnabled) {\n return this.createEncrypted(params.model, body, headers);\n }\n\n const { response } = await this.client._fetch(\n \"/api/v1/images/generations\",\n { method: \"POST\", body, headers },\n );\n const result = (await readJsonReply(response)) as ImageResponse;\n return withPlacement(result, response.headers, result.pendra);\n }\n\n private async createEncrypted(\n model: string,\n body: Record<string, unknown>,\n headers: Record<string, string> | undefined,\n ): Promise<ImageResponse> {\n const engine = await this.client._privateEngine();\n // Image generation is never streamed and carries no affinity messages.\n const { topLevel, decryptor } = engine.seal({\n model,\n stream: false,\n taskType: \"image_generation\",\n body: ENCODER.encode(JSON.stringify(body)),\n });\n const { response } = await this.client._fetch(\n \"/api/v1/images/generations\",\n { method: \"POST\", body: topLevel, headers },\n );\n const { inner, placement } = await readSealedReply(response);\n const plain = decryptor.openResult(inner);\n const parsed = parseDecryptedJson(DECODER.decode(plain), response.status);\n if (typeof parsed !== \"object\" || parsed === null || !Array.isArray((parsed as ImageResponse).data)) {\n throw new APIResponseValidationError(\"Decrypted response was not an image generation\", {\n status: response.status,\n body: DECODER.decode(plain),\n });\n }\n const result = parsed as ImageResponse;\n return withPlacement(result, response.headers, result.pendra, placement);\n }\n}\n","import type { Pendra } from \"../../client\";\nimport { Generations } from \"./generations\";\n\nexport class Images {\n generations: Generations;\n\n constructor(client: Pendra) {\n this.generations = new Generations(client);\n }\n}\n","import type { Pendra } from \"../client\";\nimport type { Model } from \"../types/models\";\n\nexport class Models {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n async list(): Promise<Model[]> {\n const { response } = await this.client._fetch(\"/api/v1/models\", {\n method: \"GET\",\n });\n const data = (await response.json()) as { data: Model[] };\n return data.data;\n }\n}\n","import type { Pendra } from \"../client\";\nimport type {\n ModerationCreateParams,\n ModerationResponse,\n} from \"../types/moderations\";\nimport { APIResponseValidationError } from \"../errors\";\nimport { parseDecryptedJson, readJsonReply, readSealedReply } from \"../_parsing\";\nimport { withPlacement } from \"../_placement\";\n\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\n\n/** Most inputs one request may carry (the endpoint's limit). */\nconst MAX_INPUTS = 32;\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nfunction validatePart(part: unknown): void {\n if (!isPlainObject(part)) {\n throw new Error(\"input can't mix strings and parts\");\n }\n if (part.type === \"text\") {\n if (typeof part.text !== \"string\" || part.text.length === 0) {\n throw new Error(\"a text part needs a non-empty text\");\n }\n return;\n }\n if (part.type === \"image_url\") {\n const url = isPlainObject(part.image_url) ? part.image_url.url : undefined;\n if (typeof url !== \"string\" || url.length === 0) {\n throw new Error(\"an image_url part needs image_url.url\");\n }\n return;\n }\n throw new Error(\"parts must be of type text or image_url\");\n}\n\n/**\n * The endpoint's input rules, checked here so an encrypted request (which the\n * server can't read to validate) fails the same way as a plaintext one.\n */\nfunction validateParams(params: ModerationCreateParams): void {\n if (!params.model || typeof params.model !== \"string\") {\n throw new Error(\"model must be a non-empty string\");\n }\n const input: unknown = params.input;\n if (typeof input === \"string\") {\n if (input.length === 0) throw new Error(\"input must be a non-empty string\");\n return;\n }\n if (!Array.isArray(input)) {\n throw new Error(\"input must be a string, an array of strings, or an array of text and image_url parts\");\n }\n if (input.length === 0 || input.length > MAX_INPUTS) {\n throw new Error(`input must hold 1 to ${MAX_INPUTS} items`);\n }\n if (input.every((i) => typeof i === \"string\")) {\n if (!input.every((s: string) => s.length > 0)) {\n throw new Error(\"input strings must be non-empty\");\n }\n return;\n }\n input.forEach(validatePart);\n}\n\nfunction asModeration(parsed: unknown, status: number, label: string): ModerationResponse {\n if (!isPlainObject(parsed) || !Array.isArray(parsed.results)) {\n throw new APIResponseValidationError(`${label} was not a moderation response`, {\n status,\n body: JSON.stringify(parsed),\n });\n }\n return parsed as unknown as ModerationResponse;\n}\n\nexport class Moderations {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n /**\n * Check content with a moderation model installed on one of your workers\n * (OpenAI-compatible).\n *\n * `input` is a string, an array of up to 32 strings (one result each) or an\n * array of up to 32 `text` / `image_url` parts checked together (one\n * result). With private inference turned on, the check is end-to-end\n * encrypted: Pendra sees neither the content nor the verdict.\n *\n * @example\n * ```ts\n * const result = await client.moderations.create({\n * model: \"llama-guard3:1b\",\n * input: \"Hello world\",\n * });\n * console.log(result.results[0].flagged);\n * ```\n */\n async create(params: ModerationCreateParams): Promise<ModerationResponse> {\n validateParams(params);\n\n const body: Record<string, unknown> = {\n model: params.model,\n input: params.input,\n };\n\n const headers = params.worker_id ? { \"X-Pendra-Worker-Id\": params.worker_id } : undefined;\n\n if (this.client.privateInferenceEnabled) {\n return this.createEncrypted(params.model, body, headers);\n }\n\n const { response } = await this.client._fetch(\n \"/api/v1/moderations\",\n { method: \"POST\", body, headers },\n );\n const result = asModeration(await readJsonReply(response), response.status, \"Response\");\n return withPlacement(result, response.headers, result.pendra);\n }\n\n private async createEncrypted(\n model: string,\n body: Record<string, unknown>,\n headers: Record<string, string> | undefined,\n ): Promise<ModerationResponse> {\n const engine = await this.client._privateEngine();\n // Moderation is never streamed and carries no affinity messages. The task\n // type must be the API router's dispatch string: it is bound into the AAD.\n const { topLevel, decryptor } = engine.seal({\n model,\n stream: false,\n taskType: \"moderation\",\n body: ENCODER.encode(JSON.stringify({ model: body.model, stream: false, input: body.input })),\n });\n const { response } = await this.client._fetch(\n \"/api/v1/moderations\",\n { method: \"POST\", body: topLevel, headers },\n );\n // A late failure arrives in-band, unsealed; readSealedReply raises it.\n const { inner, placement } = await readSealedReply(response);\n const plain = decryptor.openResult(inner);\n // The worker pads the reply with trailing spaces so its length doesn't\n // depend on the verdict; JSON.parse ignores them.\n const result = asModeration(\n parseDecryptedJson(DECODER.decode(plain), response.status),\n response.status,\n \"Decrypted response\",\n );\n // Placement rides unsealed beside the envelope (see withPlacement).\n return withPlacement(result, response.headers, result.pendra, placement);\n }\n}\n","import type { Pendra } from \"../client\";\nimport type { RerankCreateParams, RerankResponse } from \"../types/rerank\";\nimport { readJsonReply, readSealedReply } from \"../_parsing\";\nimport { withPlacement } from \"../_placement\";\n\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\n\nfunction validateParams(params: RerankCreateParams): void {\n if (!params.model || typeof params.model !== \"string\") {\n throw new Error(\"model must be a non-empty string\");\n }\n if (!params.query || typeof params.query !== \"string\") {\n throw new Error(\"query must be a non-empty string\");\n }\n const { documents } = params;\n if (\n !Array.isArray(documents) ||\n documents.length === 0 ||\n !documents.every((d) => typeof d === \"string\" && d.length > 0)\n ) {\n throw new Error(\"documents must be a non-empty array of non-empty strings\");\n }\n if (params.top_n != null && params.top_n < 1) {\n throw new Error(\"top_n must be >= 1 when provided\");\n }\n}\n\nexport class Rerank {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n /**\n * Rerank `documents` by relevance to `query` (Cohere-compatible).\n *\n * @example\n * ```ts\n * const result = await client.rerank.create({\n * model: \"bge-reranker-v2-m3\",\n * query: \"What is the capital of France?\",\n * documents: [\"Paris is the capital of France.\", \"Berlin is in Germany.\"],\n * top_n: 1,\n * });\n * console.log(result.results[0].index, result.results[0].relevance_score);\n * ```\n */\n async create(params: RerankCreateParams): Promise<RerankResponse> {\n validateParams(params);\n\n const body: Record<string, unknown> = {\n model: params.model,\n query: params.query,\n documents: params.documents,\n return_documents: params.return_documents ?? false,\n };\n if (params.top_n != null) body.top_n = params.top_n;\n\n const headers = params.worker_id ? { \"X-Pendra-Worker-Id\": params.worker_id } : undefined;\n\n if (this.client.privateInferenceEnabled) {\n return this.createEncrypted(params.model, body, headers);\n }\n\n const { response } = await this.client._fetch(\n \"/api/v1/rerank\",\n { method: \"POST\", body, headers },\n );\n const result = (await readJsonReply(response)) as RerankResponse;\n return withPlacement(result, response.headers, result.pendra);\n }\n\n private async createEncrypted(\n model: string,\n body: Record<string, unknown>,\n headers: Record<string, string> | undefined,\n ): Promise<RerankResponse> {\n const engine = await this.client._privateEngine();\n // Rerank is never streamed and carries no affinity messages. On the\n // encrypted path the worker builds + seals the final Cohere response, which\n // we decrypt verbatim.\n const { topLevel, decryptor } = engine.seal({\n model,\n stream: false,\n taskType: \"rerank\",\n body: ENCODER.encode(JSON.stringify(body)),\n });\n const { response } = await this.client._fetch(\n \"/api/v1/rerank\",\n { method: \"POST\", body: topLevel, headers },\n );\n // A late failure arrives in-band, unsealed; readSealedReply raises it.\n const { inner, placement } = await readSealedReply(response);\n const plain = decryptor.openResult(inner);\n const result = JSON.parse(DECODER.decode(plain)) as RerankResponse;\n // Placement rides unsealed beside the envelope (see withPlacement).\n return withPlacement(result, response.headers, result.pendra, placement);\n }\n}\n","/**\n * The published package version, sent as the User-Agent on every request so the\n * API can record which client made it.\n *\n * Duplicated from package.json deliberately: the SDK ships as both ESM and CJS\n * and must work without a JSON import assertion or a bundler resolving\n * `../package.json`. `version.test.ts` keeps the two in step.\n */\nexport const VERSION = \"0.18.0\";\n\n/** e.g. `pendra-node/0.18.0`. */\nexport const USER_AGENT = `pendra-node/${VERSION}`;\n","import { Audio } from \"./resources/audio/index\";\nimport { Chat } from \"./resources/chat/index\";\nimport { Embeddings } from \"./resources/embeddings\";\nimport { Images } from \"./resources/images/index\";\nimport { Models } from \"./resources/models\";\nimport { Moderations } from \"./resources/moderations\";\nimport { Rerank } from \"./resources/rerank\";\nimport { USER_AGENT } from \"./version\";\nimport { APIConnectionError, messageFromDetail, readErrorBody, statusErrorFromBody } from \"./errors\";\nimport {\n PrivateInferenceEngine,\n PrivateInferenceError,\n type FetchedKey,\n} from \"./_privateInferenceEngine\";\n\nexport interface PendraOptions {\n apiKey?: string;\n baseURL?: string;\n timeout?: number;\n /**\n * Enable end-to-end encrypted (private) inference. When `true`, inference\n * requests (chat, embeddings, moderations and the rest) are sealed to your\n * org's workload key (TOFU-pinned on first use) and the responses are decrypted client-side — Pendra relays only\n * ciphertext. Pass `{ pinnedFingerprint }` to hard-pin the org key fingerprint\n * (required in browser bundles, which cannot use the TOFU key store).\n *\n * Defaults to the `PENDRA_PRIVATE_INFERENCE` environment variable\n * (`1`/`true`/`yes`/`on` enables it).\n */\n privateInference?: boolean | { pinnedFingerprint?: string };\n}\n\nfunction envTruthy(v: string | undefined): boolean {\n if (!v) return false;\n return [\"1\", \"true\", \"yes\", \"on\"].includes(v.trim().toLowerCase());\n}\n\nexport class Pendra {\n readonly apiKey: string;\n readonly baseURL: string;\n readonly timeout: number;\n\n chat: Chat;\n images: Images;\n embeddings: Embeddings;\n models: Models;\n audio: Audio;\n rerank: Rerank;\n moderations: Moderations;\n\n /** @internal Whether end-to-end encrypted inference is enabled for this client. */\n readonly privateInferenceEnabled: boolean;\n private _piEngine: PrivateInferenceEngine | null = null;\n // Serialises the one-time key fetch across concurrent first calls.\n private _piKeyFetch: Promise<void> | null = null;\n\n constructor(options: PendraOptions = {}) {\n const env = typeof process !== \"undefined\" ? process.env : undefined;\n const apiKey = options.apiKey ?? env?.PENDRA_API_KEY;\n\n if (!apiKey) {\n throw new Error(\n \"API key is required — pass apiKey or set the PENDRA_API_KEY environment variable\",\n );\n }\n\n this.apiKey = apiKey;\n this.baseURL = (options.baseURL ?? \"https://api.pendra.ai\").replace(\n /\\/$/,\n \"\",\n );\n this.timeout = options.timeout ?? 120_000;\n\n // --- private inference config ---\n let piOpt = options.privateInference;\n if (piOpt === undefined) {\n piOpt = envTruthy(env?.PENDRA_PRIVATE_INFERENCE);\n }\n let pinnedFingerprint: string | undefined;\n if (typeof piOpt === \"object\" && piOpt !== null) {\n // An unknown key is almost always a typo or the snake_case spelling from\n // the Python SDK. Ignoring it would, for a mistyped pin, leave the client\n // unpinned while its author believes it is pinned — so refuse it.\n for (const key of Object.keys(piOpt)) {\n if (key !== \"pinnedFingerprint\") {\n throw new TypeError(\n `Unknown privateInference option \"${key}\". Accepted options: pinnedFingerprint.`,\n );\n }\n }\n this.privateInferenceEnabled = true;\n pinnedFingerprint = piOpt.pinnedFingerprint;\n } else {\n this.privateInferenceEnabled = Boolean(piOpt);\n }\n // An explicitly passed pin (even \"\") goes to the engine, which rejects it\n // rather than silently running unpinned. Only an unset or empty environment\n // variable means \"not pinned\".\n pinnedFingerprint = pinnedFingerprint ?? (env?.PENDRA_PINNED_ORG_FINGERPRINT || undefined);\n\n if (this.privateInferenceEnabled) {\n // PENDRA_AFFINITY_SALT, when set, is used as raw UTF-8 bytes (mirrors Python).\n const affinitySalt = env?.PENDRA_AFFINITY_SALT\n ? new TextEncoder().encode(env.PENDRA_AFFINITY_SALT)\n : null;\n this._piEngine = new PrivateInferenceEngine({\n baseUrl: this.baseURL,\n apiKey: this.apiKey,\n pinnedFingerprint: pinnedFingerprint ?? null,\n affinitySalt,\n tofuPath: env?.PENDRA_TOFU_PATH ?? null,\n });\n }\n\n this.chat = new Chat(this);\n this.images = new Images(this);\n this.embeddings = new Embeddings(this);\n this.models = new Models(this);\n this.audio = new Audio(this);\n this.rerank = new Rerank(this);\n this.moderations = new Moderations(this);\n }\n\n /**\n * @internal\n * Return the private-inference engine with its org key resolved. Fetches\n * `GET {baseUrl}/v1/private-inference/key` exactly once (subsequent calls reuse\n * the cached key). Throws if private inference is not enabled.\n */\n async _privateEngine(): Promise<PrivateInferenceEngine> {\n if (!this._piEngine) {\n throw new PrivateInferenceError(\"private inference is not enabled on this client\");\n }\n if (this._piEngine.cachedOrgPublicKeys() !== null) {\n return this._piEngine;\n }\n if (!this._piKeyFetch) {\n this._piKeyFetch = this._fetchAndResolveOrgKey().catch((err) => {\n // Reset so a failed fetch can be retried on the next call.\n this._piKeyFetch = null;\n throw err;\n });\n }\n await this._piKeyFetch;\n return this._piEngine;\n }\n\n private async _fetchAndResolveOrgKey(): Promise<void> {\n const engine = this._piEngine as PrivateInferenceEngine;\n const url = `${this.baseURL}/v1/private-inference/key`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n let response: Response;\n try {\n response = await fetch(url, {\n method: \"GET\",\n headers: { Authorization: `Bearer ${this.apiKey}`, \"User-Agent\": USER_AGENT },\n signal: controller.signal,\n });\n } catch (err) {\n if (err instanceof DOMException && err.name === \"AbortError\") {\n throw new APIConnectionError(`Request timed out after ${this.timeout}ms`);\n }\n throw new APIConnectionError(\n err instanceof Error ? err.message : \"Failed to fetch the private-inference workload key\",\n );\n } finally {\n clearTimeout(timeoutId);\n }\n\n if (response.status === 404) {\n // The server's `detail` says why there is no key (a connected worker\n // awaiting approval needs approving, not a second worker), so prefer it.\n const body = (await readErrorBody(response)) as { detail?: unknown } | null | undefined;\n const detail = typeof body === \"object\" && body !== null ? body.detail : undefined;\n throw new PrivateInferenceError(\n messageFromDetail(detail) ??\n \"No encryption key is registered for this organisation. Start a worker \" +\n \"and it will be issued one automatically.\",\n );\n }\n if (!response.ok) {\n // FastAPI errors carry `detail` (a string, or an array/object for\n // validation and structured errors); the inference routes' worker and\n // server errors carry an OpenAI-style `{\"error\": {\"message\"}}`.\n throw statusErrorFromBody(response.status, await readErrorBody(response), response.statusText);\n }\n\n const json = (await response.json()) as { keys?: FetchedKey[] };\n await engine.resolveOrgKey(json.keys ?? []);\n }\n\n /** @internal */\n async _fetch(\n path: string,\n options: {\n method: string;\n body?: Record<string, unknown>;\n headers?: Record<string, string>;\n /** Overrides the client timeout for this request (ms). */\n timeout?: number;\n },\n ): Promise<{ response: Response; controller: AbortController }> {\n const timeout = options.timeout ?? this.timeout;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n ...(options.headers ?? {}),\n };\n\n let response: Response;\n try {\n response = await fetch(`${this.baseURL}${path}`, {\n method: options.method,\n headers,\n body: options.body ? JSON.stringify(options.body) : undefined,\n signal: controller.signal,\n });\n } catch (err) {\n clearTimeout(timeoutId);\n if (err instanceof DOMException && err.name === \"AbortError\") {\n throw new APIConnectionError(\n `Request timed out after ${timeout}ms`,\n );\n }\n throw new APIConnectionError(\n err instanceof Error ? err.message : \"Failed to connect to the Pendra API\",\n );\n }\n\n // The timeout covers connecting and receiving the headers. A stream then\n // runs for as long as it keeps producing data: leaving this timer armed\n // aborted every stream longer than `timeout` partway through (#2185), and\n // `Stream` applies its own per-read idle timeout instead.\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n // A fleet re-key leaves this client sealing to a fingerprint no worker\n // holds. The key set is cached for the whole process lifetime, so without\n // this a long-running server would fail EVERY subsequent request until\n // someone restarted it. Dropping the cache lets the next call recover.\n this.invalidateKeyCacheIfRekeyed(response);\n // FastAPI errors carry `detail` (a string, or an array/object for\n // validation and structured errors); the inference routes' worker and\n // server errors carry an OpenAI-style `{\"error\": {\"message\"}}`.\n throw statusErrorFromBody(response.status, await readErrorBody(response), response.statusText);\n }\n\n return { response, controller };\n }\n\n /**\n * Drop the cached encryption keys when the API reports that no worker holds\n * the one this request was sealed to — the signal that the org's fleet has\n * re-keyed. Returns true if the cache was dropped.\n *\n * A PINNED client is left alone on purpose: a pin is an allowlist, so\n * re-fetching could only return fingerprints the pin already rejects and\n * would loop rather than recover. The error surfaces instead, which is\n * exactly what pinning is for.\n */\n private invalidateKeyCacheIfRekeyed(response: Response): boolean {\n const engine = this._piEngine;\n if (!engine || engine.isPinned) return false;\n if (response.headers?.get(\"X-Pendra-Error-Code\") !== \"no_private_inference_worker\") {\n return false;\n }\n engine.invalidateOrgKey();\n // Clearing the engine's cache is not enough on its own. `_piKeyFetch` holds\n // the RESOLVED promise from the first successful fetch and is only ever\n // reset on failure, so `_privateEngine()` would await it, no-op, and hand\n // back an engine whose key is still null — every later call then throwing\n // \"org key not resolved yet\" for the life of the process. That is worse\n // than the behaviour this recovery replaces, which at least kept asking the\n // network. Drop it so the next call genuinely re-fetches.\n this._piKeyFetch = null;\n return true;\n }\n}\n","export { Pendra } from \"./client\";\nexport type { PendraOptions } from \"./client\";\nexport { Stream } from \"./streaming\";\n\nexport type {\n ChatCompletion,\n ChatCompletionChunk,\n ChatCompletionContentPart,\n ChatCompletionMessage,\n ChatCompletionMessageParam,\n ChatCompletionMessageToolCall,\n ChatCompletionCreateParams,\n Choice,\n StreamChoice,\n ChoiceDelta,\n Usage,\n CompletionTokensDetails,\n PendraExtension,\n PendraNotice,\n PendraTiming,\n PendraWorker,\n PendraWebToolStep,\n} from \"./types/chat\";\n\nexport type { Model } from \"./types/models\";\n\nexport type {\n ImageGenerationCreateParams,\n ImageData,\n ImageResponse,\n} from \"./types/images\";\n\nexport type {\n EmbeddingCreateParams,\n Embedding,\n EmbeddingUsage,\n CreateEmbeddingResponse,\n} from \"./types/embeddings\";\n\nexport type {\n AudioFileInput,\n SpeechCreateParams,\n SpeechResponse,\n TranscriptionCreateParams,\n TranscriptionResponse,\n TranscriptionSegment,\n} from \"./types/audio\";\n\nexport type {\n RerankCreateParams,\n RerankResult,\n RerankResultDocument,\n RerankResponse,\n} from \"./types/rerank\";\n\nexport type {\n ModerationCreateParams,\n ModerationImageURLInput,\n ModerationInput,\n ModerationInputPart,\n ModerationResponse,\n ModerationResult,\n ModerationTextInput,\n} from \"./types/moderations\";\n\nexport {\n APIError,\n APIConnectionError,\n APIStatusError,\n APIStreamError,\n APIResponseValidationError,\n AuthenticationError,\n RateLimitError,\n} from \"./errors\";\nexport type { APIStatusErrorOptions } from \"./errors\";\n\nexport { PrivateInferenceError } from \"./_privateInferenceEngine\";\n\n// Default export for convenient usage:\n// import Pendra from 'pendra';\nimport { Pendra as _Pendra } from \"./client\";\nexport default _Pendra;\n"],"mappings":";AAAO,IAAM,WAAN,cAAuB,MAAM;AAAA,EAGlC,YAAY,SAAiB,QAAiB;AAC5C,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AACF;AAEO,IAAM,qBAAN,cAAiC,SAAS;AAAA,EAC/C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AAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYQ,4BAA4B,UAA6B;AAC/D,UAAM,SAAS,KAAK;AACpB,QAAI,CAAC,UAAU,OAAO,SAAU,QAAO;AACvC,QAAI,SAAS,SAAS,IAAI,qBAAqB,MAAM,+BAA+B;AAClF,aAAO;AAAA,IACT;AACA,WAAO,iBAAiB;AAQxB,SAAK,cAAc;AACnB,WAAO;AAAA,EACT;AACF;;;ACzMA,IAAO,gBAAQ;","names":["chacha20poly1305","extract","expand","TEXT_ENCODER","chacha20poly1305","extract","expand","b64d","bytes","isRecord","DECODER","ENCODER","DECODER","response","ENCODER","DECODER","ENCODER","DECODER","validateParams","ENCODER","DECODER","isPlainObject","validateParams","ENCODER","DECODER","validateParams"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/_privateInference.ts","../src/_hpke.ts","../src/_parsing.ts","../src/_placement.ts","../src/_privateInferenceEngine.ts","../src/resources/audio/speech.ts","../src/resources/audio/transcriptions.ts","../src/resources/audio/index.ts","../src/_sse.ts","../src/streaming.ts","../src/_privateStreaming.ts","../src/resources/chat/completions.ts","../src/resources/chat/index.ts","../src/resources/embeddings.ts","../src/resources/images/generations.ts","../src/resources/images/index.ts","../src/resources/models.ts","../src/resources/moderations.ts","../src/resources/rerank.ts","../src/version.ts","../src/client.ts","../src/index.ts"],"sourcesContent":["export class APIError extends Error {\n readonly status: number | undefined;\n\n constructor(message: string, status?: number) {\n super(message);\n this.name = \"APIError\";\n this.status = status;\n }\n}\n\nexport class APIConnectionError extends APIError {\n constructor(message = \"Failed to connect to the Pendra API\") {\n super(message);\n this.name = \"APIConnectionError\";\n }\n}\n\nexport interface APIStatusErrorOptions {\n /** The parsed JSON body, or the raw text when it wasn't JSON. */\n body?: unknown;\n /** The body's `detail` field as the API sent it (string, array or object). */\n detail?: unknown;\n}\n\n/**\n * Raised when the API returns a non-2xx response.\n *\n * `message` is always a readable string. The response stays available for\n * callers that want to act on its structure: `body` is the parsed JSON body (or\n * the raw text when it wasn't JSON), and `detail` is the body's `detail` field\n * as sent — an array or object for validation and structured errors.\n */\nexport class APIStatusError extends APIError {\n override readonly status: number;\n readonly body: unknown;\n readonly detail: unknown;\n\n constructor(message: string, status: number, options: APIStatusErrorOptions = {}) {\n super(message, status);\n this.name = \"APIStatusError\";\n this.status = status;\n this.body = options.body;\n this.detail = options.detail;\n }\n}\n\nexport class AuthenticationError extends APIStatusError {\n constructor(\n message = \"Invalid API key — check your PENDRA_API_KEY\",\n options: APIStatusErrorOptions = {},\n ) {\n super(message, 401, options);\n this.name = \"AuthenticationError\";\n }\n}\n\nexport class RateLimitError extends APIStatusError {\n constructor(message = \"Rate limit exceeded\", options: APIStatusErrorOptions = {}) {\n super(message, 429, options);\n this.name = \"RateLimitError\";\n }\n}\n\n/**\n * Raised when a response arrives but isn't the shape the SDK expects.\n *\n * A server or proxy problem, not a transport one: the request reached Pendra\n * and came back, but the body could not be read as the documented type — a 200\n * missing a required field, a captive-portal HTML page from a corporate proxy,\n * a truncated body.\n *\n * Deliberately NOT an `APIConnectionError`: retrying a response that will never\n * parse just burns the retry budget, so callers that retry on connection\n * failures should let this one through. `body` holds a short excerpt of what\n * actually came back.\n */\nexport class APIResponseValidationError extends APIError {\n /** How much of the offending body to keep in the message. */\n static readonly BODY_EXCERPT_CHARS = 200;\n\n readonly body: string | undefined;\n\n constructor(message: string, options: { status?: number; body?: string } = {}) {\n const { status, body } = options;\n let text = message;\n if (body) {\n const max = APIResponseValidationError.BODY_EXCERPT_CHARS;\n text = `${message} (body: ${body.slice(0, max)}${body.length > max ? \"…\" : \"\"})`;\n }\n super(text, status);\n this.name = \"APIResponseValidationError\";\n this.body = body;\n }\n}\n\n/**\n * Raised when a stream reports a failure in-band, after HTTP 200.\n *\n * A streaming response commits its status line before the worker has done any\n * work, so anything that goes wrong afterwards — the worker crashing, the\n * request timing out, the fleet being at capacity — can only be described in\n * the body. The API sends `data: {\"error\": {…}}` followed by `data: [DONE]`,\n * and this error is how the SDK surfaces that instead of ending the stream as\n * though it had succeeded.\n *\n * `requestId` and `workerId` identify the failed inference to Pendra support.\n *\n * Note this extends `APIError`, not `APIStatusError`, because the API omits\n * `code` on some frames (the timeout and the generic catch-all) — so `status`\n * is genuinely optional here, which `APIStatusError`'s always-present `status`\n * cannot express. Check `status` for undefined before comparing it.\n */\nexport class APIStreamError extends APIError {\n readonly type: string | undefined;\n readonly code: number | undefined;\n readonly requestId: string | undefined;\n readonly workerId: string | undefined;\n readonly workerName: string | undefined;\n\n constructor(\n message: string,\n options: {\n type?: string;\n code?: number;\n requestId?: string;\n workerId?: string;\n workerName?: string;\n } = {},\n ) {\n super(message, typeof options.code === \"number\" ? options.code : undefined);\n this.name = \"APIStreamError\";\n this.type = options.type;\n this.code = options.code;\n this.requestId = options.requestId;\n this.workerId = options.workerId;\n this.workerName = options.workerName;\n }\n}\n\n/** Pydantic `loc` segments naming where FastAPI looked, not a caller field. */\nconst LOC_SOURCES = new Set([\"body\", \"query\", \"path\", \"header\", \"cookie\"]);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === \"string\" && value ? value : undefined;\n}\n\nfunction compactJson(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nfunction messageFromItem(item: unknown): string | undefined {\n if (isRecord(item)) {\n const msg = nonEmptyString(item.msg) ?? nonEmptyString(item.message);\n if (msg) {\n let field = typeof item.field === \"string\" ? item.field : undefined;\n if (field === undefined) {\n const loc = Array.isArray(item.loc) ? [...item.loc] : [];\n if (loc.length && LOC_SOURCES.has(String(loc[0]))) loc.shift();\n field = loc.map(String).join(\".\");\n }\n return field ? `${field}: ${msg}` : msg;\n }\n }\n return messageFromDetail(item);\n}\n\n/**\n * Render a FastAPI `detail` of any shape as a readable string: a validation\n * error list becomes `field: problem; …`, an object its `error.message` /\n * `message` / `msg`. `undefined` when there is nothing worth showing.\n * @internal\n */\nexport function messageFromDetail(detail: unknown): string | undefined {\n if (detail === undefined || detail === null) return undefined;\n if (typeof detail === \"string\") return detail || undefined;\n if (Array.isArray(detail)) {\n const parts = detail.map(messageFromItem).filter((p): p is string => !!p);\n return parts.length ? parts.join(\"; \") : undefined;\n }\n if (isRecord(detail)) {\n const err = detail.error;\n const nested = isRecord(err) ? nonEmptyString(err.message) : undefined;\n const msg = nested ?? nonEmptyString(detail.message) ?? nonEmptyString(detail.msg);\n if (msg) return msg;\n return Object.keys(detail).length ? compactJson(detail) : undefined;\n }\n return compactJson(detail);\n}\n\n/**\n * Read an error response's body once: parsed JSON, else the raw text, else\n * `undefined` (empty or unreadable). Never throws.\n * @internal\n */\nexport async function readErrorBody(response: Response): Promise<unknown> {\n let raw: string;\n try {\n raw = await response.text();\n } catch {\n return undefined;\n }\n if (!raw) return undefined;\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n return raw;\n }\n}\n\n/**\n * Build the error for a non-2xx response from its already-read `body` (see\n * `readErrorBody`). The one place every request path turns an error response\n * into an exception, so they agree. The message follows the order the API\n * errors page documents: the OpenAI-style `error.message`, then `detail` (a\n * string as-is; an array or object rendered as text), then a top-level\n * `message`, then the raw body, then `fallback`.\n * @internal\n */\nexport function statusErrorFromBody(\n status: number,\n body: unknown,\n fallback: string,\n): APIStatusError {\n const detail = isRecord(body) ? body.detail : undefined;\n const err = isRecord(body) ? body.error : undefined;\n let message =\n (isRecord(err) ? nonEmptyString(err.message) : undefined) ??\n messageFromDetail(detail) ??\n (isRecord(body) ? nonEmptyString(body.message) : undefined);\n if (message === undefined) {\n if (typeof body === \"string\") message = body || fallback;\n else if (Array.isArray(body) ? body.length : isRecord(body) && Object.keys(body).length) {\n message = compactJson(body);\n } else message = fallback;\n }\n const options = { body, detail };\n if (status === 401) return new AuthenticationError(message, options);\n if (status === 429) return new RateLimitError(message, options);\n return new APIStatusError(message, status, options);\n}\n","/**\n * Client-side Private Inference wire format (byte-for-byte port of the Python\n * SDK's `pendra._private_inference`, itself a mirror of the worker's\n * internal/privinf). Seals a request body to the org workload key, decrypts the\n * worker's sealed response, and computes the opaque conversation-affinity token.\n *\n * The API only ever relays ciphertext + routing metadata; see docs/PRIVATE_INFERENCE.md.\n */\n\nimport { chacha20poly1305 } from \"@noble/ciphers/chacha.js\";\nimport { extract, expand } from \"@noble/hashes/hkdf.js\";\nimport * as hpke from \"./_hpke\";\n\nexport const ENVELOPE_KEY = \"pendra_encrypted\";\n// v2: the response key is exported from the request's own HPKE context, so only\n// a worker holding the workload key can produce a reply this client opens. v1\n// sealed replies to a cleartext response_pk the relay could seal to as well\n// (#2142); this client never sends v1 and refuses v1 replies.\nexport const ENVELOPE_VERSION = 2;\n\nconst TEXT_ENCODER = new TextEncoder();\nconst TEXT_DECODER = new TextDecoder();\n\nconst SUITE_INFO = TEXT_ENCODER.encode(\"pendra-pi-v1\");\nconst RESPONSE_EXPORT_CTX = TEXT_ENCODER.encode(\"pendra-pi-v1:rdek\");\nconst AFFINITY_SALT_INFO = TEXT_ENCODER.encode(\"pendra-affinity-salt-v1\");\n\nfunction utf8(s: string): Uint8Array {\n return TEXT_ENCODER.encode(s);\n}\n\nfunction b64(b: Uint8Array): string {\n // Node/browser-safe base64 of raw bytes (standard alphabet, padded).\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(b).toString(\"base64\");\n }\n let binary = \"\";\n for (let i = 0; i < b.length; i++) binary += String.fromCharCode(b[i]);\n // eslint-disable-next-line no-undef\n return btoa(binary);\n}\n\nfunction b64d(s: string): Uint8Array {\n if (typeof Buffer !== \"undefined\") {\n return new Uint8Array(Buffer.from(s, \"base64\"));\n }\n // eslint-disable-next-line no-undef\n const binary = atob(s);\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);\n return out;\n}\n\nfunction toHex(b: Uint8Array): string {\n return Array.from(b)\n .map((x) => x.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/** Hex SHA-256 of a raw 32-byte X25519 public key (the recipient `kid`). */\nexport function fingerprint(pub: Uint8Array): string {\n return hpke.sha256Hex(pub);\n}\n\n/**\n * Routing-metadata AAD bound to the request ciphertext (matches the worker):\n * `pendra-pi-v1 \\x00 model \\x00 stream-bit \\x00 task_type \\x00` — v1's layout\n * with its response_pk slot left empty, which v2 has no value for.\n */\nexport function buildAad(model: string, stream: boolean, taskType: string): Uint8Array {\n const streamBit = stream ? utf8(\"1\") : utf8(\"0\");\n const sep = new Uint8Array([0x00]);\n const parts = [utf8(\"pendra-pi-v1\"), utf8(model), streamBit, utf8(taskType), new Uint8Array(0)];\n let total = 0;\n for (let i = 0; i < parts.length; i++) {\n if (i > 0) total += 1;\n total += parts[i].length;\n }\n const out = new Uint8Array(total);\n let off = 0;\n for (let i = 0; i < parts.length; i++) {\n if (i > 0) {\n out.set(sep, off);\n off += 1;\n }\n out.set(parts[i], off);\n off += parts[i].length;\n }\n return out;\n}\n\n/**\n * 12-byte ChaCha20-Poly1305 nonce with a big-endian seq counter in the low\n * 8 bytes — matches the worker's response chunk framing.\n */\nexport function seqNonce(seq: number): Uint8Array {\n const nonce = new Uint8Array(12);\n // Big-endian uint64 in the low 8 bytes (bytes 4..11).\n let n = BigInt(seq);\n for (let i = 11; i >= 4; i--) {\n nonce[i] = Number(n & 0xffn);\n n >>= 8n;\n }\n return nonce;\n}\n\nexport interface Recipient {\n kid: string;\n enc: string;\n sealed_dek: string;\n}\n\nexport interface Envelope {\n v: number;\n recipients: Recipient[];\n nonce: string;\n ciphertext: string;\n affinity_key?: string;\n binary_nonce?: string;\n binary_ciphertext?: string;\n}\n\nexport interface SealOptions {\n model: string;\n stream: boolean;\n taskType: string;\n affinityKey?: string | null;\n binary?: Uint8Array | null;\n}\n\n/**\n * Seal a full request body to one or more org workload public keys.\n *\n * `orgPubs` is a single 32-byte X25519 public key, or a list of them (the org\n * may register up to a few distinct worker keys). The request body is encrypted\n * **once** under a fresh data key (DEK); that DEK is then HPKE-sealed separately\n * to each public key, producing one `recipients` entry per key. Any worker\n * holding **any** of those keys can open its matching recipient and decrypt the\n * shared DEK.\n *\n * Returns `{ envelope, responseKeys }`. `responseKeys` maps each recipient `kid`\n * to the response key exported from that recipient's HPKE context; hand it to\n * {@link ResponseDecryptor}. Place the envelope under `pendra_encrypted`\n * alongside cleartext model/stream.\n */\nexport function sealRequest(\n orgPubs: Uint8Array | Uint8Array[],\n body: Uint8Array,\n opts: SealOptions,\n): { envelope: Envelope; responseKeys: Map<string, Uint8Array> } {\n const pubs = Array.isArray(orgPubs) ? orgPubs : [orgPubs];\n if (pubs.length === 0) {\n throw new Error(\"sealRequest: no org public keys to seal to\");\n }\n // Dedupe by fingerprint, preserving order — a duplicate recipient would be\n // dead weight (the worker opens the first match either way).\n const seen = new Set<string>();\n const uniquePubs: Uint8Array[] = [];\n for (const p of pubs) {\n const fp = fingerprint(p);\n if (!seen.has(fp)) {\n seen.add(fp);\n uniquePubs.push(p);\n }\n }\n\n const dek = hpke.randomBytes(32);\n const nonce = hpke.randomBytes(12);\n const aad = buildAad(opts.model, opts.stream, opts.taskType);\n const ciphertext = chacha20poly1305(dek, nonce, aad).encrypt(body);\n\n const recipients: Recipient[] = [];\n const responseKeys = new Map<string, Uint8Array>();\n for (const pub of uniquePubs) {\n const { enc, ctx: sealer } = hpke.setupBaseS(pub, SUITE_INFO);\n const sealedDek = sealer.seal(new Uint8Array(0), dek);\n const kid = fingerprint(pub);\n responseKeys.set(kid, sealer.export(RESPONSE_EXPORT_CTX, 32));\n recipients.push({ kid, enc: b64(enc), sealed_dek: b64(sealedDek) });\n }\n\n const envelope: Envelope = {\n v: ENVELOPE_VERSION,\n recipients,\n nonce: b64(nonce),\n ciphertext: b64(ciphertext),\n };\n if (opts.affinityKey != null) {\n envelope.affinity_key = opts.affinityKey;\n }\n if (opts.binary != null) {\n const binaryNonce = hpke.randomBytes(12);\n envelope.binary_nonce = b64(binaryNonce);\n envelope.binary_ciphertext = b64(chacha20poly1305(dek, binaryNonce, aad).encrypt(opts.binary));\n }\n return { envelope, responseKeys };\n}\n\nexport interface ResponseInner {\n v?: number;\n /** Legacy v1 encapsulated key. A v2 client refuses any frame carrying it. */\n enc?: string;\n kid?: string;\n seq: number;\n ciphertext: string;\n}\n\nconst API_TRAILER_CHUNK_KEYS = new Set([\"id\", \"object\", \"created\", \"model\", \"choices\", \"pendra\"]);\nconst API_TRAILER_PENDRA_KEYS = new Set([\"timing\", \"worker\", \"request_id\"]);\n\n/**\n * Whether an unsealed frame on an encrypted stream is the API's trailer chunk:\n * empty `choices`, and under `pendra` only what the API itself knows about the\n * request — `timing`, the serving `worker` and the `request_id` — with none of\n * the fields that carry model output. The API appends it after the worker's\n * sealed chunks, so it is the one chunk that legitimately arrives unsealed.\n *\n * The placement keys are there only because the request sent\n * `X-Pendra-Placement: 1`; SDKs that don't send it get a timing-only trailer.\n * They are still checked for shape, so a relay cannot pass off something that\n * isn't placement under their names.\n */\nexport function isApiTrailerChunk(frame: unknown): boolean {\n if (frame === null || typeof frame !== \"object\" || Array.isArray(frame)) return false;\n const obj = frame as Record<string, unknown>;\n const pendra = obj.pendra;\n if (\n !Object.keys(obj).every((k) => API_TRAILER_CHUNK_KEYS.has(k)) ||\n !Array.isArray(obj.choices) ||\n obj.choices.length !== 0 ||\n pendra === null ||\n typeof pendra !== \"object\" ||\n Array.isArray(pendra)\n ) {\n return false;\n }\n const block = pendra as Record<string, unknown>;\n const keys = Object.keys(block);\n if (keys.length === 0 || !keys.every((k) => API_TRAILER_PENDRA_KEYS.has(k))) return false;\n if (\n \"worker\" in block &&\n (block.worker === null || typeof block.worker !== \"object\" || Array.isArray(block.worker))\n ) {\n return false;\n }\n if (\"request_id\" in block && typeof block.request_id !== \"string\") return false;\n return true;\n}\n\n/**\n * The error for a reply to an encrypted request that arrived without an\n * envelope. Only a worker can seal a reply, so an unsealed one could have come\n * from anyone on the path (#2142) and is refused rather than returned.\n */\nexport function unsealedReplyError(): Error {\n return new Error(\n \"private_inference: refusing an unencrypted reply to an encrypted request (it could have been forged in transit)\",\n );\n}\n\n/**\n * Request-body key, inside the sealed body, asking the worker to seal the end\n * of a private-inference stream (#2157). The relay can neither add nor strip it.\n */\nexport const STREAM_TERMINATOR_KEY = \"pendra_stream_terminator\";\n\n/**\n * Whether a decrypted frame is the worker's declaration that it will seal the\n * end of this stream. Only the first sealed frame (seq 0) may carry it.\n */\nexport function isStreamTerminatorDeclaration(plaintext: string): boolean {\n try {\n const obj = JSON.parse(plaintext) as unknown;\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n !Array.isArray(obj) &&\n Object.keys(obj).length === 1 &&\n (obj as Record<string, unknown>)[STREAM_TERMINATOR_KEY] === 1\n );\n } catch {\n return false;\n }\n}\n\n/**\n * The error for a stream the server ended before the worker's sealed `[DONE]`,\n * after the worker declared it would send one: the relay may have cut the\n * reply short (#2157).\n */\nexport function truncatedStreamError(): Error {\n return new Error(\n \"private_inference: the stream ended before the worker's sealed end-of-stream marker; the response may have been truncated in transit\",\n );\n}\n\n/**\n * Decrypts a worker's sealed response. The first frame names the `kid` the\n * worker opened; its response key (from {@link sealRequest}) decrypts every\n * frame. Refuses any frame not in v2 form and enforces a monotonic `seq` across\n * streaming chunks.\n */\nexport class ResponseDecryptor {\n private keys: Map<string, Uint8Array>;\n private dek: Uint8Array | null = null;\n private nextSeq = 0;\n\n constructor(responseKeys: Map<string, Uint8Array>) {\n this.keys = responseKeys;\n }\n\n private ensureDek(inner: ResponseInner): void {\n // A v1 reply (sealed to a key carried in the request) is exactly what a\n // relay can forge (#2142). This client sealed a v2 request, so a genuine\n // worker never sends one — refuse it rather than fall back.\n if (inner.v !== ENVELOPE_VERSION || inner.enc !== undefined) {\n throw new Error(\n \"private_inference: refusing a response that is not in v2 form (it could have been forged in transit)\",\n );\n }\n if (this.dek !== null) return;\n const dek = inner.kid === undefined ? undefined : this.keys.get(inner.kid);\n if (dek === undefined) {\n throw new Error(\"private_inference: first response frame names no key this request was sealed to\");\n }\n this.dek = dek;\n }\n\n /** Decrypt a non-streaming result envelope `{v, kid, seq, ciphertext}`. */\n openResult(inner: ResponseInner): Uint8Array {\n this.ensureDek(inner);\n return chacha20poly1305(this.dek as Uint8Array, seqNonce(Number(inner.seq))).decrypt(b64d(inner.ciphertext));\n }\n\n /** Decrypt one streaming chunk envelope, enforcing monotonic `seq`. */\n openChunk(inner: ResponseInner): Uint8Array {\n const seq = Number(inner.seq);\n if (seq !== this.nextSeq) {\n throw new Error(\n `private_inference: out-of-order response chunk (seq ${seq}, expected ${this.nextSeq})`,\n );\n }\n this.ensureDek(inner);\n // Advance seq only after a successful decrypt: a transient decrypt failure\n // then leaves the counter unchanged so a retry of the same (correct) chunk\n // isn't wrongly rejected as out-of-order.\n const pt = chacha20poly1305(this.dek as Uint8Array, seqNonce(seq)).decrypt(b64d(inner.ciphertext));\n this.nextSeq += 1;\n return pt;\n }\n}\n\n/** salt = HKDF-SHA256(ikm=utf8(apiKey), salt='', info='pendra-affinity-salt-v1', L=32). */\nexport function deriveSalt(rawApiKey: string): Uint8Array {\n // Mirror Python's HKDF (which uses an empty salt → HMAC treats it as NH zeros).\n const prk = extract(hpke.sha256, utf8(rawApiKey), new Uint8Array(32));\n return expand(hpke.sha256, prk, AFFINITY_SALT_INFO, 32);\n}\n\n/**\n * Canonical JSON matching Python's\n * `json.dumps(value, sort_keys=True, separators=(\",\",\":\"), ensure_ascii=True)`:\n * recursively sort object keys, no whitespace, and escape ALL non-ASCII code\n * units as `\\uXXXX` (per UTF-16 code unit) plus the standard escapes.\n * `JSON.stringify` does NOT match this (it emits raw non-ASCII), so we serialize\n * by hand.\n */\nexport function canonicalJson(value: unknown): string {\n if (value === null) return \"null\";\n const t = typeof value;\n if (t === \"boolean\") return value ? \"true\" : \"false\";\n if (t === \"number\") {\n // Python's json emits Infinity/NaN unquoted; mirror JSON.stringify's finite\n // handling which is what any realistic message content will carry.\n return String(value);\n }\n if (t === \"string\") return encodeString(value as string);\n if (Array.isArray(value)) {\n return \"[\" + value.map((v) => canonicalJson(v)).join(\",\") + \"]\";\n }\n if (t === \"object\") {\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n const items = keys.map((k) => encodeString(k) + \":\" + canonicalJson(obj[k]));\n return \"{\" + items.join(\",\") + \"}\";\n }\n // undefined / function / symbol shouldn't appear in message content; be safe.\n return \"null\";\n}\n\nfunction encodeString(s: string): string {\n let out = '\"';\n for (let i = 0; i < s.length; i++) {\n const code = s.charCodeAt(i); // UTF-16 code unit\n switch (code) {\n case 0x22:\n out += '\\\\\"';\n break;\n case 0x5c:\n out += \"\\\\\\\\\";\n break;\n case 0x08:\n out += \"\\\\b\";\n break;\n case 0x09:\n out += \"\\\\t\";\n break;\n case 0x0a:\n out += \"\\\\n\";\n break;\n case 0x0c:\n out += \"\\\\f\";\n break;\n case 0x0d:\n out += \"\\\\r\";\n break;\n default:\n if (code < 0x20 || code > 0x7e) {\n // Control chars and all non-ASCII (incl. each surrogate half of an\n // astral char) as \\uXXXX — matches Python's ensure_ascii=True.\n out += \"\\\\u\" + code.toString(16).padStart(4, \"0\");\n } else {\n out += s[i];\n }\n }\n }\n return out + '\"';\n}\n\nfunction flattenContent(content: unknown): string {\n if (typeof content === \"string\") return content;\n return canonicalJson(content);\n}\n\nexport interface AffinityMessage {\n role?: string;\n content?: unknown;\n}\n\n/**\n * Compute the opaque conversation-affinity token (chat only). Canonicalises\n * model + roles/content up to and including the first `user` message, then\n * HMAC-SHA256s it under a salt derived from the API key (or an explicit\n * override). Returns null when there is no user message.\n *\n * Stable across the Python and Node SDKs so KV-cache affinity survives a client\n * switching SDKs; the API treats it as opaque (no server-side recompute).\n */\nexport function affinityKey(\n rawApiKey: string,\n model: string,\n messages: AffinityMessage[] | null | undefined,\n saltOverride?: Uint8Array | null,\n): string | null {\n const parts: string[] = [\"model=\" + model];\n let sawUser = false;\n for (const m of messages ?? []) {\n const role = m.role ?? \"\";\n parts.push(role + \":\" + flattenContent(m.content));\n if (role === \"user\") {\n sawUser = true;\n break;\n }\n }\n if (!sawUser) return null;\n const salt = saltOverride != null ? saltOverride : deriveSalt(rawApiKey);\n const mac = hpke.hmac(hpke.sha256, salt, utf8(parts.join(\"\\x00\")));\n return toHex(mac);\n}\n\n/** Internal helpers exported for the resources / tests. */\nexport const _internal = { b64, b64d, utf8, TEXT_DECODER };\n","/**\n * Minimal RFC 9180 HPKE — base mode, single fixed suite:\n * DHKEM(X25519, HKDF-SHA256) + HKDF-SHA256 + ChaCha20-Poly1305.\n *\n * This is the byte-for-byte port of the Python SDK's `pendra._hpke`, itself the\n * client mirror of the worker's github.com/cloudflare/circl/hpke usage (see\n * packages/worker/internal/privinf). It implements exactly what Pendra Private\n * Inference needs — Setup(Base){S,R}, Seal/Open, and Export — and nothing else.\n * Validated against the RFC 9180 Appendix A.2 known-answer vector (see the\n * __tests__ suite), which guarantees byte-for-byte interop with circl.\n *\n * Depends on @noble/curves, @noble/ciphers, and @noble/hashes.\n */\n\nimport { x25519 } from \"@noble/curves/ed25519.js\";\nimport { chacha20poly1305 } from \"@noble/ciphers/chacha.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { hmac } from \"@noble/hashes/hmac.js\";\nimport { extract, expand } from \"@noble/hashes/hkdf.js\";\nimport { randomBytes as nobleRandomBytes } from \"@noble/hashes/utils.js\";\n\n// Fixed suite identifiers (RFC 9180 §7).\nconst KEM_ID = 0x0020; // DHKEM(X25519, HKDF-SHA256)\nconst KDF_ID = 0x0001; // HKDF-SHA256\nconst AEAD_ID = 0x0003; // ChaCha20Poly1305\n\nconst NH = 32; // HKDF-SHA256 output / exporter secret size\nconst NK = 32; // ChaCha20 key size\nconst NN = 12; // ChaCha20 nonce size\nconst NSECRET = 32; // DHKEM(X25519) shared-secret size\n\nfunction i2osp(n: number, len: number): Uint8Array {\n const out = new Uint8Array(len);\n for (let i = len - 1; i >= 0; i--) {\n out[i] = n & 0xff;\n n = Math.floor(n / 256);\n }\n return out;\n}\n\nconst TEXT_ENCODER = new TextEncoder();\n\nfunction bytes(s: string): Uint8Array {\n return TEXT_ENCODER.encode(s);\n}\n\nfunction concat(...parts: Uint8Array[]): Uint8Array {\n let total = 0;\n for (const p of parts) total += p.length;\n const out = new Uint8Array(total);\n let off = 0;\n for (const p of parts) {\n out.set(p, off);\n off += p.length;\n }\n return out;\n}\n\n// \"HPKE\" ‖ I2OSP(kem,2) ‖ I2OSP(kdf,2) ‖ I2OSP(aead,2)\nconst SUITE_ID = concat(bytes(\"HPKE\"), i2osp(KEM_ID, 2), i2osp(KDF_ID, 2), i2osp(AEAD_ID, 2));\n// \"KEM\" ‖ I2OSP(kem,2)\nconst KEM_SUITE_ID = concat(bytes(\"KEM\"), i2osp(KEM_ID, 2));\nconst HPKE_VERSION = bytes(\"HPKE-v1\");\n\nfunction hkdfExtract(salt: Uint8Array, ikm: Uint8Array): Uint8Array {\n // Mirror Python's _hkdf_extract: an empty salt becomes NH zero bytes.\n const effectiveSalt = salt.length === 0 ? new Uint8Array(NH) : salt;\n return extract(sha256, ikm, effectiveSalt);\n}\n\nfunction hkdfExpand(prk: Uint8Array, info: Uint8Array, length: number): Uint8Array {\n return expand(sha256, prk, info, length);\n}\n\nfunction labeledExtract(salt: Uint8Array, label: Uint8Array, ikm: Uint8Array, suiteId: Uint8Array): Uint8Array {\n return hkdfExtract(salt, concat(HPKE_VERSION, suiteId, label, ikm));\n}\n\nfunction labeledExpand(\n prk: Uint8Array,\n label: Uint8Array,\n info: Uint8Array,\n length: number,\n suiteId: Uint8Array,\n): Uint8Array {\n const labeledInfo = concat(i2osp(length, 2), HPKE_VERSION, suiteId, label, info);\n return hkdfExpand(prk, labeledInfo, length);\n}\n\nfunction extractAndExpand(dh: Uint8Array, kemContext: Uint8Array): Uint8Array {\n const eaePrk = labeledExtract(new Uint8Array(0), bytes(\"eae_prk\"), dh, KEM_SUITE_ID);\n return labeledExpand(eaePrk, bytes(\"shared_secret\"), kemContext, NSECRET, KEM_SUITE_ID);\n}\n\n/** DHKEM Encap → [shared_secret, enc]. `skE` injectable for known-answer tests. */\nfunction encap(pkR: Uint8Array, skE?: Uint8Array): [Uint8Array, Uint8Array] {\n const skEObj = skE ?? x25519.utils.randomSecretKey();\n const enc = x25519.getPublicKey(skEObj);\n const dh = x25519.getSharedSecret(skEObj, pkR);\n const kemContext = concat(enc, pkR);\n return [extractAndExpand(dh, kemContext), enc];\n}\n\n/** DHKEM Decap → shared_secret. */\nfunction decap(enc: Uint8Array, skR: Uint8Array): Uint8Array {\n const dh = x25519.getSharedSecret(skR, enc);\n const pkRm = x25519.getPublicKey(skR);\n const kemContext = concat(enc, pkRm);\n return extractAndExpand(dh, kemContext);\n}\n\n/**\n * An HPKE encryption context (RFC 9180 §5.2): AEAD key + base nonce +\n * monotonic sequence, plus the exporter secret.\n */\nexport class Context {\n readonly key: Uint8Array;\n readonly baseNonce: Uint8Array;\n readonly exporterSecret: Uint8Array;\n private seq = 0;\n\n constructor(key: Uint8Array, baseNonce: Uint8Array, exporterSecret: Uint8Array) {\n this.key = key;\n this.baseNonce = baseNonce;\n this.exporterSecret = exporterSecret;\n }\n\n private computeNonce(): Uint8Array {\n const seqBytes = i2osp(this.seq, NN);\n const nonce = new Uint8Array(NN);\n for (let i = 0; i < NN; i++) {\n nonce[i] = this.baseNonce[i] ^ seqBytes[i];\n }\n return nonce;\n }\n\n seal(aad: Uint8Array, pt: Uint8Array): Uint8Array {\n const ct = chacha20poly1305(this.key, this.computeNonce(), aad).encrypt(pt);\n this.seq += 1;\n return ct;\n }\n\n open(aad: Uint8Array, ct: Uint8Array): Uint8Array {\n const pt = chacha20poly1305(this.key, this.computeNonce(), aad).decrypt(ct);\n this.seq += 1;\n return pt;\n }\n\n export(exporterContext: Uint8Array, length: number): Uint8Array {\n return labeledExpand(this.exporterSecret, bytes(\"sec\"), exporterContext, length, SUITE_ID);\n }\n}\n\nfunction keySchedule(sharedSecret: Uint8Array, info: Uint8Array): Context {\n // Base mode (mode_id = 0x00), empty PSK / PSK id.\n const empty = new Uint8Array(0);\n const pskIdHash = labeledExtract(empty, bytes(\"psk_id_hash\"), empty, SUITE_ID);\n const infoHash = labeledExtract(empty, bytes(\"info_hash\"), info, SUITE_ID);\n const keyScheduleContext = concat(new Uint8Array([0x00]), pskIdHash, infoHash);\n const secret = labeledExtract(sharedSecret, bytes(\"secret\"), empty, SUITE_ID);\n const key = labeledExpand(secret, bytes(\"key\"), keyScheduleContext, NK, SUITE_ID);\n const baseNonce = labeledExpand(secret, bytes(\"base_nonce\"), keyScheduleContext, NN, SUITE_ID);\n const exporterSecret = labeledExpand(secret, bytes(\"exp\"), keyScheduleContext, NH, SUITE_ID);\n return new Context(key, baseNonce, exporterSecret);\n}\n\n/**\n * Sender setup (RFC 9180 §5.1.1). Returns { enc, ctx }. `skE` is only for\n * deterministic tests; production callers omit it for a random ephemeral key.\n */\nexport function setupBaseS(pkR: Uint8Array, info: Uint8Array, skE?: Uint8Array): { enc: Uint8Array; ctx: Context } {\n const [sharedSecret, enc] = encap(pkR, skE);\n return { enc, ctx: keySchedule(sharedSecret, info) };\n}\n\n/** Receiver setup (RFC 9180 §5.1.1). */\nexport function setupBaseR(skR: Uint8Array, enc: Uint8Array, info: Uint8Array): Context {\n const sharedSecret = decap(enc, skR);\n return keySchedule(sharedSecret, info);\n}\n\n/** Return { priv, pub } — raw 32-byte X25519 keypair. */\nexport function generateX25519Keypair(): { priv: Uint8Array; pub: Uint8Array } {\n const priv = x25519.utils.randomSecretKey();\n return { priv, pub: x25519.getPublicKey(priv) };\n}\n\nexport function x25519PublicFromPrivate(sk: Uint8Array): Uint8Array {\n return x25519.getPublicKey(sk);\n}\n\nexport function randomBytes(n: number): Uint8Array {\n return nobleRandomBytes(n);\n}\n\n/** Lowercase hex SHA-256 of the given bytes (fingerprint / TOFU identity). */\nexport function sha256Hex(data: Uint8Array): string {\n return Array.from(sha256(data))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nexport { hmac, sha256 };\n","/**\n * Turning API responses into SDK types — and failures into SDK errors.\n *\n * Both parsers live here rather than beside either consumer so the plaintext\n * and private-inference paths cannot drift apart in what they throw. They used\n * to: a stream frame that wasn't a chunk was either skipped (malformed JSON) or\n * yielded *as if it were a chunk* (an in-band `{\"error\": …}` report), and a\n * non-streaming body was cast to `ChatCompletion` without being looked at.\n *\n * Mirrors `packages/sdk-python/pendra/_parsing.py` (issues #2252, #2253).\n */\n\nimport { APIResponseValidationError, APIStreamError } from \"./errors\";\nimport { unsealedReplyError, type ResponseInner } from \"./_privateInference\";\nimport type { ChatCompletion, ChatCompletionChunk } from \"./types/chat\";\n\ninterface InBandError {\n message?: unknown;\n type?: unknown;\n code?: unknown;\n request_id?: unknown;\n worker_id?: unknown;\n worker_name?: unknown;\n}\n\nfunction asString(v: unknown): string | undefined {\n return typeof v === \"string\" ? v : undefined;\n}\n\n/**\n * Throw if `parsed` is the API reporting a failure in-band rather than a chunk.\n *\n * A streaming response commits HTTP 200 before inference starts, so a worker\n * crash, a timeout or an at-capacity rejection arrives as\n * `data: {\"error\": {…}}` and then `data: [DONE]`. `JSON.parse` succeeds on\n * that, so without this check the frame was yielded as a `ChatCompletionChunk`\n * and the caller blew up on `chunk.choices[0]` — or, with `[DONE]` right\n * behind it, simply saw the reply stop.\n */\nexport function throwIfInBandError(\n parsed: unknown,\n fallback = \"The server reported an error mid-stream\",\n): void {\n if (typeof parsed !== \"object\" || parsed === null) return;\n const err = (parsed as { error?: unknown }).error;\n if (typeof err !== \"object\" || err === null || Array.isArray(err)) return;\n const e = err as InBandError;\n throw new APIStreamError(\n asString(e.message) ?? fallback,\n {\n type: asString(e.type),\n code: typeof e.code === \"number\" ? e.code : undefined,\n requestId: asString(e.request_id),\n workerId: asString(e.worker_id),\n workerName: asString(e.worker_name),\n },\n );\n}\n\n/**\n * A chunk must carry `id`, `model` and a `choices` array.\n *\n * The API sets all three on every frame it emits, including the synthesised\n * timing, usage and notice chunks — those use `\"\"` and `[]` rather than\n * omitting the fields — so requiring them cannot reject a real chunk. The\n * Python SDK has required `id` and `model` in production for many versions,\n * which is live proof the API never omits them.\n *\n * `choices` is the one callers actually index, so checking it here is what\n * turns a would-be `TypeError` on `chunk.choices[0]` — thrown from inside the\n * caller's own loop, naming nothing useful — into an error that quotes the\n * offending frame.\n */\nfunction isChunkShaped(parsed: unknown): parsed is ChatCompletionChunk {\n if (typeof parsed !== \"object\" || parsed === null) return false;\n const c = parsed as Record<string, unknown>;\n return typeof c.id === \"string\" && typeof c.model === \"string\" && Array.isArray(c.choices);\n}\n\n/**\n * Turn one SSE `data:` payload into a chunk, or throw.\n *\n * `label` distinguishes a plaintext frame from one a private-inference stream\n * decrypted to, so the error says which stage produced the bad payload.\n */\nexport function parseStreamFrame(\n data: string,\n label: \"Stream frame\" | \"Decrypted stream frame\" = \"Stream frame\",\n): ChatCompletionChunk {\n let parsed: unknown;\n try {\n parsed = JSON.parse(data);\n } catch {\n throw new APIResponseValidationError(`${label} was not valid JSON`, { body: data });\n }\n throwIfInBandError(parsed);\n if (!isChunkShaped(parsed)) {\n throw new APIResponseValidationError(`${label} was not a chat completion chunk`, {\n body: data,\n });\n }\n return parsed;\n}\n\nfunction completionFrom(parsed: unknown, body: string, status?: number): ChatCompletion {\n if (typeof parsed !== \"object\" || parsed === null) {\n throw new APIResponseValidationError(\"Response was not a chat completion\", { status, body });\n }\n const c = parsed as Record<string, unknown>;\n if (typeof c.id !== \"string\" || typeof c.model !== \"string\" || !Array.isArray(c.choices)) {\n throw new APIResponseValidationError(\"Response was not a chat completion\", { status, body });\n }\n return parsed as ChatCompletion;\n}\n\n/**\n * Read a non-streaming completion body, or throw `APIResponseValidationError`.\n *\n * Reads the body as text first so the raw response is available for the error\n * excerpt — `response.json()` consumes the body, leaving nothing to quote when\n * it throws a bare `SyntaxError` (e.g. an HTML error page from a proxy).\n */\nexport async function parseCompletion(response: Response): Promise<ChatCompletion> {\n const body = await response.text();\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n throw new APIResponseValidationError(\"Response was not valid JSON\", {\n status: response.status,\n body,\n });\n }\n // A late failure on a slow reply, reported in-band (see readJsonReply).\n throwIfInBandError(parsed, \"The server reported an error\");\n return completionFrom(parsed, body, response.status);\n}\n\n/**\n * Read a non-streaming JSON reply, throwing the API's in-band error if it is one.\n *\n * A request that runs past the API's keep-alive threshold has its 200\n * committed before the worker finishes, so a late failure (worker error,\n * timeout, capacity) arrives as a 200 `{\"error\": {…}}` body. Resources used to\n * cast that straight to their response type and hand the caller the error\n * object as if it were a result (issue #2582). A body that isn't JSON still\n * throws the `SyntaxError` `response.json()` always did.\n */\nexport async function readJsonReply(response: Response): Promise<unknown> {\n const parsed: unknown = await response.json();\n throwIfInBandError(parsed, \"The server reported an error\");\n return parsed;\n}\n\n/** Parse the plaintext a private-inference reply decrypted to, or throw. */\nexport function parseDecryptedCompletion(json: string, status?: number): ChatCompletion {\n let parsed: unknown;\n try {\n parsed = JSON.parse(json);\n } catch {\n throw new APIResponseValidationError(\"Decrypted response was not valid JSON\", {\n status,\n body: json,\n });\n }\n try {\n return completionFrom(parsed, json, status);\n } catch {\n throw new APIResponseValidationError(\"Decrypted response was not a chat completion\", {\n status,\n body: json,\n });\n }\n}\n\n/**\n * Read a private-inference reply and return its sealed envelope, or throw —\n * along with the unsealed `pendra` block the API sets beside the envelope to\n * say which worker served the request (see `withPlacement`).\n *\n * A request that runs past the API's keep-alive threshold has its 200\n * committed before the worker finishes, so a late failure (worker error,\n * timeout, capacity) arrives as a 200 `{\"error\": {…}}` body. That is reported\n * as the API error it is rather than as a forgery: an unauthenticated error\n * carries no content, so at worst a forged one fails a request that could be\n * dropped in transit anyway. Anything else without an envelope is refused.\n */\nexport async function readSealedReply(\n response: Response,\n): Promise<{ inner: ResponseInner; placement: unknown }> {\n const body = await response.text();\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n throw new APIResponseValidationError(\"Response was not valid JSON\", {\n status: response.status,\n body,\n });\n }\n throwIfInBandError(parsed, \"The server reported an error\");\n const wrapper =\n typeof parsed === \"object\" && parsed !== null\n ? (parsed as { pendra_encrypted?: ResponseInner; pendra?: unknown })\n : undefined;\n const inner = wrapper?.pendra_encrypted;\n if (!inner) throw unsealedReplyError();\n return { inner, placement: wrapper.pendra };\n}\n\n/** Parse the JSON a private-inference reply decrypted to, or throw. */\nexport function parseDecryptedJson(json: string, status?: number): unknown {\n try {\n return JSON.parse(json);\n } catch {\n throw new APIResponseValidationError(\"Decrypted response was not valid JSON\", {\n status,\n body: json,\n });\n }\n}\n","/**\n * Which worker served a request (\"placement\"), read off an API response.\n *\n * The API reports it two ways. Every JSON body carries it in the `pendra`\n * extension block — `{\"worker\": {\"id\", \"name\"}, \"request_id\"}` — and a\n * non-streaming reply also sends the `X-Worker-Id` / `X-Worker-Name` /\n * `X-Request-Id` headers. The body is the one to trust: a request slower than\n * the API's keep-alive threshold commits its headers before any worker is\n * known, so they are missing exactly when a caller is most likely to want\n * them. The headers are only a fallback for an API older than this SDK.\n *\n * A stream reports it on its trailer chunk instead (see `Stream`), since its\n * headers go out before the request is dispatched.\n *\n * @internal\n */\n\nimport type { PendraExtension, PendraWorker } from \"./types/chat\";\n\ninterface Placement {\n worker: PendraWorker;\n request_id?: string;\n}\n\nconst UTF8_EXT_PREFIX = \"utf-8''\";\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/** A `{id, name}` worker, or `undefined` when `v` isn't one. */\nexport function parseWorker(v: unknown): PendraWorker | undefined {\n if (!isPlainObject(v) || typeof v.id !== \"string\" || !v.id) return undefined;\n return {\n id: v.id,\n name: typeof v.name === \"string\" && v.name ? v.name : null,\n version: typeof v.version === \"string\" && v.version ? v.version : null,\n };\n}\n\nfunction placementFromBlock(block: unknown): Placement | undefined {\n if (!isPlainObject(block)) return undefined;\n const worker = parseWorker(block.worker);\n if (!worker) return undefined;\n const requestId = block.request_id;\n return typeof requestId === \"string\" && requestId\n ? { worker, request_id: requestId }\n : { worker };\n}\n\n/**\n * Decode `X-Worker-Name`: plain ASCII, or RFC 8187 `UTF-8''<percent-encoded>`\n * for a name that isn't. A malformed encoding is kept as sent rather than lost.\n */\nexport function decodeWorkerNameHeader(raw: string): string {\n if (raw.slice(0, UTF8_EXT_PREFIX.length).toLowerCase() !== UTF8_EXT_PREFIX) return raw;\n try {\n return decodeURIComponent(raw.slice(UTF8_EXT_PREFIX.length));\n } catch {\n return raw;\n }\n}\n\nfunction header(headers: Headers | undefined, name: string): string | undefined {\n // Tolerate a response without real Headers (a hand-built mock, a fetch shim).\n if (!headers || typeof headers.get !== \"function\") return undefined;\n return headers.get(name) || undefined;\n}\n\n/**\n * Placement from the response headers. Needs `X-Worker-Id`: the API stamps an\n * `X-Request-Id` on every response, served by a worker or not, so on its own\n * it names no worker.\n */\nfunction placementFromHeaders(headers: Headers | undefined): Placement | undefined {\n const id = header(headers, \"X-Worker-Id\");\n if (!id) return undefined;\n const rawName = header(headers, \"X-Worker-Name\");\n const requestId = header(headers, \"X-Request-Id\");\n // There is no version header: the body block is the only place it rides.\n const worker: PendraWorker = {\n id,\n name: rawName ? decodeWorkerNameHeader(rawName) : null,\n version: null,\n };\n return requestId ? { worker, request_id: requestId } : { worker };\n}\n\n/**\n * Drop a malformed `worker` / `request_id` from a `pendra` block in place, so\n * the typed fields never hold something other than what they declare.\n */\nfunction sanitise(block: Record<string, unknown>): void {\n if (\"worker\" in block && block.worker !== null) {\n const worker = parseWorker(block.worker);\n if (worker) block.worker = worker;\n else delete block.worker;\n }\n if (\"request_id\" in block && block.request_id !== null && typeof block.request_id !== \"string\") {\n delete block.request_id;\n }\n}\n\n/**\n * Set `result.pendra.worker` / `.request_id` from the first of `blocks` that\n * names a worker, else from the response headers. Everything else already in\n * `result.pendra` (a notice, web-tool steps) is kept, and `result` is returned\n * for chaining. Non-objects pass through untouched.\n *\n * Only the placement keys are ever taken from `blocks`. On a private-inference\n * reply one of them is the unsealed sibling of the envelope, which anyone on\n * the path could have written, so it must not be able to add a notice or\n * web-tool steps to the sealed reply — only say which worker served it, which\n * the headers could claim just as well.\n */\nexport function withPlacement<T>(result: T, headers: Headers | undefined, ...blocks: unknown[]): T {\n if (!isPlainObject(result)) return result;\n const own = isPlainObject(result.pendra) ? result.pendra : undefined;\n if (own) sanitise(own);\n\n let placement: Placement | undefined;\n for (const block of blocks) {\n placement = placementFromBlock(block);\n if (placement) break;\n }\n placement ??= placementFromHeaders(headers);\n if (!placement) return result;\n\n const merged: Record<string, unknown> = { ...(own ?? {}), worker: placement.worker };\n if (placement.request_id) merged.request_id = placement.request_id;\n else delete merged.request_id;\n (result as Record<string, unknown>).pendra = merged;\n return result;\n}\n\n/**\n * The placement a stream chunk carries, if any, after dropping a malformed\n * `worker` / `request_id` from it in place.\n */\nexport function chunkPlacement(\n chunk: { pendra?: PendraExtension | null },\n): { worker?: PendraWorker; requestId?: string } {\n const block: unknown = chunk.pendra;\n if (!isPlainObject(block)) return {};\n sanitise(block);\n const worker = block.worker as PendraWorker | null | undefined;\n const requestId = block.request_id as string | null | undefined;\n return { worker: worker ?? undefined, requestId: requestId || undefined };\n}\n\n/** Request header asking for placement on a private-inference stream's trailer. */\nexport const PLACEMENT_OPT_IN_HEADER = \"X-Pendra-Placement\";\n","/**\n * Private Inference engine: resolves and caches the org workload public key\n * (TOFU by default, or an explicit pinned fingerprint), then seals requests to\n * it. Byte-for-byte port of the Python SDK's `_private_inference_engine`.\n *\n * Deliberately HTTP-agnostic — the calling resource performs the key-fetch GET\n * and hands the returned keys to `resolveOrgKey`, so all the trust logic lives\n * here in one place and is unit-testable without a network. TOFU file I/O uses a\n * dynamic `import(\"node:fs\")` so browser bundles (which require a pinned\n * fingerprint) never need it.\n */\n\nimport * as hpke from \"./_hpke\";\nimport * as pi from \"./_privateInference\";\n\nexport class PrivateInferenceError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PrivateInferenceError\";\n }\n}\n\nconst FINGERPRINT_RE = /^[0-9a-f]{64}$/;\n\n/**\n * Parse a pin (one fingerprint or a comma-separated allowlist) into a set.\n * Fails closed: a pin that names no fingerprint (`\",\"`, a blank string) or holds\n * anything other than 64-hex-char fingerprints throws, instead of silently\n * leaving the client unpinned or pinned to a value that can never match.\n */\nexport function parsePinnedFingerprints(pin: unknown): Set<string> {\n if (typeof pin !== \"string\") {\n throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);\n }\n const fps = pin\n .split(\",\")\n .map((f) => f.trim().toLowerCase())\n .filter((f) => f.length > 0);\n if (fps.length === 0) {\n throw new PrivateInferenceError(\n \"pinnedFingerprint was set but contains no fingerprint. Pass the 64-character \" +\n \"fingerprint shown in the console, or leave it unset to use automatic trust.\",\n );\n }\n const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();\n if (bad.length > 0) {\n throw new PrivateInferenceError(\n `pinnedFingerprint \"${bad[0]}\" is not a valid fingerprint: expected 64 ` +\n \"hexadecimal characters, as shown in the console.\",\n );\n }\n return new Set(fps);\n}\n\nexport interface FetchedKey {\n public_key: string;\n fingerprint?: string;\n}\n\nfunction defaultTofuPath(): string {\n const env = typeof process !== \"undefined\" ? process.env : undefined;\n if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;\n const home = env?.HOME || env?.USERPROFILE || \".\";\n // Join with \"/\" — path.join would require importing node:path eagerly.\n return `${home.replace(/\\/$/, \"\")}/.pendra/known_org_keys.json`;\n}\n\nfunction b64d(s: string): Uint8Array {\n if (typeof Buffer !== \"undefined\") return new Uint8Array(Buffer.from(s, \"base64\"));\n // eslint-disable-next-line no-undef\n const binary = atob(s);\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);\n return out;\n}\n\nexport interface EngineOptions {\n baseUrl: string;\n apiKey: string;\n pinnedFingerprint?: string | null;\n affinitySalt?: Uint8Array | null;\n tofuPath?: string | null;\n}\n\nexport class PrivateInferenceEngine {\n private baseUrl: string;\n private apiKey: string;\n // A pin is an allowlist: accept one fingerprint or a comma-separated set.\n // The client seals only to fetched keys whose fingerprint is pinned.\n private pinnedFingerprints: Set<string> | null;\n private affinitySalt: Uint8Array | null;\n private tofuPath: string;\n private orgPubs: Uint8Array[] | null = null;\n\n constructor(opts: EngineOptions) {\n this.baseUrl = opts.baseUrl.replace(/\\/$/, \"\");\n this.apiKey = opts.apiKey;\n // null / undefined mean \"not pinned\"; anything else (even \"\") must parse\n // to a valid, non-empty set (a pin must never silently turn itself off).\n const pin = opts.pinnedFingerprint;\n this.pinnedFingerprints = pin === null || pin === undefined ? null : parsePinnedFingerprints(pin);\n this.affinitySalt = opts.affinitySalt ?? null;\n this.tofuPath = opts.tofuPath || defaultTofuPath();\n }\n\n // --- key resolution ---\n\n cachedOrgPublicKeys(): Uint8Array[] | null {\n return this.orgPubs;\n }\n\n cachedOrgPublicKey(): Uint8Array | null {\n // Back-compat scalar accessor — the first resolved key, or null.\n return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;\n }\n\n private tofuIdentity(): string {\n // Key the TOFU record by (base_url, api-key hash). We never store the raw\n // key; the hash just distinguishes orgs sharing a base URL.\n const digest = hpke.sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);\n return `${this.baseUrl}|${digest}`;\n }\n\n /**\n * Drop the cached key set so the next call re-fetches it.\n *\n * The cache is otherwise held for the whole process lifetime, which is\n * correct while a fleet keeps one key but fatal when it re-keys: a\n * long-running server would go on sealing to a fingerprint no worker holds\n * and fail EVERY request until someone restarted it. The API signals a re-key\n * with `X-Pendra-Error-Code: no_private_inference_worker`, and this is what\n * lets the client recover on its own.\n *\n * Pinned clients are deliberately NOT re-fetched on that signal — a pin is an\n * allowlist, so a fetch could only return fingerprints the pin already\n * rejects. They surface the error instead, which is what pinning means.\n */\n invalidateOrgKey(): void {\n this.orgPubs = null;\n }\n\n /** Whether this client seals only to an explicit fingerprint allowlist. */\n get isPinned(): boolean {\n return this.pinnedFingerprints !== null;\n }\n\n /**\n * Validate the key(s) returned by GET /v1/private-inference/key, apply the pin\n * allowlist (or auto-trust TOFU), cache the accepted public keys, and return\n * them (newest-seen first). The client seals to **all** of the returned keys\n * so any worker holding any of them can serve the request. Throws\n * PrivateInferenceError on absence, a malformed key, or (when pinned) an empty\n * intersection with the pin set.\n */\n async resolveOrgKey(fetchedKeys: FetchedKey[]): Promise<Uint8Array[]> {\n if (this.orgPubs !== null) return this.orgPubs;\n if (!fetchedKeys || fetchedKeys.length === 0) {\n throw new PrivateInferenceError(\n \"No encryption key is registered for this organisation. Start a worker \" +\n \"and it will be issued one automatically.\",\n );\n }\n // Validate EVERY key before any trust write: recompute each fingerprint from\n // its bytes (never trust the server's claimed value), and reject a\n // wrong-length key up front so a bad key can't be persisted to TOFU and only\n // fail later inside HPKE.\n const pubs: Uint8Array[] = [];\n const fps: string[] = [];\n for (const entry of fetchedKeys) {\n let pub: Uint8Array;\n try {\n pub = b64d(entry.public_key);\n } catch (e) {\n throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);\n }\n if (pub.length !== 32) {\n throw new PrivateInferenceError(\n `Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`,\n );\n }\n pubs.push(pub);\n fps.push(pi.fingerprint(pub));\n }\n\n let accepted: Uint8Array[];\n if (this.pinnedFingerprints !== null) {\n // Pin = allowlist. Seal only to fetched keys whose fingerprint is pinned;\n // error if none of them are (nothing we're allowed to use).\n accepted = pubs.filter((_p, i) => this.pinnedFingerprints!.has(fps[i]));\n if (accepted.length === 0) {\n const pinned = Array.from(this.pinnedFingerprints).sort().join(\", \");\n throw new PrivateInferenceError(\n `None of the org's workload key fingerprints (${fps.join(\", \")}) match your ` +\n `pinned fingerprint(s) (${pinned}). Refusing to seal (possible man-in-the-middle). ` +\n \"If your fleet re-keyed — which happens when every worker goes offline at \" +\n \"once — update the pin to a current fingerprint from the console.\",\n );\n }\n } else {\n // TOFU, auto-add: trust every fingerprint the server returns, adding any\n // new ones to the store. New worker keys \"just work\"; the pin is the\n // opt-in strict path for callers who want an allowlist instead.\n await this.tofuTrust(fps);\n accepted = pubs;\n }\n\n this.orgPubs = accepted;\n return accepted;\n }\n\n private async tofuTrust(fps: string[]): Promise<void> {\n // Record every fingerprint as trusted for this identity (auto-add). No\n // rejection — a caller who wants to gate on an allowlist uses a pin.\n const store = await this.loadTofu();\n const identity = this.tofuIdentity();\n const known = store[identity];\n // Backward-compat: earlier versions stored a single fingerprint string.\n const trusted = new Set<string>();\n if (typeof known === \"string\") {\n trusted.add(known);\n } else if (Array.isArray(known)) {\n for (const f of known) if (typeof f === \"string\") trusted.add(f);\n }\n const before = trusted.size;\n for (const f of fps) trusted.add(f);\n if (trusted.size !== before || !Array.isArray(known)) {\n store[identity] = Array.from(trusted).sort();\n await this.saveTofu(store);\n }\n }\n\n private async loadTofu(): Promise<Record<string, string | string[]>> {\n try {\n const fs = await import(\"node:fs\");\n const raw = fs.readFileSync(this.tofuPath, \"utf-8\");\n const data = JSON.parse(raw);\n return data && typeof data === \"object\" && !Array.isArray(data)\n ? (data as Record<string, string | string[]>)\n : {};\n } catch {\n return {};\n }\n }\n\n private async saveTofu(store: Record<string, string | string[]>): Promise<void> {\n const fs = await import(\"node:fs\");\n const path = await import(\"node:path\");\n const directory = path.dirname(this.tofuPath) || \".\";\n fs.mkdirSync(directory, { recursive: true });\n // Write-then-rename so a crash can't leave a truncated store; 0600 since it\n // records the fingerprints a client trusts.\n const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);\n try {\n fs.writeFileSync(tmp, JSON.stringify(store), { mode: 0o600 });\n // writeFileSync's `mode` only applies when it creates the file; enforce it\n // explicitly so the final store is always 0600 regardless of prior state.\n try {\n fs.chmodSync(tmp, 0o600);\n } catch {\n /* best effort — some platforms (Windows) don't honour POSIX modes */\n }\n fs.renameSync(tmp, this.tofuPath);\n } catch (e) {\n try {\n fs.unlinkSync(tmp);\n } catch {\n /* ignore */\n }\n throw e;\n }\n }\n\n // --- sealing ---\n\n /**\n * Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.\n * `messages` (chat only) drives the affinity token; pass undefined for non-chat.\n * `binary` (audio only) is sealed under the same data key as the body.\n */\n seal(args: {\n model: string;\n stream: boolean;\n taskType: string;\n body: Uint8Array;\n messages?: pi.AffinityMessage[] | null;\n binary?: Uint8Array | null;\n }): { topLevel: Record<string, unknown>; decryptor: pi.ResponseDecryptor } {\n if (this.orgPubs === null || this.orgPubs.length === 0) {\n throw new PrivateInferenceError(\n \"private inference: org key not resolved yet (call resolveOrgKey first)\",\n );\n }\n let affinity: string | null = null;\n if (args.messages != null) {\n affinity = pi.affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);\n }\n const { envelope, responseKeys } = pi.sealRequest(this.orgPubs, args.body, {\n model: args.model,\n stream: args.stream,\n taskType: args.taskType,\n affinityKey: affinity,\n binary: args.binary ?? null,\n });\n const topLevel: Record<string, unknown> = {\n model: args.model,\n stream: args.stream,\n pendra_encrypted: envelope,\n };\n return { topLevel, decryptor: new pi.ResponseDecryptor(responseKeys) };\n }\n\n get keyFetchUrl(): string {\n return `${this.baseUrl}/v1/private-inference/key`;\n }\n}\n","import type { Pendra } from \"../../client\";\nimport { APIResponseValidationError } from \"../../errors\";\nimport type { SpeechCreateParams, SpeechResponse } from \"../../types/audio\";\nimport type { PendraExtension } from \"../../types/chat\";\nimport { throwIfInBandError } from \"../../_parsing\";\nimport { withPlacement } from \"../../_placement\";\nimport { _internal } from \"../../_privateInference\";\nimport { PrivateInferenceError } from \"../../_privateInferenceEngine\";\n\n// Standard-alphabet base64, padding optional. Checked before decoding because\n// both `Buffer.from(s, \"base64\")` and some `atob` shims skip characters they\n// don't recognise, which would turn a corrupt body into a truncated WAV rather\n// than an error.\nconst BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;\n\nfunction decodeAudio(value: unknown): Uint8Array | undefined {\n if (typeof value !== \"string\") return undefined;\n const s = value.replace(/\\s+/g, \"\");\n if (!s || !BASE64_RE.test(s) || s.replace(/=+$/, \"\").length % 4 === 1) return undefined;\n if (s.includes(\"=\") && s.length % 4 !== 0) return undefined;\n let bytes: Uint8Array;\n try {\n bytes = _internal.b64d(s);\n } catch {\n return undefined;\n }\n return bytes.length > 0 ? bytes : undefined;\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nexport class Speech {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n /**\n * Turn text into spoken audio (OpenAI-compatible).\n *\n * @example\n * ```ts\n * import { writeFileSync } from \"node:fs\";\n *\n * const speech = await client.audio.speech.create({\n * model: \"qwen3-tts\",\n * input: \"Hello from Pendra.\",\n * });\n * writeFileSync(\"speech.wav\", speech.audio);\n * ```\n */\n async create(params: SpeechCreateParams): Promise<SpeechResponse> {\n if (!params.model || typeof params.model !== \"string\") {\n throw new Error(\"model must be a non-empty string\");\n }\n if (typeof params.input !== \"string\" || !params.input.trim()) {\n throw new Error(\"input must be a non-empty string\");\n }\n\n // Refuse rather than send the text in plaintext: a caller who turned\n // private inference on expects nothing to leave the machine unencrypted.\n if (this.client.privateInferenceEnabled) {\n throw new PrivateInferenceError(\"Private inference does not support speech synthesis yet.\");\n }\n\n const body: Record<string, unknown> = { model: params.model, input: params.input };\n if (params.voice != null) body.voice = params.voice;\n if (params.response_format != null) body.response_format = params.response_format;\n\n // Asking for JSON lets the API keep a long generation alive through the\n // edge proxy, and puts the placement in the body where it always arrives.\n const headers: Record<string, string> = { Accept: \"application/json\" };\n if (params.worker_id) headers[\"X-Pendra-Worker-Id\"] = params.worker_id;\n\n // Generation time grows with the length of the input, so give it the same\n // floor as transcription; a larger client `timeout` still wins.\n const timeout = Math.max(this.client.timeout ?? 0, 300_000);\n\n const { response } = await this.client._fetch(\"/api/v1/audio/speech\", {\n method: \"POST\",\n body,\n headers,\n timeout,\n });\n\n const text = await response.text();\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new APIResponseValidationError(\"Response was not valid JSON\", {\n status: response.status,\n body: text,\n });\n }\n // A request slower than the API's keep-alive threshold has its 200\n // committed before the worker finishes, so a late failure arrives in-band.\n throwIfInBandError(parsed, \"The server reported an error\");\n if (!isRecord(parsed)) {\n throw new APIResponseValidationError(\"Response was not a speech result\", {\n status: response.status,\n body: text,\n });\n }\n\n const audio = decodeAudio(parsed.audio);\n if (!audio) {\n throw new APIResponseValidationError(\"Response did not contain decodable audio\", {\n status: response.status,\n body: text,\n });\n }\n\n const result: SpeechResponse = {\n audio,\n format:\n typeof parsed.format === \"string\" && parsed.format\n ? parsed.format\n : (params.response_format ?? \"wav\"),\n duration_ms:\n typeof parsed.duration_ms === \"number\" && Number.isFinite(parsed.duration_ms)\n ? parsed.duration_ms\n : null,\n arrayBuffer: async () => audio.slice().buffer as ArrayBuffer,\n };\n if (isRecord(parsed.pendra)) result.pendra = parsed.pendra as PendraExtension;\n return withPlacement(result, response.headers, result.pendra);\n }\n}\n","import type { Pendra } from \"../../client\";\nimport {\n APIConnectionError,\n APIResponseValidationError,\n readErrorBody,\n statusErrorFromBody,\n} from \"../../errors\";\nimport type { AudioFileInput, TranscriptionCreateParams, TranscriptionResponse } from \"../../types/audio\";\nimport { parseDecryptedJson, readJsonReply, readSealedReply } from \"../../_parsing\";\nimport { withPlacement } from \"../../_placement\";\n\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\n\n// Mirrors the API's hard cap (25MB). It also bounds the encrypted path, where\n// sealing base64-inflates the audio by ~4/3 inside a JSON body.\nconst MAX_FILE_SIZE = 25 * 1024 * 1024;\n\n// Map common audio MIME types to file extensions so multipart uploads\n// without an explicit filename still carry an extension the API can use\n// for format detection.\nconst MIME_EXT: Record<string, string> = {\n \"audio/mpeg\": \"mp3\",\n \"audio/mp3\": \"mp3\",\n \"audio/mp4\": \"m4a\",\n \"audio/x-m4a\": \"m4a\",\n \"audio/wav\": \"wav\",\n \"audio/wave\": \"wav\",\n \"audio/x-wav\": \"wav\",\n \"audio/webm\": \"webm\",\n \"audio/ogg\": \"ogg\",\n \"audio/flac\": \"flac\",\n \"audio/x-flac\": \"flac\",\n};\n\nfunction extFromMime(type: string | undefined): string | undefined {\n if (!type) return undefined;\n // Strip codec parameters (e.g. `audio/webm;codecs=opus`).\n const base = type.split(\";\")[0].trim().toLowerCase();\n return MIME_EXT[base];\n}\n\n// Name the container from the file's own header: the three the API accepts\n// (WAV, FLAC, and MP3 by its ID3 tag or first frame). Anything else has no\n// extension we can honestly give it.\nasync function extFromHeader(blob: Blob): Promise<string | undefined> {\n const head = new Uint8Array(await blob.slice(0, 12).arrayBuffer());\n const ascii = (from: number, to: number) => String.fromCharCode(...head.subarray(from, to));\n if (head.length >= 12 && ascii(0, 4) === \"RIFF\" && ascii(8, 12) === \"WAVE\") return \"wav\";\n if (head.length >= 4 && ascii(0, 4) === \"fLaC\") return \"flac\";\n if (head.length >= 3 && ascii(0, 3) === \"ID3\") return \"mp3\";\n if (head.length >= 2 && head[0] === 0xff && (head[1] & 0xe0) === 0xe0) return \"mp3\";\n return undefined;\n}\n\nasync function asBlob(file: AudioFileInput): Promise<{ blob: Blob; filename: string }> {\n if (file instanceof Blob) {\n // Browser `File` extends Blob and carries a .name. For plain Blobs\n // we derive an extension from blob.type, or failing that from the\n // file's header, so the multipart upload still carries enough info\n // for server-side format detection. A blob that is neither typed nor\n // recognisable is sent without an extension rather than called an MP3:\n // the API then answers with a clear \"unsupported format\" error.\n const asFile = file as File;\n if (asFile.name) {\n return { blob: file, filename: asFile.name };\n }\n const ext = extFromMime(file.type) ?? (await extFromHeader(file));\n return { blob: file, filename: ext ? `audio.${ext}` : \"audio\" };\n }\n const { filename, content } = file;\n if (content instanceof Blob) {\n return { blob: content, filename };\n }\n // ArrayBuffer and Uint8Array both satisfy BlobPart at runtime; the\n // explicit cast keeps strict TS dts builds happy where Uint8Array's\n // generic ArrayBufferLike parameter doesn't unify cleanly with the\n // BlobPart union.\n return { blob: new Blob([content as BlobPart]), filename };\n}\n\nexport class Transcriptions {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n async create(params: TranscriptionCreateParams): Promise<TranscriptionResponse> {\n if (!params.model) {\n throw new Error(\"model is required\");\n }\n\n // The API rejects an out-of-range beam on a plaintext upload, but can't see\n // one inside a sealed body, so check here to reject both paths alike.\n if (\n params.beam_size != null &&\n !(Number.isInteger(params.beam_size) && params.beam_size >= 1 && params.beam_size <= 8)\n ) {\n throw new Error(`beam_size must be an integer between 1 and 8 (got ${params.beam_size})`);\n }\n\n const { blob, filename } = await asBlob(params.file);\n if (blob.size === 0) {\n throw new Error(\"audio file is empty\");\n }\n if (blob.size > MAX_FILE_SIZE) {\n throw new Error(`audio file exceeds ${MAX_FILE_SIZE / (1024 * 1024)}MB limit`);\n }\n\n // Audio uploads need a higher floor than the default client timeout\n // (long files routinely take >2 min server-side), but callers who\n // explicitly pass a larger `timeout` to the client should still win.\n const timeout = Math.max(this.client.timeout ?? 0, 300_000);\n\n if (this.client.privateInferenceEnabled) {\n return this.createEncrypted(params, blob, timeout);\n }\n\n const form = new FormData();\n form.append(\"file\", blob, filename);\n form.append(\"model\", params.model);\n if (params.language) form.append(\"language\", params.language);\n if (params.prompt) form.append(\"prompt\", params.prompt);\n if (params.response_format) form.append(\"response_format\", params.response_format);\n if (params.temperature != null) form.append(\"temperature\", String(params.temperature));\n if (params.beam_size != null) form.append(\"beam_size\", String(params.beam_size));\n if (params.timestamp_granularities) {\n // FastAPI's Form(list[str]) expects repeated `field[]=value` per the\n // OpenAI convention. Each granularity is appended as its own entry.\n for (const g of params.timestamp_granularities) {\n form.append(\"timestamp_granularities[]\", g);\n }\n }\n\n // Bypass client._fetch (which JSON-stringifies) and hit fetch() directly\n // — the multipart boundary needs to live on Content-Type, which fetch\n // sets automatically when given a FormData body. Manually setting any\n // Content-Type header here would clobber that.\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n let response: Response;\n try {\n response = await fetch(`${this.client.baseURL}/api/v1/audio/transcriptions`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.client.apiKey}`,\n ...(params.worker_id ? { \"X-Pendra-Worker-Id\": params.worker_id } : {}),\n },\n body: form,\n signal: controller.signal,\n });\n } catch (err) {\n clearTimeout(timeoutId);\n if (err instanceof DOMException && err.name === \"AbortError\") {\n throw new APIConnectionError(\"Transcription request timed out\");\n }\n throw new APIConnectionError(String(err));\n }\n clearTimeout(timeoutId);\n\n if (response.status >= 400) {\n const body = await readErrorBody(response);\n throw statusErrorFromBody(response.status, body, response.statusText);\n }\n\n // Non-JSON response formats (text/srt/vtt) come back as raw text. Wrap\n // them in the response envelope so the return type stays consistent. With\n // no JSON body to carry it, their placement comes from the headers alone.\n const format = params.response_format;\n if (format === \"text\" || format === \"srt\" || format === \"vtt\") {\n const text = await response.text();\n return withPlacement({ text } as TranscriptionResponse, response.headers);\n }\n\n const result = (await readJsonReply(response)) as TranscriptionResponse;\n return withPlacement(result, response.headers, result.pendra);\n }\n\n /**\n * Private-inference transcription. There is no multipart upload: the audio\n * bytes ride inside the envelope (sealed under the request's data key) and\n * the request options are the sealed JSON body, POSTed as JSON to the same\n * route.\n */\n private async createEncrypted(\n params: TranscriptionCreateParams,\n blob: Blob,\n timeout: number,\n ): Promise<TranscriptionResponse> {\n const body: Record<string, unknown> = { model: params.model };\n if (params.language) body.language = params.language;\n if (params.prompt) body.prompt = params.prompt;\n if (params.response_format) body.response_format = params.response_format;\n if (params.temperature != null) body.temperature = params.temperature;\n if (params.beam_size != null) body.beam_size = params.beam_size;\n if (params.timestamp_granularities) {\n body.timestamp_granularities = params.timestamp_granularities;\n }\n\n const engine = await this.client._privateEngine();\n const { topLevel, decryptor } = engine.seal({\n model: params.model,\n stream: false,\n taskType: \"transcription\",\n body: ENCODER.encode(JSON.stringify(body)),\n binary: new Uint8Array(await blob.arrayBuffer()),\n });\n const { response } = await this.client._fetch(\n \"/api/v1/audio/transcriptions\",\n {\n method: \"POST\",\n body: topLevel,\n headers: params.worker_id ? { \"X-Pendra-Worker-Id\": params.worker_id } : undefined,\n timeout,\n },\n );\n // The worker JSON-encodes the sealed result: json/verbose_json decrypt to\n // an object, text/srt/vtt to a JSON string. Wrap the string in the same\n // `{ text }` envelope the plaintext path returns.\n const { inner, placement } = await readSealedReply(response);\n const raw = DECODER.decode(decryptor.openResult(inner));\n const parsed = parseDecryptedJson(raw, response.status);\n const place = (r: TranscriptionResponse) =>\n withPlacement(r, response.headers, r.pendra, placement);\n if (typeof parsed === \"string\") return place({ text: parsed });\n if (typeof parsed === \"object\" && parsed !== null) {\n if (typeof (parsed as TranscriptionResponse).text !== \"string\") {\n throw new APIResponseValidationError(\"Decrypted response was not a transcription\", {\n status: response.status,\n body: raw,\n });\n }\n return place(parsed as TranscriptionResponse);\n }\n // A plain-text transcript that happens to be valid JSON on its own (e.g.\n // \"42\\n\") reaches us unwrapped, so fall back to the raw plaintext.\n return place({ text: raw });\n }\n}\n","import type { Pendra } from \"../../client\";\nimport { Speech } from \"./speech\";\nimport { Transcriptions } from \"./transcriptions\";\n\nexport class Audio {\n transcriptions: Transcriptions;\n speech: Speech;\n\n constructor(client: Pendra) {\n this.transcriptions = new Transcriptions(client);\n this.speech = new Speech(client);\n }\n}\n","/**\n * Minimal server-sent-events frame decoder.\n *\n * Streaming responses are a sequence of *frames*, not a sequence of lines: a\n * frame is one or more field lines terminated by a blank line, and a `data:`\n * line belongs to whichever `event:` precedes it in the same frame.\n *\n * Reading line-by-line instead — filtering for `data:` and treating every hit\n * as a chat chunk — silently mis-parses any named event the server sends: the\n * `event:` line is skipped and *its* `data:` line is then parsed as a chunk.\n * That is the bug this module exists to prevent (Pendra issue #1398).\n *\n * Only frames belonging to the default event are emitted: no `event:` field, or\n * `event: message`. Anything else is a named event this SDK doesn't model, and\n * is dropped whole.\n */\n\n/** Field value for the default event type. */\nconst DEFAULT_EVENT = \"message\";\n\n/**\n * Strip a field name and its separator off a line.\n *\n * Per the spec the separator is a colon optionally followed by a *single*\n * space, so both `data: {…}` and `data:{…}` are valid and carry the same value.\n * Further leading spaces are part of the value and are preserved.\n */\nfunction fieldValue(line: string, name: string): string {\n const value = line.slice(name.length + 1);\n return value.startsWith(\" \") ? value.slice(1) : value;\n}\n\n/**\n * Incremental SSE decoder. Feed it decoded text with `push()` and it returns\n * the data payload of every complete default-event frame, in order.\n */\nexport class SseDecoder {\n private buffer = \"\";\n private event = \"\";\n private data: string[] = [];\n\n /** Feed a chunk of decoded text; returns the payloads it completed. */\n push(text: string): string[] {\n this.buffer += text;\n const lines = this.buffer.split(\"\\n\");\n // The trailing element is whatever follows the last newline — an\n // incomplete line, held back until more bytes arrive.\n this.buffer = lines.pop() ?? \"\";\n\n const out: string[] = [];\n for (const line of lines) {\n const payload = this.pushLine(line);\n if (payload !== null) out.push(payload);\n }\n return out;\n }\n\n /**\n * Release what the stream ended without terminating: the held-back partial\n * line, plus any frame that never got its blank line.\n *\n * The spec discards an unterminated final block; we keep it, so a connection\n * that drops after the last `data:` line but before its blank line still\n * delivers that payload rather than silently losing it.\n */\n flush(): string[] {\n const out: string[] = [];\n if (this.buffer !== \"\") {\n const payload = this.pushLine(this.buffer);\n this.buffer = \"\";\n if (payload !== null) out.push(payload);\n }\n const tail = this.endFrame();\n if (tail !== null) out.push(tail);\n return out;\n }\n\n private pushLine(rawLine: string): string | null {\n const line = rawLine.endsWith(\"\\r\") ? rawLine.slice(0, -1) : rawLine;\n if (line === \"\") return this.endFrame();\n if (line.startsWith(\":\")) return null; // comment / keep-alive\n if (line.startsWith(\"event:\")) {\n this.event = fieldValue(line, \"event\");\n return null;\n }\n if (line.startsWith(\"data:\")) {\n this.data.push(fieldValue(line, \"data\"));\n return null;\n }\n // Any other field (`id:`, `retry:`, or an unknown one) is ignored per the\n // spec — but it must not reset the frame being accumulated.\n return null;\n }\n\n private endFrame(): string | null {\n const { data, event } = this;\n this.data = [];\n this.event = \"\";\n if (data.length === 0) return null;\n if (event !== \"\" && event !== DEFAULT_EVENT) return null;\n // Multiple data lines in one frame join with a newline.\n return data.join(\"\\n\");\n }\n}\n","import { APIConnectionError } from \"./errors\";\nimport { parseStreamFrame } from \"./_parsing\";\nimport { SseDecoder } from \"./_sse\";\nimport { chunkPlacement } from \"./_placement\";\nimport type { ChatCompletionChunk, PendraWorker } from \"./types/chat\";\n\n/**\n * Async-iterable reader for a streaming chat completion.\n *\n * Framing is handled by {@link SseDecoder}, which assembles whole SSE frames\n * rather than filtering lines — so a frame the server tags with a named\n * `event:` is dropped in one piece instead of having its `data:` line mistaken\n * for a chat chunk (issue #1398).\n *\n * Each surviving frame goes through {@link parseStreamFrame}, which throws on\n * the API's in-band `{\"error\": …}` failure reports and on a frame that isn't a\n * chunk. The error frames used to be yielded *as* chunks (`JSON.parse` succeeds\n * on them), so a worker crash surfaced as a `TypeError` on `chunk.choices[0]`\n * rather than as something a caller could catch and read (issue #2252).\n *\n * `idleTimeoutMs` bounds the gap between reads, not the whole stream: the API\n * sends a keep-alive comment every 15 s, so a healthy stream never goes quiet\n * for long however long it runs, while a stalled one fails with an\n * `APIConnectionError` rather than hanging (#2185). Leaving the loop before the\n * stream ends — a `break`, or a frame that throws — aborts the request, so the\n * connection is released and the worker stops generating tokens nobody will\n * read (#2216).\n *\n * The worker that served the stream is reported on its trailer chunk, the last\n * one before `[DONE]` — `stream.worker` and `stream.requestId` hold it once\n * that chunk has been iterated.\n */\nexport class Stream implements AsyncIterable<ChatCompletionChunk> {\n private reader: ReadableStreamDefaultReader<Uint8Array>;\n private decoder = new TextDecoder();\n private sse = new SseDecoder();\n private done = false;\n private controller: AbortController;\n private placement = new PlacementTracker();\n\n private idleTimeoutMs: number | undefined;\n\n constructor(response: Response, controller: AbortController, idleTimeoutMs?: number) {\n if (!response.body) {\n throw new Error(\"Response body is null — streaming not supported\");\n }\n this.reader = response.body.getReader();\n this.controller = controller;\n this.idleTimeoutMs = idleTimeoutMs;\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk> {\n try {\n while (!this.done) {\n const { value, done: readerDone } = await readWithIdleTimeout(\n this.reader,\n this.idleTimeoutMs,\n );\n\n const payloads = readerDone\n ? this.sse.flush()\n : this.sse.push(this.decoder.decode(value, { stream: true }));\n\n for (const data of payloads) {\n if (data === \"[DONE]\") {\n this.done = true;\n return;\n }\n yield this.placement.observe(parseStreamFrame(data));\n }\n\n if (readerDone) {\n this.done = true;\n break;\n }\n }\n } finally {\n releaseReader(this.reader, this.controller, this.done);\n }\n }\n\n /**\n * The worker that served this stream, or `null` until the chunk reporting it\n * — the trailer, just before `[DONE]` — has been iterated (and on an API too\n * old to report it). Same as that chunk's `pendra.worker`.\n */\n get worker(): PendraWorker | null {\n return this.placement.worker;\n }\n\n /**\n * Pendra's id for this request, reported alongside {@link Stream.worker};\n * `null` until then.\n */\n get requestId(): string | null {\n return this.placement.requestId;\n }\n\n abort(): void {\n this.done = true;\n this.controller.abort();\n }\n}\n\n/**\n * Remembers the placement a stream's chunks report, for the `worker` /\n * `requestId` getters. Shared with the private-inference stream.\n *\n * @internal\n */\nexport class PlacementTracker {\n worker: PendraWorker | null = null;\n requestId: string | null = null;\n\n /** Record `chunk`'s placement, if it carries any, and hand it back. */\n observe(chunk: ChatCompletionChunk): ChatCompletionChunk {\n const { worker, requestId } = chunkPlacement(chunk);\n if (worker) this.worker = worker;\n if (requestId) this.requestId = requestId;\n return chunk;\n }\n}\n\n/**\n * `reader.read()`, failing with an `APIConnectionError` if nothing arrives\n * within `idleTimeoutMs`. The caller's `finally` then aborts the request.\n *\n * @internal\n */\nexport async function readWithIdleTimeout(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n idleTimeoutMs: number | undefined,\n): ReturnType<ReadableStreamDefaultReader<Uint8Array>[\"read\"]> {\n if (!idleTimeoutMs) return reader.read();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const idle = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new APIConnectionError(`Stream received no data for ${idleTimeoutMs}ms`)),\n idleTimeoutMs,\n );\n });\n try {\n return await Promise.race([reader.read(), idle]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * End a stream's read loop. One that stopped before the server finished — the\n * consumer broke out, or a frame threw — aborts the request and cancels the\n * body rather than leaving the connection open.\n *\n * @internal\n */\nexport function releaseReader(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n controller: AbortController,\n finished: boolean,\n): void {\n if (!finished) {\n controller.abort();\n reader.cancel().catch(() => {});\n }\n reader.releaseLock();\n}\n","import { APIResponseValidationError } from \"./errors\";\nimport { parseStreamFrame } from \"./_parsing\";\nimport { SseDecoder } from \"./_sse\";\nimport { PlacementTracker, readWithIdleTimeout, releaseReader } from \"./streaming\";\nimport type { ChatCompletionChunk, PendraWorker } from \"./types/chat\";\nimport {\n isApiTrailerChunk,\n isStreamTerminatorDeclaration,\n truncatedStreamError,\n unsealedReplyError,\n type ResponseDecryptor,\n type ResponseInner,\n} from \"./_privateInference\";\n\nconst DECODER = new TextDecoder();\n\n/**\n * A private-inference variant of `Stream` for encrypted chat streaming. Each\n * SSE `data:` payload carries `{\"pendra_encrypted\":{…,\"seq\":N,\"ciphertext\":\"…\"}}`;\n * we decrypt it (enforcing monotonic seq) back to the original chunk JSON and\n * yield the parsed chunk.\n *\n * Framing is {@link SseDecoder}'s job, shared with the plaintext `Stream`. The\n * worker seals only the payload after `data: ` and leaves the framing intact,\n * so a sealed stream is framed exactly like a plaintext one — including that a\n * named `event:` frame is dropped whole rather than mistaken for a chunk\n * (issue #1398). The idle timeout and early-exit abort also match `Stream`\n * (#2185, #2216).\n *\n * The request asks the worker to seal the end of the stream (#2157). A worker\n * that does so declares it in its first sealed frame and seals `[DONE]` as its\n * last. Once the declaration has been seen, a stream the server ends without\n * the sealed `[DONE]` — a plaintext `[DONE]` or the body closing — throws, since\n * the relay may have cut the reply short. After the sealed `[DONE]` only the\n * API's trailer chunk may follow, and a stall is a clean end: the reply is\n * already known to be complete. A worker too old to declare it leaves the\n * stream checked as before, except that a stream with no sealed frame at all\n * is refused either way: every worker seals at least one frame on a chat reply\n * that succeeds, so an empty one could only mean the relay dropped them all.\n * Stopping early (`break`, `abort()`) never throws this error.\n */\nexport class EncryptedStream implements AsyncIterable<ChatCompletionChunk> {\n private reader: ReadableStreamDefaultReader<Uint8Array>;\n private decoder = new TextDecoder();\n private sse = new SseDecoder();\n private done = false;\n private controller: AbortController;\n private decryptor: ResponseDecryptor;\n private aborted = false;\n private openedAny = false;\n private declared = false;\n private terminated = false;\n private placement = new PlacementTracker();\n\n private idleTimeoutMs: number | undefined;\n\n constructor(\n response: Response,\n controller: AbortController,\n decryptor: ResponseDecryptor,\n idleTimeoutMs?: number,\n ) {\n if (!response.body) {\n throw new Error(\"Response body is null — streaming not supported\");\n }\n this.reader = response.body.getReader();\n this.controller = controller;\n this.decryptor = decryptor;\n this.idleTimeoutMs = idleTimeoutMs;\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk> {\n try {\n while (!this.done) {\n let read: Awaited<ReturnType<typeof readWithIdleTimeout>>;\n try {\n read = await readWithIdleTimeout(this.reader, this.idleTimeoutMs);\n } catch (e) {\n // The reply is already complete; a relay holding the connection open\n // after it is not a failure. Returning with `done` unset still aborts\n // the request in `finally`.\n if (this.terminated) return;\n throw e;\n }\n const { value, done: readerDone } = read;\n\n const payloads = readerDone\n ? this.sse.flush()\n : this.sse.push(this.decoder.decode(value, { stream: true }));\n\n for (const data of payloads) {\n if (data === \"[DONE]\") {\n this.checkEnded();\n this.done = true;\n return;\n }\n\n // A frame that isn't an encrypted envelope is legitimate only when the\n // API added it, after the worker was already out of the picture: an\n // in-band failure report, which parseStreamFrame throws on (issue\n // #2252), or the trailer chunk carrying timings and placement. Anything else unsealed on an\n // encrypted stream is content nobody can vouch for — a relay could\n // inject it (#2142) — so it is refused, never yielded.\n let frame: { pendra_encrypted?: ResponseInner };\n try {\n frame = JSON.parse(data) as { pendra_encrypted?: ResponseInner };\n } catch {\n // A partial last line released at EOF: the connection was cut\n // mid-frame. After the sealed [DONE] the reply is complete anyway;\n // before it, that is a truncation, not a parse error to retry.\n // The consumer already left via abort(): nothing it will read.\n if (this.aborted) continue;\n if (readerDone) {\n if (this.terminated) continue;\n this.checkEnded();\n }\n throw new APIResponseValidationError(\"Stream frame was not valid JSON\", {\n body: data,\n });\n }\n const inner = frame?.pendra_encrypted;\n if (!inner) {\n if (isApiTrailerChunk(frame)) {\n // The API sends it only once the worker's stream has ended, so\n // the same end-of-stream check applies here.\n this.checkEnded();\n yield this.placement.observe(parseStreamFrame(data));\n continue;\n }\n parseStreamFrame(data);\n // An integrity failure, like a chunk that fails to decrypt — not a\n // parse error that invites a blind retry.\n throw unsealedReplyError();\n }\n if (this.terminated) {\n throw new Error(\n \"private_inference: refusing a frame after the worker's sealed end of stream\",\n );\n }\n const plain = this.decryptor.openChunk(inner);\n const chunkJson = DECODER.decode(plain).trim();\n const first = !this.openedAny;\n this.openedAny = true;\n if (first && isStreamTerminatorDeclaration(chunkJson)) {\n this.declared = true;\n continue;\n }\n if (chunkJson === \"[DONE]\") {\n if (this.declared) {\n // Keep reading: the API's trailer chunk and its [DONE] follow.\n this.terminated = true;\n continue;\n }\n this.done = true;\n return;\n }\n if (!chunkJson) continue;\n yield this.placement.observe(parseStreamFrame(chunkJson, \"Decrypted stream frame\"));\n }\n\n if (readerDone) {\n this.checkEnded();\n this.done = true;\n break;\n }\n }\n } finally {\n releaseReader(this.reader, this.controller, this.done);\n }\n }\n\n /**\n * The server ended the stream: it must have carried a sealed frame, and after\n * a declaration, it must have ended on the sealed `[DONE]`.\n */\n private checkEnded(): void {\n if (this.aborted) return;\n if (!this.openedAny || (this.declared && !this.terminated)) {\n throw truncatedStreamError();\n }\n }\n\n /** Same as `Stream.worker`: set once the trailer chunk has been iterated. */\n get worker(): PendraWorker | null {\n return this.placement.worker;\n }\n\n /** Same as `Stream.requestId`. */\n get requestId(): string | null {\n return this.placement.requestId;\n }\n\n abort(): void {\n this.aborted = true;\n this.done = true;\n this.controller.abort();\n }\n}\n","import type { Pendra } from \"../../client\";\nimport type {\n ChatCompletion,\n ChatCompletionCreateParams,\n} from \"../../types/chat\";\nimport { parseCompletion, parseDecryptedCompletion, readSealedReply } from \"../../_parsing\";\nimport { Stream } from \"../../streaming\";\nimport { EncryptedStream } from \"../../_privateStreaming\";\nimport { STREAM_TERMINATOR_KEY } from \"../../_privateInference\";\nimport { PLACEMENT_OPT_IN_HEADER, withPlacement } from \"../../_placement\";\n\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\n\nexport class Completions {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n create(\n params: ChatCompletionCreateParams & { stream: true },\n ): Promise<Stream>;\n create(\n params: ChatCompletionCreateParams & { stream?: false },\n ): Promise<ChatCompletion>;\n create(\n params: ChatCompletionCreateParams,\n ): Promise<ChatCompletion | Stream>;\n async create(\n params: ChatCompletionCreateParams,\n ): Promise<ChatCompletion | Stream> {\n // Forward everything the caller passed rather than copying a fixed list of\n // fields. The API models chat with `extra=\"allow\"` and hands anything it\n // doesn't recognise to the worker, so an allowlist here meant a documented\n // parameter the SDK hadn't caught up with (enable_thinking,\n // reasoning_effort, response_format, ...) was silently dropped on the floor\n // — a request that quietly did something else instead of failing (#1865).\n // `worker_id` is the one exception: it's a routing directive we send as a\n // header, not a body field. Null/undefined values are omitted so an\n // explicitly-unset option doesn't reach the API as a null it would reject.\n const { worker_id: _workerId, ...rest } = params;\n const body: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rest)) {\n if (value != null) body[key] = value;\n }\n\n const headers: Record<string, string> = {};\n if (params.worker_id) headers[\"X-Pendra-Worker-Id\"] = params.worker_id;\n // A stream reports its worker on the trailer chunk. The API always adds it\n // to a plaintext stream, but on a private-inference one only when asked:\n // SDKs that predate it refuse any unsealed trailer carrying more than\n // timings. Sent on both, so the two paths build the same request.\n if (params.stream) headers[PLACEMENT_OPT_IN_HEADER] = \"1\";\n\n if (this.client.privateInferenceEnabled) {\n return this.createEncrypted(params, body, headers);\n }\n\n if (params.stream) {\n const { response, controller } = await this.client._fetch(\n \"/api/v1/chat/completions\",\n { method: \"POST\", body, headers },\n );\n return new Stream(response, controller, this.client.timeout);\n }\n\n const { response } = await this.client._fetch(\n \"/api/v1/chat/completions\",\n { method: \"POST\", body, headers },\n );\n // Not a bare cast: a 200 whose body is missing `id` — or an HTML error page\n // from a proxy — used to sail through as a `ChatCompletion` with undefined\n // fields, or throw a raw `SyntaxError` with nothing to quote (issue #2253).\n const completion = await parseCompletion(response);\n return withPlacement(completion, response.headers, completion.pendra);\n }\n\n private async createEncrypted(\n params: ChatCompletionCreateParams,\n body: Record<string, unknown>,\n headers: Record<string, string>,\n ): Promise<ChatCompletion | Stream> {\n const engine = await this.client._privateEngine();\n const stream = Boolean(params.stream);\n const { topLevel, decryptor } = engine.seal({\n model: params.model,\n stream,\n taskType: \"chat\",\n // The terminator request rides inside the sealed body, so the relay can\n // neither strip nor add it: it asks the worker to seal the end of the\n // stream (#2157).\n body: ENCODER.encode(JSON.stringify(stream ? { ...body, [STREAM_TERMINATOR_KEY]: 1 } : body)),\n messages: params.messages,\n });\n\n if (stream) {\n const { response, controller } = await this.client._fetch(\n \"/api/v1/chat/completions\",\n { method: \"POST\", body: topLevel, headers },\n );\n // EncryptedStream is a drop-in AsyncIterable<ChatCompletionChunk>, same as Stream.\n return new EncryptedStream(response, controller, decryptor, this.client.timeout) as unknown as Stream;\n }\n\n const { response } = await this.client._fetch(\n \"/api/v1/chat/completions\",\n { method: \"POST\", body: topLevel, headers },\n );\n // A late failure arrives in-band, unsealed; readSealedReply raises it.\n const { inner, placement } = await readSealedReply(response);\n // The decrypt stays outside the parsing helpers: a ciphertext-integrity\n // failure must keep propagating distinctly rather than being flattened into\n // a parse error that invites a blind retry.\n const plain = decryptor.openResult(inner);\n const completion = parseDecryptedCompletion(DECODER.decode(plain), response.status);\n // Placement is the API's to report, so it rides beside the envelope rather\n // than inside it; the sealed reply keeps its own notice.\n return withPlacement(completion, response.headers, completion.pendra, placement);\n }\n}\n","import type { Pendra } from \"../../client\";\nimport { Completions } from \"./completions\";\n\nexport class Chat {\n completions: Completions;\n\n constructor(client: Pendra) {\n this.completions = new Completions(client);\n }\n}\n","import type { Pendra } from \"../client\";\nimport type {\n CreateEmbeddingResponse,\n EmbeddingCreateParams,\n} from \"../types/embeddings\";\nimport { readJsonReply, readSealedReply } from \"../_parsing\";\nimport { withPlacement } from \"../_placement\";\n\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\n\nfunction validateParams(params: EmbeddingCreateParams): void {\n if (!params.model || typeof params.model !== \"string\") {\n throw new Error(\"model must be a non-empty string\");\n }\n const { input } = params;\n if (typeof input === \"string\") {\n if (input.length === 0) {\n throw new Error(\"input must be a non-empty string or non-empty array of strings\");\n }\n return;\n }\n if (Array.isArray(input)) {\n if (input.length === 0) {\n throw new Error(\"input must be a non-empty string or non-empty array of strings\");\n }\n if (!input.every((s) => typeof s === \"string\" && s.length > 0)) {\n throw new Error(\"input array entries must all be non-empty strings\");\n }\n return;\n }\n throw new Error(\"input must be a string or an array of strings\");\n}\n\nexport class Embeddings {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n /**\n * Create embeddings for the given input.\n *\n * @example\n * ```ts\n * const result = await client.embeddings.create({\n * model: \"nomic-embed-text:latest\",\n * input: \"Hello world\",\n * });\n * console.log(result.data[0].embedding);\n * ```\n */\n async create(params: EmbeddingCreateParams): Promise<CreateEmbeddingResponse> {\n validateParams(params);\n\n const body: Record<string, unknown> = {\n model: params.model,\n input: params.input,\n };\n if (params.encoding_format != null) body.encoding_format = params.encoding_format;\n if (params.dimensions != null) body.dimensions = params.dimensions;\n if (params.user != null) body.user = params.user;\n\n const headers = params.worker_id ? { \"X-Pendra-Worker-Id\": params.worker_id } : undefined;\n\n if (this.client.privateInferenceEnabled) {\n return this.createEncrypted(params.model, body, headers);\n }\n\n const { response } = await this.client._fetch(\n \"/api/v1/embeddings\",\n { method: \"POST\", body, headers },\n );\n const result = (await readJsonReply(response)) as CreateEmbeddingResponse;\n return withPlacement(result, response.headers, result.pendra);\n }\n\n private async createEncrypted(\n model: string,\n body: Record<string, unknown>,\n headers: Record<string, string> | undefined,\n ): Promise<CreateEmbeddingResponse> {\n const engine = await this.client._privateEngine();\n // Embeddings are never streamed and carry no affinity messages.\n const { topLevel, decryptor } = engine.seal({\n model,\n stream: false,\n taskType: \"embeddings\",\n body: ENCODER.encode(JSON.stringify(body)),\n });\n const { response } = await this.client._fetch(\n \"/api/v1/embeddings\",\n { method: \"POST\", body: topLevel, headers },\n );\n // A late failure arrives in-band, unsealed; readSealedReply raises it.\n const { inner, placement } = await readSealedReply(response);\n const plain = decryptor.openResult(inner);\n const result = JSON.parse(DECODER.decode(plain)) as CreateEmbeddingResponse;\n // Placement rides unsealed beside the envelope (see withPlacement).\n return withPlacement(result, response.headers, result.pendra, placement);\n }\n}\n","import type { Pendra } from \"../../client\";\nimport { APIResponseValidationError } from \"../../errors\";\nimport type { ImageGenerationCreateParams, ImageResponse } from \"../../types/images\";\nimport { parseDecryptedJson, readJsonReply, readSealedReply } from \"../../_parsing\";\nimport { withPlacement } from \"../../_placement\";\n\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\n\nconst SIZE_RE = /^\\d+x\\d+$/;\n\nfunction validateParams(params: ImageGenerationCreateParams): void {\n if (!params.prompt || !params.prompt.trim()) {\n throw new Error(\"prompt must be a non-empty string\");\n }\n if (params.n != null && (params.n < 1 || params.n > 4)) {\n throw new Error(\"n must be between 1 and 4\");\n }\n if (params.size != null && !SIZE_RE.test(params.size)) {\n throw new Error(\"size must be in the form WIDTHxHEIGHT (e.g. '1024x1024')\");\n }\n}\n\nexport class Generations {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n async create(params: ImageGenerationCreateParams): Promise<ImageResponse> {\n validateParams(params);\n\n const body: Record<string, unknown> = {\n model: params.model,\n prompt: params.prompt,\n };\n\n if (params.n != null) body.n = params.n;\n if (params.size != null) body.size = params.size;\n if (params.response_format != null) body.response_format = params.response_format;\n if (params.num_inference_steps != null) body.num_inference_steps = params.num_inference_steps;\n if (params.seed != null) body.seed = params.seed;\n if (params.negative_prompt != null) body.negative_prompt = params.negative_prompt;\n\n const headers = params.worker_id ? { \"X-Pendra-Worker-Id\": params.worker_id } : undefined;\n\n if (this.client.privateInferenceEnabled) {\n return this.createEncrypted(params.model, body, headers);\n }\n\n const { response } = await this.client._fetch(\n \"/api/v1/images/generations\",\n { method: \"POST\", body, headers },\n );\n const result = (await readJsonReply(response)) as ImageResponse;\n return withPlacement(result, response.headers, result.pendra);\n }\n\n private async createEncrypted(\n model: string,\n body: Record<string, unknown>,\n headers: Record<string, string> | undefined,\n ): Promise<ImageResponse> {\n const engine = await this.client._privateEngine();\n // Image generation is never streamed and carries no affinity messages.\n const { topLevel, decryptor } = engine.seal({\n model,\n stream: false,\n taskType: \"image_generation\",\n body: ENCODER.encode(JSON.stringify(body)),\n });\n const { response } = await this.client._fetch(\n \"/api/v1/images/generations\",\n { method: \"POST\", body: topLevel, headers },\n );\n const { inner, placement } = await readSealedReply(response);\n const plain = decryptor.openResult(inner);\n const parsed = parseDecryptedJson(DECODER.decode(plain), response.status);\n if (typeof parsed !== \"object\" || parsed === null || !Array.isArray((parsed as ImageResponse).data)) {\n throw new APIResponseValidationError(\"Decrypted response was not an image generation\", {\n status: response.status,\n body: DECODER.decode(plain),\n });\n }\n const result = parsed as ImageResponse;\n return withPlacement(result, response.headers, result.pendra, placement);\n }\n}\n","import type { Pendra } from \"../../client\";\nimport { Generations } from \"./generations\";\n\nexport class Images {\n generations: Generations;\n\n constructor(client: Pendra) {\n this.generations = new Generations(client);\n }\n}\n","import type { Pendra } from \"../client\";\nimport type { Model } from \"../types/models\";\n\nexport class Models {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n async list(): Promise<Model[]> {\n const { response } = await this.client._fetch(\"/api/v1/models\", {\n method: \"GET\",\n });\n const data = (await response.json()) as { data: Model[] };\n return data.data;\n }\n}\n","import type { Pendra } from \"../client\";\nimport type {\n ModerationCreateParams,\n ModerationResponse,\n} from \"../types/moderations\";\nimport { APIResponseValidationError } from \"../errors\";\nimport { parseDecryptedJson, readJsonReply, readSealedReply } from \"../_parsing\";\nimport { withPlacement } from \"../_placement\";\n\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\n\n/** Most inputs one request may carry (the endpoint's limit). */\nconst MAX_INPUTS = 32;\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nfunction validatePart(part: unknown): void {\n if (!isPlainObject(part)) {\n throw new Error(\"input can't mix strings and parts\");\n }\n if (part.type === \"text\") {\n if (typeof part.text !== \"string\" || part.text.length === 0) {\n throw new Error(\"a text part needs a non-empty text\");\n }\n return;\n }\n if (part.type === \"image_url\") {\n const url = isPlainObject(part.image_url) ? part.image_url.url : undefined;\n if (typeof url !== \"string\" || url.length === 0) {\n throw new Error(\"an image_url part needs image_url.url\");\n }\n return;\n }\n throw new Error(\"parts must be of type text or image_url\");\n}\n\n/**\n * The endpoint's input rules, checked here so an encrypted request (which the\n * server can't read to validate) fails the same way as a plaintext one.\n */\nfunction validateParams(params: ModerationCreateParams): void {\n if (!params.model || typeof params.model !== \"string\") {\n throw new Error(\"model must be a non-empty string\");\n }\n const input: unknown = params.input;\n if (typeof input === \"string\") {\n if (input.length === 0) throw new Error(\"input must be a non-empty string\");\n return;\n }\n if (!Array.isArray(input)) {\n throw new Error(\"input must be a string, an array of strings, or an array of text and image_url parts\");\n }\n if (input.length === 0 || input.length > MAX_INPUTS) {\n throw new Error(`input must hold 1 to ${MAX_INPUTS} items`);\n }\n if (input.every((i) => typeof i === \"string\")) {\n if (!input.every((s: string) => s.length > 0)) {\n throw new Error(\"input strings must be non-empty\");\n }\n return;\n }\n input.forEach(validatePart);\n}\n\nfunction asModeration(parsed: unknown, status: number, label: string): ModerationResponse {\n if (!isPlainObject(parsed) || !Array.isArray(parsed.results)) {\n throw new APIResponseValidationError(`${label} was not a moderation response`, {\n status,\n body: JSON.stringify(parsed),\n });\n }\n return parsed as unknown as ModerationResponse;\n}\n\nexport class Moderations {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n /**\n * Check content with a moderation model installed on one of your workers\n * (OpenAI-compatible).\n *\n * `input` is a string, an array of up to 32 strings (one result each) or an\n * array of up to 32 `text` / `image_url` parts checked together (one\n * result). With private inference turned on, the check is end-to-end\n * encrypted: Pendra sees neither the content nor the verdict.\n *\n * @example\n * ```ts\n * const result = await client.moderations.create({\n * model: \"llama-guard3:1b\",\n * input: \"Hello world\",\n * });\n * console.log(result.results[0].flagged);\n * ```\n */\n async create(params: ModerationCreateParams): Promise<ModerationResponse> {\n validateParams(params);\n\n const body: Record<string, unknown> = {\n model: params.model,\n input: params.input,\n };\n\n const headers = params.worker_id ? { \"X-Pendra-Worker-Id\": params.worker_id } : undefined;\n\n if (this.client.privateInferenceEnabled) {\n return this.createEncrypted(params.model, body, headers);\n }\n\n const { response } = await this.client._fetch(\n \"/api/v1/moderations\",\n { method: \"POST\", body, headers },\n );\n const result = asModeration(await readJsonReply(response), response.status, \"Response\");\n return withPlacement(result, response.headers, result.pendra);\n }\n\n private async createEncrypted(\n model: string,\n body: Record<string, unknown>,\n headers: Record<string, string> | undefined,\n ): Promise<ModerationResponse> {\n const engine = await this.client._privateEngine();\n // Moderation is never streamed and carries no affinity messages. The task\n // type must be the API router's dispatch string: it is bound into the AAD.\n const { topLevel, decryptor } = engine.seal({\n model,\n stream: false,\n taskType: \"moderation\",\n body: ENCODER.encode(JSON.stringify({ model: body.model, stream: false, input: body.input })),\n });\n const { response } = await this.client._fetch(\n \"/api/v1/moderations\",\n { method: \"POST\", body: topLevel, headers },\n );\n // A late failure arrives in-band, unsealed; readSealedReply raises it.\n const { inner, placement } = await readSealedReply(response);\n const plain = decryptor.openResult(inner);\n // The worker pads the reply with trailing spaces so its length doesn't\n // depend on the verdict; JSON.parse ignores them.\n const result = asModeration(\n parseDecryptedJson(DECODER.decode(plain), response.status),\n response.status,\n \"Decrypted response\",\n );\n // Placement rides unsealed beside the envelope (see withPlacement).\n return withPlacement(result, response.headers, result.pendra, placement);\n }\n}\n","import type { Pendra } from \"../client\";\nimport type { RerankCreateParams, RerankResponse } from \"../types/rerank\";\nimport { readJsonReply, readSealedReply } from \"../_parsing\";\nimport { withPlacement } from \"../_placement\";\n\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\n\nfunction validateParams(params: RerankCreateParams): void {\n if (!params.model || typeof params.model !== \"string\") {\n throw new Error(\"model must be a non-empty string\");\n }\n if (!params.query || typeof params.query !== \"string\") {\n throw new Error(\"query must be a non-empty string\");\n }\n const { documents } = params;\n if (\n !Array.isArray(documents) ||\n documents.length === 0 ||\n !documents.every((d) => typeof d === \"string\" && d.length > 0)\n ) {\n throw new Error(\"documents must be a non-empty array of non-empty strings\");\n }\n if (params.top_n != null && params.top_n < 1) {\n throw new Error(\"top_n must be >= 1 when provided\");\n }\n}\n\nexport class Rerank {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n /**\n * Rerank `documents` by relevance to `query` (Cohere-compatible).\n *\n * @example\n * ```ts\n * const result = await client.rerank.create({\n * model: \"bge-reranker-v2-m3\",\n * query: \"What is the capital of France?\",\n * documents: [\"Paris is the capital of France.\", \"Berlin is in Germany.\"],\n * top_n: 1,\n * });\n * console.log(result.results[0].index, result.results[0].relevance_score);\n * ```\n */\n async create(params: RerankCreateParams): Promise<RerankResponse> {\n validateParams(params);\n\n const body: Record<string, unknown> = {\n model: params.model,\n query: params.query,\n documents: params.documents,\n return_documents: params.return_documents ?? false,\n };\n if (params.top_n != null) body.top_n = params.top_n;\n\n const headers = params.worker_id ? { \"X-Pendra-Worker-Id\": params.worker_id } : undefined;\n\n if (this.client.privateInferenceEnabled) {\n return this.createEncrypted(params.model, body, headers);\n }\n\n const { response } = await this.client._fetch(\n \"/api/v1/rerank\",\n { method: \"POST\", body, headers },\n );\n const result = (await readJsonReply(response)) as RerankResponse;\n return withPlacement(result, response.headers, result.pendra);\n }\n\n private async createEncrypted(\n model: string,\n body: Record<string, unknown>,\n headers: Record<string, string> | undefined,\n ): Promise<RerankResponse> {\n const engine = await this.client._privateEngine();\n // Rerank is never streamed and carries no affinity messages. On the\n // encrypted path the worker builds + seals the final Cohere response, which\n // we decrypt verbatim.\n const { topLevel, decryptor } = engine.seal({\n model,\n stream: false,\n taskType: \"rerank\",\n body: ENCODER.encode(JSON.stringify(body)),\n });\n const { response } = await this.client._fetch(\n \"/api/v1/rerank\",\n { method: \"POST\", body: topLevel, headers },\n );\n // A late failure arrives in-band, unsealed; readSealedReply raises it.\n const { inner, placement } = await readSealedReply(response);\n const plain = decryptor.openResult(inner);\n const result = JSON.parse(DECODER.decode(plain)) as RerankResponse;\n // Placement rides unsealed beside the envelope (see withPlacement).\n return withPlacement(result, response.headers, result.pendra, placement);\n }\n}\n","/**\n * The published package version, sent as the User-Agent on every request so the\n * API can record which client made it.\n *\n * Duplicated from package.json deliberately: the SDK ships as both ESM and CJS\n * and must work without a JSON import assertion or a bundler resolving\n * `../package.json`. `version.test.ts` keeps the two in step.\n */\nexport const VERSION = \"0.18.1\";\n\n/** e.g. `pendra-node/0.18.1`. */\nexport const USER_AGENT = `pendra-node/${VERSION}`;\n","import { Audio } from \"./resources/audio/index\";\nimport { Chat } from \"./resources/chat/index\";\nimport { Embeddings } from \"./resources/embeddings\";\nimport { Images } from \"./resources/images/index\";\nimport { Models } from \"./resources/models\";\nimport { Moderations } from \"./resources/moderations\";\nimport { Rerank } from \"./resources/rerank\";\nimport { USER_AGENT } from \"./version\";\nimport { APIConnectionError, messageFromDetail, readErrorBody, statusErrorFromBody } from \"./errors\";\nimport {\n PrivateInferenceEngine,\n PrivateInferenceError,\n type FetchedKey,\n} from \"./_privateInferenceEngine\";\n\nexport interface PendraOptions {\n apiKey?: string;\n baseURL?: string;\n timeout?: number;\n /**\n * Enable end-to-end encrypted (private) inference. When `true`, inference\n * requests (chat, embeddings, moderations and the rest) are sealed to your\n * org's workload key (TOFU-pinned on first use) and the responses are decrypted client-side — Pendra relays only\n * ciphertext. Pass `{ pinnedFingerprint }` to hard-pin the org key fingerprint\n * (required in browser bundles, which cannot use the TOFU key store).\n *\n * Defaults to the `PENDRA_PRIVATE_INFERENCE` environment variable\n * (`1`/`true`/`yes`/`on` enables it).\n */\n privateInference?: boolean | { pinnedFingerprint?: string };\n}\n\nfunction envTruthy(v: string | undefined): boolean {\n if (!v) return false;\n return [\"1\", \"true\", \"yes\", \"on\"].includes(v.trim().toLowerCase());\n}\n\nexport class Pendra {\n readonly apiKey: string;\n readonly baseURL: string;\n readonly timeout: number;\n\n chat: Chat;\n images: Images;\n embeddings: Embeddings;\n models: Models;\n audio: Audio;\n rerank: Rerank;\n moderations: Moderations;\n\n /** @internal Whether end-to-end encrypted inference is enabled for this client. */\n readonly privateInferenceEnabled: boolean;\n private _piEngine: PrivateInferenceEngine | null = null;\n // Serialises the one-time key fetch across concurrent first calls.\n private _piKeyFetch: Promise<void> | null = null;\n\n constructor(options: PendraOptions = {}) {\n const env = typeof process !== \"undefined\" ? process.env : undefined;\n const apiKey = options.apiKey ?? env?.PENDRA_API_KEY;\n\n if (!apiKey) {\n throw new Error(\n \"API key is required — pass apiKey or set the PENDRA_API_KEY environment variable\",\n );\n }\n\n this.apiKey = apiKey;\n this.baseURL = (options.baseURL ?? \"https://api.pendra.ai\").replace(\n /\\/$/,\n \"\",\n );\n this.timeout = options.timeout ?? 120_000;\n\n // --- private inference config ---\n let piOpt = options.privateInference;\n if (piOpt === undefined) {\n piOpt = envTruthy(env?.PENDRA_PRIVATE_INFERENCE);\n }\n let pinnedFingerprint: string | undefined;\n if (typeof piOpt === \"object\" && piOpt !== null) {\n // An unknown key is almost always a typo or the snake_case spelling from\n // the Python SDK. Ignoring it would, for a mistyped pin, leave the client\n // unpinned while its author believes it is pinned — so refuse it.\n for (const key of Object.keys(piOpt)) {\n if (key !== \"pinnedFingerprint\") {\n throw new TypeError(\n `Unknown privateInference option \"${key}\". Accepted options: pinnedFingerprint.`,\n );\n }\n }\n this.privateInferenceEnabled = true;\n pinnedFingerprint = piOpt.pinnedFingerprint;\n } else {\n this.privateInferenceEnabled = Boolean(piOpt);\n }\n // An explicitly passed pin (even \"\") goes to the engine, which rejects it\n // rather than silently running unpinned. Only an unset or empty environment\n // variable means \"not pinned\".\n pinnedFingerprint = pinnedFingerprint ?? (env?.PENDRA_PINNED_ORG_FINGERPRINT || undefined);\n\n if (this.privateInferenceEnabled) {\n // PENDRA_AFFINITY_SALT, when set, is used as raw UTF-8 bytes (mirrors Python).\n const affinitySalt = env?.PENDRA_AFFINITY_SALT\n ? new TextEncoder().encode(env.PENDRA_AFFINITY_SALT)\n : null;\n this._piEngine = new PrivateInferenceEngine({\n baseUrl: this.baseURL,\n apiKey: this.apiKey,\n pinnedFingerprint: pinnedFingerprint ?? null,\n affinitySalt,\n tofuPath: env?.PENDRA_TOFU_PATH ?? null,\n });\n }\n\n this.chat = new Chat(this);\n this.images = new Images(this);\n this.embeddings = new Embeddings(this);\n this.models = new Models(this);\n this.audio = new Audio(this);\n this.rerank = new Rerank(this);\n this.moderations = new Moderations(this);\n }\n\n /**\n * @internal\n * Return the private-inference engine with its org key resolved. Fetches\n * `GET {baseUrl}/v1/private-inference/key` exactly once (subsequent calls reuse\n * the cached key). Throws if private inference is not enabled.\n */\n async _privateEngine(): Promise<PrivateInferenceEngine> {\n if (!this._piEngine) {\n throw new PrivateInferenceError(\"private inference is not enabled on this client\");\n }\n if (this._piEngine.cachedOrgPublicKeys() !== null) {\n return this._piEngine;\n }\n if (!this._piKeyFetch) {\n this._piKeyFetch = this._fetchAndResolveOrgKey().catch((err) => {\n // Reset so a failed fetch can be retried on the next call.\n this._piKeyFetch = null;\n throw err;\n });\n }\n await this._piKeyFetch;\n return this._piEngine;\n }\n\n private async _fetchAndResolveOrgKey(): Promise<void> {\n const engine = this._piEngine as PrivateInferenceEngine;\n const url = `${this.baseURL}/v1/private-inference/key`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n let response: Response;\n try {\n response = await fetch(url, {\n method: \"GET\",\n headers: { Authorization: `Bearer ${this.apiKey}`, \"User-Agent\": USER_AGENT },\n signal: controller.signal,\n });\n } catch (err) {\n if (err instanceof DOMException && err.name === \"AbortError\") {\n throw new APIConnectionError(`Request timed out after ${this.timeout}ms`);\n }\n throw new APIConnectionError(\n err instanceof Error ? err.message : \"Failed to fetch the private-inference workload key\",\n );\n } finally {\n clearTimeout(timeoutId);\n }\n\n if (response.status === 404) {\n // The server's `detail` says why there is no key (a connected worker\n // awaiting approval needs approving, not a second worker), so prefer it.\n const body = (await readErrorBody(response)) as { detail?: unknown } | null | undefined;\n const detail = typeof body === \"object\" && body !== null ? body.detail : undefined;\n throw new PrivateInferenceError(\n messageFromDetail(detail) ??\n \"No encryption key is registered for this organisation. Start a worker \" +\n \"and it will be issued one automatically.\",\n );\n }\n if (!response.ok) {\n // FastAPI errors carry `detail` (a string, or an array/object for\n // validation and structured errors); the inference routes' worker and\n // server errors carry an OpenAI-style `{\"error\": {\"message\"}}`.\n throw statusErrorFromBody(response.status, await readErrorBody(response), response.statusText);\n }\n\n const json = (await response.json()) as { keys?: FetchedKey[] };\n await engine.resolveOrgKey(json.keys ?? []);\n }\n\n /** @internal */\n async _fetch(\n path: string,\n options: {\n method: string;\n body?: Record<string, unknown>;\n headers?: Record<string, string>;\n /** Overrides the client timeout for this request (ms). */\n timeout?: number;\n },\n ): Promise<{ response: Response; controller: AbortController }> {\n const timeout = options.timeout ?? this.timeout;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n \"User-Agent\": USER_AGENT,\n ...(options.headers ?? {}),\n };\n\n let response: Response;\n try {\n response = await fetch(`${this.baseURL}${path}`, {\n method: options.method,\n headers,\n body: options.body ? JSON.stringify(options.body) : undefined,\n signal: controller.signal,\n });\n } catch (err) {\n clearTimeout(timeoutId);\n if (err instanceof DOMException && err.name === \"AbortError\") {\n throw new APIConnectionError(\n `Request timed out after ${timeout}ms`,\n );\n }\n throw new APIConnectionError(\n err instanceof Error ? err.message : \"Failed to connect to the Pendra API\",\n );\n }\n\n // The timeout covers connecting and receiving the headers. A stream then\n // runs for as long as it keeps producing data: leaving this timer armed\n // aborted every stream longer than `timeout` partway through (#2185), and\n // `Stream` applies its own per-read idle timeout instead.\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n // A fleet re-key leaves this client sealing to a fingerprint no worker\n // holds. The key set is cached for the whole process lifetime, so without\n // this a long-running server would fail EVERY subsequent request until\n // someone restarted it. Dropping the cache lets the next call recover.\n this.invalidateKeyCacheIfRekeyed(response);\n // FastAPI errors carry `detail` (a string, or an array/object for\n // validation and structured errors); the inference routes' worker and\n // server errors carry an OpenAI-style `{\"error\": {\"message\"}}`.\n throw statusErrorFromBody(response.status, await readErrorBody(response), response.statusText);\n }\n\n return { response, controller };\n }\n\n /**\n * Drop the cached encryption keys when the API reports that no worker holds\n * the one this request was sealed to — the signal that the org's fleet has\n * re-keyed. Returns true if the cache was dropped.\n *\n * A PINNED client is left alone on purpose: a pin is an allowlist, so\n * re-fetching could only return fingerprints the pin already rejects and\n * would loop rather than recover. The error surfaces instead, which is\n * exactly what pinning is for.\n */\n private invalidateKeyCacheIfRekeyed(response: Response): boolean {\n const engine = this._piEngine;\n if (!engine || engine.isPinned) return false;\n if (response.headers?.get(\"X-Pendra-Error-Code\") !== \"no_private_inference_worker\") {\n return false;\n }\n engine.invalidateOrgKey();\n // Clearing the engine's cache is not enough on its own. `_piKeyFetch` holds\n // the RESOLVED promise from the first successful fetch and is only ever\n // reset on failure, so `_privateEngine()` would await it, no-op, and hand\n // back an engine whose key is still null — every later call then throwing\n // \"org key not resolved yet\" for the life of the process. That is worse\n // than the behaviour this recovery replaces, which at least kept asking the\n // network. Drop it so the next call genuinely re-fetches.\n this._piKeyFetch = null;\n return true;\n }\n}\n","export { Pendra } from \"./client\";\nexport type { PendraOptions } from \"./client\";\nexport { Stream } from \"./streaming\";\n\nexport type {\n ChatCompletion,\n ChatCompletionChunk,\n ChatCompletionContentPart,\n ChatCompletionMessage,\n ChatCompletionMessageParam,\n ChatCompletionMessageToolCall,\n ChatCompletionCreateParams,\n Choice,\n StreamChoice,\n ChoiceDelta,\n Usage,\n CompletionTokensDetails,\n PendraExtension,\n PendraNotice,\n PendraTiming,\n PendraWorker,\n PendraWebToolStep,\n} from \"./types/chat\";\n\nexport type { Model } from \"./types/models\";\n\nexport type {\n ImageGenerationCreateParams,\n ImageData,\n ImageResponse,\n} from \"./types/images\";\n\nexport type {\n EmbeddingCreateParams,\n Embedding,\n EmbeddingUsage,\n CreateEmbeddingResponse,\n} from \"./types/embeddings\";\n\nexport type {\n AudioFileInput,\n SpeechCreateParams,\n SpeechResponse,\n TranscriptionCreateParams,\n TranscriptionResponse,\n TranscriptionSegment,\n} from \"./types/audio\";\n\nexport type {\n RerankCreateParams,\n RerankResult,\n RerankResultDocument,\n RerankResponse,\n} from \"./types/rerank\";\n\nexport type {\n ModerationCreateParams,\n ModerationImageURLInput,\n ModerationInput,\n ModerationInputPart,\n ModerationResponse,\n ModerationResult,\n ModerationTextInput,\n} from \"./types/moderations\";\n\nexport {\n APIError,\n APIConnectionError,\n APIStatusError,\n APIStreamError,\n APIResponseValidationError,\n AuthenticationError,\n RateLimitError,\n} from \"./errors\";\nexport type { APIStatusErrorOptions } from \"./errors\";\n\nexport { PrivateInferenceError } from \"./_privateInferenceEngine\";\n\n// Default export for convenient usage:\n// import Pendra from 'pendra';\nimport { Pendra as _Pendra } from \"./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;AAMA,iBAAa,SAAS;AAEtB,QAAI,CAAC,SAAS,IAAI;AAKhB,WAAK,4BAA4B,QAAQ;AAIzC,YAAM,oBAAoB,SAAS,QAAQ,MAAM,cAAc,QAAQ,GAAG,SAAS,UAAU;AAAA,IAC/F;AAEA,WAAO,EAAE,UAAU,WAAW;AAAA,EAChC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYQ,4BAA4B,UAA6B;AAC/D,UAAM,SAAS,KAAK;AACpB,QAAI,CAAC,UAAU,OAAO,SAAU,QAAO;AACvC,QAAI,SAAS,SAAS,IAAI,qBAAqB,MAAM,+BAA+B;AAClF,aAAO;AAAA,IACT;AACA,WAAO,iBAAiB;AAQxB,SAAK,cAAc;AACnB,WAAO;AAAA,EACT;AACF;;;ACzMA,IAAO,gBAAQ;","names":["chacha20poly1305","extract","expand","TEXT_ENCODER","chacha20poly1305","extract","expand","b64d","bytes","isRecord","DECODER","ENCODER","DECODER","response","ENCODER","DECODER","ENCODER","DECODER","validateParams","ENCODER","DECODER","isPlainObject","validateParams","ENCODER","DECODER","validateParams"]}
|