pendra 0.13.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -0
- package/dist/index.d.mts +19 -8
- package/dist/index.d.ts +19 -8
- package/dist/index.js +621 -584
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +621 -584
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/resources/audio/transcriptions.ts","../src/resources/audio/index.ts","../src/_parsing.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/rerank.ts","../src/version.ts","../src/_hpke.ts","../src/_privateInference.ts","../src/_privateInferenceEngine.ts","../src/client.ts"],"sourcesContent":["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 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 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 {\n APIError,\n APIConnectionError,\n APIStatusError,\n APIStreamError,\n APIResponseValidationError,\n AuthenticationError,\n RateLimitError,\n} 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","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 class APIStatusError extends APIError {\n override readonly status: number;\n\n constructor(message: string, status: number) {\n super(message, status);\n this.name = \"APIStatusError\";\n this.status = status;\n }\n}\n\nexport class AuthenticationError extends APIStatusError {\n constructor(\n message = \"Invalid API key — check your PENDRA_API_KEY\",\n ) {\n super(message, 401);\n this.name = \"AuthenticationError\";\n }\n}\n\nexport class RateLimitError extends APIStatusError {\n constructor(message = \"Rate limit exceeded\") {\n super(message, 429);\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","import type { Pendra } from \"../../client\";\nimport { APIConnectionError, APIStatusError, AuthenticationError, RateLimitError } from \"../../errors\";\nimport type { AudioFileInput, TranscriptionCreateParams, TranscriptionResponse } from \"../../types/audio\";\n\n// Mirrors the API's hard cap (25MB).\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 {\n if (!type) return \"mp3\";\n // Strip codec parameters (e.g. `audio/webm;codecs=opus`).\n const base = type.split(\";\")[0].trim().toLowerCase();\n return MIME_EXT[base] ?? \"mp3\";\n}\n\nfunction asBlob(file: AudioFileInput): { 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 so the multipart upload\n // still carries enough info for server-side format detection.\n const asFile = file as File;\n if (asFile.name) {\n return { blob: file, filename: asFile.name };\n }\n return { blob: file, filename: `audio.${extFromMime(file.type)}` };\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\n// Read the response body once and try to extract a useful error message.\n// Falls back to the raw text (then statusText) when the body isn't JSON.\nasync function extractErrorDetail(response: Response): Promise<string> {\n let raw = \"\";\n try {\n raw = await response.text();\n } catch {\n return response.statusText;\n }\n if (!raw) return response.statusText;\n try {\n const body = JSON.parse(raw) as { detail?: string; error?: { message?: string } };\n return body.detail ?? body.error?.message ?? raw;\n } catch {\n return raw;\n }\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 (this.client.privateInferenceEnabled) {\n // Don't fall through to a plaintext upload when the caller expects E2E\n // encryption — fail loudly instead. (Deferred to a later SDK release.)\n throw new Error(\"private inference is not yet supported for images/audio\");\n }\n\n if (!params.model) {\n throw new Error(\"model is required\");\n }\n\n const { blob, filename } = 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 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 //\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 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 detail = await extractErrorDetail(response);\n if (response.status === 401) {\n throw new AuthenticationError(detail);\n }\n if (response.status === 429) {\n throw new RateLimitError(detail);\n }\n throw new APIStatusError(detail, response.status);\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.\n const format = params.response_format;\n if (format === \"text\" || format === \"srt\" || format === \"vtt\") {\n const text = await response.text();\n return { text };\n }\n\n return (await response.json()) as TranscriptionResponse;\n }\n}\n","import type { Pendra } from \"../../client\";\nimport { Transcriptions } from \"./transcriptions\";\n\nexport class Audio {\n transcriptions: Transcriptions;\n\n constructor(client: Pendra) {\n this.transcriptions = new Transcriptions(client);\n }\n}\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 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 */\nfunction throwIfInBandError(parsed: unknown): 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) ?? \"The server reported an error mid-stream\",\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 return completionFrom(parsed, body, response.status);\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 * 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 { parseStreamFrame } from \"./_parsing\";\nimport { SseDecoder } from \"./_sse\";\nimport type { ChatCompletionChunk } 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 */\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\n constructor(response: Response, controller: AbortController) {\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 }\n\n async *[Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk> {\n try {\n while (!this.done) {\n const { value, done: readerDone } = await this.reader.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.done = true;\n return;\n }\n yield parseStreamFrame(data);\n }\n\n if (readerDone) {\n this.done = true;\n break;\n }\n }\n } finally {\n this.reader.releaseLock();\n }\n }\n\n abort(): void {\n this.done = true;\n this.controller.abort();\n }\n}\n","import { APIResponseValidationError } from \"./errors\";\nimport { parseStreamFrame } from \"./_parsing\";\nimport { SseDecoder } from \"./_sse\";\nimport type { ChatCompletionChunk } from \"./types/chat\";\nimport type { ResponseDecryptor, ResponseInner } 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).\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\n constructor(response: Response, controller: AbortController, decryptor: ResponseDecryptor) {\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 }\n\n async *[Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk> {\n try {\n while (!this.done) {\n const { value, done: readerDone } = await this.reader.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.done = true;\n return;\n }\n\n // A frame that isn't an encrypted envelope is either a plaintext\n // chunk or the API reporting a failure in-band — the latter is never\n // sealed, because it is produced after the worker is already out of\n // the picture. parseStreamFrame tells those apart and throws on the\n // error report instead of yielding it as a chunk (issue #2252).\n let inner: ResponseInner | undefined;\n try {\n inner = (JSON.parse(data) as { pendra_encrypted?: ResponseInner }).pendra_encrypted;\n } catch {\n throw new APIResponseValidationError(\"Stream frame was not valid JSON\", {\n body: data,\n });\n }\n if (!inner) {\n yield parseStreamFrame(data);\n continue;\n }\n const plain = this.decryptor.openChunk(inner);\n const chunkJson = DECODER.decode(plain).trim();\n if (!chunkJson || chunkJson === \"[DONE]\") {\n if (chunkJson === \"[DONE]\") {\n this.done = true;\n return;\n }\n continue;\n }\n yield parseStreamFrame(chunkJson, \"Decrypted stream frame\");\n }\n\n if (readerDone) {\n this.done = true;\n break;\n }\n }\n } finally {\n this.reader.releaseLock();\n }\n }\n\n abort(): void {\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 { APIResponseValidationError } from \"../../errors\";\nimport { parseCompletion, parseDecryptedCompletion } from \"../../_parsing\";\nimport { Stream } from \"../../streaming\";\nimport { EncryptedStream } from \"../../_privateStreaming\";\nimport type { ResponseInner } from \"../../_privateInference\";\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 = params.worker_id\n ? { \"X-Pendra-Worker-Id\": params.worker_id }\n : undefined;\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, stream: true, headers },\n );\n return new Stream(response, controller);\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 return parseCompletion(response);\n }\n\n private async createEncrypted(\n params: ChatCompletionCreateParams,\n body: Record<string, unknown>,\n headers: Record<string, string> | undefined,\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 body: ENCODER.encode(JSON.stringify(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, stream: true, headers },\n );\n // EncryptedStream is a drop-in AsyncIterable<ChatCompletionChunk>, same as Stream.\n return new EncryptedStream(response, controller, decryptor) 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 const raw = await response.text();\n let wrapper: { pendra_encrypted?: ResponseInner };\n try {\n wrapper = JSON.parse(raw) as { pendra_encrypted?: ResponseInner };\n } catch {\n throw new APIResponseValidationError(\"Response was not valid JSON\", {\n status: response.status,\n body: raw,\n });\n }\n if (!wrapper.pendra_encrypted) {\n // Server returned plaintext despite an encrypted request — validate it as\n // an ordinary completion rather than casting it sight-unseen.\n return parseDecryptedCompletion(raw, response.status);\n }\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(wrapper.pendra_encrypted);\n return parseDecryptedCompletion(DECODER.decode(plain), response.status);\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 type { ResponseInner } from \"../_privateInference\";\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 return (await response.json()) as CreateEmbeddingResponse;\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 const wrapper = (await response.json()) as { pendra_encrypted?: ResponseInner };\n if (!wrapper.pendra_encrypted) {\n return wrapper as unknown as CreateEmbeddingResponse;\n }\n const plain = decryptor.openResult(wrapper.pendra_encrypted);\n return JSON.parse(DECODER.decode(plain)) as CreateEmbeddingResponse;\n }\n}\n","import type { Pendra } from \"../../client\";\nimport type { ImageGenerationCreateParams, ImageResponse } from \"../../types/images\";\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 if (this.client.privateInferenceEnabled) {\n // Don't fall through to a plaintext request when the caller expects E2E\n // encryption — fail loudly instead. (Deferred to a later SDK release.)\n throw new Error(\"private inference is not yet supported for images/audio\");\n }\n\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 { response } = await this.client._fetch(\n \"/api/v1/images/generations\",\n {\n method: \"POST\",\n body,\n headers: params.worker_id ? { \"X-Pendra-Worker-Id\": params.worker_id } : undefined,\n },\n );\n return (await response.json()) as ImageResponse;\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 { RerankCreateParams, RerankResponse } from \"../types/rerank\";\nimport type { ResponseInner } from \"../_privateInference\";\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 return (await response.json()) as RerankResponse;\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 const wrapper = (await response.json()) as { pendra_encrypted?: ResponseInner };\n if (!wrapper.pendra_encrypted) {\n return wrapper as unknown as RerankResponse;\n }\n const plain = decryptor.openResult(wrapper.pendra_encrypted);\n return JSON.parse(DECODER.decode(plain)) as RerankResponse;\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.13.0\";\n\n/** e.g. `pendra-node/0.13.0`. */\nexport const USER_AGENT = `pendra-node/${VERSION}`;\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 * 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\";\nexport const ENVELOPE_VERSION = 1;\n\nconst TEXT_ENCODER = new TextEncoder();\nconst TEXT_DECODER = new TextDecoder();\n\nconst SUITE_INFO = TEXT_ENCODER.encode(\"pendra-pi-v1\");\nconst RESPONSE_INFO = TEXT_ENCODER.encode(\"pendra-pi-v1:response\");\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 response_pk_b64`.\n */\nexport function buildAad(model: string, stream: boolean, taskType: string, responsePkB64: 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), utf8(responsePkB64)];\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 response_pk: 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, responsePriv }`. The caller keeps the ephemeral response\n * private key to decrypt the worker's reply, and places the returned envelope\n * under `pendra_encrypted` alongside cleartext model/stream.\n */\nexport function sealRequest(\n orgPubs: Uint8Array | Uint8Array[],\n body: Uint8Array,\n opts: SealOptions,\n): { envelope: Envelope; responsePriv: 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 { priv: respPriv, pub: respPub } = hpke.generateX25519Keypair();\n const respPkB64 = b64(respPub);\n\n const dek = hpke.randomBytes(32);\n const nonce = hpke.randomBytes(12);\n const aad = buildAad(opts.model, opts.stream, opts.taskType, respPkB64);\n const ciphertext = chacha20poly1305(dek, nonce, aad).encrypt(body);\n\n const recipients: Recipient[] = [];\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 recipients.push({ kid: fingerprint(pub), 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 response_pk: respPkB64,\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, responsePriv: respPriv };\n}\n\nexport interface ResponseInner {\n v?: number;\n enc?: string;\n seq: number;\n ciphertext: string;\n}\n\n/**\n * Decrypts a worker's sealed response. Derives the response DEK once from the\n * first frame's `enc` (HPKE Export to the client's ephemeral key) and enforces a\n * monotonic `seq` across streaming chunks.\n */\nexport class ResponseDecryptor {\n private respPriv: Uint8Array;\n private dek: Uint8Array | null = null;\n private nextSeq = 0;\n\n constructor(responsePrivateKey: Uint8Array) {\n this.respPriv = responsePrivateKey;\n }\n\n private ensureDek(encB64: string | undefined): void {\n if (this.dek !== null) return;\n if (!encB64) {\n throw new Error(\"private_inference: first response frame is missing the encapsulated key\");\n }\n const ctx = hpke.setupBaseR(this.respPriv, b64d(encB64), RESPONSE_INFO);\n this.dek = ctx.export(RESPONSE_EXPORT_CTX, 32);\n }\n\n /** Decrypt a non-streaming result envelope `{v, enc, seq, ciphertext}`. */\n openResult(inner: ResponseInner): Uint8Array {\n this.ensureDek(inner.enc);\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.enc);\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 * 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\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 const fps = (opts.pinnedFingerprint || \"\")\n .split(\",\")\n .map((f) => f.trim().toLowerCase())\n .filter((f) => f.length > 0);\n this.pinnedFingerprints = fps.length > 0 ? new Set(fps) : null;\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 */\n seal(args: {\n model: string;\n stream: boolean;\n taskType: string;\n body: Uint8Array;\n messages?: pi.AffinityMessage[] | 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, responsePriv } = pi.sealRequest(this.orgPubs, args.body, {\n model: args.model,\n stream: args.stream,\n taskType: args.taskType,\n affinityKey: affinity,\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(responsePriv) };\n }\n\n get keyFetchUrl(): string {\n return `${this.baseUrl}/v1/private-inference/key`;\n }\n}\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 { Rerank } from \"./resources/rerank\";\nimport { USER_AGENT } from \"./version\";\nimport {\n APIConnectionError,\n APIStatusError,\n AuthenticationError,\n RateLimitError,\n} 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`, chat and\n * embeddings requests are sealed to your org's workload key (TOFU-pinned on\n * 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\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 this.privateInferenceEnabled = true;\n pinnedFingerprint = piOpt.pinnedFingerprint;\n } else {\n this.privateInferenceEnabled = Boolean(piOpt);\n }\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 }\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 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 if (!response.ok) {\n let message: string;\n try {\n const body = (await response.json()) as { detail?: string };\n message = body.detail ?? response.statusText;\n } catch {\n message = response.statusText;\n }\n if (response.status === 401) throw new AuthenticationError(message);\n if (response.status === 429) throw new RateLimitError(message);\n throw new APIStatusError(message, response.status);\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 stream?: boolean;\n headers?: Record<string, string>;\n },\n ): Promise<{ response: Response; controller: AbortController }> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.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 ${this.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 if (!options.stream) {\n clearTimeout(timeoutId);\n }\n\n if (!response.ok) {\n clearTimeout(timeoutId);\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 let message: string;\n try {\n const body = (await response.json()) as { detail?: string };\n message = body.detail ?? response.statusText;\n } catch {\n message = response.statusText;\n }\n\n if (response.status === 401) throw new AuthenticationError(message);\n if (response.status === 429) throw new RateLimitError(message);\n throw new APIStatusError(message, response.status);\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,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,YAAY,UAAU,uCAAuC;AAC3D,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,iBAAN,cAA6B,SAAS;AAAA,EAG3C,YAAY,SAAiB,QAAgB;AAC3C,UAAM,SAAS,MAAM;AACrB,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AACF;AAEO,IAAM,sBAAN,cAAkC,eAAe;AAAA,EACtD,YACE,UAAU,oDACV;AACA,UAAM,SAAS,GAAG;AAClB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,iBAAN,cAA6B,eAAe;AAAA,EACjD,YAAY,UAAU,uBAAuB;AAC3C,UAAM,SAAS,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O;AAClE,UAAI,SAAS,WAAW,IAAK,OAAM,IAAI,eAAe,OAAO;AAC7D,YAAM,IAAI,eAAe,SAAS,SAAS,MAAM;AAAA,IACnD;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;;;AnBjNA,IAAO,gBAAQ;","names":["DECODER","response","ENCODER","DECODER","validateParams","ENCODER","DECODER","validateParams","nobleRandomBytes","import_chacha","import_hkdf","TEXT_ENCODER","b64d"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/resources/audio/transcriptions.ts","../src/resources/audio/index.ts","../src/_parsing.ts","../src/_sse.ts","../src/streaming.ts","../src/_privateInference.ts","../src/_hpke.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/rerank.ts","../src/version.ts","../src/_privateInferenceEngine.ts","../src/client.ts"],"sourcesContent":["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 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 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 {\n APIError,\n APIConnectionError,\n APIStatusError,\n APIStreamError,\n APIResponseValidationError,\n AuthenticationError,\n RateLimitError,\n} 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","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 class APIStatusError extends APIError {\n override readonly status: number;\n\n constructor(message: string, status: number) {\n super(message, status);\n this.name = \"APIStatusError\";\n this.status = status;\n }\n}\n\nexport class AuthenticationError extends APIStatusError {\n constructor(\n message = \"Invalid API key — check your PENDRA_API_KEY\",\n ) {\n super(message, 401);\n this.name = \"AuthenticationError\";\n }\n}\n\nexport class RateLimitError extends APIStatusError {\n constructor(message = \"Rate limit exceeded\") {\n super(message, 429);\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","import type { Pendra } from \"../../client\";\nimport { APIConnectionError, APIStatusError, AuthenticationError, RateLimitError } from \"../../errors\";\nimport type { AudioFileInput, TranscriptionCreateParams, TranscriptionResponse } from \"../../types/audio\";\n\n// Mirrors the API's hard cap (25MB).\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 {\n if (!type) return \"mp3\";\n // Strip codec parameters (e.g. `audio/webm;codecs=opus`).\n const base = type.split(\";\")[0].trim().toLowerCase();\n return MIME_EXT[base] ?? \"mp3\";\n}\n\nfunction asBlob(file: AudioFileInput): { 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 so the multipart upload\n // still carries enough info for server-side format detection.\n const asFile = file as File;\n if (asFile.name) {\n return { blob: file, filename: asFile.name };\n }\n return { blob: file, filename: `audio.${extFromMime(file.type)}` };\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\n// Read the response body once and try to extract a useful error message.\n// Falls back to the raw text (then statusText) when the body isn't JSON.\nasync function extractErrorDetail(response: Response): Promise<string> {\n let raw = \"\";\n try {\n raw = await response.text();\n } catch {\n return response.statusText;\n }\n if (!raw) return response.statusText;\n try {\n const body = JSON.parse(raw) as { detail?: string; error?: { message?: string } };\n return body.detail ?? body.error?.message ?? raw;\n } catch {\n return raw;\n }\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 (this.client.privateInferenceEnabled) {\n // Don't fall through to a plaintext upload when the caller expects E2E\n // encryption — fail loudly instead. (Deferred to a later SDK release.)\n throw new Error(\"private inference is not yet supported for images/audio\");\n }\n\n if (!params.model) {\n throw new Error(\"model is required\");\n }\n\n const { blob, filename } = 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 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 //\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 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 detail = await extractErrorDetail(response);\n if (response.status === 401) {\n throw new AuthenticationError(detail);\n }\n if (response.status === 429) {\n throw new RateLimitError(detail);\n }\n throw new APIStatusError(detail, response.status);\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.\n const format = params.response_format;\n if (format === \"text\" || format === \"srt\" || format === \"vtt\") {\n const text = await response.text();\n return { text };\n }\n\n return (await response.json()) as TranscriptionResponse;\n }\n}\n","import type { Pendra } from \"../../client\";\nimport { Transcriptions } from \"./transcriptions\";\n\nexport class Audio {\n transcriptions: Transcriptions;\n\n constructor(client: Pendra) {\n this.transcriptions = new Transcriptions(client);\n }\n}\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 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 */\nfunction throwIfInBandError(parsed: unknown): 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) ?? \"The server reported an error mid-stream\",\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 return completionFrom(parsed, body, response.status);\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 * 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 type { ChatCompletionChunk } 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 */\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\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 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 abort(): void {\n this.done = true;\n this.controller.abort();\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","/**\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_TIMING_CHUNK_KEYS = new Set([\"id\", \"object\", \"created\", \"model\", \"choices\", \"pendra\"]);\n\n/**\n * Whether an unsealed frame on an encrypted stream is the API's terminal timing\n * chunk: empty `choices`, only `timing` under `pendra`, and none of the fields\n * that carry model output. The API appends it after the worker's sealed chunks —\n * it reports timings the API measured, not anything the model wrote — so it is\n * the one chunk that legitimately arrives unsealed.\n */\nexport function isApiTimingChunk(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 return (\n Object.keys(obj).every((k) => API_TIMING_CHUNK_KEYS.has(k)) &&\n Array.isArray(obj.choices) &&\n obj.choices.length === 0 &&\n pendra !== null &&\n typeof pendra === \"object\" &&\n Object.keys(pendra).length === 1 &&\n \"timing\" in pendra\n );\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 * 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","import { APIResponseValidationError } from \"./errors\";\nimport { parseStreamFrame } from \"./_parsing\";\nimport { SseDecoder } from \"./_sse\";\nimport { readWithIdleTimeout, releaseReader } from \"./streaming\";\nimport type { ChatCompletionChunk } from \"./types/chat\";\nimport { isApiTimingChunk, unsealedReplyError, type ResponseDecryptor, type ResponseInner } 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 */\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\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 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\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 terminal timing chunk. 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 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 (isApiTimingChunk(frame)) {\n yield 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 const plain = this.decryptor.openChunk(inner);\n const chunkJson = DECODER.decode(plain).trim();\n if (!chunkJson || chunkJson === \"[DONE]\") {\n if (chunkJson === \"[DONE]\") {\n this.done = true;\n return;\n }\n continue;\n }\n yield parseStreamFrame(chunkJson, \"Decrypted stream frame\");\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 abort(): void {\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 { APIResponseValidationError } from \"../../errors\";\nimport { parseCompletion, parseDecryptedCompletion } from \"../../_parsing\";\nimport { Stream } from \"../../streaming\";\nimport { EncryptedStream } from \"../../_privateStreaming\";\nimport { unsealedReplyError, type ResponseInner } from \"../../_privateInference\";\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 = params.worker_id\n ? { \"X-Pendra-Worker-Id\": params.worker_id }\n : undefined;\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 return parseCompletion(response);\n }\n\n private async createEncrypted(\n params: ChatCompletionCreateParams,\n body: Record<string, unknown>,\n headers: Record<string, string> | undefined,\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 body: ENCODER.encode(JSON.stringify(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 const raw = await response.text();\n let wrapper: { pendra_encrypted?: ResponseInner };\n try {\n wrapper = JSON.parse(raw) as { pendra_encrypted?: ResponseInner };\n } catch {\n throw new APIResponseValidationError(\"Response was not valid JSON\", {\n status: response.status,\n body: raw,\n });\n }\n if (!wrapper.pendra_encrypted) {\n throw unsealedReplyError();\n }\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(wrapper.pendra_encrypted);\n return parseDecryptedCompletion(DECODER.decode(plain), response.status);\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 { unsealedReplyError, type ResponseInner } from \"../_privateInference\";\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 return (await response.json()) as CreateEmbeddingResponse;\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 const wrapper = (await response.json()) as { pendra_encrypted?: ResponseInner };\n if (!wrapper.pendra_encrypted) {\n throw unsealedReplyError();\n }\n const plain = decryptor.openResult(wrapper.pendra_encrypted);\n return JSON.parse(DECODER.decode(plain)) as CreateEmbeddingResponse;\n }\n}\n","import type { Pendra } from \"../../client\";\nimport type { ImageGenerationCreateParams, ImageResponse } from \"../../types/images\";\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 if (this.client.privateInferenceEnabled) {\n // Don't fall through to a plaintext request when the caller expects E2E\n // encryption — fail loudly instead. (Deferred to a later SDK release.)\n throw new Error(\"private inference is not yet supported for images/audio\");\n }\n\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 { response } = await this.client._fetch(\n \"/api/v1/images/generations\",\n {\n method: \"POST\",\n body,\n headers: params.worker_id ? { \"X-Pendra-Worker-Id\": params.worker_id } : undefined,\n },\n );\n return (await response.json()) as ImageResponse;\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 { RerankCreateParams, RerankResponse } from \"../types/rerank\";\nimport { unsealedReplyError, type ResponseInner } from \"../_privateInference\";\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 return (await response.json()) as RerankResponse;\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 const wrapper = (await response.json()) as { pendra_encrypted?: ResponseInner };\n if (!wrapper.pendra_encrypted) {\n throw unsealedReplyError();\n }\n const plain = decryptor.openResult(wrapper.pendra_encrypted);\n return JSON.parse(DECODER.decode(plain)) as RerankResponse;\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.14.0\";\n\n/** e.g. `pendra-node/0.14.0`. */\nexport const USER_AGENT = `pendra-node/${VERSION}`;\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\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 const fps = (opts.pinnedFingerprint || \"\")\n .split(\",\")\n .map((f) => f.trim().toLowerCase())\n .filter((f) => f.length > 0);\n this.pinnedFingerprints = fps.length > 0 ? new Set(fps) : null;\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 */\n seal(args: {\n model: string;\n stream: boolean;\n taskType: string;\n body: Uint8Array;\n messages?: pi.AffinityMessage[] | 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 });\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 { 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 { Rerank } from \"./resources/rerank\";\nimport { USER_AGENT } from \"./version\";\nimport {\n APIConnectionError,\n APIStatusError,\n AuthenticationError,\n RateLimitError,\n} 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`, chat and\n * embeddings requests are sealed to your org's workload key (TOFU-pinned on\n * 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\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 this.privateInferenceEnabled = true;\n pinnedFingerprint = piOpt.pinnedFingerprint;\n } else {\n this.privateInferenceEnabled = Boolean(piOpt);\n }\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 }\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 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 if (!response.ok) {\n let message: string;\n try {\n const body = (await response.json()) as { detail?: string };\n message = body.detail ?? response.statusText;\n } catch {\n message = response.statusText;\n }\n if (response.status === 401) throw new AuthenticationError(message);\n if (response.status === 429) throw new RateLimitError(message);\n throw new APIStatusError(message, response.status);\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 },\n ): Promise<{ response: Response; controller: AbortController }> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.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 ${this.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 let message: string;\n try {\n const body = (await response.json()) as { detail?: string };\n message = body.detail ?? response.statusText;\n } catch {\n message = response.statusText;\n }\n\n if (response.status === 401) throw new AuthenticationError(message);\n if (response.status === 429) throw new RateLimitError(message);\n throw new APIStatusError(message, response.status);\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,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,YAAY,UAAU,uCAAuC;AAC3D,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,iBAAN,cAA6B,SAAS;AAAA,E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YAAM,IAAI,eAAe,SAAS,SAAS,MAAM;AAAA,IACnD;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;;;AnBjNA,IAAO,gBAAQ;","names":["import_chacha","import_hkdf","nobleRandomBytes","TEXT_ENCODER","DECODER","response","ENCODER","DECODER","validateParams","ENCODER","DECODER","validateParams","b64d"]}
|