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