pendra 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -339,7 +339,7 @@ var SseDecoder = class {
339
339
 
340
340
  // src/streaming.ts
341
341
  var Stream = class {
342
- constructor(response, controller) {
342
+ constructor(response, controller, idleTimeoutMs) {
343
343
  this.decoder = new TextDecoder();
344
344
  this.sse = new SseDecoder();
345
345
  this.done = false;
@@ -348,11 +348,15 @@ var Stream = class {
348
348
  }
349
349
  this.reader = response.body.getReader();
350
350
  this.controller = controller;
351
+ this.idleTimeoutMs = idleTimeoutMs;
351
352
  }
352
353
  async *[Symbol.asyncIterator]() {
353
354
  try {
354
355
  while (!this.done) {
355
- const { value, done: readerDone } = await this.reader.read();
356
+ const { value, done: readerDone } = await readWithIdleTimeout(
357
+ this.reader,
358
+ this.idleTimeoutMs
359
+ );
356
360
  const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
357
361
  for (const data of payloads) {
358
362
  if (data === "[DONE]") {
@@ -367,69 +371,7 @@ var Stream = class {
367
371
  }
368
372
  }
369
373
  } finally {
370
- this.reader.releaseLock();
371
- }
372
- }
373
- abort() {
374
- this.done = true;
375
- this.controller.abort();
376
- }
377
- };
378
-
379
- // src/_privateStreaming.ts
380
- var DECODER = new TextDecoder();
381
- var EncryptedStream = class {
382
- constructor(response, controller, decryptor) {
383
- this.decoder = new TextDecoder();
384
- this.sse = new SseDecoder();
385
- this.done = false;
386
- if (!response.body) {
387
- throw new Error("Response body is null \u2014 streaming not supported");
388
- }
389
- this.reader = response.body.getReader();
390
- this.controller = controller;
391
- this.decryptor = decryptor;
392
- }
393
- async *[Symbol.asyncIterator]() {
394
- try {
395
- while (!this.done) {
396
- const { value, done: readerDone } = await this.reader.read();
397
- const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
398
- for (const data of payloads) {
399
- if (data === "[DONE]") {
400
- this.done = true;
401
- return;
402
- }
403
- let inner;
404
- try {
405
- inner = JSON.parse(data).pendra_encrypted;
406
- } catch {
407
- throw new APIResponseValidationError("Stream frame was not valid JSON", {
408
- body: data
409
- });
410
- }
411
- if (!inner) {
412
- yield parseStreamFrame(data);
413
- continue;
414
- }
415
- const plain = this.decryptor.openChunk(inner);
416
- const chunkJson = DECODER.decode(plain).trim();
417
- if (!chunkJson || chunkJson === "[DONE]") {
418
- if (chunkJson === "[DONE]") {
419
- this.done = true;
420
- return;
421
- }
422
- continue;
423
- }
424
- yield parseStreamFrame(chunkJson, "Decrypted stream frame");
425
- }
426
- if (readerDone) {
427
- this.done = true;
428
- break;
429
- }
430
- }
431
- } finally {
432
- this.reader.releaseLock();
374
+ releaseReader(this.reader, this.controller, this.done);
433
375
  }
434
376
  }
435
377
  abort() {
@@ -437,392 +379,111 @@ var EncryptedStream = class {
437
379
  this.controller.abort();
438
380
  }
439
381
  };
440
-
441
- // src/resources/chat/completions.ts
442
- var ENCODER = new TextEncoder();
443
- var DECODER2 = new TextDecoder();
444
- var Completions = class {
445
- constructor(client) {
446
- this.client = client;
447
- }
448
- async create(params) {
449
- const { worker_id: _workerId, ...rest } = params;
450
- const body = {};
451
- for (const [key, value] of Object.entries(rest)) {
452
- if (value != null) body[key] = value;
453
- }
454
- const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
455
- if (this.client.privateInferenceEnabled) {
456
- return this.createEncrypted(params, body, headers);
457
- }
458
- if (params.stream) {
459
- const { response: response2, controller } = await this.client._fetch(
460
- "/api/v1/chat/completions",
461
- { method: "POST", body, stream: true, headers }
462
- );
463
- return new Stream(response2, controller);
464
- }
465
- const { response } = await this.client._fetch(
466
- "/api/v1/chat/completions",
467
- { method: "POST", body, headers }
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
468
389
  );
469
- return parseCompletion(response);
390
+ });
391
+ try {
392
+ return await Promise.race([reader.read(), idle]);
393
+ } finally {
394
+ clearTimeout(timer);
470
395
  }
471
- async createEncrypted(params, body, headers) {
472
- const engine = await this.client._privateEngine();
473
- const stream = Boolean(params.stream);
474
- const { topLevel, decryptor } = engine.seal({
475
- model: params.model,
476
- stream,
477
- taskType: "chat",
478
- body: ENCODER.encode(JSON.stringify(body)),
479
- messages: params.messages
396
+ }
397
+ function releaseReader(reader, controller, finished) {
398
+ if (!finished) {
399
+ controller.abort();
400
+ reader.cancel().catch(() => {
480
401
  });
481
- if (stream) {
482
- const { response: response2, controller } = await this.client._fetch(
483
- "/api/v1/chat/completions",
484
- { method: "POST", body: topLevel, stream: true, headers }
485
- );
486
- return new EncryptedStream(response2, controller, decryptor);
487
- }
488
- const { response } = await this.client._fetch(
489
- "/api/v1/chat/completions",
490
- { method: "POST", body: topLevel, headers }
491
- );
492
- const raw = await response.text();
493
- let wrapper;
494
- try {
495
- wrapper = JSON.parse(raw);
496
- } catch {
497
- throw new APIResponseValidationError("Response was not valid JSON", {
498
- status: response.status,
499
- body: raw
500
- });
501
- }
502
- if (!wrapper.pendra_encrypted) {
503
- return parseDecryptedCompletion(raw, response.status);
504
- }
505
- const plain = decryptor.openResult(wrapper.pendra_encrypted);
506
- return parseDecryptedCompletion(DECODER2.decode(plain), response.status);
507
402
  }
508
- };
403
+ reader.releaseLock();
404
+ }
509
405
 
510
- // src/resources/chat/index.ts
511
- var Chat = class {
512
- constructor(client) {
513
- this.completions = new Completions(client);
514
- }
515
- };
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";
516
409
 
517
- // src/resources/embeddings.ts
518
- var ENCODER2 = new TextEncoder();
519
- var DECODER3 = new TextDecoder();
520
- function validateParams(params) {
521
- if (!params.model || typeof params.model !== "string") {
522
- throw new Error("model must be a non-empty string");
523
- }
524
- const { input } = params;
525
- if (typeof input === "string") {
526
- if (input.length === 0) {
527
- throw new Error("input must be a non-empty string or non-empty array of strings");
528
- }
529
- return;
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);
530
429
  }
531
- if (Array.isArray(input)) {
532
- if (input.length === 0) {
533
- throw new Error("input must be a non-empty string or non-empty array of strings");
534
- }
535
- if (!input.every((s) => typeof s === "string" && s.length > 0)) {
536
- throw new Error("input array entries must all be non-empty strings");
537
- }
538
- return;
430
+ return out;
431
+ }
432
+ var TEXT_ENCODER = new TextEncoder();
433
+ function bytes(s) {
434
+ return TEXT_ENCODER.encode(s);
435
+ }
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;
539
444
  }
540
- throw new Error("input must be a string or an array of strings");
445
+ return out;
541
446
  }
542
- var Embeddings = class {
543
- constructor(client) {
544
- this.client = client;
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);
453
+ }
454
+ function hkdfExpand(prk, info, length) {
455
+ return expand(sha256, prk, info, length);
456
+ }
457
+ function labeledExtract(salt, label, ikm, suiteId) {
458
+ return hkdfExtract(salt, concat(HPKE_VERSION, suiteId, label, ikm));
459
+ }
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);
463
+ }
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);
467
+ }
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];
474
+ }
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;
545
481
  }
