pendra 0.13.1 → 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,7 +59,474 @@ var APIStreamError = class extends APIError {
59
59
  }
60
60
  };
61
61
 
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);
85
+ }
86
+ return out;
87
+ }
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;
100
+ }
101
+ return out;
102
+ }
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;
137
+ }
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];
143
+ }
144
+ return nonce;
145
+ }
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);
158
+ }
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
+ }
181
+
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);
191
+ }
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);
199
+ }
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;
208
+ }
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;
233
+ }
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;
242
+ }
243
+ return nonce;
244
+ }
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");
249
+ }
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
+ }
258
+ }
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) });
271
+ }
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;
280
+ }
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));
285
+ }
286
+ return { envelope, responseKeys };
287
+ }
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;
294
+ }
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;
305
+ }
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
+ );
311
+ }
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");
316
+ }
317
+ this.dek = dek;
318
+ }
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));
323
+ }
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
+ );
331
+ }
332
+ this.ensureDek(inner);
333
+ const pt = chacha20poly13052(this.dek, seqNonce(seq)).decrypt(b64d(inner.ciphertext));
334
+ this.nextSeq += 1;
335
+ return pt;
336
+ }
337
+ };
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);
348
+ }
349
+ if (t === "string") return encodeString(value);
350
+ if (Array.isArray(value)) {
351
+ return "[" + value.map((v) => canonicalJson(v)).join(",") + "]";
352
+ }
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(",") + "}";
358
+ }
359
+ return "null";
360
+ }
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
+ }
394
+ }
395
+ return out + '"';
396
+ }
397
+ function flattenContent(content) {
398
+ if (typeof content === "string") return content;
399
+ return canonicalJson(content);
400
+ }
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);
416
+ }
417
+
418
+ // src/_parsing.ts
419
+ function asString(v) {
420
+ return typeof v === "string" ? v : void 0;
421
+ }
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
+ );
437
+ }
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);
442
+ }
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 });
449
+ }
450
+ throwIfInBandError(parsed);
451
+ if (!isChunkShaped(parsed)) {
452
+ throw new APIResponseValidationError(`${label} was not a chat completion chunk`, {
453
+ body: data
454
+ });
455
+ }
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 });
461
+ }
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 });
465
+ }
466
+ return parsed;
467
+ }
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);
480
+ }
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
+ });
498
+ }
499
+ }
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
+ });
510
+ }
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;
515
+ }
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
+ }
525
+ }
526
+
62
527
  // src/resources/audio/transcriptions.ts
528
+ var ENCODER = new TextEncoder();
529
+ var DECODER = new TextDecoder();
63
530
  var MAX_FILE_SIZE = 25 * 1024 * 1024;
64
531
  var MIME_EXT = {
65
532
  "audio/mpeg": "mp3",
@@ -113,12 +580,12 @@ var Transcriptions = class {
113
580
  this.client = client;
114
581
  }
115
582
  async create(params) {
116
- if (this.client.privateInferenceEnabled) {
117
- throw new Error("private inference is not yet supported for images/audio");
118
- }
119
583
  if (!params.model) {
120
584
  throw new Error("model is required");
121
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
+ }
122
589
  const { blob, filename } = asBlob(params.file);
123
590
  if (blob.size === 0) {
124
591
  throw new Error("audio file is empty");
@@ -126,6 +593,10 @@ var Transcriptions = class {
126
593
  if (blob.size > MAX_FILE_SIZE) {
127
594
  throw new Error(`audio file exceeds ${MAX_FILE_SIZE / (1024 * 1024)}MB limit`);
128
595
  }
596
+ const timeout = Math.max(this.client.timeout ?? 0, 3e5);
597
+ if (this.client.privateInferenceEnabled) {
598
+ return this.createEncrypted(params, blob, timeout);
599
+ }
129
600
  const form = new FormData();
130
601
  form.append("file", blob, filename);
131
602
  form.append("model", params.model);
@@ -139,7 +610,6 @@ var Transcriptions = class {
139
610
  form.append("timestamp_granularities[]", g);
140
611
  }
141
612
  }
142
- const timeout = Math.max(this.client.timeout ?? 0, 3e5);
143
613
  const controller = new AbortController();
144
614
  const timeoutId = setTimeout(() => controller.abort(), timeout);
145
615
  let response;
@@ -178,6 +648,53 @@ var Transcriptions = class {
178
648
  }
179
649
  return await response.json();
180
650
  }
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 };
697
+ }
181
698
  };
182
699
 
183
700
  // src/resources/audio/index.ts
@@ -187,89 +704,6 @@ var Audio = class {
187
704
  }
188
705
  };
189
706
 
190
- // src/_parsing.ts
191
- function asString(v) {
192
- return typeof v === "string" ? v : void 0;
193
- }
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
- );
209
- }
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);
214
- }
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 });
221
- }
222
- throwIfInBandError(parsed);
223
- if (!isChunkShaped(parsed)) {
224
- throw new APIResponseValidationError(`${label} was not a chat completion chunk`, {
225
- body: data
226
- });
227
- }
228
- return parsed;
229
- }
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 });
233
- }
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 });
237
- }
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
- });
250
- }
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
- });
262
- }
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
- });
270
- }
271
- }
272
-
273
707
  // src/_sse.ts
274
708
  var DEFAULT_EVENT = "message";
