pendra 0.14.0 → 0.15.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/dist/index.mjs CHANGED
@@ -59,708 +59,786 @@ var APIStreamError = class extends APIError {
59
59
  }
60
60
  };
61
61
 
62
- // src/resources/audio/transcriptions.ts
63
- var MAX_FILE_SIZE = 25 * 1024 * 1024;
64
- var MIME_EXT = {
65
- "audio/mpeg": "mp3",
66
- "audio/mp3": "mp3",
67
- "audio/mp4": "m4a",
68
- "audio/x-m4a": "m4a",
69
- "audio/wav": "wav",
70
- "audio/wave": "wav",
71
- "audio/x-wav": "wav",
72
- "audio/webm": "webm",
73
- "audio/ogg": "ogg",
74
- "audio/flac": "flac",
75
- "audio/x-flac": "flac"
76
- };
77
- function extFromMime(type) {
78
- if (!type) return "mp3";
79
- const base = type.split(";")[0].trim().toLowerCase();
80
- return MIME_EXT[base] ?? "mp3";
81
- }
82
- function asBlob(file) {
83
- if (file instanceof Blob) {
84
- const asFile = file;
85
- if (asFile.name) {
86
- return { blob: file, filename: asFile.name };
87
- }
88
- return { blob: file, filename: `audio.${extFromMime(file.type)}` };
89
- }
90
- const { filename, content } = file;
91
- if (content instanceof Blob) {
92
- return { blob: content, filename };
62
+ // src/_privateInference.ts
63
+ import { chacha20poly1305 as chacha20poly13052 } from "@noble/ciphers/chacha.js";
64
+ import { extract as extract2, expand as expand2 } from "@noble/hashes/hkdf.js";
65
+
66
+ // src/_hpke.ts
67
+ import { x25519 } from "@noble/curves/ed25519.js";
68
+ import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
69
+ import { sha256 } from "@noble/hashes/sha2.js";
70
+ import { hmac } from "@noble/hashes/hmac.js";
71
+ import { extract, expand } from "@noble/hashes/hkdf.js";
72
+ import { randomBytes as nobleRandomBytes } from "@noble/hashes/utils.js";
73
+ var KEM_ID = 32;
74
+ var KDF_ID = 1;
75
+ var AEAD_ID = 3;
76
+ var NH = 32;
77
+ var NK = 32;
78
+ var NN = 12;
79
+ var NSECRET = 32;
80
+ function i2osp(n, len) {
81
+ const out = new Uint8Array(len);
82
+ for (let i = len - 1; i >= 0; i--) {
83
+ out[i] = n & 255;
84
+ n = Math.floor(n / 256);
93
85
  }
94
- return { blob: new Blob([content]), filename };
86
+ return out;
95
87
  }
96
- async function extractErrorDetail(response) {
97
- let raw = "";
98
- try {
99
- raw = await response.text();
100
- } catch {
101
- return response.statusText;
102
- }
103
- if (!raw) return response.statusText;
104
- try {
105
- const body = JSON.parse(raw);
106
- return body.detail ?? body.error?.message ?? raw;
107
- } catch {
108
- return raw;
88
+ var TEXT_ENCODER = new TextEncoder();
89
+ function bytes(s) {
90
+ return TEXT_ENCODER.encode(s);
91
+ }
92
+ function concat(...parts) {
93
+ let total = 0;
94
+ for (const p of parts) total += p.length;
95
+ const out = new Uint8Array(total);
96
+ let off = 0;
97
+ for (const p of parts) {
98
+ out.set(p, off);
99
+ off += p.length;
109
100
  }
101
+ return out;
110
102
  }
111
- var Transcriptions = class {
112
- constructor(client) {
113
- this.client = client;
103
+ var SUITE_ID = concat(bytes("HPKE"), i2osp(KEM_ID, 2), i2osp(KDF_ID, 2), i2osp(AEAD_ID, 2));
104
+ var KEM_SUITE_ID = concat(bytes("KEM"), i2osp(KEM_ID, 2));
105
+ var HPKE_VERSION = bytes("HPKE-v1");
106
+ function hkdfExtract(salt, ikm) {
107
+ const effectiveSalt = salt.length === 0 ? new Uint8Array(NH) : salt;
108
+ return extract(sha256, ikm, effectiveSalt);
109
+ }
110
+ function hkdfExpand(prk, info, length) {
111
+ return expand(sha256, prk, info, length);
112
+ }
113
+ function labeledExtract(salt, label, ikm, suiteId) {
114
+ return hkdfExtract(salt, concat(HPKE_VERSION, suiteId, label, ikm));
115
+ }
116
+ function labeledExpand(prk, label, info, length, suiteId) {
117
+ const labeledInfo = concat(i2osp(length, 2), HPKE_VERSION, suiteId, label, info);
118
+ return hkdfExpand(prk, labeledInfo, length);
119
+ }
120
+ function extractAndExpand(dh, kemContext) {
121
+ const eaePrk = labeledExtract(new Uint8Array(0), bytes("eae_prk"), dh, KEM_SUITE_ID);
122
+ return labeledExpand(eaePrk, bytes("shared_secret"), kemContext, NSECRET, KEM_SUITE_ID);
123
+ }
124
+ function encap(pkR, skE) {
125
+ const skEObj = skE ?? x25519.utils.randomSecretKey();
126
+ const enc = x25519.getPublicKey(skEObj);
127
+ const dh = x25519.getSharedSecret(skEObj, pkR);
128
+ const kemContext = concat(enc, pkR);
129
+ return [extractAndExpand(dh, kemContext), enc];
130
+ }
131
+ var Context = class {
132
+ constructor(key, baseNonce, exporterSecret) {
133
+ this.seq = 0;
134
+ this.key = key;
135
+ this.baseNonce = baseNonce;
136
+ this.exporterSecret = exporterSecret;
114
137
  }
115
- async create(params) {
116
- if (this.client.privateInferenceEnabled) {
117
- throw new Error("private inference is not yet supported for images/audio");
118
- }
119
- if (!params.model) {
120
- throw new Error("model is required");
121
- }
122
- const { blob, filename } = asBlob(params.file);
123
- if (blob.size === 0) {
124
- throw new Error("audio file is empty");
125
- }
126
- if (blob.size > MAX_FILE_SIZE) {
127
- throw new Error(`audio file exceeds ${MAX_FILE_SIZE / (1024 * 1024)}MB limit`);
128
- }
129
- const form = new FormData();
130
- form.append("file", blob, filename);
131
- form.append("model", params.model);
132
- if (params.language) form.append("language", params.language);
133
- if (params.prompt) form.append("prompt", params.prompt);
134
- if (params.response_format) form.append("response_format", params.response_format);
135
- if (params.temperature != null) form.append("temperature", String(params.temperature));
136
- if (params.beam_size != null) form.append("beam_size", String(params.beam_size));
137
- if (params.timestamp_granularities) {
138
- for (const g of params.timestamp_granularities) {
139
- form.append("timestamp_granularities[]", g);
140
- }
141
- }
142
- const timeout = Math.max(this.client.timeout ?? 0, 3e5);
143
- const controller = new AbortController();
144
- const timeoutId = setTimeout(() => controller.abort(), timeout);
145
- let response;
146
- try {
147
- response = await fetch(`${this.client.baseURL}/api/v1/audio/transcriptions`, {
148
- method: "POST",
149
- headers: {
150
- Authorization: `Bearer ${this.client.apiKey}`,
151
- ...params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : {}
152
- },
153
- body: form,
154
- signal: controller.signal
155
- });
156
- } catch (err) {
157
- clearTimeout(timeoutId);
158
- if (err instanceof DOMException && err.name === "AbortError") {
159
- throw new APIConnectionError("Transcription request timed out");
160
- }
161
- throw new APIConnectionError(String(err));
162
- }
163
- clearTimeout(timeoutId);
164
- if (response.status >= 400) {
165
- const detail = await extractErrorDetail(response);
166
- if (response.status === 401) {
167
- throw new AuthenticationError(detail);
168
- }
169
- if (response.status === 429) {
170
- throw new RateLimitError(detail);
171
- }
172
- throw new APIStatusError(detail, response.status);
173
- }
174
- const format = params.response_format;
175
- if (format === "text" || format === "srt" || format === "vtt") {
176
- const text = await response.text();
177
- return { text };
138
+ computeNonce() {
139
+ const seqBytes = i2osp(this.seq, NN);
140
+ const nonce = new Uint8Array(NN);
141
+ for (let i = 0; i < NN; i++) {
142
+ nonce[i] = this.baseNonce[i] ^ seqBytes[i];
178
143
  }
179
- return await response.json();
144
+ return nonce;
180
145
  }
181
- };
182
-
183
- // src/resources/audio/index.ts
184
- var Audio = class {
185
- constructor(client) {
186
- this.transcriptions = new Transcriptions(client);
146
+ seal(aad, pt) {
147
+ const ct = chacha20poly1305(this.key, this.computeNonce(), aad).encrypt(pt);
148
+ this.seq += 1;
149
+ return ct;
150
+ }
151
+ open(aad, ct) {
152
+ const pt = chacha20poly1305(this.key, this.computeNonce(), aad).decrypt(ct);
153
+ this.seq += 1;
154
+ return pt;
155
+ }
156
+ export(exporterContext, length) {
157
+ return labeledExpand(this.exporterSecret, bytes("sec"), exporterContext, length, SUITE_ID);
187
158
  }
188
159
  };
160
+ function keySchedule(sharedSecret, info) {
161
+ const empty = new Uint8Array(0);
162
+ const pskIdHash = labeledExtract(empty, bytes("psk_id_hash"), empty, SUITE_ID);
163
+ const infoHash = labeledExtract(empty, bytes("info_hash"), info, SUITE_ID);
164
+ const keyScheduleContext = concat(new Uint8Array([0]), pskIdHash, infoHash);
165
+ const secret = labeledExtract(sharedSecret, bytes("secret"), empty, SUITE_ID);
166
+ const key = labeledExpand(secret, bytes("key"), keyScheduleContext, NK, SUITE_ID);
167
+ const baseNonce = labeledExpand(secret, bytes("base_nonce"), keyScheduleContext, NN, SUITE_ID);
168
+ const exporterSecret = labeledExpand(secret, bytes("exp"), keyScheduleContext, NH, SUITE_ID);
169
+ return new Context(key, baseNonce, exporterSecret);
170
+ }
171
+ function setupBaseS(pkR, info, skE) {
172
+ const [sharedSecret, enc] = encap(pkR, skE);
173
+ return { enc, ctx: keySchedule(sharedSecret, info) };
174
+ }
175
+ function randomBytes(n) {
176
+ return nobleRandomBytes(n);
177
+ }
178
+ function sha256Hex(data) {
179
+ return Array.from(sha256(data)).map((b) => b.toString(16).padStart(2, "0")).join("");
180
+ }
189
181
 
190
- // src/_parsing.ts
191
- function asString(v) {
192
- return typeof v === "string" ? v : void 0;
182
+ // src/_privateInference.ts
183
+ var ENVELOPE_VERSION = 2;
184
+ var TEXT_ENCODER2 = new TextEncoder();
185
+ var TEXT_DECODER = new TextDecoder();
186
+ var SUITE_INFO = TEXT_ENCODER2.encode("pendra-pi-v1");
187
+ var RESPONSE_EXPORT_CTX = TEXT_ENCODER2.encode("pendra-pi-v1:rdek");
188
+ var AFFINITY_SALT_INFO = TEXT_ENCODER2.encode("pendra-affinity-salt-v1");
189
+ function utf8(s) {
190
+ return TEXT_ENCODER2.encode(s);
193
191
  }
194
- function throwIfInBandError(parsed) {
195
- if (typeof parsed !== "object" || parsed === null) return;
196
- const err = parsed.error;
197
- if (typeof err !== "object" || err === null || Array.isArray(err)) return;
198
- const e = err;
199
- throw new APIStreamError(
200
- asString(e.message) ?? "The server reported an error mid-stream",
201
- {
202
- type: asString(e.type),
203
- code: typeof e.code === "number" ? e.code : void 0,
204
- requestId: asString(e.request_id),
205
- workerId: asString(e.worker_id),
206
- workerName: asString(e.worker_name)
207
- }
208
- );
192
+ function b64(b) {
193
+ if (typeof Buffer !== "undefined") {
194
+ return Buffer.from(b).toString("base64");
195
+ }
196
+ let binary = "";
197
+ for (let i = 0; i < b.length; i++) binary += String.fromCharCode(b[i]);
198
+ return btoa(binary);
209
199
  }
210
- function isChunkShaped(parsed) {
211
- if (typeof parsed !== "object" || parsed === null) return false;
212
- const c = parsed;
213
- return typeof c.id === "string" && typeof c.model === "string" && Array.isArray(c.choices);
200
+ function b64d(s) {
201
+ if (typeof Buffer !== "undefined") {
202
+ return new Uint8Array(Buffer.from(s, "base64"));
203
+ }
204
+ const binary = atob(s);
205
+ const out = new Uint8Array(binary.length);
206
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
207
+ return out;
214
208
  }
215
- function parseStreamFrame(data, label = "Stream frame") {
216
- let parsed;
217
- try {
218
- parsed = JSON.parse(data);
219
- } catch {
220
- throw new APIResponseValidationError(`${label} was not valid JSON`, { body: data });
209
+ function toHex(b) {
210
+ return Array.from(b).map((x) => x.toString(16).padStart(2, "0")).join("");
211
+ }
212
+ function fingerprint(pub) {
213
+ return sha256Hex(pub);
214
+ }
215
+ function buildAad(model, stream, taskType) {
216
+ const streamBit = stream ? utf8("1") : utf8("0");
217
+ const sep = new Uint8Array([0]);
218
+ const parts = [utf8("pendra-pi-v1"), utf8(model), streamBit, utf8(taskType), new Uint8Array(0)];
219
+ let total = 0;
220
+ for (let i = 0; i < parts.length; i++) {
221
+ if (i > 0) total += 1;
222
+ total += parts[i].length;
223
+ }
224
+ const out = new Uint8Array(total);
225
+ let off = 0;
226
+ for (let i = 0; i < parts.length; i++) {
227
+ if (i > 0) {
228
+ out.set(sep, off);
229
+ off += 1;
230
+ }
231
+ out.set(parts[i], off);
232
+ off += parts[i].length;
221
233
  }
222
- throwIfInBandError(parsed);
223
- if (!isChunkShaped(parsed)) {
224
- throw new APIResponseValidationError(`${label} was not a chat completion chunk`, {
225
- body: data
226
- });
234
+ return out;
235
+ }
236
+ function seqNonce(seq) {
237
+ const nonce = new Uint8Array(12);
238
+ let n = BigInt(seq);
239
+ for (let i = 11; i >= 4; i--) {
240
+ nonce[i] = Number(n & 0xffn);
241
+ n >>= 8n;
227
242
  }
228
- return parsed;
243
+ return nonce;
229
244
  }
230
- function completionFrom(parsed, body, status) {
231
- if (typeof parsed !== "object" || parsed === null) {
232
- throw new APIResponseValidationError("Response was not a chat completion", { status, body });
245
+ function sealRequest(orgPubs, body, opts) {
246
+ const pubs = Array.isArray(orgPubs) ? orgPubs : [orgPubs];
247
+ if (pubs.length === 0) {
248
+ throw new Error("sealRequest: no org public keys to seal to");
233
249
  }
234
- const c = parsed;
235
- if (typeof c.id !== "string" || typeof c.model !== "string" || !Array.isArray(c.choices)) {
236
- throw new APIResponseValidationError("Response was not a chat completion", { status, body });
250
+ const seen = /* @__PURE__ */ new Set();
251
+ const uniquePubs = [];
252
+ for (const p of pubs) {
253
+ const fp = fingerprint(p);
254
+ if (!seen.has(fp)) {
255
+ seen.add(fp);
256
+ uniquePubs.push(p);
257
+ }
237
258
  }
238
- return parsed;
239
- }
240
- async function parseCompletion(response) {
241
- const body = await response.text();
242
- let parsed;
243
- try {
244
- parsed = JSON.parse(body);
245
- } catch {
246
- throw new APIResponseValidationError("Response was not valid JSON", {
247
- status: response.status,
248
- body
249
- });
259
+ const dek = randomBytes(32);
260
+ const nonce = randomBytes(12);
261
+ const aad = buildAad(opts.model, opts.stream, opts.taskType);
262
+ const ciphertext = chacha20poly13052(dek, nonce, aad).encrypt(body);
263
+ const recipients = [];
264
+ const responseKeys = /* @__PURE__ */ new Map();
265
+ for (const pub of uniquePubs) {
266
+ const { enc, ctx: sealer } = setupBaseS(pub, SUITE_INFO);
267
+ const sealedDek = sealer.seal(new Uint8Array(0), dek);
268
+ const kid = fingerprint(pub);
269
+ responseKeys.set(kid, sealer.export(RESPONSE_EXPORT_CTX, 32));
270
+ recipients.push({ kid, enc: b64(enc), sealed_dek: b64(sealedDek) });
250
271
  }
251
- return completionFrom(parsed, body, response.status);
252
- }
253
- function parseDecryptedCompletion(json, status) {
254
- let parsed;
255
- try {
256
- parsed = JSON.parse(json);
257
- } catch {
258
- throw new APIResponseValidationError("Decrypted response was not valid JSON", {
259
- status,
260
- body: json
261
- });
272
+ const envelope = {
273
+ v: ENVELOPE_VERSION,
274
+ recipients,
275
+ nonce: b64(nonce),
276
+ ciphertext: b64(ciphertext)
277
+ };
278
+ if (opts.affinityKey != null) {
279
+ envelope.affinity_key = opts.affinityKey;
262
280
  }
263
- try {
264
- return completionFrom(parsed, json, status);
265
- } catch {
266
- throw new APIResponseValidationError("Decrypted response was not a chat completion", {
267
- status,
268
- body: json
269
- });
281
+ if (opts.binary != null) {
282
+ const binaryNonce = randomBytes(12);
283
+ envelope.binary_nonce = b64(binaryNonce);
284
+ envelope.binary_ciphertext = b64(chacha20poly13052(dek, binaryNonce, aad).encrypt(opts.binary));
270
285
  }
286
+ return { envelope, responseKeys };
271
287
  }
272
-
273
- // src/_sse.ts
274
- var DEFAULT_EVENT = "message";
275
- function fieldValue(line, name) {
276
- const value = line.slice(name.length + 1);
277
- return value.startsWith(" ") ? value.slice(1) : value;
288
+ var API_TIMING_CHUNK_KEYS = /* @__PURE__ */ new Set(["id", "object", "created", "model", "choices", "pendra"]);
289
+ function isApiTimingChunk(frame) {
290
+ if (frame === null || typeof frame !== "object" || Array.isArray(frame)) return false;
291
+ const obj = frame;
292
+ const pendra = obj.pendra;
293
+ return Object.keys(obj).every((k) => API_TIMING_CHUNK_KEYS.has(k)) && Array.isArray(obj.choices) && obj.choices.length === 0 && pendra !== null && typeof pendra === "object" && Object.keys(pendra).length === 1 && "timing" in pendra;
278
294
  }
279
- var SseDecoder = class {
280
- constructor() {
281
- this.buffer = "";
282
- this.event = "";
283
- this.data = [];
284
- }
285
- /** Feed a chunk of decoded text; returns the payloads it completed. */
286
- push(text) {
287
- this.buffer += text;
288
- const lines = this.buffer.split("\n");
289
- this.buffer = lines.pop() ?? "";
290
- const out = [];
291
- for (const line of lines) {
292
- const payload = this.pushLine(line);
293
- if (payload !== null) out.push(payload);
294
- }
295
- return out;
296
- }
297
- /**
298
- * Release what the stream ended without terminating: the held-back partial
299
- * line, plus any frame that never got its blank line.
300
- *
301
- * The spec discards an unterminated final block; we keep it, so a connection
302
- * that drops after the last `data:` line but before its blank line still
303
- * delivers that payload rather than silently losing it.
304
- */
305
- flush() {
306
- const out = [];
307
- if (this.buffer !== "") {
308
- const payload = this.pushLine(this.buffer);
309
- this.buffer = "";
310
- if (payload !== null) out.push(payload);
311
- }
312
- const tail = this.endFrame();
313
- if (tail !== null) out.push(tail);
314
- return out;
295
+ function unsealedReplyError() {
296
+ return new Error(
297
+ "private_inference: refusing an unencrypted reply to an encrypted request (it could have been forged in transit)"
298
+ );
299
+ }
300
+ var ResponseDecryptor = class {
301
+ constructor(responseKeys) {
302
+ this.dek = null;
303
+ this.nextSeq = 0;
304
+ this.keys = responseKeys;
315
305
  }
316
- pushLine(rawLine) {
317
- const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
318
- if (line === "") return this.endFrame();
319
- if (line.startsWith(":")) return null;
320
- if (line.startsWith("event:")) {
321
- this.event = fieldValue(line, "event");
322
- return null;
306
+ ensureDek(inner) {
307
+ if (inner.v !== ENVELOPE_VERSION || inner.enc !== void 0) {
308
+ throw new Error(
309
+ "private_inference: refusing a response that is not in v2 form (it could have been forged in transit)"
310
+ );
323
311
  }
324
- if (line.startsWith("data:")) {
325
- this.data.push(fieldValue(line, "data"));
326
- return null;
312
+ if (this.dek !== null) return;
313
+ const dek = inner.kid === void 0 ? void 0 : this.keys.get(inner.kid);
314
+ if (dek === void 0) {
315
+ throw new Error("private_inference: first response frame names no key this request was sealed to");
327
316
  }
328
- return null;
329
- }
330
- endFrame() {
331
- const { data, event } = this;
332
- this.data = [];
333
- this.event = "";
334
- if (data.length === 0) return null;
335
- if (event !== "" && event !== DEFAULT_EVENT) return null;
336
- return data.join("\n");
317
+ this.dek = dek;
337
318
  }
338
- };
339
-
340
- // src/streaming.ts
341
- var Stream = class {
342
- constructor(response, controller, idleTimeoutMs) {
343
- this.decoder = new TextDecoder();
344
- this.sse = new SseDecoder();
345
- this.done = false;
346
- if (!response.body) {
347
- throw new Error("Response body is null \u2014 streaming not supported");
348
- }
349
- this.reader = response.body.getReader();
350
- this.controller = controller;
351
- this.idleTimeoutMs = idleTimeoutMs;
319
+ /** Decrypt a non-streaming result envelope `{v, kid, seq, ciphertext}`. */
320
+ openResult(inner) {
321
+ this.ensureDek(inner);
322
+ return chacha20poly13052(this.dek, seqNonce(Number(inner.seq))).decrypt(b64d(inner.ciphertext));
352
323
  }
353
- async *[Symbol.asyncIterator]() {
354
- try {
355
- while (!this.done) {
356
- const { value, done: readerDone } = await readWithIdleTimeout(
357
- this.reader,
358
- this.idleTimeoutMs
359
- );
360
- const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
361
- for (const data of payloads) {
362
- if (data === "[DONE]") {
363
- this.done = true;
364
- return;
365
- }
366
- yield parseStreamFrame(data);
367
- }
368
- if (readerDone) {
369
- this.done = true;
370
- break;
371
- }
372
- }
373
- } finally {
374
- releaseReader(this.reader, this.controller, this.done);
324
+ /** Decrypt one streaming chunk envelope, enforcing monotonic `seq`. */
325
+ openChunk(inner) {
326
+ const seq = Number(inner.seq);
327
+ if (seq !== this.nextSeq) {
328
+ throw new Error(
329
+ `private_inference: out-of-order response chunk (seq ${seq}, expected ${this.nextSeq})`
330
+ );
375
331
  }
376
- }
377
- abort() {
378
- this.done = true;
379
- this.controller.abort();
332
+ this.ensureDek(inner);
333
+ const pt = chacha20poly13052(this.dek, seqNonce(seq)).decrypt(b64d(inner.ciphertext));
334
+ this.nextSeq += 1;
335
+ return pt;
380
336
  }
381
337
  };
382
- async function readWithIdleTimeout(reader, idleTimeoutMs) {
383
- if (!idleTimeoutMs) return reader.read();
384
- let timer;
385
- const idle = new Promise((_, reject) => {
386
- timer = setTimeout(
387
- () => reject(new APIConnectionError(`Stream received no data for ${idleTimeoutMs}ms`)),
388
- idleTimeoutMs
389
- );
390
- });
391
- try {
392
- return await Promise.race([reader.read(), idle]);
393
- } finally {
394
- clearTimeout(timer);
338
+ function deriveSalt(rawApiKey) {
339
+ const prk = extract2(sha256, utf8(rawApiKey), new Uint8Array(32));
340
+ return expand2(sha256, prk, AFFINITY_SALT_INFO, 32);
341
+ }
342
+ function canonicalJson(value) {
343
+ if (value === null) return "null";
344
+ const t = typeof value;
345
+ if (t === "boolean") return value ? "true" : "false";
346
+ if (t === "number") {
347
+ return String(value);
395
348
  }
396
- }
397
- function releaseReader(reader, controller, finished) {
398
- if (!finished) {
399
- controller.abort();
400
- reader.cancel().catch(() => {
401
- });
349
+ if (t === "string") return encodeString(value);
350
+ if (Array.isArray(value)) {
351
+ return "[" + value.map((v) => canonicalJson(v)).join(",") + "]";
402
352
  }
403
- reader.releaseLock();
404
- }
405
-
406
- // src/_privateInference.ts
407
- import { chacha20poly1305 as chacha20poly13052 } from "@noble/ciphers/chacha.js";
408
- import { extract as extract2, expand as expand2 } from "@noble/hashes/hkdf.js";
409
-
410
- // src/_hpke.ts
411
- import { x25519 } from "@noble/curves/ed25519.js";
412
- import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
413
- import { sha256 } from "@noble/hashes/sha2.js";
414
- import { hmac } from "@noble/hashes/hmac.js";
415
- import { extract, expand } from "@noble/hashes/hkdf.js";
416
- import { randomBytes as nobleRandomBytes } from "@noble/hashes/utils.js";
417
- var KEM_ID = 32;
418
- var KDF_ID = 1;
419
- var AEAD_ID = 3;
420
- var NH = 32;
421
- var NK = 32;
422
- var NN = 12;
423
- var NSECRET = 32;
424
- function i2osp(n, len) {
425
- const out = new Uint8Array(len);
426
- for (let i = len - 1; i >= 0; i--) {
427
- out[i] = n & 255;
428
- n = Math.floor(n / 256);
353
+ if (t === "object") {
354
+ const obj = value;
355
+ const keys = Object.keys(obj).sort();
356
+ const items = keys.map((k) => encodeString(k) + ":" + canonicalJson(obj[k]));
357
+ return "{" + items.join(",") + "}";
429
358
  }
430
- return out;
431
- }
432
- var TEXT_ENCODER = new TextEncoder();
433
- function bytes(s) {
434
- return TEXT_ENCODER.encode(s);
359
+ return "null";
435
360
  }
436
- function concat(...parts) {
437
- let total = 0;
438
- for (const p of parts) total += p.length;
439
- const out = new Uint8Array(total);
440
- let off = 0;
441
- for (const p of parts) {
442
- out.set(p, off);
443
- off += p.length;
361
+ function encodeString(s) {
362
+ let out = '"';
363
+ for (let i = 0; i < s.length; i++) {
364
+ const code = s.charCodeAt(i);
365
+ switch (code) {
366
+ case 34:
367
+ out += '\\"';
368
+ break;
369
+ case 92:
370
+ out += "\\\\";
371
+ break;
372
+ case 8:
373
+ out += "\\b";
374
+ break;
375
+ case 9:
376
+ out += "\\t";
377
+ break;
378
+ case 10:
379
+ out += "\\n";
380
+ break;
381
+ case 12:
382
+ out += "\\f";
383
+ break;
384
+ case 13:
385
+ out += "\\r";
386
+ break;
387
+ default:
388
+ if (code < 32 || code > 126) {
389
+ out += "\\u" + code.toString(16).padStart(4, "0");
390
+ } else {
391
+ out += s[i];
392
+ }
393
+ }
444
394
  }
445
- return out;
446
- }
447
- var SUITE_ID = concat(bytes("HPKE"), i2osp(KEM_ID, 2), i2osp(KDF_ID, 2), i2osp(AEAD_ID, 2));
448
- var KEM_SUITE_ID = concat(bytes("KEM"), i2osp(KEM_ID, 2));
449
- var HPKE_VERSION = bytes("HPKE-v1");
450
- function hkdfExtract(salt, ikm) {
451
- const effectiveSalt = salt.length === 0 ? new Uint8Array(NH) : salt;
452
- return extract(sha256, ikm, effectiveSalt);
395
+ return out + '"';
453
396
  }
454
- function hkdfExpand(prk, info, length) {
455
- return expand(sha256, prk, info, length);
397
+ function flattenContent(content) {
398
+ if (typeof content === "string") return content;
399
+ return canonicalJson(content);
456
400
  }
457
- function labeledExtract(salt, label, ikm, suiteId) {
458
- return hkdfExtract(salt, concat(HPKE_VERSION, suiteId, label, ikm));
401
+ function affinityKey(rawApiKey, model, messages, saltOverride) {
402
+ const parts = ["model=" + model];
403
+ let sawUser = false;
404
+ for (const m of messages ?? []) {
405
+ const role = m.role ?? "";
406
+ parts.push(role + ":" + flattenContent(m.content));
407
+ if (role === "user") {
408
+ sawUser = true;
409
+ break;
410
+ }
411
+ }
412
+ if (!sawUser) return null;
413
+ const salt = saltOverride != null ? saltOverride : deriveSalt(rawApiKey);
414
+ const mac = hmac(sha256, salt, utf8(parts.join("\0")));
415
+ return toHex(mac);
459
416
  }
460
- function labeledExpand(prk, label, info, length, suiteId) {
461
- const labeledInfo = concat(i2osp(length, 2), HPKE_VERSION, suiteId, label, info);
462
- return hkdfExpand(prk, labeledInfo, length);
417
+
418
+ // src/_parsing.ts
419
+ function asString(v) {
420
+ return typeof v === "string" ? v : void 0;
463
421
  }
464
- function extractAndExpand(dh, kemContext) {
465
- const eaePrk = labeledExtract(new Uint8Array(0), bytes("eae_prk"), dh, KEM_SUITE_ID);
466
- return labeledExpand(eaePrk, bytes("shared_secret"), kemContext, NSECRET, KEM_SUITE_ID);
422
+ function throwIfInBandError(parsed, fallback = "The server reported an error mid-stream") {
423
+ if (typeof parsed !== "object" || parsed === null) return;
424
+ const err = parsed.error;
425
+ if (typeof err !== "object" || err === null || Array.isArray(err)) return;
426
+ const e = err;
427
+ throw new APIStreamError(
428
+ asString(e.message) ?? fallback,
429
+ {
430
+ type: asString(e.type),
431
+ code: typeof e.code === "number" ? e.code : void 0,
432
+ requestId: asString(e.request_id),
433
+ workerId: asString(e.worker_id),
434
+ workerName: asString(e.worker_name)
435
+ }
436
+ );
467
437
  }
468
- function encap(pkR, skE) {
469
- const skEObj = skE ?? x25519.utils.randomSecretKey();
470
- const enc = x25519.getPublicKey(skEObj);
471
- const dh = x25519.getSharedSecret(skEObj, pkR);
472
- const kemContext = concat(enc, pkR);
473
- return [extractAndExpand(dh, kemContext), enc];
438
+ function isChunkShaped(parsed) {
439
+ if (typeof parsed !== "object" || parsed === null) return false;
440
+ const c = parsed;
441
+ return typeof c.id === "string" && typeof c.model === "string" && Array.isArray(c.choices);
474
442
  }
475
- var Context = class {
476
- constructor(key, baseNonce, exporterSecret) {
477
- this.seq = 0;
478
- this.key = key;
479
- this.baseNonce = baseNonce;
480
- this.exporterSecret = exporterSecret;
481
- }
482
- computeNonce() {
483
- const seqBytes = i2osp(this.seq, NN);
484
- const nonce = new Uint8Array(NN);
485
- for (let i = 0; i < NN; i++) {
486
- nonce[i] = this.baseNonce[i] ^ seqBytes[i];
487
- }
488
- return nonce;
443
+ function parseStreamFrame(data, label = "Stream frame") {
444
+ let parsed;
445
+ try {
446
+ parsed = JSON.parse(data);
447
+ } catch {
448
+ throw new APIResponseValidationError(`${label} was not valid JSON`, { body: data });
489
449
  }
490
- seal(aad, pt) {
491
- const ct = chacha20poly1305(this.key, this.computeNonce(), aad).encrypt(pt);
492
- this.seq += 1;
493
- return ct;
450
+ throwIfInBandError(parsed);
451
+ if (!isChunkShaped(parsed)) {
452
+ throw new APIResponseValidationError(`${label} was not a chat completion chunk`, {
453
+ body: data
454
+ });
494
455
  }
495
- open(aad, ct) {
496
- const pt = chacha20poly1305(this.key, this.computeNonce(), aad).decrypt(ct);
497
- this.seq += 1;
498
- return pt;
456
+ return parsed;
457
+ }
458
+ function completionFrom(parsed, body, status) {
459
+ if (typeof parsed !== "object" || parsed === null) {
460
+ throw new APIResponseValidationError("Response was not a chat completion", { status, body });
499
461
  }
500
- export(exporterContext, length) {
501
- return labeledExpand(this.exporterSecret, bytes("sec"), exporterContext, length, SUITE_ID);
462
+ const c = parsed;
463
+ if (typeof c.id !== "string" || typeof c.model !== "string" || !Array.isArray(c.choices)) {
464
+ throw new APIResponseValidationError("Response was not a chat completion", { status, body });
502
465
  }
503
- };
504
- function keySchedule(sharedSecret, info) {
505
- const empty = new Uint8Array(0);
506
- const pskIdHash = labeledExtract(empty, bytes("psk_id_hash"), empty, SUITE_ID);
507
- const infoHash = labeledExtract(empty, bytes("info_hash"), info, SUITE_ID);
508
- const keyScheduleContext = concat(new Uint8Array([0]), pskIdHash, infoHash);
509
- const secret = labeledExtract(sharedSecret, bytes("secret"), empty, SUITE_ID);
510
- const key = labeledExpand(secret, bytes("key"), keyScheduleContext, NK, SUITE_ID);
511
- const baseNonce = labeledExpand(secret, bytes("base_nonce"), keyScheduleContext, NN, SUITE_ID);
512
- const exporterSecret = labeledExpand(secret, bytes("exp"), keyScheduleContext, NH, SUITE_ID);
513
- return new Context(key, baseNonce, exporterSecret);
514
- }
515
- function setupBaseS(pkR, info, skE) {
516
- const [sharedSecret, enc] = encap(pkR, skE);
517
- return { enc, ctx: keySchedule(sharedSecret, info) };
518
- }
519
- function randomBytes(n) {
520
- return nobleRandomBytes(n);
521
- }
522
- function sha256Hex(data) {
523
- return Array.from(sha256(data)).map((b) => b.toString(16).padStart(2, "0")).join("");
466
+ return parsed;
524
467
  }
525
-
526
- // src/_privateInference.ts
527
- var ENVELOPE_VERSION = 2;
528
- var TEXT_ENCODER2 = new TextEncoder();
529
- var TEXT_DECODER = new TextDecoder();
530
- var SUITE_INFO = TEXT_ENCODER2.encode("pendra-pi-v1");
531
- var RESPONSE_EXPORT_CTX = TEXT_ENCODER2.encode("pendra-pi-v1:rdek");
532
- var AFFINITY_SALT_INFO = TEXT_ENCODER2.encode("pendra-affinity-salt-v1");
533
- function utf8(s) {
534
- return TEXT_ENCODER2.encode(s);
468
+ async function parseCompletion(response) {
469
+ const body = await response.text();
470
+ let parsed;
471
+ try {
472
+ parsed = JSON.parse(body);
473
+ } catch {
474
+ throw new APIResponseValidationError("Response was not valid JSON", {
475
+ status: response.status,
476
+ body
477
+ });
478
+ }
479
+ return completionFrom(parsed, body, response.status);
535
480
  }
536
- function b64(b) {
537
- if (typeof Buffer !== "undefined") {
538
- return Buffer.from(b).toString("base64");
481
+ function parseDecryptedCompletion(json, status) {
482
+ let parsed;
483
+ try {
484
+ parsed = JSON.parse(json);
485
+ } catch {
486
+ throw new APIResponseValidationError("Decrypted response was not valid JSON", {
487
+ status,
488
+ body: json
489
+ });
490
+ }
491
+ try {
492
+ return completionFrom(parsed, json, status);
493
+ } catch {
494
+ throw new APIResponseValidationError("Decrypted response was not a chat completion", {
495
+ status,
496
+ body: json
497
+ });
539
498
  }
540
- let binary = "";
541
- for (let i = 0; i < b.length; i++) binary += String.fromCharCode(b[i]);
542
- return btoa(binary);
543
499
  }
544
- function b64d(s) {
545
- if (typeof Buffer !== "undefined") {
546
- return new Uint8Array(Buffer.from(s, "base64"));
500
+ async function readSealedReply(response) {
501
+ const body = await response.text();
502
+ let parsed;
503
+ try {
504
+ parsed = JSON.parse(body);
505
+ } catch {
506
+ throw new APIResponseValidationError("Response was not valid JSON", {
507
+ status: response.status,
508
+ body
509
+ });
547
510
  }
548
- const binary = atob(s);
549
- const out = new Uint8Array(binary.length);
550
- for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
551
- return out;
511
+ throwIfInBandError(parsed, "The server reported an error");
512
+ const inner = typeof parsed === "object" && parsed !== null ? parsed.pendra_encrypted : void 0;
513
+ if (!inner) throw unsealedReplyError();
514
+ return inner;
552
515
  }
553
- function toHex(b) {
554
- return Array.from(b).map((x) => x.toString(16).padStart(2, "0")).join("");
516
+ function parseDecryptedJson(json, status) {
517
+ try {
518
+ return JSON.parse(json);
519
+ } catch {
520
+ throw new APIResponseValidationError("Decrypted response was not valid JSON", {
521
+ status,
522
+ body: json
523
+ });
524
+ }
555
525
  }
556
- function fingerprint(pub) {
557
- return sha256Hex(pub);
526
+
527
+ // src/resources/audio/transcriptions.ts
528
+ var ENCODER = new TextEncoder();
529
+ var DECODER = new TextDecoder();
530
+ var MAX_FILE_SIZE = 25 * 1024 * 1024;
531
+ var MIME_EXT = {
532
+ "audio/mpeg": "mp3",
533
+ "audio/mp3": "mp3",
534
+ "audio/mp4": "m4a",
535
+ "audio/x-m4a": "m4a",
536
+ "audio/wav": "wav",
537
+ "audio/wave": "wav",
538
+ "audio/x-wav": "wav",
539
+ "audio/webm": "webm",
540
+ "audio/ogg": "ogg",
541
+ "audio/flac": "flac",
542
+ "audio/x-flac": "flac"
543
+ };
544
+ function extFromMime(type) {
545
+ if (!type) return "mp3";
546
+ const base = type.split(";")[0].trim().toLowerCase();
547
+ return MIME_EXT[base] ?? "mp3";
558
548
  }
559
- function buildAad(model, stream, taskType) {
560
- const streamBit = stream ? utf8("1") : utf8("0");
561
- const sep = new Uint8Array([0]);
562
- const parts = [utf8("pendra-pi-v1"), utf8(model), streamBit, utf8(taskType), new Uint8Array(0)];
563
- let total = 0;
564
- for (let i = 0; i < parts.length; i++) {
565
- if (i > 0) total += 1;
566
- total += parts[i].length;
567
- }
568
- const out = new Uint8Array(total);
569
- let off = 0;
570
- for (let i = 0; i < parts.length; i++) {
571
- if (i > 0) {
572
- out.set(sep, off);
573
- off += 1;
549
+ function asBlob(file) {
550
+ if (file instanceof Blob) {
551
+ const asFile = file;
552
+ if (asFile.name) {
553
+ return { blob: file, filename: asFile.name };
574
554
  }
575
- out.set(parts[i], off);
576
- off += parts[i].length;
555
+ return { blob: file, filename: `audio.${extFromMime(file.type)}` };
577
556
  }
578
- return out;
557
+ const { filename, content } = file;
558
+ if (content instanceof Blob) {
559
+ return { blob: content, filename };
560
+ }
561
+ return { blob: new Blob([content]), filename };
579
562
  }
580
- function seqNonce(seq) {
581
- const nonce = new Uint8Array(12);
582
- let n = BigInt(seq);
583
- for (let i = 11; i >= 4; i--) {
584
- nonce[i] = Number(n & 0xffn);
585
- n >>= 8n;
563
+ async function extractErrorDetail(response) {
564
+ let raw = "";
565
+ try {
566
+ raw = await response.text();
567
+ } catch {
568
+ return response.statusText;
569
+ }
570
+ if (!raw) return response.statusText;
571
+ try {
572
+ const body = JSON.parse(raw);
573
+ return body.detail ?? body.error?.message ?? raw;
574
+ } catch {
575
+ return raw;
586
576
  }
587
- return nonce;
588
577
  }
589
- function sealRequest(orgPubs, body, opts) {
590
- const pubs = Array.isArray(orgPubs) ? orgPubs : [orgPubs];
591
- if (pubs.length === 0) {
592
- throw new Error("sealRequest: no org public keys to seal to");
578
+ var Transcriptions = class {
579
+ constructor(client) {
580
+ this.client = client;
593
581
  }
594
- const seen = /* @__PURE__ */ new Set();
595
- const uniquePubs = [];
596
- for (const p of pubs) {
597
- const fp = fingerprint(p);
598
- if (!seen.has(fp)) {
599
- seen.add(fp);
600
- uniquePubs.push(p);
582
+ async create(params) {
583
+ if (!params.model) {
584
+ throw new Error("model is required");
601
585
  }
586
+ if (params.beam_size != null && !(Number.isInteger(params.beam_size) && params.beam_size >= 1 && params.beam_size <= 8)) {
587
+ throw new Error(`beam_size must be an integer between 1 and 8 (got ${params.beam_size})`);
588
+ }
589
+ const { blob, filename } = asBlob(params.file);
590
+ if (blob.size === 0) {
591
+ throw new Error("audio file is empty");
592
+ }
593
+ if (blob.size > MAX_FILE_SIZE) {
594
+ throw new Error(`audio file exceeds ${MAX_FILE_SIZE / (1024 * 1024)}MB limit`);
595
+ }
596
+ const timeout = Math.max(this.client.timeout ?? 0, 3e5);
597
+ if (this.client.privateInferenceEnabled) {
598
+ return this.createEncrypted(params, blob, timeout);
599
+ }
600
+ const form = new FormData();
601
+ form.append("file", blob, filename);
602
+ form.append("model", params.model);
603
+ if (params.language) form.append("language", params.language);
604
+ if (params.prompt) form.append("prompt", params.prompt);
605
+ if (params.response_format) form.append("response_format", params.response_format);
606
+ if (params.temperature != null) form.append("temperature", String(params.temperature));
607
+ if (params.beam_size != null) form.append("beam_size", String(params.beam_size));
608
+ if (params.timestamp_granularities) {
609
+ for (const g of params.timestamp_granularities) {
610
+ form.append("timestamp_granularities[]", g);
611
+ }
612
+ }
613
+ const controller = new AbortController();
614
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
615
+ let response;
616
+ try {
617
+ response = await fetch(`${this.client.baseURL}/api/v1/audio/transcriptions`, {
618
+ method: "POST",
619
+ headers: {
620
+ Authorization: `Bearer ${this.client.apiKey}`,
621
+ ...params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : {}
622
+ },
623
+ body: form,
624
+ signal: controller.signal
625
+ });
626
+ } catch (err) {
627
+ clearTimeout(timeoutId);
628
+ if (err instanceof DOMException && err.name === "AbortError") {
629
+ throw new APIConnectionError("Transcription request timed out");
630
+ }
631
+ throw new APIConnectionError(String(err));
632
+ }
633
+ clearTimeout(timeoutId);
634
+ if (response.status >= 400) {
635
+ const detail = await extractErrorDetail(response);
636
+ if (response.status === 401) {
637
+ throw new AuthenticationError(detail);
638
+ }
639
+ if (response.status === 429) {
640
+ throw new RateLimitError(detail);
641
+ }
642
+ throw new APIStatusError(detail, response.status);
643
+ }
644
+ const format = params.response_format;
645
+ if (format === "text" || format === "srt" || format === "vtt") {
646
+ const text = await response.text();
647
+ return { text };
648
+ }
649
+ return await response.json();
602
650
  }
603
- const dek = randomBytes(32);
604
- const nonce = randomBytes(12);
605
- const aad = buildAad(opts.model, opts.stream, opts.taskType);
606
- const ciphertext = chacha20poly13052(dek, nonce, aad).encrypt(body);
607
- const recipients = [];
608
- const responseKeys = /* @__PURE__ */ new Map();
609
- for (const pub of uniquePubs) {
610
- const { enc, ctx: sealer } = setupBaseS(pub, SUITE_INFO);
611
- const sealedDek = sealer.seal(new Uint8Array(0), dek);
612
- const kid = fingerprint(pub);
613
- responseKeys.set(kid, sealer.export(RESPONSE_EXPORT_CTX, 32));
614
- recipients.push({ kid, enc: b64(enc), sealed_dek: b64(sealedDek) });
615
- }
616
- const envelope = {
617
- v: ENVELOPE_VERSION,
618
- recipients,
619
- nonce: b64(nonce),
620
- ciphertext: b64(ciphertext)
621
- };
622
- if (opts.affinityKey != null) {
623
- envelope.affinity_key = opts.affinityKey;
651
+ /**
652
+ * Private-inference transcription. There is no multipart upload: the audio
653
+ * bytes ride inside the envelope (sealed under the request's data key) and
654
+ * the request options are the sealed JSON body, POSTed as JSON to the same
655
+ * route.
656
+ */
657
+ async createEncrypted(params, blob, timeout) {
658
+ const body = { model: params.model };
659
+ if (params.language) body.language = params.language;
660
+ if (params.prompt) body.prompt = params.prompt;
661
+ if (params.response_format) body.response_format = params.response_format;
662
+ if (params.temperature != null) body.temperature = params.temperature;
663
+ if (params.beam_size != null) body.beam_size = params.beam_size;
664
+ if (params.timestamp_granularities) {
665
+ body.timestamp_granularities = params.timestamp_granularities;
666
+ }
667
+ const engine = await this.client._privateEngine();
668
+ const { topLevel, decryptor } = engine.seal({
669
+ model: params.model,
670
+ stream: false,
671
+ taskType: "transcription",
672
+ body: ENCODER.encode(JSON.stringify(body)),
673
+ binary: new Uint8Array(await blob.arrayBuffer())
674
+ });
675
+ const { response } = await this.client._fetch(
676
+ "/api/v1/audio/transcriptions",
677
+ {
678
+ method: "POST",
679
+ body: topLevel,
680
+ headers: params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0,
681
+ timeout
682
+ }
683
+ );
684
+ const raw = DECODER.decode(decryptor.openResult(await readSealedReply(response)));
685
+ const parsed = parseDecryptedJson(raw, response.status);
686
+ if (typeof parsed === "string") return { text: parsed };
687
+ if (typeof parsed === "object" && parsed !== null) {
688
+ if (typeof parsed.text !== "string") {
689
+ throw new APIResponseValidationError("Decrypted response was not a transcription", {
690
+ status: response.status,
691
+ body: raw
692
+ });
693
+ }
694
+ return parsed;
695
+ }
696
+ return { text: raw };
624
697
  }
625
- if (opts.binary != null) {
626
- const binaryNonce = randomBytes(12);
627
- envelope.binary_nonce = b64(binaryNonce);
628
- envelope.binary_ciphertext = b64(chacha20poly13052(dek, binaryNonce, aad).encrypt(opts.binary));
698
+ };
699
+
700
+ // src/resources/audio/index.ts
701
+ var Audio = class {
702
+ constructor(client) {
703
+ this.transcriptions = new Transcriptions(client);
629
704
  }
630
- return { envelope, responseKeys };
631
- }
632
- var API_TIMING_CHUNK_KEYS = /* @__PURE__ */ new Set(["id", "object", "created", "model", "choices", "pendra"]);
633
- function isApiTimingChunk(frame) {
634
- if (frame === null || typeof frame !== "object" || Array.isArray(frame)) return false;
635
- const obj = frame;
636
- const pendra = obj.pendra;
637
- return Object.keys(obj).every((k) => API_TIMING_CHUNK_KEYS.has(k)) && Array.isArray(obj.choices) && obj.choices.length === 0 && pendra !== null && typeof pendra === "object" && Object.keys(pendra).length === 1 && "timing" in pendra;
638
- }
639
- function unsealedReplyError() {
640
- return new Error(
641
- "private_inference: refusing an unencrypted reply to an encrypted request (it could have been forged in transit)"
642
- );
643
- }
644
- var ResponseDecryptor = class {
645
- constructor(responseKeys) {
646
- this.dek = null;
647
- this.nextSeq = 0;
648
- this.keys = responseKeys;
705
+ };
706
+
707
+ // src/_sse.ts
708
+ var DEFAULT_EVENT = "message";
709
+ function fieldValue(line, name) {
710
+ const value = line.slice(name.length + 1);
711
+ return value.startsWith(" ") ? value.slice(1) : value;
712
+ }
713
+ var SseDecoder = class {
714
+ constructor() {
715
+ this.buffer = "";
716
+ this.event = "";
717
+ this.data = [];
649
718
  }
650
- ensureDek(inner) {
651
- if (inner.v !== ENVELOPE_VERSION || inner.enc !== void 0) {
652
- throw new Error(
653
- "private_inference: refusing a response that is not in v2 form (it could have been forged in transit)"
654
- );
655
- }
656
- if (this.dek !== null) return;
657
- const dek = inner.kid === void 0 ? void 0 : this.keys.get(inner.kid);
658
- if (dek === void 0) {
659
- throw new Error("private_inference: first response frame names no key this request was sealed to");
719
+ /** Feed a chunk of decoded text; returns the payloads it completed. */
720
+ push(text) {
721
+ this.buffer += text;
722
+ const lines = this.buffer.split("\n");
723
+ this.buffer = lines.pop() ?? "";
724
+ const out = [];
725
+ for (const line of lines) {
726
+ const payload = this.pushLine(line);
727
+ if (payload !== null) out.push(payload);
660
728
  }
661
- this.dek = dek;
662
- }
663
- /** Decrypt a non-streaming result envelope `{v, kid, seq, ciphertext}`. */
664
- openResult(inner) {
665
- this.ensureDek(inner);
666
- return chacha20poly13052(this.dek, seqNonce(Number(inner.seq))).decrypt(b64d(inner.ciphertext));
729
+ return out;
667
730
  }
668
- /** Decrypt one streaming chunk envelope, enforcing monotonic `seq`. */
669
- openChunk(inner) {
670
- const seq = Number(inner.seq);
671
- if (seq !== this.nextSeq) {
672
- throw new Error(
673
- `private_inference: out-of-order response chunk (seq ${seq}, expected ${this.nextSeq})`
674
- );
731
+ /**
732
+ * Release what the stream ended without terminating: the held-back partial
733
+ * line, plus any frame that never got its blank line.
734
+ *
735
+ * The spec discards an unterminated final block; we keep it, so a connection
736
+ * that drops after the last `data:` line but before its blank line still
737
+ * delivers that payload rather than silently losing it.
738
+ */
739
+ flush() {
740
+ const out = [];
741
+ if (this.buffer !== "") {
742
+ const payload = this.pushLine(this.buffer);
743
+ this.buffer = "";
744
+ if (payload !== null) out.push(payload);
675
745
  }
676
- this.ensureDek(inner);
677
- const pt = chacha20poly13052(this.dek, seqNonce(seq)).decrypt(b64d(inner.ciphertext));
678
- this.nextSeq += 1;
679
- return pt;
746
+ const tail = this.endFrame();
747
+ if (tail !== null) out.push(tail);
748
+ return out;
680
749
  }
681
- };
682
- function deriveSalt(rawApiKey) {
683
- const prk = extract2(sha256, utf8(rawApiKey), new Uint8Array(32));
684
- return expand2(sha256, prk, AFFINITY_SALT_INFO, 32);
685
- }
686
- function canonicalJson(value) {
687
- if (value === null) return "null";
688
- const t = typeof value;
689
- if (t === "boolean") return value ? "true" : "false";
690
- if (t === "number") {
691
- return String(value);
750
+ pushLine(rawLine) {
751
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
752
+ if (line === "") return this.endFrame();
753
+ if (line.startsWith(":")) return null;
754
+ if (line.startsWith("event:")) {
755
+ this.event = fieldValue(line, "event");
756
+ return null;
757
+ }
758
+ if (line.startsWith("data:")) {
759
+ this.data.push(fieldValue(line, "data"));
760
+ return null;
761
+ }
762
+ return null;
692
763
  }
693
- if (t === "string") return encodeString(value);
694
- if (Array.isArray(value)) {
695
- return "[" + value.map((v) => canonicalJson(v)).join(",") + "]";
764
+ endFrame() {
765
+ const { data, event } = this;
766
+ this.data = [];
767
+ this.event = "";
768
+ if (data.length === 0) return null;
769
+ if (event !== "" && event !== DEFAULT_EVENT) return null;
770
+ return data.join("\n");
696
771
  }
697
- if (t === "object") {
698
- const obj = value;
699
- const keys = Object.keys(obj).sort();
700
- const items = keys.map((k) => encodeString(k) + ":" + canonicalJson(obj[k]));
701
- return "{" + items.join(",") + "}";
772
+ };
773
+
774
+ // src/streaming.ts
775
+ var Stream = class {
776
+ constructor(response, controller, idleTimeoutMs) {
777
+ this.decoder = new TextDecoder();
778
+ this.sse = new SseDecoder();
779
+ this.done = false;
780
+ if (!response.body) {
781
+ throw new Error("Response body is null \u2014 streaming not supported");
782
+ }
783
+ this.reader = response.body.getReader();
784
+ this.controller = controller;
785
+ this.idleTimeoutMs = idleTimeoutMs;
702
786
  }
703
- return "null";
704
- }
705
- function encodeString(s) {
706
- let out = '"';
707
- for (let i = 0; i < s.length; i++) {
708
- const code = s.charCodeAt(i);
709
- switch (code) {
710
- case 34:
711
- out += '\\"';
712
- break;
713
- case 92:
714
- out += "\\\\";
715
- break;
716
- case 8:
717
- out += "\\b";
718
- break;
719
- case 9:
720
- out += "\\t";
721
- break;
722
- case 10:
723
- out += "\\n";
724
- break;
725
- case 12:
726
- out += "\\f";
727
- break;
728
- case 13:
729
- out += "\\r";
730
- break;
731
- default:
732
- if (code < 32 || code > 126) {
733
- out += "\\u" + code.toString(16).padStart(4, "0");
734
- } else {
735
- out += s[i];
787
+ async *[Symbol.asyncIterator]() {
788
+ try {
789
+ while (!this.done) {
790
+ const { value, done: readerDone } = await readWithIdleTimeout(
791
+ this.reader,
792
+ this.idleTimeoutMs
793
+ );
794
+ const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
795
+ for (const data of payloads) {
796
+ if (data === "[DONE]") {
797
+ this.done = true;
798
+ return;
799
+ }
800
+ yield parseStreamFrame(data);
801
+ }
802
+ if (readerDone) {
803
+ this.done = true;
804
+ break;
736
805
  }
806
+ }
807
+ } finally {
808
+ releaseReader(this.reader, this.controller, this.done);
737
809
  }
738
810
  }
739
- return out + '"';
740
- }
741
- function flattenContent(content) {
742
- if (typeof content === "string") return content;
743
- return canonicalJson(content);
811
+ abort() {
812
+ this.done = true;
813
+ this.controller.abort();
814
+ }
815
+ };
816
+ async function readWithIdleTimeout(reader, idleTimeoutMs) {
817
+ if (!idleTimeoutMs) return reader.read();
818
+ let timer;
819
+ const idle = new Promise((_, reject) => {
820
+ timer = setTimeout(
821
+ () => reject(new APIConnectionError(`Stream received no data for ${idleTimeoutMs}ms`)),
822
+ idleTimeoutMs
823
+ );
824
+ });
825
+ try {
826
+ return await Promise.race([reader.read(), idle]);
827
+ } finally {
828
+ clearTimeout(timer);
829
+ }
744
830
  }
745
- function affinityKey(rawApiKey, model, messages, saltOverride) {
746
- const parts = ["model=" + model];
747
- let sawUser = false;
748
- for (const m of messages ?? []) {
749
- const role = m.role ?? "";
750
- parts.push(role + ":" + flattenContent(m.content));
751
- if (role === "user") {
752
- sawUser = true;
753
- break;
754
- }
831
+ function releaseReader(reader, controller, finished) {
832
+ if (!finished) {
833
+ controller.abort();
834
+ reader.cancel().catch(() => {
835
+ });
755
836
  }
756
- if (!sawUser) return null;
757
- const salt = saltOverride != null ? saltOverride : deriveSalt(rawApiKey);
758
- const mac = hmac(sha256, salt, utf8(parts.join("\0")));
759
- return toHex(mac);
837
+ reader.releaseLock();
760
838
  }
761
839
 
762
840
  // src/_privateStreaming.ts
763
- var DECODER = new TextDecoder();
841
+ var DECODER2 = new TextDecoder();
764
842
  var EncryptedStream = class {
765
843
  constructor(response, controller, decryptor, idleTimeoutMs) {
766
844
  this.decoder = new TextDecoder();
@@ -805,7 +883,7 @@ var EncryptedStream = class {
805
883
  throw unsealedReplyError();
806
884
  }
807
885
  const plain = this.decryptor.openChunk(inner);
808
- const chunkJson = DECODER.decode(plain).trim();
886
+ const chunkJson = DECODER2.decode(plain).trim();
809
887
  if (!chunkJson || chunkJson === "[DONE]") {
810
888
  if (chunkJson === "[DONE]") {
811
889
  this.done = true;
@@ -831,8 +909,8 @@ var EncryptedStream = class {
831
909
  };
832
910
 
833
911
  // src/resources/chat/completions.ts
834
- var ENCODER = new TextEncoder();
835
- var DECODER2 = new TextDecoder();
912
+ var ENCODER2 = new TextEncoder();
913
+ var DECODER3 = new TextDecoder();
836
914
  var Completions = class {
837
915
  constructor(client) {
838
916
  this.client = client;
@@ -867,7 +945,7 @@ var Completions = class {
867
945
  model: params.model,
868
946
  stream,
869
947
  taskType: "chat",
870
- body: ENCODER.encode(JSON.stringify(body)),
948
+ body: ENCODER2.encode(JSON.stringify(body)),
871
949
  messages: params.messages
872
950
  });
873
951
  if (stream) {
@@ -895,7 +973,7 @@ var Completions = class {
895
973
  throw unsealedReplyError();
896
974
  }
897
975
  const plain = decryptor.openResult(wrapper.pendra_encrypted);
898
- return parseDecryptedCompletion(DECODER2.decode(plain), response.status);
976
+ return parseDecryptedCompletion(DECODER3.decode(plain), response.status);
899
977
  }
900
978
  };
901
979
 
@@ -907,8 +985,8 @@ var Chat = class {
907
985
  };
908
986
 
909
987
  // src/resources/embeddings.ts
910
- var ENCODER2 = new TextEncoder();
911
- var DECODER3 = new TextDecoder();
988
+ var ENCODER3 = new TextEncoder();
989
+ var DECODER4 = new TextDecoder();
912
990
  function validateParams(params) {
913
991
  if (!params.model || typeof params.model !== "string") {
914
992
  throw new Error("model must be a non-empty string");
@@ -972,7 +1050,7 @@ var Embeddings = class {
972
1050
  model,
973
1051
  stream: false,
974
1052
  taskType: "embeddings",
975
- body: ENCODER2.encode(JSON.stringify(body))
1053
+ body: ENCODER3.encode(JSON.stringify(body))
976
1054
  });
977
1055
  const { response } = await this.client._fetch(
978
1056
  "/api/v1/embeddings",
@@ -983,11 +1061,13 @@ var Embeddings = class {
983
1061
  throw unsealedReplyError();
984
1062
  }
985
1063
  const plain = decryptor.openResult(wrapper.pendra_encrypted);
986
- return JSON.parse(DECODER3.decode(plain));
1064
+ return JSON.parse(DECODER4.decode(plain));
987
1065
  }
988
1066
  };
989
1067
 
990
1068
  // src/resources/images/generations.ts
1069
+ var ENCODER4 = new TextEncoder();
1070
+ var DECODER5 = new TextDecoder();
991
1071
  var SIZE_RE = /^\d+x\d+$/;
992
1072
  function validateParams2(params) {
993
1073
  if (!params.prompt || !params.prompt.trim()) {
@@ -1005,9 +1085,6 @@ var Generations = class {
1005
1085
  this.client = client;
1006
1086
  }
1007
1087
  async create(params) {
1008
- if (this.client.privateInferenceEnabled) {
1009
- throw new Error("private inference is not yet supported for images/audio");
1010
- }
1011
1088
  validateParams2(params);
1012
1089
  const body = {
1013
1090
  model: params.model,
@@ -1019,16 +1096,38 @@ var Generations = class {
1019
1096
  if (params.num_inference_steps != null) body.num_inference_steps = params.num_inference_steps;
1020
1097
  if (params.seed != null) body.seed = params.seed;
1021
1098
  if (params.negative_prompt != null) body.negative_prompt = params.negative_prompt;
1099
+ const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
1100
+ if (this.client.privateInferenceEnabled) {
1101
+ return this.createEncrypted(params.model, body, headers);
1102
+ }
1022
1103
  const { response } = await this.client._fetch(
1023
1104
  "/api/v1/images/generations",
1024
- {
1025
- method: "POST",
1026
- body,
1027
- headers: params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0
1028
- }
1105
+ { method: "POST", body, headers }
1029
1106
  );
1030
1107
  return await response.json();
1031
1108
  }
1109
+ async createEncrypted(model, body, headers) {
1110
+ const engine = await this.client._privateEngine();
1111
+ const { topLevel, decryptor } = engine.seal({
1112
+ model,
1113
+ stream: false,
1114
+ taskType: "image_generation",
1115
+ body: ENCODER4.encode(JSON.stringify(body))
1116
+ });
1117
+ const { response } = await this.client._fetch(
1118
+ "/api/v1/images/generations",
1119
+ { method: "POST", body: topLevel, headers }
1120
+ );
1121
+ const plain = decryptor.openResult(await readSealedReply(response));
1122
+ const parsed = parseDecryptedJson(DECODER5.decode(plain), response.status);
1123
+ if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.data)) {
1124
+ throw new APIResponseValidationError("Decrypted response was not an image generation", {
1125
+ status: response.status,
1126
+ body: DECODER5.decode(plain)
1127
+ });
1128
+ }
1129
+ return parsed;
1130
+ }
1032
1131
  };
1033
1132
 
1034
1133
  // src/resources/images/index.ts
@@ -1053,8 +1152,8 @@ var Models = class {
1053
1152
  };
1054
1153
 
1055
1154
  // src/resources/rerank.ts
1056
- var ENCODER3 = new TextEncoder();
1057
- var DECODER4 = new TextDecoder();
1155
+ var ENCODER5 = new TextEncoder();
1156
+ var DECODER6 = new TextDecoder();
1058
1157
  function validateParams3(params) {
1059
1158
  if (!params.model || typeof params.model !== "string") {
1060
1159
  throw new Error("model must be a non-empty string");
@@ -1113,7 +1212,7 @@ var Rerank = class {
1113
1212
  model,
1114
1213
  stream: false,
1115
1214
  taskType: "rerank",
1116
- body: ENCODER3.encode(JSON.stringify(body))
1215
+ body: ENCODER5.encode(JSON.stringify(body))
1117
1216
  });
1118
1217
  const { response } = await this.client._fetch(
1119
1218
  "/api/v1/rerank",
@@ -1124,12 +1223,12 @@ var Rerank = class {
1124
1223
  throw unsealedReplyError();
1125
1224
  }
1126
1225
  const plain = decryptor.openResult(wrapper.pendra_encrypted);
1127
- return JSON.parse(DECODER4.decode(plain));
1226
+ return JSON.parse(DECODER6.decode(plain));
1128
1227
  }
1129
1228
  };
1130
1229
 
1131
1230
  // src/version.ts
1132
- var VERSION = "0.14.0";
1231
+ var VERSION = "0.15.0";
1133
1232
  var USER_AGENT = `pendra-node/${VERSION}`;
1134
1233
 
1135
1234
  // src/_privateInferenceEngine.ts
@@ -1294,6 +1393,7 @@ var PrivateInferenceEngine = class {
1294
1393
  /**
1295
1394
  * Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
1296
1395
  * `messages` (chat only) drives the affinity token; pass undefined for non-chat.
1396
+ * `binary` (audio only) is sealed under the same data key as the body.
1297
1397
  */
1298
1398
  seal(args) {
1299
1399
  if (this.orgPubs === null || this.orgPubs.length === 0) {
@@ -1309,7 +1409,8 @@ var PrivateInferenceEngine = class {
1309
1409
  model: args.model,
1310
1410
  stream: args.stream,
1311
1411
  taskType: args.taskType,
1312
- affinityKey: affinity
1412
+ affinityKey: affinity,
1413
+ binary: args.binary ?? null
1313
1414
  });
1314
1415
  const topLevel = {
1315
1416
  model: args.model,
@@ -1428,7 +1529,10 @@ var Pendra = class {
1428
1529
  let message;
1429
1530
  try {
1430
1531
  const body = await response.json();
1431
- message = body.detail ?? response.statusText;
1532
+ if (typeof body.detail === "string") message = body.detail;
1533
+ else if (typeof body.error?.message === "string") message = body.error.message;
1534
+ else if (body.detail != null) message = JSON.stringify(body.detail);
1535
+ else message = response.statusText;
1432
1536
  } catch {
1433
1537
  message = response.statusText;
1434
1538
  }
@@ -1441,8 +1545,9 @@ var Pendra = class {
1441
1545
  }
1442
1546
  /** @internal */
1443
1547
  async _fetch(path, options) {
1548
+ const timeout = options.timeout ?? this.timeout;
1444
1549
  const controller = new AbortController();
1445
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
1550
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
1446
1551
  const headers = {
1447
1552
  Authorization: `Bearer ${this.apiKey}`,
1448
1553
  "Content-Type": "application/json",
@@ -1461,7 +1566,7 @@ var Pendra = class {
1461
1566
  clearTimeout(timeoutId);
1462
1567
  if (err instanceof DOMException && err.name === "AbortError") {
1463
1568
  throw new APIConnectionError(
1464
- `Request timed out after ${this.timeout}ms`
1569
+ `Request timed out after ${timeout}ms`
1465
1570
  );
1466
1571
  }
1467
1572
  throw new APIConnectionError(
@@ -1474,7 +1579,10 @@ var Pendra = class {
1474
1579
  let message;
1475
1580
  try {
1476
1581
  const body = await response.json();
1477
- message = body.detail ?? response.statusText;
1582
+ if (typeof body.detail === "string") message = body.detail;
1583
+ else if (typeof body.error?.message === "string") message = body.error.message;
1584
+ else if (body.detail != null) message = JSON.stringify(body.detail);
1585
+ else message = response.statusText;
1478
1586
  } catch {
1479
1587
  message = response.statusText;
1480
1588
  }