546
- /**
547
- * Create embeddings for the given input.
548
- *
549
- * @example
550
- * ```ts
551
- * const result = await client.embeddings.create({
552
- * model: "nomic-embed-text:latest",
553
- * input: "Hello world",
554
- * });
555
- * console.log(result.data[0].embedding);
556
- * ```
557
- */
558
- async create(params) {
559
- validateParams(params);
560
- const body = {
561
- model: params.model,
562
- input: params.input
563
- };
564
- if (params.encoding_format != null) body.encoding_format = params.encoding_format;
565
- if (params.dimensions != null) body.dimensions = params.dimensions;
566
- if (params.user != null) body.user = params.user;
567
- const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
568
- if (this.client.privateInferenceEnabled) {
569
- return this.createEncrypted(params.model, body, headers);
570
- }
571
- const { response } = await this.client._fetch(
572
- "/api/v1/embeddings",
573
- { method: "POST", body, headers }
574
- );
575
- return await response.json();
576
- }
577
- async createEncrypted(model, body, headers) {
578
- const engine = await this.client._privateEngine();
579
- const { topLevel, decryptor } = engine.seal({
580
- model,
581
- stream: false,
582
- taskType: "embeddings",
583
- body: ENCODER2.encode(JSON.stringify(body))
584
- });
585
- const { response } = await this.client._fetch(
586
- "/api/v1/embeddings",
587
- { method: "POST", body: topLevel, headers }
588
- );
589
- const wrapper = await response.json();
590
- if (!wrapper.pendra_encrypted) {
591
- return wrapper;
592
- }
593
- const plain = decryptor.openResult(wrapper.pendra_encrypted);
594
- return JSON.parse(DECODER3.decode(plain));
595
- }
596
- };
597
-
598
- // src/resources/images/generations.ts
599
- var SIZE_RE = /^\d+x\d+$/;
600
- function validateParams2(params) {
601
- if (!params.prompt || !params.prompt.trim()) {
602
- throw new Error("prompt must be a non-empty string");
603
- }
604
- if (params.n != null && (params.n < 1 || params.n > 4)) {
605
- throw new Error("n must be between 1 and 4");
606
- }
607
- if (params.size != null && !SIZE_RE.test(params.size)) {
608
- throw new Error("size must be in the form WIDTHxHEIGHT (e.g. '1024x1024')");
609
- }
610
- }
611
- var Generations = class {
612
- constructor(client) {
613
- this.client = client;
614
- }
615
- async create(params) {
616
- if (this.client.privateInferenceEnabled) {
617
- throw new Error("private inference is not yet supported for images/audio");
618
- }
619
- validateParams2(params);
620
- const body = {
621
- model: params.model,
622
- prompt: params.prompt
623
- };
624
- if (params.n != null) body.n = params.n;
625
- if (params.size != null) body.size = params.size;
626
- if (params.response_format != null) body.response_format = params.response_format;
627
- if (params.num_inference_steps != null) body.num_inference_steps = params.num_inference_steps;
628
- if (params.seed != null) body.seed = params.seed;
629
- if (params.negative_prompt != null) body.negative_prompt = params.negative_prompt;
630
- const { response } = await this.client._fetch(
631
- "/api/v1/images/generations",
632
- {
633
- method: "POST",
634
- body,
635
- headers: params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0
636
- }
637
- );
638
- return await response.json();
639
- }
640
- };
641
-
642
- // src/resources/images/index.ts
643
- var Images = class {
644
- constructor(client) {
645
- this.generations = new Generations(client);
646
- }
647
- };
648
-
649
- // src/resources/models.ts
650
- var Models = class {
651
- constructor(client) {
652
- this.client = client;
653
- }
654
- async list() {
655
- const { response } = await this.client._fetch("/api/v1/models", {
656
- method: "GET"
657
- });
658
- const data = await response.json();
659
- return data.data;
660
- }
661
- };
662
-
663
- // src/resources/rerank.ts
664
- var ENCODER3 = new TextEncoder();
665
- var DECODER4 = new TextDecoder();
666
- function validateParams3(params) {
667
- if (!params.model || typeof params.model !== "string") {
668
- throw new Error("model must be a non-empty string");
669
- }
670
- if (!params.query || typeof params.query !== "string") {
671
- throw new Error("query must be a non-empty string");
672
- }
673
- const { documents } = params;
674
- if (!Array.isArray(documents) || documents.length === 0 || !documents.every((d) => typeof d === "string" && d.length > 0)) {
675
- throw new Error("documents must be a non-empty array of non-empty strings");
676
- }
677
- if (params.top_n != null && params.top_n < 1) {
678
- throw new Error("top_n must be >= 1 when provided");
679
- }
680
- }
681
- var Rerank = class {
682
- constructor(client) {
683
- this.client = client;
684
- }
685
- /**
686
- * Rerank `documents` by relevance to `query` (Cohere-compatible).
687
- *
688
- * @example
689
- * ```ts
690
- * const result = await client.rerank.create({
691
- * model: "bge-reranker-v2-m3",
692
- * query: "What is the capital of France?",
693
- * documents: ["Paris is the capital of France.", "Berlin is in Germany."],
694
- * top_n: 1,
695
- * });
696
- * console.log(result.results[0].index, result.results[0].relevance_score);
697
- * ```
698
- */
699
- async create(params) {
700
- validateParams3(params);
701
- const body = {
702
- model: params.model,
703
- query: params.query,
704
- documents: params.documents,
705
- return_documents: params.return_documents ?? false
706
- };
707
- if (params.top_n != null) body.top_n = params.top_n;
708
- const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
709
- if (this.client.privateInferenceEnabled) {
710
- return this.createEncrypted(params.model, body, headers);
711
- }
712
- const { response } = await this.client._fetch(
713
- "/api/v1/rerank",
714
- { method: "POST", body, headers }
715
- );
716
- return await response.json();
717
- }
718
- async createEncrypted(model, body, headers) {
719
- const engine = await this.client._privateEngine();
720
- const { topLevel, decryptor } = engine.seal({
721
- model,
722
- stream: false,
723
- taskType: "rerank",
724
- body: ENCODER3.encode(JSON.stringify(body))
725
- });
726
- const { response } = await this.client._fetch(
727
- "/api/v1/rerank",
728
- { method: "POST", body: topLevel, headers }
729
- );
730
- const wrapper = await response.json();
731
- if (!wrapper.pendra_encrypted) {
732
- return wrapper;
733
- }
734
- const plain = decryptor.openResult(wrapper.pendra_encrypted);
735
- return JSON.parse(DECODER4.decode(plain));
736
- }
737
- };
738
-
739
- // src/version.ts
740
- var VERSION = "0.13.0";
741
- var USER_AGENT = `pendra-node/${VERSION}`;
742
-
743
- // src/_hpke.ts
744
- import { x25519 } from "@noble/curves/ed25519.js";
745
- import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
746
- import { sha256 } from "@noble/hashes/sha2.js";
747
- import { hmac } from "@noble/hashes/hmac.js";
748
- import { extract, expand } from "@noble/hashes/hkdf.js";
749
- import { randomBytes as nobleRandomBytes } from "@noble/hashes/utils.js";
750
- var KEM_ID = 32;
751
- var KDF_ID = 1;
752
- var AEAD_ID = 3;
753
- var NH = 32;
754
- var NK = 32;
755
- var NN = 12;
756
- var NSECRET = 32;
757
- function i2osp(n, len) {
758
- const out = new Uint8Array(len);
759
- for (let i = len - 1; i >= 0; i--) {
760
- out[i] = n & 255;
761
- n = Math.floor(n / 256);
762
- }
763
- return out;
764
- }
765
- var TEXT_ENCODER = new TextEncoder();
766
- function bytes(s) {
767
- return TEXT_ENCODER.encode(s);
768
- }
769
- function concat(...parts) {
770
- let total = 0;
771
- for (const p of parts) total += p.length;
772
- const out = new Uint8Array(total);
773
- let off = 0;
774
- for (const p of parts) {
775
- out.set(p, off);
776
- off += p.length;
777
- }
778
- return out;
779
- }
780
- var SUITE_ID = concat(bytes("HPKE"), i2osp(KEM_ID, 2), i2osp(KDF_ID, 2), i2osp(AEAD_ID, 2));
781
- var KEM_SUITE_ID = concat(bytes("KEM"), i2osp(KEM_ID, 2));
782
- var HPKE_VERSION = bytes("HPKE-v1");
783
- function hkdfExtract(salt, ikm) {
784
- const effectiveSalt = salt.length === 0 ? new Uint8Array(NH) : salt;
785
- return extract(sha256, ikm, effectiveSalt);
786
- }
787
- function hkdfExpand(prk, info, length) {
788
- return expand(sha256, prk, info, length);
789
- }
790
- function labeledExtract(salt, label, ikm, suiteId) {
791
- return hkdfExtract(salt, concat(HPKE_VERSION, suiteId, label, ikm));
792
- }
793
- function labeledExpand(prk, label, info, length, suiteId) {
794
- const labeledInfo = concat(i2osp(length, 2), HPKE_VERSION, suiteId, label, info);
795
- return hkdfExpand(prk, labeledInfo, length);
796
- }
797
- function extractAndExpand(dh, kemContext) {
798
- const eaePrk = labeledExtract(new Uint8Array(0), bytes("eae_prk"), dh, KEM_SUITE_ID);
799
- return labeledExpand(eaePrk, bytes("shared_secret"), kemContext, NSECRET, KEM_SUITE_ID);
800
- }
801
- function encap(pkR, skE) {
802
- const skEObj = skE ?? x25519.utils.randomSecretKey();
803
- const enc = x25519.getPublicKey(skEObj);
804
- const dh = x25519.getSharedSecret(skEObj, pkR);
805
- const kemContext = concat(enc, pkR);
806
- return [extractAndExpand(dh, kemContext), enc];
807
- }
808
- function decap(enc, skR) {
809
- const dh = x25519.getSharedSecret(skR, enc);
810
- const pkRm = x25519.getPublicKey(skR);
811
- const kemContext = concat(enc, pkRm);
812
- return extractAndExpand(dh, kemContext);
813
- }
814
- var Context = class {
815
- constructor(key, baseNonce, exporterSecret) {
816
- this.seq = 0;
817
- this.key = key;
818
- this.baseNonce = baseNonce;
819
- this.exporterSecret = exporterSecret;
820
- }
821
- computeNonce() {
822
- const seqBytes = i2osp(this.seq, NN);
823
- const nonce = new Uint8Array(NN);
824
- for (let i = 0; i < NN; i++) {
825
- nonce[i] = this.baseNonce[i] ^ seqBytes[i];
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];
826
487
  }
827
488
  return nonce;
828
489
  }