275
709
  function fieldValue(line, name) {
@@ -404,7 +838,7 @@ function releaseReader(reader, controller, finished) {
404
838
  }
405
839
 
406
840
  // src/_privateStreaming.ts
407
- var DECODER = new TextDecoder();
841
+ var DECODER2 = new TextDecoder();
408
842
  var EncryptedStream = class {
409
843
  constructor(response, controller, decryptor, idleTimeoutMs) {
410
844
  this.decoder = new TextDecoder();
@@ -431,20 +865,25 @@ var EncryptedStream = class {
431
865
  this.done = true;
432
866
  return;
433
867
  }
434
- let inner;
868
+ let frame;
435
869
  try {
436
- inner = JSON.parse(data).pendra_encrypted;
870
+ frame = JSON.parse(data);
437
871
  } catch {
438
872
  throw new APIResponseValidationError("Stream frame was not valid JSON", {
439
873
  body: data
440
874
  });
441
875
  }
876
+ const inner = frame?.pendra_encrypted;
442
877
  if (!inner) {
443
- yield parseStreamFrame(data);
444
- continue;
878
+ if (isApiTimingChunk(frame)) {
879
+ yield parseStreamFrame(data);
880
+ continue;
881
+ }
882
+ parseStreamFrame(data);
883
+ throw unsealedReplyError();
445
884
  }
446
885
  const plain = this.decryptor.openChunk(inner);
447
- const chunkJson = DECODER.decode(plain).trim();
886
+ const chunkJson = DECODER2.decode(plain).trim();
448
887
  if (!chunkJson || chunkJson === "[DONE]") {
449
888
  if (chunkJson === "[DONE]") {
450
889
  this.done = true;
@@ -470,8 +909,8 @@ var EncryptedStream = class {
470
909
  };
471
910
 
472
911
  // src/resources/chat/completions.ts
473
- var ENCODER = new TextEncoder();
474
- var DECODER2 = new TextDecoder();
912
+ var ENCODER2 = new TextEncoder();
913
+ var DECODER3 = new TextDecoder();
475
914
  var Completions = class {
476
915
  constructor(client) {
477
916
  this.client = client;
@@ -506,7 +945,7 @@ var Completions = class {
506
945
  model: params.model,
507
946
  stream,
508
947
  taskType: "chat",
509
- body: ENCODER.encode(JSON.stringify(body)),
948
+ body: ENCODER2.encode(JSON.stringify(body)),
510
949
  messages: params.messages
511
950
  });
512
951
  if (stream) {
@@ -531,10 +970,10 @@ var Completions = class {
531
970
  });
532
971
  }
533
972
  if (!wrapper.pendra_encrypted) {
534
- return parseDecryptedCompletion(raw, response.status);
973
+ throw unsealedReplyError();
535
974
  }
536
975
  const plain = decryptor.openResult(wrapper.pendra_encrypted);
537
- return parseDecryptedCompletion(DECODER2.decode(plain), response.status);
976
+ return parseDecryptedCompletion(DECODER3.decode(plain), response.status);
538
977
  }
539
978
  };
540
979
 
@@ -546,582 +985,251 @@ var Chat = class {
546
985
  };
547
986
 
548
987
  // src/resources/embeddings.ts
549
- var ENCODER2 = new TextEncoder();
550
- var DECODER3 = new TextDecoder();
988
+ var ENCODER3 = new TextEncoder();
989
+ var DECODER4 = new TextDecoder();
551
990
  function validateParams(params) {
552
991
  if (!params.model || typeof params.model !== "string") {
553
992
  throw new Error("model must be a non-empty string");
554
993
  }
555
994
  const { input } = params;
556
995
  if (typeof input === "string") {
557
- if (input.length === 0) {
558
- throw new Error("input must be a non-empty string or non-empty array of strings");
559
- }
560
- return;
561
- }
562
- if (Array.isArray(input)) {
563
- if (input.length === 0) {
564
- throw new Error("input must be a non-empty string or non-empty array of strings");
565
- }
566
- if (!input.every((s) => typeof s === "string" && s.length > 0)) {
567
- throw new Error("input array entries must all be non-empty strings");
568
- }
569
- return;
570
- }
571
- throw new Error("input must be a string or an array of strings");
572
- }
573
- var Embeddings = class {
574
- constructor(client) {
575
- this.client = client;
576
- }
577
- /**
578
- * Create embeddings for the given input.
579
- *
580
- * @example
581
- * ```ts
582
- * const result = await client.embeddings.create({
583
- * model: "nomic-embed-text:latest",
584
- * input: "Hello world",
585
- * });
586
- * console.log(result.data[0].embedding);
587
- * ```
588
- */
589
- async create(params) {
590
- validateParams(params);
591
- const body = {
592
- model: params.model,
593
- input: params.input
594
- };
595
- if (params.encoding_format != null) body.encoding_format = params.encoding_format;
596
- if (params.dimensions != null) body.dimensions = params.dimensions;
597
- if (params.user != null) body.user = params.user;
598
- const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
599
- if (this.client.privateInferenceEnabled) {
600
- return this.createEncrypted(params.model, body, headers);
601
- }
602
- const { response } = await this.client._fetch(
603
- "/api/v1/embeddings",
604
- { method: "POST", body, headers }
605
- );
606
- return await response.json();
607
- }
608
- async createEncrypted(model, body, headers) {
609
- const engine = await this.client._privateEngine();
610
- const { topLevel, decryptor } = engine.seal({
611
- model,
612
- stream: false,
613
- taskType: "embeddings",
614
- body: ENCODER2.encode(JSON.stringify(body))
615
- });
616
- const { response } = await this.client._fetch(
617
- "/api/v1/embeddings",
618
- { method: "POST", body: topLevel, headers }
619
- );
620
- const wrapper = await response.json();
621
- if (!wrapper.pendra_encrypted) {
622
- return wrapper;
623
- }
624
- const plain = decryptor.openResult(wrapper.pendra_encrypted);
625
- return JSON.parse(DECODER3.decode(plain));
626
- }
627
- };
628
-
629
- // src/resources/images/generations.ts
630
- var SIZE_RE = /^\d+x\d+$/;
631
- function validateParams2(params) {
632
- if (!params.prompt || !params.prompt.trim()) {
633
- throw new Error("prompt must be a non-empty string");
634
- }
635
- if (params.n != null && (params.n < 1 || params.n > 4)) {
636
- throw new Error("n must be between 1 and 4");
637
- }
638
- if (params.size != null && !SIZE_RE.test(params.size)) {
639
- throw new Error("size must be in the form WIDTHxHEIGHT (e.g. '1024x1024')");
640
- }
641
- }
642
- var Generations = class {
643
- constructor(client) {
644
- this.client = client;
645
- }
646
- async create(params) {
647
- if (this.client.privateInferenceEnabled) {
648
- throw new Error("private inference is not yet supported for images/audio");
649
- }
650
- validateParams2(params);
651
- const body = {
652
- model: params.model,
653
- prompt: params.prompt
654
- };
655
- if (params.n != null) body.n = params.n;
656
- if (params.size != null) body.size = params.size;
657
- if (params.response_format != null) body.response_format = params.response_format;
658
- if (params.num_inference_steps != null) body.num_inference_steps = params.num_inference_steps;
659
- if (params.seed != null) body.seed = params.seed;
660
- if (params.negative_prompt != null) body.negative_prompt = params.negative_prompt;
661
- const { response } = await this.client._fetch(
662
- "/api/v1/images/generations",
663
- {
664
- method: "POST",
665
- body,
666
- headers: params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0
667
- }
668
- );
669
- return await response.json();
670
- }
671
- };
672
-
673
- // src/resources/images/index.ts
674
- var Images = class {
675
- constructor(client) {
676
- this.generations = new Generations(client);
677
- }
678
- };
679
-
680
- // src/resources/models.ts
681
- var Models = class {
682
- constructor(client) {
683
- this.client = client;
684
- }
685
- async list() {
686
- const { response } = await this.client._fetch("/api/v1/models", {
687
- method: "GET"
688
- });
689
- const data = await response.json();
690
- return data.data;
691
- }
692
- };
693
-
694
- // src/resources/rerank.ts
695
- var ENCODER3 = new TextEncoder();
696
- var DECODER4 = new TextDecoder();
697
- function validateParams3(params) {
698
- if (!params.model || typeof params.model !== "string") {
699
- throw new Error("model must be a non-empty string");
700
- }
701
- if (!params.query || typeof params.query !== "string") {
702
- throw new Error("query must be a non-empty string");
703
- }
704
- const { documents } = params;
705
- if (!Array.isArray(documents) || documents.length === 0 || !documents.every((d) => typeof d === "string" && d.length > 0)) {
706
- throw new Error("documents must be a non-empty array of non-empty strings");
996
+ if (input.length === 0) {
997
+ throw new Error("input must be a non-empty string or non-empty array of strings");
998
+ }
999
+ return;
707
1000
  }
708
- if (params.top_n != null && params.top_n < 1) {
709
- throw new Error("top_n must be >= 1 when provided");
1001
+ if (Array.isArray(input)) {
1002
+ if (input.length === 0) {
1003
+ throw new Error("input must be a non-empty string or non-empty array of strings");
1004
+ }
1005
+ if (!input.every((s) => typeof s === "string" && s.length > 0)) {
1006
+ throw new Error("input array entries must all be non-empty strings");
1007
+ }
1008
+ return;
710
1009
  }
1010
+ throw new Error("input must be a string or an array of strings");
711
1011
  }
712
- var Rerank = class {
1012
+ var Embeddings = class {
713
1013
  constructor(client) {
714
1014
  this.client = client;
715
1015
  }
716
1016
  /**
717
- * Rerank `documents` by relevance to `query` (Cohere-compatible).
1017
+ * Create embeddings for the given input.
718
1018
  *
719
1019
  * @example
720
1020
  * ```ts
721
- * const result = await client.rerank.create({
722
- * model: "bge-reranker-v2-m3",
723
- * query: "What is the capital of France?",
724
- * documents: ["Paris is the capital of France.", "Berlin is in Germany."],
725
- * top_n: 1,
1021
+ * const result = await client.embeddings.create({
1022
+ * model: "nomic-embed-text:latest",
1023
+ * input: "Hello world",
726
1024
  * });
727
- * console.log(result.results[0].index, result.results[0].relevance_score);
1025
+ * console.log(result.data[0].embedding);
728
1026
  * ```
729
1027
  */
730
1028
  async create(params) {
731
- validateParams3(params);
1029
+ validateParams(params);
732
1030
  const body = {
733
1031
  model: params.model,
734
- query: params.query,
735
- documents: params.documents,
736
- return_documents: params.return_documents ?? false
1032
+ input: params.input
737
1033
  };
738
- if (params.top_n != null) body.top_n = params.top_n;
1034
+ if (params.encoding_format != null) body.encoding_format = params.encoding_format;
1035
+ if (params.dimensions != null) body.dimensions = params.dimensions;
1036
+ if (params.user != null) body.user = params.user;
739
1037
  const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
740
1038
  if (this.client.privateInferenceEnabled) {
741
1039
  return this.createEncrypted(params.model, body, headers);
742
1040
  }
743
1041
  const { response } = await this.client._fetch(
744
- "/api/v1/rerank",
1042
+ "/api/v1/embeddings",
745
1043
  { method: "POST", body, headers }
746
1044
  );
747
1045
  return await response.json();
748
1046
  }
749
1047
  async createEncrypted(model, body, headers) {
750
- const engine = await this.client._privateEngine();
751
- const { topLevel, decryptor } = engine.seal({
752
- model,
753
- stream: false,
754
- taskType: "rerank",
755
- body: ENCODER3.encode(JSON.stringify(body))
756
- });
757
- const { response } = await this.client._fetch(
758
- "/api/v1/rerank",
759
- { method: "POST", body: topLevel, headers }
760
- );
761
- const wrapper = await response.json();
762
- if (!wrapper.pendra_encrypted) {
763
- return wrapper;
764
- }
765
- const plain = decryptor.openResult(wrapper.pendra_encrypted);
766
- return JSON.parse(DECODER4.decode(plain));
767
- }
768
- };
769
-
770
- // src/version.ts
771
- var VERSION = "0.13.1";
772
- var USER_AGENT = `pendra-node/${VERSION}`;
773
-
774
- // src/_hpke.ts
775
- import { x25519 } from "@noble/curves/ed25519.js";
776
- import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
777
- import { sha256 } from "@noble/hashes/sha2.js";
778
- import { hmac } from "@noble/hashes/hmac.js";
779
- import { extract, expand } from "@noble/hashes/hkdf.js";
780
- import { randomBytes as nobleRandomBytes } from "@noble/hashes/utils.js";
781
- var KEM_ID = 32;
782
- var KDF_ID = 1;
783
- var AEAD_ID = 3;
784
- var NH = 32;
785
- var NK = 32;
786
- var NN = 12;
787
- var NSECRET = 32;
788
- function i2osp(n, len) {
789
- const out = new Uint8Array(len);
790
- for (let i = len - 1; i >= 0; i--) {
791
- out[i] = n & 255;
792
- n = Math.floor(n / 256);
793
- }
794
- return out;
795
- }
796
- var TEXT_ENCODER = new TextEncoder();
797
- function bytes(s) {
798
- return TEXT_ENCODER.encode(s);
799
- }
800
- function concat(...parts) {
801
- let total = 0;
802
- for (const p of parts) total += p.length;
803
- const out = new Uint8Array(total);
804
- let off = 0;
805
- for (const p of parts) {
806
- out.set(p, off);
807
- off += p.length;
808
- }
809
- return out;
810
- }
811
- var SUITE_ID = concat(bytes("HPKE"), i2osp(KEM_ID, 2), i2osp(KDF_ID, 2), i2osp(AEAD_ID, 2));
812
- var KEM_SUITE_ID = concat(bytes("KEM"), i2osp(KEM_ID, 2));
813
- var HPKE_VERSION = bytes("HPKE-v1");
814
- function hkdfExtract(salt, ikm) {
815
- const effectiveSalt = salt.length === 0 ? new Uint8Array(NH) : salt;
816
- return extract(sha256, ikm, effectiveSalt);
817
- }
818
- function hkdfExpand(prk, info, length) {
819
- return expand(sha256, prk, info, length);
820
- }
821
- function labeledExtract(salt, label, ikm, suiteId) {
822
- return hkdfExtract(salt, concat(HPKE_VERSION, suiteId, label, ikm));
823
- }
824
- function labeledExpand(prk, label, info, length, suiteId) {
825
- const labeledInfo = concat(i2osp(length, 2), HPKE_VERSION, suiteId, label, info);
826
- return hkdfExpand(prk, labeledInfo, length);
827
- }
828
- function extractAndExpand(dh, kemContext) {
829
- const eaePrk = labeledExtract(new Uint8Array(0), bytes("eae_prk"), dh, KEM_SUITE_ID);
830
- return labeledExpand(eaePrk, bytes("shared_secret"), kemContext, NSECRET, KEM_SUITE_ID);
831
- }
832
- function encap(pkR, skE) {
833
- const skEObj = skE ?? x25519.utils.randomSecretKey();
834
- const enc = x25519.getPublicKey(skEObj);
835
- const dh = x25519.getSharedSecret(skEObj, pkR);
836
- const kemContext = concat(enc, pkR);
837
- return [extractAndExpand(dh, kemContext), enc];
838
- }
839
- function decap(enc, skR) {
840
- const dh = x25519.getSharedSecret(skR, enc);
841
- const pkRm = x25519.getPublicKey(skR);
842
- const kemContext = concat(enc, pkRm);
843
- return extractAndExpand(dh, kemContext);
844
- }
845
- var Context = class {
846
- constructor(key, baseNonce, exporterSecret) {
847
- this.seq = 0;
848
- this.key = key;
849
- this.baseNonce = baseNonce;
850
- this.exporterSecret = exporterSecret;
851
- }
852
- computeNonce() {
853
- const seqBytes = i2osp(this.seq, NN);
854
- const nonce = new Uint8Array(NN);
855
- for (let i = 0; i < NN; i++) {
856
- nonce[i] = this.baseNonce[i] ^ seqBytes[i];
857
- }
858
- return nonce;
859
- }
860
- seal(aad, pt) {
861
- const ct = chacha20poly1305(this.key, this.computeNonce(), aad).encrypt(pt);
862
- this.seq += 1;
863
- return ct;
864
- }
865
- open(aad, ct) {
866
- const pt = chacha20poly1305(this.key, this.computeNonce(), aad).decrypt(ct);
867
- this.seq += 1;
868
- return pt;
869
- }
870
- export(exporterContext, length) {
871
- return labeledExpand(this.exporterSecret, bytes("sec"), exporterContext, length, SUITE_ID);
872
- }
873
- };
874
- function keySchedule(sharedSecret, info) {
875
- const empty = new Uint8Array(0);
876
- const pskIdHash = labeledExtract(empty, bytes("psk_id_hash"), empty, SUITE_ID);
877
- const infoHash = labeledExtract(empty, bytes("info_hash"), info, SUITE_ID);
878
- const keyScheduleContext = concat(new Uint8Array([0]), pskIdHash, infoHash);
879
- const secret = labeledExtract(sharedSecret, bytes("secret"), empty, SUITE_ID);
880
- const key = labeledExpand(secret, bytes("key"), keyScheduleContext, NK, SUITE_ID);
881
- const baseNonce = labeledExpand(secret, bytes("base_nonce"), keyScheduleContext, NN, SUITE_ID);
882
- const exporterSecret = labeledExpand(secret, bytes("exp"), keyScheduleContext, NH, SUITE_ID);
883
- return new Context(key, baseNonce, exporterSecret);
884
- }
885
- function setupBaseS(pkR, info, skE) {
886
- const [sharedSecret, enc] = encap(pkR, skE);
887
- return { enc, ctx: keySchedule(sharedSecret, info) };
888
- }
889
- function setupBaseR(skR, enc, info) {
890
- const sharedSecret = decap(enc, skR);
891
- return keySchedule(sharedSecret, info);
892
- }
893
- function generateX25519Keypair() {
894
- const priv = x25519.utils.randomSecretKey();
895
- return { priv, pub: x25519.getPublicKey(priv) };
896
- }
897
- function randomBytes(n) {
898
- return nobleRandomBytes(n);
899
- }
900
- function sha256Hex(data) {
901
- return Array.from(sha256(data)).map((b) => b.toString(16).padStart(2, "0")).join("");
902
- }
903
-
904
- // src/_privateInference.ts
905
- import { chacha20poly1305 as chacha20poly13052 } from "@noble/ciphers/chacha.js";
906
- import { extract as extract2, expand as expand2 } from "@noble/hashes/hkdf.js";
907
- var ENVELOPE_VERSION = 1;
908
- var TEXT_ENCODER2 = new TextEncoder();
909
- var TEXT_DECODER = new TextDecoder();
910
- var SUITE_INFO = TEXT_ENCODER2.encode("pendra-pi-v1");
911
- var RESPONSE_INFO = TEXT_ENCODER2.encode("pendra-pi-v1:response");
912
- var RESPONSE_EXPORT_CTX = TEXT_ENCODER2.encode("pendra-pi-v1:rdek");
913
- var AFFINITY_SALT_INFO = TEXT_ENCODER2.encode("pendra-affinity-salt-v1");
914
- function utf8(s) {
915
- return TEXT_ENCODER2.encode(s);
916
- }
917
- function b64(b) {
918
- if (typeof Buffer !== "undefined") {
919
- return Buffer.from(b).toString("base64");
920
- }
921
- let binary = "";
922
- for (let i = 0; i < b.length; i++) binary += String.fromCharCode(b[i]);
923
- return btoa(binary);
924
- }
925
- function b64d(s) {
926
- if (typeof Buffer !== "undefined") {
927
- return new Uint8Array(Buffer.from(s, "base64"));
928
- }
929
- const binary = atob(s);
930
- const out = new Uint8Array(binary.length);
931
- for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
932
- return out;
933
- }
934
- function toHex(b) {
935
- return Array.from(b).map((x) => x.toString(16).padStart(2, "0")).join("");
936
- }
937
- function fingerprint(pub) {
938
- return sha256Hex(pub);
939
- }
940
- function buildAad(model, stream, taskType, responsePkB64) {
941
- const streamBit = stream ? utf8("1") : utf8("0");
942
- const sep = new Uint8Array([0]);
943
- const parts = [utf8("pendra-pi-v1"), utf8(model), streamBit, utf8(taskType), utf8(responsePkB64)];
944
- let total = 0;
945
- for (let i = 0; i < parts.length; i++) {
946
- if (i > 0) total += 1;
947
- total += parts[i].length;
948
- }
949
- const out = new Uint8Array(total);
950
- let off = 0;
951
- for (let i = 0; i < parts.length; i++) {
952
- if (i > 0) {
953
- out.set(sep, off);
954
- off += 1;
955
- }
956
- out.set(parts[i], off);
957
- off += parts[i].length;
958
- }
959
- return out;
960
- }
961
- function seqNonce(seq) {
962
- const nonce = new Uint8Array(12);
963
- let n = BigInt(seq);
964
- for (let i = 11; i >= 4; i--) {
965
- nonce[i] = Number(n & 0xffn);
966
- n >>= 8n;
967
- }
968
- return nonce;
969
- }
970
- function sealRequest(orgPubs, body, opts) {
971
- const pubs = Array.isArray(orgPubs) ? orgPubs : [orgPubs];
972
- if (pubs.length === 0) {
973
- throw new Error("sealRequest: no org public keys to seal to");
974
- }
975
- const seen = /* @__PURE__ */ new Set();
976
- const uniquePubs = [];
977
- for (const p of pubs) {
978
- const fp = fingerprint(p);
979
- if (!seen.has(fp)) {
980
- seen.add(fp);
981
- uniquePubs.push(p);
1048
+ const engine = await this.client._privateEngine();
1049
+ const { topLevel, decryptor } = engine.seal({
1050
+ model,
1051
+ stream: false,
1052
+ taskType: "embeddings",
1053
+ body: ENCODER3.encode(JSON.stringify(body))
1054
+ });
1055
+ const { response } = await this.client._fetch(
1056
+ "/api/v1/embeddings",
1057
+ { method: "POST", body: topLevel, headers }
1058
+ );
1059
+ const wrapper = await response.json();
1060
+ if (!wrapper.pendra_encrypted) {
1061
+ throw unsealedReplyError();
982
1062
  }
1063
+ const plain = decryptor.openResult(wrapper.pendra_encrypted);
1064
+ return JSON.parse(DECODER4.decode(plain));
983
1065
  }
984
- const { priv: respPriv, pub: respPub } = generateX25519Keypair();
985
- const respPkB64 = b64(respPub);
986
- const dek = randomBytes(32);
987
- const nonce = randomBytes(12);
988
- const aad = buildAad(opts.model, opts.stream, opts.taskType, respPkB64);
989
- const ciphertext = chacha20poly13052(dek, nonce, aad).encrypt(body);
990
- const recipients = [];
991
- for (const pub of uniquePubs) {
992
- const { enc, ctx: sealer } = setupBaseS(pub, SUITE_INFO);
993
- const sealedDek = sealer.seal(new Uint8Array(0), dek);
994
- recipients.push({ kid: fingerprint(pub), enc: b64(enc), sealed_dek: b64(sealedDek) });
1066
+ };
1067
+
1068
+ // src/resources/images/generations.ts
1069
+ var ENCODER4 = new TextEncoder();
1070
+ var DECODER5 = new TextDecoder();
1071
+ var SIZE_RE = /^\d+x\d+$/;
1072
+ function validateParams2(params) {
1073
+ if (!params.prompt || !params.prompt.trim()) {
1074
+ throw new Error("prompt must be a non-empty string");
995
1075
  }
996
- const envelope = {
997
- v: ENVELOPE_VERSION,
998
- recipients,
999
- nonce: b64(nonce),
1000
- ciphertext: b64(ciphertext),
1001
- response_pk: respPkB64
1002
- };
1003
- if (opts.affinityKey != null) {
1004
- envelope.affinity_key = opts.affinityKey;
1076
+ if (params.n != null && (params.n < 1 || params.n > 4)) {
1077
+ throw new Error("n must be between 1 and 4");
1005
1078
  }
1006
- if (opts.binary != null) {
1007
- const binaryNonce = randomBytes(12);
1008
- envelope.binary_nonce = b64(binaryNonce);
1009
- envelope.binary_ciphertext = b64(chacha20poly13052(dek, binaryNonce, aad).encrypt(opts.binary));
1079
+ if (params.size != null && !SIZE_RE.test(params.size)) {
1080
+ throw new Error("size must be in the form WIDTHxHEIGHT (e.g. '1024x1024')");
1010
1081
  }
1011
- return { envelope, responsePriv: respPriv };
1012
1082
  }
1013
- var ResponseDecryptor = class {
1014
- constructor(responsePrivateKey) {
1015
- this.dek = null;
1016
- this.nextSeq = 0;
1017
- this.respPriv = responsePrivateKey;
1083
+ var Generations = class {
1084
+ constructor(client) {
1085
+ this.client = client;
1018
1086
  }
1019
- ensureDek(encB64) {
1020
- if (this.dek !== null) return;
1021
- if (!encB64) {
1022
- throw new Error("private_inference: first response frame is missing the encapsulated key");
1087
+ async create(params) {
1088
+ validateParams2(params);
1089
+ const body = {
1090
+ model: params.model,
1091
+ prompt: params.prompt
1092
+ };
1093
+ if (params.n != null) body.n = params.n;
1094
+ if (params.size != null) body.size = params.size;
1095
+ if (params.response_format != null) body.response_format = params.response_format;
1096
+ if (params.num_inference_steps != null) body.num_inference_steps = params.num_inference_steps;
1097
+ if (params.seed != null) body.seed = params.seed;
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);
1023
1102
  }
1024
- const ctx = setupBaseR(this.respPriv, b64d(encB64), RESPONSE_INFO);
1025
- this.dek = ctx.export(RESPONSE_EXPORT_CTX, 32);
1026
- }
1027
- /** Decrypt a non-streaming result envelope `{v, enc, seq, ciphertext}`. */
1028
- openResult(inner) {
1029
- this.ensureDek(inner.enc);
1030
- return chacha20poly13052(this.dek, seqNonce(Number(inner.seq))).decrypt(b64d(inner.ciphertext));
1103
+ const { response } = await this.client._fetch(
1104
+ "/api/v1/images/generations",
1105
+ { method: "POST", body, headers }
1106
+ );
1107
+ return await response.json();
1031
1108
  }
1032
- /** Decrypt one streaming chunk envelope, enforcing monotonic `seq`. */
1033
- openChunk(inner) {
1034
- const seq = Number(inner.seq);
1035
- if (seq !== this.nextSeq) {
1036
- throw new Error(
1037
- `private_inference: out-of-order response chunk (seq ${seq}, expected ${this.nextSeq})`
1038
- );
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
+ });
1039
1128
  }
1040
- this.ensureDek(inner.enc);
1041
- const pt = chacha20poly13052(this.dek, seqNonce(seq)).decrypt(b64d(inner.ciphertext));
1042
- this.nextSeq += 1;
1043
- return pt;
1129
+ return parsed;
1044
1130
  }
1045
1131
  };
1046
- function deriveSalt(rawApiKey) {
1047
- const prk = extract2(sha256, utf8(rawApiKey), new Uint8Array(32));
1048
- return expand2(sha256, prk, AFFINITY_SALT_INFO, 32);
1049
- }
1050
- function canonicalJson(value) {
1051
- if (value === null) return "null";
1052
- const t = typeof value;
1053
- if (t === "boolean") return value ? "true" : "false";
1054
- if (t === "number") {
1055
- return String(value);
1132
+
1133
+ // src/resources/images/index.ts
1134
+ var Images = class {
1135
+ constructor(client) {
1136
+ this.generations = new Generations(client);
1056
1137
  }
1057
- if (t === "string") return encodeString(value);
1058
- if (Array.isArray(value)) {
1059
- return "[" + value.map((v) => canonicalJson(v)).join(",") + "]";
1138
+ };
1139
+
1140
+ // src/resources/models.ts
1141
+ var Models = class {
1142
+ constructor(client) {
1143
+ this.client = client;
1060
1144
  }
1061
- if (t === "object") {
1062
- const obj = value;
1063
- const keys = Object.keys(obj).sort();
1064
- const items = keys.map((k) => encodeString(k) + ":" + canonicalJson(obj[k]));
1065
- return "{" + items.join(",") + "}";
1145
+ async list() {
1146
+ const { response } = await this.client._fetch("/api/v1/models", {
1147
+ method: "GET"
1148
+ });
1149
+ const data = await response.json();
1150
+ return data.data;
1151
+ }
1152
+ };
1153
+
1154
+ // src/resources/rerank.ts
1155
+ var ENCODER5 = new TextEncoder();
1156
+ var DECODER6 = new TextDecoder();
1157
+ function validateParams3(params) {
1158
+ if (!params.model || typeof params.model !== "string") {
1159
+ throw new Error("model must be a non-empty string");
1160
+ }
1161
+ if (!params.query || typeof params.query !== "string") {
1162
+ throw new Error("query must be a non-empty string");
1163
+ }
1164
+ const { documents } = params;
1165
+ if (!Array.isArray(documents) || documents.length === 0 || !documents.every((d) => typeof d === "string" && d.length > 0)) {
1166
+ throw new Error("documents must be a non-empty array of non-empty strings");
1167
+ }
1168
+ if (params.top_n != null && params.top_n < 1) {
1169
+ throw new Error("top_n must be >= 1 when provided");
1066
1170
  }
1067
- return "null";
1068
1171
  }
1069
- function encodeString(s) {
1070
- let out = '"';
1071
- for (let i = 0; i < s.length; i++) {
1072
- const code = s.charCodeAt(i);
1073
- switch (code) {
1074
- case 34:
1075
- out += '\\"';
1076
- break;
1077
- case 92:
1078
- out += "\\\\";
1079
- break;
1080
- case 8:
1081
- out += "\\b";
1082
- break;
1083
- case 9:
1084
- out += "\\t";
1085
- break;
1086
- case 10:
1087
- out += "\\n";
1088
- break;
1089
- case 12:
1090
- out += "\\f";
1091
- break;
1092
- case 13:
1093
- out += "\\r";
1094
- break;
1095
- default:
1096
- if (code < 32 || code > 126) {
1097
- out += "\\u" + code.toString(16).padStart(4, "0");
1098
- } else {
1099
- out += s[i];
1100
- }
1172
+ var Rerank = class {
1173
+ constructor(client) {
1174
+ this.client = client;
1175
+ }
1176
+ /**
1177
+ * Rerank `documents` by relevance to `query` (Cohere-compatible).
1178
+ *
1179
+ * @example
1180
+ * ```ts
1181
+ * const result = await client.rerank.create({
1182
+ * model: "bge-reranker-v2-m3",
1183
+ * query: "What is the capital of France?",
1184
+ * documents: ["Paris is the capital of France.", "Berlin is in Germany."],
1185
+ * top_n: 1,
1186
+ * });
1187
+ * console.log(result.results[0].index, result.results[0].relevance_score);
1188
+ * ```
1189
+ */
1190
+ async create(params) {
1191
+ validateParams3(params);
1192
+ const body = {
1193
+ model: params.model,
1194
+ query: params.query,
1195
+ documents: params.documents,
1196
+ return_documents: params.return_documents ?? false
1197
+ };
1198
+ if (params.top_n != null) body.top_n = params.top_n;
1199
+ const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
1200
+ if (this.client.privateInferenceEnabled) {
1201
+ return this.createEncrypted(params.model, body, headers);
1101
1202
  }
1203
+ const { response } = await this.client._fetch(
1204
+ "/api/v1/rerank",
1205
+ { method: "POST", body, headers }
1206
+ );
1207
+ return await response.json();
1102
1208
  }
1103
- return out + '"';
1104
- }
1105
- function flattenContent(content) {
1106
- if (typeof content === "string") return content;
1107
- return canonicalJson(content);
1108
- }
1109
- function affinityKey(rawApiKey, model, messages, saltOverride) {
1110
- const parts = ["model=" + model];
1111
- let sawUser = false;
1112
- for (const m of messages ?? []) {
1113
- const role = m.role ?? "";
1114
- parts.push(role + ":" + flattenContent(m.content));
1115
- if (role === "user") {
1116
- sawUser = true;
1117
- break;
1209
+ async createEncrypted(model, body, headers) {
1210
+ const engine = await this.client._privateEngine();
1211
+ const { topLevel, decryptor } = engine.seal({
1212
+ model,
1213
+ stream: false,
1214
+ taskType: "rerank",
1215
+ body: ENCODER5.encode(JSON.stringify(body))
1216
+ });
1217
+ const { response } = await this.client._fetch(
1218
+ "/api/v1/rerank",
1219
+ { method: "POST", body: topLevel, headers }
1220
+ );
1221
+ const wrapper = await response.json();
1222
+ if (!wrapper.pendra_encrypted) {
1223
+ throw unsealedReplyError();
1118
1224
  }
1225
+ const plain = decryptor.openResult(wrapper.pendra_encrypted);
1226
+ return JSON.parse(DECODER6.decode(plain));
1119
1227
  }
1120
- if (!sawUser) return null;
1121
- const salt = saltOverride != null ? saltOverride : deriveSalt(rawApiKey);
1122
- const mac = hmac(sha256, salt, utf8(parts.join("\0")));
1123
- return toHex(mac);
1124
- }
1228
+ };
1229
+
1230
+ // src/version.ts
1231
+ var VERSION = "0.15.0";
1232
+ var USER_AGENT = `pendra-node/${VERSION}`;
1125
1233
 
1126
1234
  // src/_privateInferenceEngine.ts
1127
1235
  var PrivateInferenceError = class extends Error {
@@ -1285,6 +1393,7 @@ var PrivateInferenceEngine = class {
1285
1393
  /**
1286
1394
  * Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
1287
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.
1288
1397
  */
1289
1398
  seal(args) {
1290
1399
  if (this.orgPubs === null || this.orgPubs.length === 0) {
@@ -1296,18 +1405,19 @@ var PrivateInferenceEngine = class {
1296
1405
  if (args.messages != null) {
1297
1406
  affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
1298
1407
  }
1299
- const { envelope, responsePriv } = sealRequest(this.orgPubs, args.body, {
1408
+ const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
1300
1409
  model: args.model,
1301
1410
  stream: args.stream,
1302
1411
  taskType: args.taskType,
1303
- affinityKey: affinity
1412
+ affinityKey: affinity,
1413
+ binary: args.binary ?? null
1304
1414
  });
1305
1415
  const topLevel = {
1306
1416
  model: args.model,
1307
1417
  stream: args.stream,
1308
1418
  pendra_encrypted: envelope
1309
1419
  };
1310
- return { topLevel, decryptor: new ResponseDecryptor(responsePriv) };
1420
+ return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
1311
1421
  }
1312
1422
  get keyFetchUrl() {
1313
1423
  return `${this.baseUrl}/v1/private-inference/key`;
@@ -1419,7 +1529,10 @@ var Pendra = class {
1419
1529
  let message;
1420
1530
  try {
1421
1531
  const body = await response.json();
1422
- 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;
1423
1536
  } catch {
1424
1537
  message = response.statusText;
1425
1538
  }
@@ -1432,8 +1545,9 @@ var Pendra = class {
1432
1545
  }
1433
1546
  /** @internal */
1434
1547
  async _fetch(path, options) {
1548
+ const timeout = options.timeout ?? this.timeout;
1435
1549
  const controller = new AbortController();
1436
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
1550
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
1437
1551
  const headers = {
1438
1552
  Authorization: `Bearer ${this.apiKey}`,
1439
1553
  "Content-Type": "application/json",
@@ -1452,7 +1566,7 @@ var Pendra = class {
1452
1566
  clearTimeout(timeoutId);
1453
1567
  if (err instanceof DOMException && err.name === "AbortError") {
1454
1568
  throw new APIConnectionError(
1455
- `Request timed out after ${this.timeout}ms`
1569
+ `Request timed out after ${timeout}ms`
1456
1570
  );
1457
1571
  }
1458
1572
  throw new APIConnectionError(
@@ -1465,7 +1579,10 @@ var Pendra = class {
1465
1579
  let message;
1466
1580
  try {
1467
1581
  const body = await response.json();
1468
- 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;
1469
1586
  } catch {
1470
1587
  message = response.statusText;
1471
1588
  }