@@ -855,14 +516,6 @@ function setupBaseS(pkR, info, skE) {
855
516
  const [sharedSecret, enc] = encap(pkR, skE);
856
517
  return { enc, ctx: keySchedule(sharedSecret, info) };
857
518
  }
858
- function setupBaseR(skR, enc, info) {
859
- const sharedSecret = decap(enc, skR);
860
- return keySchedule(sharedSecret, info);
861
- }
862
- function generateX25519Keypair() {
863
- const priv = x25519.utils.randomSecretKey();
864
- return { priv, pub: x25519.getPublicKey(priv) };
865
- }
866
519
  function randomBytes(n) {
867
520
  return nobleRandomBytes(n);
868
521
  }
@@ -871,13 +524,10 @@ function sha256Hex(data) {
871
524
  }
872
525
 
873
526
  // src/_privateInference.ts
874
- import { chacha20poly1305 as chacha20poly13052 } from "@noble/ciphers/chacha.js";
875
- import { extract as extract2, expand as expand2 } from "@noble/hashes/hkdf.js";
876
- var ENVELOPE_VERSION = 1;
527
+ var ENVELOPE_VERSION = 2;
877
528
  var TEXT_ENCODER2 = new TextEncoder();
878
529
  var TEXT_DECODER = new TextDecoder();
879
530
  var SUITE_INFO = TEXT_ENCODER2.encode("pendra-pi-v1");
880
- var RESPONSE_INFO = TEXT_ENCODER2.encode("pendra-pi-v1:response");
881
531
  var RESPONSE_EXPORT_CTX = TEXT_ENCODER2.encode("pendra-pi-v1:rdek");
882
532
  var AFFINITY_SALT_INFO = TEXT_ENCODER2.encode("pendra-affinity-salt-v1");
883
533
  function utf8(s) {
@@ -906,10 +556,10 @@ function toHex(b) {
906
556
  function fingerprint(pub) {
907
557
  return sha256Hex(pub);
908
558
  }
909
- function buildAad(model, stream, taskType, responsePkB64) {
559
+ function buildAad(model, stream, taskType) {
910
560
  const streamBit = stream ? utf8("1") : utf8("0");
911
561
  const sep = new Uint8Array([0]);
912
- const parts = [utf8("pendra-pi-v1"), utf8(model), streamBit, utf8(taskType), utf8(responsePkB64)];
562
+ const parts = [utf8("pendra-pi-v1"), utf8(model), streamBit, utf8(taskType), new Uint8Array(0)];
913
563
  let total = 0;
914
564
  for (let i = 0; i < parts.length; i++) {
915
565
  if (i > 0) total += 1;
@@ -950,147 +600,537 @@ function sealRequest(orgPubs, body, opts) {
950
600
  uniquePubs.push(p);
951
601
  }
952
602
  }
953
- const { priv: respPriv, pub: respPub } = generateX25519Keypair();
954
- const respPkB64 = b64(respPub);
955
- const dek = randomBytes(32);
956
- const nonce = randomBytes(12);
957
- const aad = buildAad(opts.model, opts.stream, opts.taskType, respPkB64);
958
- const ciphertext = chacha20poly13052(dek, nonce, aad).encrypt(body);
959
- const recipients = [];
960
- for (const pub of uniquePubs) {
961
- const { enc, ctx: sealer } = setupBaseS(pub, SUITE_INFO);
962
- const sealedDek = sealer.seal(new Uint8Array(0), dek);
963
- recipients.push({ kid: fingerprint(pub), enc: b64(enc), sealed_dek: b64(sealedDek) });
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;
624
+ }
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));
629
+ }
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;
649
+ }
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");
660
+ }
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));
667
+ }
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
+ );
675
+ }
676
+ this.ensureDek(inner);
677
+ const pt = chacha20poly13052(this.dek, seqNonce(seq)).decrypt(b64d(inner.ciphertext));
678
+ this.nextSeq += 1;
679
+ return pt;
680
+ }
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);
692
+ }
693
+ if (t === "string") return encodeString(value);
694
+ if (Array.isArray(value)) {
695
+ return "[" + value.map((v) => canonicalJson(v)).join(",") + "]";
696
+ }
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(",") + "}";
702
+ }
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];
736
+ }
737
+ }
738
+ }
739
+ return out + '"';
740
+ }
741
+ function flattenContent(content) {
742
+ if (typeof content === "string") return content;
743
+ return canonicalJson(content);
744
+ }
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
+ }
755
+ }
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);
760
+ }
761
+
762
+ // src/_privateStreaming.ts
763
+ var DECODER = new TextDecoder();
764
+ var EncryptedStream = class {
765
+ constructor(response, controller, decryptor, idleTimeoutMs) {
766
+ this.decoder = new TextDecoder();
767
+ this.sse = new SseDecoder();
768
+ this.done = false;
769
+ if (!response.body) {
770
+ throw new Error("Response body is null \u2014 streaming not supported");
771
+ }
772
+ this.reader = response.body.getReader();
773
+ this.controller = controller;
774
+ this.decryptor = decryptor;
775
+ this.idleTimeoutMs = idleTimeoutMs;
776
+ }
777
+ async *[Symbol.asyncIterator]() {
778
+ try {
779
+ while (!this.done) {
780
+ const { value, done: readerDone } = await readWithIdleTimeout(
781
+ this.reader,
782
+ this.idleTimeoutMs
783
+ );
784
+ const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
785
+ for (const data of payloads) {
786
+ if (data === "[DONE]") {
787
+ this.done = true;
788
+ return;
789
+ }
790
+ let frame;
791
+ try {
792
+ frame = JSON.parse(data);
793
+ } catch {
794
+ throw new APIResponseValidationError("Stream frame was not valid JSON", {
795
+ body: data
796
+ });
797
+ }
798
+ const inner = frame?.pendra_encrypted;
799
+ if (!inner) {
800
+ if (isApiTimingChunk(frame)) {
801
+ yield parseStreamFrame(data);
802
+ continue;
803
+ }
804
+ parseStreamFrame(data);
805
+ throw unsealedReplyError();
806
+ }
807
+ const plain = this.decryptor.openChunk(inner);
808
+ const chunkJson = DECODER.decode(plain).trim();
809
+ if (!chunkJson || chunkJson === "[DONE]") {
810
+ if (chunkJson === "[DONE]") {
811
+ this.done = true;
812
+ return;
813
+ }
814
+ continue;
815
+ }
816
+ yield parseStreamFrame(chunkJson, "Decrypted stream frame");
817
+ }
818
+ if (readerDone) {
819
+ this.done = true;
820
+ break;
821
+ }
822
+ }
823
+ } finally {
824
+ releaseReader(this.reader, this.controller, this.done);
825
+ }
826
+ }
827
+ abort() {
828
+ this.done = true;
829
+ this.controller.abort();
830
+ }
831
+ };
832
+
833
+ // src/resources/chat/completions.ts
834
+ var ENCODER = new TextEncoder();
835
+ var DECODER2 = new TextDecoder();
836
+ var Completions = class {
837
+ constructor(client) {
838
+ this.client = client;
839
+ }
840
+ async create(params) {
841
+ const { worker_id: _workerId, ...rest } = params;
842
+ const body = {};
843
+ for (const [key, value] of Object.entries(rest)) {
844
+ if (value != null) body[key] = value;
845
+ }
846
+ const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
847
+ if (this.client.privateInferenceEnabled) {
848
+ return this.createEncrypted(params, body, headers);
849
+ }
850
+ if (params.stream) {
851
+ const { response: response2, controller } = await this.client._fetch(
852
+ "/api/v1/chat/completions",
853
+ { method: "POST", body, headers }
854
+ );
855
+ return new Stream(response2, controller, this.client.timeout);
856
+ }
857
+ const { response } = await this.client._fetch(
858
+ "/api/v1/chat/completions",
859
+ { method: "POST", body, headers }
860
+ );
861
+ return parseCompletion(response);
862
+ }
863
+ async createEncrypted(params, body, headers) {
864
+ const engine = await this.client._privateEngine();
865
+ const stream = Boolean(params.stream);
866
+ const { topLevel, decryptor } = engine.seal({
867
+ model: params.model,
868
+ stream,
869
+ taskType: "chat",
870
+ body: ENCODER.encode(JSON.stringify(body)),
871
+ messages: params.messages
872
+ });
873
+ if (stream) {
874
+ const { response: response2, controller } = await this.client._fetch(
875
+ "/api/v1/chat/completions",
876
+ { method: "POST", body: topLevel, headers }
877
+ );
878
+ return new EncryptedStream(response2, controller, decryptor, this.client.timeout);
879
+ }
880
+ const { response } = await this.client._fetch(
881
+ "/api/v1/chat/completions",
882
+ { method: "POST", body: topLevel, headers }
883
+ );
884
+ const raw = await response.text();
885
+ let wrapper;
886
+ try {
887
+ wrapper = JSON.parse(raw);
888
+ } catch {
889
+ throw new APIResponseValidationError("Response was not valid JSON", {
890
+ status: response.status,
891
+ body: raw
892
+ });
893
+ }
894
+ if (!wrapper.pendra_encrypted) {
895
+ throw unsealedReplyError();
896
+ }
897
+ const plain = decryptor.openResult(wrapper.pendra_encrypted);
898
+ return parseDecryptedCompletion(DECODER2.decode(plain), response.status);
899
+ }
900
+ };
901
+
902
+ // src/resources/chat/index.ts
903
+ var Chat = class {
904
+ constructor(client) {
905
+ this.completions = new Completions(client);
906
+ }
907
+ };
908
+
909
+ // src/resources/embeddings.ts
910
+ var ENCODER2 = new TextEncoder();
911
+ var DECODER3 = new TextDecoder();
912
+ function validateParams(params) {
913
+ if (!params.model || typeof params.model !== "string") {
914
+ throw new Error("model must be a non-empty string");
915
+ }
916
+ const { input } = params;
917
+ if (typeof input === "string") {
918
+ if (input.length === 0) {
919
+ throw new Error("input must be a non-empty string or non-empty array of strings");
920
+ }
921
+ return;
922
+ }
923
+ if (Array.isArray(input)) {
924
+ if (input.length === 0) {
925
+ throw new Error("input must be a non-empty string or non-empty array of strings");
926
+ }
927
+ if (!input.every((s) => typeof s === "string" && s.length > 0)) {
928
+ throw new Error("input array entries must all be non-empty strings");
929
+ }
930
+ return;
931
+ }
932
+ throw new Error("input must be a string or an array of strings");
933
+ }
934
+ var Embeddings = class {
935
+ constructor(client) {
936
+ this.client = client;
937
+ }
938
+ /**
939
+ * Create embeddings for the given input.
940
+ *
941
+ * @example
942
+ * ```ts
943
+ * const result = await client.embeddings.create({
944
+ * model: "nomic-embed-text:latest",
945
+ * input: "Hello world",
946
+ * });
947
+ * console.log(result.data[0].embedding);
948
+ * ```
949
+ */
950
+ async create(params) {
951
+ validateParams(params);
952
+ const body = {
953
+ model: params.model,
954
+ input: params.input
955
+ };
956
+ if (params.encoding_format != null) body.encoding_format = params.encoding_format;
957
+ if (params.dimensions != null) body.dimensions = params.dimensions;
958
+ if (params.user != null) body.user = params.user;
959
+ const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
960
+ if (this.client.privateInferenceEnabled) {
961
+ return this.createEncrypted(params.model, body, headers);
962
+ }
963
+ const { response } = await this.client._fetch(
964
+ "/api/v1/embeddings",
965
+ { method: "POST", body, headers }
966
+ );
967
+ return await response.json();
968
+ }
969
+ async createEncrypted(model, body, headers) {
970
+ const engine = await this.client._privateEngine();
971
+ const { topLevel, decryptor } = engine.seal({
972
+ model,
973
+ stream: false,
974
+ taskType: "embeddings",
975
+ body: ENCODER2.encode(JSON.stringify(body))
976
+ });
977
+ const { response } = await this.client._fetch(
978
+ "/api/v1/embeddings",
979
+ { method: "POST", body: topLevel, headers }
980
+ );
981
+ const wrapper = await response.json();
982
+ if (!wrapper.pendra_encrypted) {
983
+ throw unsealedReplyError();
984
+ }
985
+ const plain = decryptor.openResult(wrapper.pendra_encrypted);
986
+ return JSON.parse(DECODER3.decode(plain));
987
+ }
988
+ };
989
+
990
+ // src/resources/images/generations.ts
991
+ var SIZE_RE = /^\d+x\d+$/;
992
+ function validateParams2(params) {
993
+ if (!params.prompt || !params.prompt.trim()) {
994
+ throw new Error("prompt must be a non-empty string");
964
995
  }
965
- const envelope = {
966
- v: ENVELOPE_VERSION,
967
- recipients,
968
- nonce: b64(nonce),
969
- ciphertext: b64(ciphertext),
970
- response_pk: respPkB64
971
- };
972
- if (opts.affinityKey != null) {
973
- envelope.affinity_key = opts.affinityKey;
996
+ if (params.n != null && (params.n < 1 || params.n > 4)) {
997
+ throw new Error("n must be between 1 and 4");
974
998
  }
975
- if (opts.binary != null) {
976
- const binaryNonce = randomBytes(12);
977
- envelope.binary_nonce = b64(binaryNonce);
978
- envelope.binary_ciphertext = b64(chacha20poly13052(dek, binaryNonce, aad).encrypt(opts.binary));
999
+ if (params.size != null && !SIZE_RE.test(params.size)) {
1000
+ throw new Error("size must be in the form WIDTHxHEIGHT (e.g. '1024x1024')");
979
1001
  }
980
- return { envelope, responsePriv: respPriv };
981
1002
  }
982
- var ResponseDecryptor = class {
983
- constructor(responsePrivateKey) {
984
- this.dek = null;
985
- this.nextSeq = 0;
986
- this.respPriv = responsePrivateKey;
1003
+ var Generations = class {
1004
+ constructor(client) {
1005
+ this.client = client;
987
1006
  }
988
- ensureDek(encB64) {
989
- if (this.dek !== null) return;
990
- if (!encB64) {
991
- throw new Error("private_inference: first response frame is missing the encapsulated key");
1007
+ async create(params) {
1008
+ if (this.client.privateInferenceEnabled) {
1009
+ throw new Error("private inference is not yet supported for images/audio");
992
1010
  }
993
- const ctx = setupBaseR(this.respPriv, b64d(encB64), RESPONSE_INFO);
994
- this.dek = ctx.export(RESPONSE_EXPORT_CTX, 32);
1011
+ validateParams2(params);
1012
+ const body = {
1013
+ model: params.model,
1014
+ prompt: params.prompt
1015
+ };
1016
+ if (params.n != null) body.n = params.n;
1017
+ if (params.size != null) body.size = params.size;
1018
+ if (params.response_format != null) body.response_format = params.response_format;
1019
+ if (params.num_inference_steps != null) body.num_inference_steps = params.num_inference_steps;
1020
+ if (params.seed != null) body.seed = params.seed;
1021
+ if (params.negative_prompt != null) body.negative_prompt = params.negative_prompt;
1022
+ const { response } = await this.client._fetch(
1023
+ "/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
+ }
1029
+ );
1030
+ return await response.json();
995
1031
  }
996
- /** Decrypt a non-streaming result envelope `{v, enc, seq, ciphertext}`. */
997
- openResult(inner) {
998
- this.ensureDek(inner.enc);
999
- return chacha20poly13052(this.dek, seqNonce(Number(inner.seq))).decrypt(b64d(inner.ciphertext));
1032
+ };
1033
+
1034
+ // src/resources/images/index.ts
1035
+ var Images = class {
1036
+ constructor(client) {
1037
+ this.generations = new Generations(client);
1000
1038
  }
1001
- /** Decrypt one streaming chunk envelope, enforcing monotonic `seq`. */
1002
- openChunk(inner) {
1003
- const seq = Number(inner.seq);
1004
- if (seq !== this.nextSeq) {
1005
- throw new Error(
1006
- `private_inference: out-of-order response chunk (seq ${seq}, expected ${this.nextSeq})`
1007
- );
1008
- }
1009
- this.ensureDek(inner.enc);
1010
- const pt = chacha20poly13052(this.dek, seqNonce(seq)).decrypt(b64d(inner.ciphertext));
1011
- this.nextSeq += 1;
1012
- return pt;
1039
+ };
1040
+
1041
+ // src/resources/models.ts
1042
+ var Models = class {
1043
+ constructor(client) {
1044
+ this.client = client;
1045
+ }
1046
+ async list() {
1047
+ const { response } = await this.client._fetch("/api/v1/models", {
1048
+ method: "GET"
1049
+ });
1050
+ const data = await response.json();
1051
+ return data.data;
1013
1052
  }
1014
1053
  };
1015
- function deriveSalt(rawApiKey) {
1016
- const prk = extract2(sha256, utf8(rawApiKey), new Uint8Array(32));
1017
- return expand2(sha256, prk, AFFINITY_SALT_INFO, 32);
1018
- }
1019
- function canonicalJson(value) {
1020
- if (value === null) return "null";
1021
- const t = typeof value;
1022
- if (t === "boolean") return value ? "true" : "false";
1023
- if (t === "number") {
1024
- return String(value);
1054
+
1055
+ // src/resources/rerank.ts
1056
+ var ENCODER3 = new TextEncoder();
1057
+ var DECODER4 = new TextDecoder();
1058
+ function validateParams3(params) {
1059
+ if (!params.model || typeof params.model !== "string") {
1060
+ throw new Error("model must be a non-empty string");
1025
1061
  }
1026
- if (t === "string") return encodeString(value);
1027
- if (Array.isArray(value)) {
1028
- return "[" + value.map((v) => canonicalJson(v)).join(",") + "]";
1062
+ if (!params.query || typeof params.query !== "string") {
1063
+ throw new Error("query must be a non-empty string");
1029
1064
  }
1030
- if (t === "object") {
1031
- const obj = value;
1032
- const keys = Object.keys(obj).sort();
1033
- const items = keys.map((k) => encodeString(k) + ":" + canonicalJson(obj[k]));
1034
- return "{" + items.join(",") + "}";
1065
+ const { documents } = params;
1066
+ if (!Array.isArray(documents) || documents.length === 0 || !documents.every((d) => typeof d === "string" && d.length > 0)) {
1067
+ throw new Error("documents must be a non-empty array of non-empty strings");
1068
+ }
1069
+ if (params.top_n != null && params.top_n < 1) {
1070
+ throw new Error("top_n must be >= 1 when provided");
1035
1071
  }
1036
- return "null";
1037
1072
  }
1038
- function encodeString(s) {
1039
- let out = '"';
1040
- for (let i = 0; i < s.length; i++) {
1041
- const code = s.charCodeAt(i);
1042
- switch (code) {
1043
- case 34:
1044
- out += '\\"';
1045
- break;
1046
- case 92:
1047
- out += "\\\\";
1048
- break;
1049
- case 8:
1050
- out += "\\b";
1051
- break;
1052
- case 9:
1053
- out += "\\t";
1054
- break;
1055
- case 10:
1056
- out += "\\n";
1057
- break;
1058
- case 12:
1059
- out += "\\f";
1060
- break;
1061
- case 13:
1062
- out += "\\r";
1063
- break;
1064
- default:
1065
- if (code < 32 || code > 126) {
1066
- out += "\\u" + code.toString(16).padStart(4, "0");
1067
- } else {
1068
- out += s[i];
1069
- }
1073
+ var Rerank = class {
1074
+ constructor(client) {
1075
+ this.client = client;
1076
+ }
1077
+ /**
1078
+ * Rerank `documents` by relevance to `query` (Cohere-compatible).
1079
+ *
1080
+ * @example
1081
+ * ```ts
1082
+ * const result = await client.rerank.create({
1083
+ * model: "bge-reranker-v2-m3",
1084
+ * query: "What is the capital of France?",
1085
+ * documents: ["Paris is the capital of France.", "Berlin is in Germany."],
1086
+ * top_n: 1,
1087
+ * });
1088
+ * console.log(result.results[0].index, result.results[0].relevance_score);
1089
+ * ```
1090
+ */
1091
+ async create(params) {
1092
+ validateParams3(params);
1093
+ const body = {
1094
+ model: params.model,
1095
+ query: params.query,
1096
+ documents: params.documents,
1097
+ return_documents: params.return_documents ?? false
1098
+ };
1099
+ if (params.top_n != null) body.top_n = params.top_n;
1100
+ const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
1101
+ if (this.client.privateInferenceEnabled) {
1102
+ return this.createEncrypted(params.model, body, headers);
1070
1103
  }
1104
+ const { response } = await this.client._fetch(
1105
+ "/api/v1/rerank",
1106
+ { method: "POST", body, headers }
1107
+ );
1108
+ return await response.json();
1071
1109
  }
1072
- return out + '"';
1073
- }
1074
- function flattenContent(content) {
1075
- if (typeof content === "string") return content;
1076
- return canonicalJson(content);
1077
- }
1078
- function affinityKey(rawApiKey, model, messages, saltOverride) {
1079
- const parts = ["model=" + model];
1080
- let sawUser = false;
1081
- for (const m of messages ?? []) {
1082
- const role = m.role ?? "";
1083
- parts.push(role + ":" + flattenContent(m.content));
1084
- if (role === "user") {
1085
- sawUser = true;
1086
- break;
1110
+ async createEncrypted(model, body, headers) {
1111
+ const engine = await this.client._privateEngine();
1112
+ const { topLevel, decryptor } = engine.seal({
1113
+ model,
1114
+ stream: false,
1115
+ taskType: "rerank",
1116
+ body: ENCODER3.encode(JSON.stringify(body))
1117
+ });
1118
+ const { response } = await this.client._fetch(
1119
+ "/api/v1/rerank",
1120
+ { method: "POST", body: topLevel, headers }
1121
+ );
1122
+ const wrapper = await response.json();
1123
+ if (!wrapper.pendra_encrypted) {
1124
+ throw unsealedReplyError();
1087
1125
  }
1126
+ const plain = decryptor.openResult(wrapper.pendra_encrypted);
1127
+ return JSON.parse(DECODER4.decode(plain));
1088
1128
  }
1089
- if (!sawUser) return null;
1090
- const salt = saltOverride != null ? saltOverride : deriveSalt(rawApiKey);
1091
- const mac = hmac(sha256, salt, utf8(parts.join("\0")));
1092
- return toHex(mac);
1093
- }
1129
+ };
1130
+
1131
+ // src/version.ts
1132
+ var VERSION = "0.14.0";
1133
+ var USER_AGENT = `pendra-node/${VERSION}`;
1094
1134
 
1095
1135
  // src/_privateInferenceEngine.ts
1096
1136
  var PrivateInferenceError = class extends Error {
@@ -1265,7 +1305,7 @@ var PrivateInferenceEngine = class {
1265
1305
  if (args.messages != null) {
1266
1306
  affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
1267
1307
  }
1268
- const { envelope, responsePriv } = sealRequest(this.orgPubs, args.body, {
1308
+ const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
1269
1309
  model: args.model,
1270
1310
  stream: args.stream,
1271
1311
  taskType: args.taskType,
@@ -1276,7 +1316,7 @@ var PrivateInferenceEngine = class {
1276
1316
  stream: args.stream,
1277
1317
  pendra_encrypted: envelope
1278
1318
  };
1279
- return { topLevel, decryptor: new ResponseDecryptor(responsePriv) };
1319
+ return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
1280
1320
  }
1281
1321
  get keyFetchUrl() {
1282
1322
  return `${this.baseUrl}/v1/private-inference/key`;
@@ -1428,11 +1468,8 @@ var Pendra = class {
1428
1468
  err instanceof Error ? err.message : "Failed to connect to the Pendra API"
1429
1469
  );
1430
1470
  }
1431
- if (!options.stream) {
1432
- clearTimeout(timeoutId);
1433
- }
1471
+ clearTimeout(timeoutId);
1434
1472
  if (!response.ok) {
1435
- clearTimeout(timeoutId);
1436
1473
  this.invalidateKeyCacheIfRekeyed(response);
1437
1474
  let message;
1438
1475
  try {