pendra 0.13.1 → 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.d.mts +9 -6
- package/dist/index.d.ts +9 -6
- package/dist/index.js +541 -532
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +541 -532
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -449,6 +449,362 @@ function releaseReader(reader, controller, finished) {
|
|
|
449
449
|
reader.releaseLock();
|
|
450
450
|
}
|
|
451
451
|
|
|
452
|
+
// src/_privateInference.ts
|
|
453
|
+
var import_chacha2 = require("@noble/ciphers/chacha.js");
|
|
454
|
+
var import_hkdf2 = require("@noble/hashes/hkdf.js");
|
|
455
|
+
|
|
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);
|
|
475
|
+
}
|
|
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;
|
|
490
|
+
}
|
|
491
|
+
return out;
|
|
492
|
+
}
|
|
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;
|
|
527
|
+
}
|
|
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];
|
|
533
|
+
}
|
|
534
|
+
return nonce;
|
|
535
|
+
}
|
|
536
|
+
seal(aad, pt) {
|
|
537
|
+
const ct = (0, import_chacha.chacha20poly1305)(this.key, this.computeNonce(), aad).encrypt(pt);
|
|
538
|
+
this.seq += 1;
|
|
539
|
+
return ct;
|
|
540
|
+
}
|
|
541
|
+
open(aad, ct) {
|
|
542
|
+
const pt = (0, import_chacha.chacha20poly1305)(this.key, this.computeNonce(), aad).decrypt(ct);
|
|
543
|
+
this.seq += 1;
|
|
544
|
+
return pt;
|
|
545
|
+
}
|
|
546
|
+
export(exporterContext, length) {
|
|
547
|
+
return labeledExpand(this.exporterSecret, bytes("sec"), exporterContext, length, SUITE_ID);
|
|
548
|
+
}
|
|
549
|
+
};
|
|
550
|
+
function keySchedule(sharedSecret, info) {
|
|
551
|
+
const empty = new Uint8Array(0);
|
|
552
|
+
const pskIdHash = labeledExtract(empty, bytes("psk_id_hash"), empty, SUITE_ID);
|
|
553
|
+
const infoHash = labeledExtract(empty, bytes("info_hash"), info, SUITE_ID);
|
|
554
|
+
const keyScheduleContext = concat(new Uint8Array([0]), pskIdHash, infoHash);
|
|
555
|
+
const secret = labeledExtract(sharedSecret, bytes("secret"), empty, SUITE_ID);
|
|
556
|
+
const key = labeledExpand(secret, bytes("key"), keyScheduleContext, NK, SUITE_ID);
|
|
557
|
+
const baseNonce = labeledExpand(secret, bytes("base_nonce"), keyScheduleContext, NN, SUITE_ID);
|
|
558
|
+
const exporterSecret = labeledExpand(secret, bytes("exp"), keyScheduleContext, NH, SUITE_ID);
|
|
559
|
+
return new Context(key, baseNonce, exporterSecret);
|
|
560
|
+
}
|
|
561
|
+
function setupBaseS(pkR, info, skE) {
|
|
562
|
+
const [sharedSecret, enc] = encap(pkR, skE);
|
|
563
|
+
return { enc, ctx: keySchedule(sharedSecret, info) };
|
|
564
|
+
}
|
|
565
|
+
function randomBytes(n) {
|
|
566
|
+
return (0, import_utils.randomBytes)(n);
|
|
567
|
+
}
|
|
568
|
+
function sha256Hex(data) {
|
|
569
|
+
return Array.from((0, import_sha2.sha256)(data)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
// src/_privateInference.ts
|
|
573
|
+
var ENVELOPE_VERSION = 2;
|
|
574
|
+
var TEXT_ENCODER2 = new TextEncoder();
|
|
575
|
+
var TEXT_DECODER = new TextDecoder();
|
|
576
|
+
var SUITE_INFO = TEXT_ENCODER2.encode("pendra-pi-v1");
|
|
577
|
+
var RESPONSE_EXPORT_CTX = TEXT_ENCODER2.encode("pendra-pi-v1:rdek");
|
|
578
|
+
var AFFINITY_SALT_INFO = TEXT_ENCODER2.encode("pendra-affinity-salt-v1");
|
|
579
|
+
function utf8(s) {
|
|
580
|
+
return TEXT_ENCODER2.encode(s);
|
|
581
|
+
}
|
|
582
|
+
function b64(b) {
|
|
583
|
+
if (typeof Buffer !== "undefined") {
|
|
584
|
+
return Buffer.from(b).toString("base64");
|
|
585
|
+
}
|
|
586
|
+
let binary = "";
|
|
587
|
+
for (let i = 0; i < b.length; i++) binary += String.fromCharCode(b[i]);
|
|
588
|
+
return btoa(binary);
|
|
589
|
+
}
|
|
590
|
+
function b64d(s) {
|
|
591
|
+
if (typeof Buffer !== "undefined") {
|
|
592
|
+
return new Uint8Array(Buffer.from(s, "base64"));
|
|
593
|
+
}
|
|
594
|
+
const binary = atob(s);
|
|
595
|
+
const out = new Uint8Array(binary.length);
|
|
596
|
+
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
597
|
+
return out;
|
|
598
|
+
}
|
|
599
|
+
function toHex(b) {
|
|
600
|
+
return Array.from(b).map((x) => x.toString(16).padStart(2, "0")).join("");
|
|
601
|
+
}
|
|
602
|
+
function fingerprint(pub) {
|
|
603
|
+
return sha256Hex(pub);
|
|
604
|
+
}
|
|
605
|
+
function buildAad(model, stream, taskType) {
|
|
606
|
+
const streamBit = stream ? utf8("1") : utf8("0");
|
|
607
|
+
const sep = new Uint8Array([0]);
|
|
608
|
+
const parts = [utf8("pendra-pi-v1"), utf8(model), streamBit, utf8(taskType), new Uint8Array(0)];
|
|
609
|
+
let total = 0;
|
|
610
|
+
for (let i = 0; i < parts.length; i++) {
|
|
611
|
+
if (i > 0) total += 1;
|
|
612
|
+
total += parts[i].length;
|
|
613
|
+
}
|
|
614
|
+
const out = new Uint8Array(total);
|
|
615
|
+
let off = 0;
|
|
616
|
+
for (let i = 0; i < parts.length; i++) {
|
|
617
|
+
if (i > 0) {
|
|
618
|
+
out.set(sep, off);
|
|
619
|
+
off += 1;
|
|
620
|
+
}
|
|
621
|
+
out.set(parts[i], off);
|
|
622
|
+
off += parts[i].length;
|
|
623
|
+
}
|
|
624
|
+
return out;
|
|
625
|
+
}
|
|
626
|
+
function seqNonce(seq) {
|
|
627
|
+
const nonce = new Uint8Array(12);
|
|
628
|
+
let n = BigInt(seq);
|
|
629
|
+
for (let i = 11; i >= 4; i--) {
|
|
630
|
+
nonce[i] = Number(n & 0xffn);
|
|
631
|
+
n >>= 8n;
|
|
632
|
+
}
|
|
633
|
+
return nonce;
|
|
634
|
+
}
|
|
635
|
+
function sealRequest(orgPubs, body, opts) {
|
|
636
|
+
const pubs = Array.isArray(orgPubs) ? orgPubs : [orgPubs];
|
|
637
|
+
if (pubs.length === 0) {
|
|
638
|
+
throw new Error("sealRequest: no org public keys to seal to");
|
|
639
|
+
}
|
|
640
|
+
const seen = /* @__PURE__ */ new Set();
|
|
641
|
+
const uniquePubs = [];
|
|
642
|
+
for (const p of pubs) {
|
|
643
|
+
const fp = fingerprint(p);
|
|
644
|
+
if (!seen.has(fp)) {
|
|
645
|
+
seen.add(fp);
|
|
646
|
+
uniquePubs.push(p);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
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
|
+
|
|
452
808
|
// src/_privateStreaming.ts
|
|
453
809
|
var DECODER = new TextDecoder();
|
|
454
810
|
var EncryptedStream = class {
|
|
@@ -477,17 +833,22 @@ var EncryptedStream = class {
|
|
|
477
833
|
this.done = true;
|
|
478
834
|
return;
|
|
479
835
|
}
|
|
480
|
-
let
|
|
836
|
+
let frame;
|
|
481
837
|
try {
|
|
482
|
-
|
|
838
|
+
frame = JSON.parse(data);
|
|
483
839
|
} catch {
|
|
484
840
|
throw new APIResponseValidationError("Stream frame was not valid JSON", {
|
|
485
841
|
body: data
|
|
486
842
|
});
|
|
487
843
|
}
|
|
844
|
+
const inner = frame?.pendra_encrypted;
|
|
488
845
|
if (!inner) {
|
|
489
|
-
|
|
490
|
-
|
|
846
|
+
if (isApiTimingChunk(frame)) {
|
|
847
|
+
yield parseStreamFrame(data);
|
|
848
|
+
continue;
|
|
849
|
+
}
|
|
850
|
+
parseStreamFrame(data);
|
|
851
|
+
throw unsealedReplyError();
|
|
491
852
|
}
|
|
492
853
|
const plain = this.decryptor.openChunk(inner);
|
|
493
854
|
const chunkJson = DECODER.decode(plain).trim();
|
|
@@ -577,7 +938,7 @@ var Completions = class {
|
|
|
577
938
|
});
|
|
578
939
|
}
|
|
579
940
|
if (!wrapper.pendra_encrypted) {
|
|
580
|
-
|
|
941
|
+
throw unsealedReplyError();
|
|
581
942
|
}
|
|
582
943
|
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
583
944
|
return parseDecryptedCompletion(DECODER2.decode(plain), response.status);
|
|
@@ -598,576 +959,224 @@ function validateParams(params) {
|
|
|
598
959
|
if (!params.model || typeof params.model !== "string") {
|
|
599
960
|
throw new Error("model must be a non-empty string");
|
|
600
961
|
}
|
|
601
|
-
const { input } = params;
|
|
602
|
-
if (typeof input === "string") {
|
|
603
|
-
if (input.length === 0) {
|
|
604
|
-
throw new Error("input must be a non-empty string or non-empty array of strings");
|
|
605
|
-
}
|
|
606
|
-
return;
|
|
607
|
-
}
|
|
608
|
-
if (Array.isArray(input)) {
|
|
609
|
-
if (input.length === 0) {
|
|
610
|
-
throw new Error("input must be a non-empty string or non-empty array of strings");
|
|
611
|
-
}
|
|
612
|
-
if (!input.every((s) => typeof s === "string" && s.length > 0)) {
|
|
613
|
-
throw new Error("input array entries must all be non-empty strings");
|
|
614
|
-
}
|
|
615
|
-
return;
|
|
616
|
-
}
|
|
617
|
-
throw new Error("input must be a string or an array of strings");
|
|
618
|
-
}
|
|
619
|
-
var Embeddings = class {
|
|
620
|
-
constructor(client) {
|
|
621
|
-
this.client = client;
|
|
622
|
-
}
|
|
623
|
-
/**
|
|
624
|
-
* Create embeddings for the given input.
|
|
625
|
-
*
|
|
626
|
-
* @example
|
|
627
|
-
* ```ts
|
|
628
|
-
* const result = await client.embeddings.create({
|
|
629
|
-
* model: "nomic-embed-text:latest",
|
|
630
|
-
* input: "Hello world",
|
|
631
|
-
* });
|
|
632
|
-
* console.log(result.data[0].embedding);
|
|
633
|
-
* ```
|
|
634
|
-
*/
|
|
635
|
-
async create(params) {
|
|
636
|
-
validateParams(params);
|
|
637
|
-
const body = {
|
|
638
|
-
model: params.model,
|
|
639
|
-
input: params.input
|
|
640
|
-
};
|
|
641
|
-
if (params.encoding_format != null) body.encoding_format = params.encoding_format;
|
|
642
|
-
if (params.dimensions != null) body.dimensions = params.dimensions;
|
|
643
|
-
if (params.user != null) body.user = params.user;
|
|
644
|
-
const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
|
|
645
|
-
if (this.client.privateInferenceEnabled) {
|
|
646
|
-
return this.createEncrypted(params.model, body, headers);
|
|
647
|
-
}
|
|
648
|
-
const { response } = await this.client._fetch(
|
|
649
|
-
"/api/v1/embeddings",
|
|
650
|
-
{ method: "POST", body, headers }
|
|
651
|
-
);
|
|
652
|
-
return await response.json();
|
|
653
|
-
}
|
|
654
|
-
async createEncrypted(model, body, headers) {
|
|
655
|
-
const engine = await this.client._privateEngine();
|
|
656
|
-
const { topLevel, decryptor } = engine.seal({
|
|
657
|
-
model,
|
|
658
|
-
stream: false,
|
|
659
|
-
taskType: "embeddings",
|
|
660
|
-
body: ENCODER2.encode(JSON.stringify(body))
|
|
661
|
-
});
|
|
662
|
-
const { response } = await this.client._fetch(
|
|
663
|
-
"/api/v1/embeddings",
|
|
664
|
-
{ method: "POST", body: topLevel, headers }
|
|
665
|
-
);
|
|
666
|
-
const wrapper = await response.json();
|
|
667
|
-
if (!wrapper.pendra_encrypted) {
|
|
668
|
-
return wrapper;
|
|
669
|
-
}
|
|
670
|
-
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
671
|
-
return JSON.parse(DECODER3.decode(plain));
|
|
672
|
-
}
|
|
673
|
-
};
|
|
674
|
-
|
|
675
|
-
// src/resources/images/generations.ts
|
|
676
|
-
var SIZE_RE = /^\d+x\d+$/;
|
|
677
|
-
function validateParams2(params) {
|
|
678
|
-
if (!params.prompt || !params.prompt.trim()) {
|
|
679
|
-
throw new Error("prompt must be a non-empty string");
|
|
680
|
-
}
|
|
681
|
-
if (params.n != null && (params.n < 1 || params.n > 4)) {
|
|
682
|
-
throw new Error("n must be between 1 and 4");
|
|
683
|
-
}
|
|
684
|
-
if (params.size != null && !SIZE_RE.test(params.size)) {
|
|
685
|
-
throw new Error("size must be in the form WIDTHxHEIGHT (e.g. '1024x1024')");
|
|
686
|
-
}
|
|
687
|
-
}
|
|
688
|
-
var Generations = class {
|
|
689
|
-
constructor(client) {
|
|
690
|
-
this.client = client;
|
|
691
|
-
}
|
|
692
|
-
async create(params) {
|
|
693
|
-
if (this.client.privateInferenceEnabled) {
|
|
694
|
-
throw new Error("private inference is not yet supported for images/audio");
|
|
695
|
-
}
|
|
696
|
-
validateParams2(params);
|
|
697
|
-
const body = {
|
|
698
|
-
model: params.model,
|
|
699
|
-
prompt: params.prompt
|
|
700
|
-
};
|
|
701
|
-
if (params.n != null) body.n = params.n;
|
|
702
|
-
if (params.size != null) body.size = params.size;
|
|
703
|
-
if (params.response_format != null) body.response_format = params.response_format;
|
|
704
|
-
if (params.num_inference_steps != null) body.num_inference_steps = params.num_inference_steps;
|
|
705
|
-
if (params.seed != null) body.seed = params.seed;
|
|
706
|
-
if (params.negative_prompt != null) body.negative_prompt = params.negative_prompt;
|
|
707
|
-
const { response } = await this.client._fetch(
|
|
708
|
-
"/api/v1/images/generations",
|
|
709
|
-
{
|
|
710
|
-
method: "POST",
|
|
711
|
-
body,
|
|
712
|
-
headers: params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0
|
|
713
|
-
}
|
|
714
|
-
);
|
|
715
|
-
return await response.json();
|
|
716
|
-
}
|
|
717
|
-
};
|
|
718
|
-
|
|
719
|
-
// src/resources/images/index.ts
|
|
720
|
-
var Images = class {
|
|
721
|
-
constructor(client) {
|
|
722
|
-
this.generations = new Generations(client);
|
|
723
|
-
}
|
|
724
|
-
};
|
|
725
|
-
|
|
726
|
-
// src/resources/models.ts
|
|
727
|
-
var Models = class {
|
|
728
|
-
constructor(client) {
|
|
729
|
-
this.client = client;
|
|
730
|
-
}
|
|
731
|
-
async list() {
|
|
732
|
-
const { response } = await this.client._fetch("/api/v1/models", {
|
|
733
|
-
method: "GET"
|
|
734
|
-
});
|
|
735
|
-
const data = await response.json();
|
|
736
|
-
return data.data;
|
|
737
|
-
}
|
|
738
|
-
};
|
|
739
|
-
|
|
740
|
-
// src/resources/rerank.ts
|
|
741
|
-
var ENCODER3 = new TextEncoder();
|
|
742
|
-
var DECODER4 = new TextDecoder();
|
|
743
|
-
function validateParams3(params) {
|
|
744
|
-
if (!params.model || typeof params.model !== "string") {
|
|
745
|
-
throw new Error("model must be a non-empty string");
|
|
746
|
-
}
|
|
747
|
-
if (!params.query || typeof params.query !== "string") {
|
|
748
|
-
throw new Error("query must be a non-empty string");
|
|
749
|
-
}
|
|
750
|
-
const { documents } = params;
|
|
751
|
-
if (!Array.isArray(documents) || documents.length === 0 || !documents.every((d) => typeof d === "string" && d.length > 0)) {
|
|
752
|
-
throw new Error("documents must be a non-empty array of non-empty strings");
|
|
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;
|
|
753
968
|
}
|
|
754
|
-
if (
|
|
755
|
-
|
|
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;
|
|
756
977
|
}
|
|
978
|
+
throw new Error("input must be a string or an array of strings");
|
|
757
979
|
}
|
|
758
|
-
var
|
|
980
|
+
var Embeddings = class {
|
|
759
981
|
constructor(client) {
|
|
760
982
|
this.client = client;
|
|
761
983
|
}
|
|
762
984
|
/**
|
|
763
|
-
*
|
|
985
|
+
* Create embeddings for the given input.
|
|
764
986
|
*
|
|
765
987
|
* @example
|
|
766
988
|
* ```ts
|
|
767
|
-
* const result = await client.
|
|
768
|
-
* model: "
|
|
769
|
-
*
|
|
770
|
-
* documents: ["Paris is the capital of France.", "Berlin is in Germany."],
|
|
771
|
-
* top_n: 1,
|
|
989
|
+
* const result = await client.embeddings.create({
|
|
990
|
+
* model: "nomic-embed-text:latest",
|
|
991
|
+
* input: "Hello world",
|
|
772
992
|
* });
|
|
773
|
-
* console.log(result.
|
|
993
|
+
* console.log(result.data[0].embedding);
|
|
774
994
|
* ```
|
|
775
995
|
*/
|
|
776
996
|
async create(params) {
|
|
777
|
-
|
|
997
|
+
validateParams(params);
|
|
778
998
|
const body = {
|
|
779
999
|
model: params.model,
|
|
780
|
-
|
|
781
|
-
documents: params.documents,
|
|
782
|
-
return_documents: params.return_documents ?? false
|
|
1000
|
+
input: params.input
|
|
783
1001
|
};
|
|
784
|
-
if (params.
|
|
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;
|
|
785
1005
|
const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
|
|
786
1006
|
if (this.client.privateInferenceEnabled) {
|
|
787
1007
|
return this.createEncrypted(params.model, body, headers);
|
|
788
1008
|
}
|
|
789
1009
|
const { response } = await this.client._fetch(
|
|
790
|
-
"/api/v1/
|
|
1010
|
+
"/api/v1/embeddings",
|
|
791
1011
|
{ method: "POST", body, headers }
|
|
792
1012
|
);
|
|
793
|
-
return await response.json();
|
|
794
|
-
}
|
|
795
|
-
async createEncrypted(model, body, headers) {
|
|
796
|
-
const engine = await this.client._privateEngine();
|
|
797
|
-
const { topLevel, decryptor } = engine.seal({
|
|
798
|
-
model,
|
|
799
|
-
stream: false,
|
|
800
|
-
taskType: "rerank",
|
|
801
|
-
body: ENCODER3.encode(JSON.stringify(body))
|
|
802
|
-
});
|
|
803
|
-
const { response } = await this.client._fetch(
|
|
804
|
-
"/api/v1/rerank",
|
|
805
|
-
{ method: "POST", body: topLevel, headers }
|
|
806
|
-
);
|
|
807
|
-
const wrapper = await response.json();
|
|
808
|
-
if (!wrapper.pendra_encrypted) {
|
|
809
|
-
return wrapper;
|
|
810
|
-
}
|
|
811
|
-
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
812
|
-
return JSON.parse(DECODER4.decode(plain));
|
|
813
|
-
}
|
|
814
|
-
};
|
|
815
|
-
|
|
816
|
-
// src/version.ts
|
|
817
|
-
var VERSION = "0.13.1";
|
|
818
|
-
var USER_AGENT = `pendra-node/${VERSION}`;
|
|
819
|
-
|
|
820
|
-
// src/_hpke.ts
|
|
821
|
-
var import_ed25519 = require("@noble/curves/ed25519.js");
|
|
822
|
-
var import_chacha = require("@noble/ciphers/chacha.js");
|
|
823
|
-
var import_sha2 = require("@noble/hashes/sha2.js");
|
|
824
|
-
var import_hmac = require("@noble/hashes/hmac.js");
|
|
825
|
-
var import_hkdf = require("@noble/hashes/hkdf.js");
|
|
826
|
-
var import_utils = require("@noble/hashes/utils.js");
|
|
827
|
-
var KEM_ID = 32;
|
|
828
|
-
var KDF_ID = 1;
|
|
829
|
-
var AEAD_ID = 3;
|
|
830
|
-
var NH = 32;
|
|
831
|
-
var NK = 32;
|
|
832
|
-
var NN = 12;
|
|
833
|
-
var NSECRET = 32;
|
|
834
|
-
function i2osp(n, len) {
|
|
835
|
-
const out = new Uint8Array(len);
|
|
836
|
-
for (let i = len - 1; i >= 0; i--) {
|
|
837
|
-
out[i] = n & 255;
|
|
838
|
-
n = Math.floor(n / 256);
|
|
839
|
-
}
|
|
840
|
-
return out;
|
|
841
|
-
}
|
|
842
|
-
var TEXT_ENCODER = new TextEncoder();
|
|
843
|
-
function bytes(s) {
|
|
844
|
-
return TEXT_ENCODER.encode(s);
|
|
845
|
-
}
|
|
846
|
-
function concat(...parts) {
|
|
847
|
-
let total = 0;
|
|
848
|
-
for (const p of parts) total += p.length;
|
|
849
|
-
const out = new Uint8Array(total);
|
|
850
|
-
let off = 0;
|
|
851
|
-
for (const p of parts) {
|
|
852
|
-
out.set(p, off);
|
|
853
|
-
off += p.length;
|
|
854
|
-
}
|
|
855
|
-
return out;
|
|
856
|
-
}
|
|
857
|
-
var SUITE_ID = concat(bytes("HPKE"), i2osp(KEM_ID, 2), i2osp(KDF_ID, 2), i2osp(AEAD_ID, 2));
|
|
858
|
-
var KEM_SUITE_ID = concat(bytes("KEM"), i2osp(KEM_ID, 2));
|
|
859
|
-
var HPKE_VERSION = bytes("HPKE-v1");
|
|
860
|
-
function hkdfExtract(salt, ikm) {
|
|
861
|
-
const effectiveSalt = salt.length === 0 ? new Uint8Array(NH) : salt;
|
|
862
|
-
return (0, import_hkdf.extract)(import_sha2.sha256, ikm, effectiveSalt);
|
|
863
|
-
}
|
|
864
|
-
function hkdfExpand(prk, info, length) {
|
|
865
|
-
return (0, import_hkdf.expand)(import_sha2.sha256, prk, info, length);
|
|
866
|
-
}
|
|
867
|
-
function labeledExtract(salt, label, ikm, suiteId) {
|
|
868
|
-
return hkdfExtract(salt, concat(HPKE_VERSION, suiteId, label, ikm));
|
|
869
|
-
}
|
|
870
|
-
function labeledExpand(prk, label, info, length, suiteId) {
|
|
871
|
-
const labeledInfo = concat(i2osp(length, 2), HPKE_VERSION, suiteId, label, info);
|
|
872
|
-
return hkdfExpand(prk, labeledInfo, length);
|
|
873
|
-
}
|
|
874
|
-
function extractAndExpand(dh, kemContext) {
|
|
875
|
-
const eaePrk = labeledExtract(new Uint8Array(0), bytes("eae_prk"), dh, KEM_SUITE_ID);
|
|
876
|
-
return labeledExpand(eaePrk, bytes("shared_secret"), kemContext, NSECRET, KEM_SUITE_ID);
|
|
877
|
-
}
|
|
878
|
-
function encap(pkR, skE) {
|
|
879
|
-
const skEObj = skE ?? import_ed25519.x25519.utils.randomSecretKey();
|
|
880
|
-
const enc = import_ed25519.x25519.getPublicKey(skEObj);
|
|
881
|
-
const dh = import_ed25519.x25519.getSharedSecret(skEObj, pkR);
|
|
882
|
-
const kemContext = concat(enc, pkR);
|
|
883
|
-
return [extractAndExpand(dh, kemContext), enc];
|
|
884
|
-
}
|
|
885
|
-
function decap(enc, skR) {
|
|
886
|
-
const dh = import_ed25519.x25519.getSharedSecret(skR, enc);
|
|
887
|
-
const pkRm = import_ed25519.x25519.getPublicKey(skR);
|
|
888
|
-
const kemContext = concat(enc, pkRm);
|
|
889
|
-
return extractAndExpand(dh, kemContext);
|
|
890
|
-
}
|
|
891
|
-
var Context = class {
|
|
892
|
-
constructor(key, baseNonce, exporterSecret) {
|
|
893
|
-
this.seq = 0;
|
|
894
|
-
this.key = key;
|
|
895
|
-
this.baseNonce = baseNonce;
|
|
896
|
-
this.exporterSecret = exporterSecret;
|
|
897
|
-
}
|
|
898
|
-
computeNonce() {
|
|
899
|
-
const seqBytes = i2osp(this.seq, NN);
|
|
900
|
-
const nonce = new Uint8Array(NN);
|
|
901
|
-
for (let i = 0; i < NN; i++) {
|
|
902
|
-
nonce[i] = this.baseNonce[i] ^ seqBytes[i];
|
|
903
|
-
}
|
|
904
|
-
return nonce;
|
|
905
|
-
}
|
|
906
|
-
seal(aad, pt) {
|
|
907
|
-
const ct = (0, import_chacha.chacha20poly1305)(this.key, this.computeNonce(), aad).encrypt(pt);
|
|
908
|
-
this.seq += 1;
|
|
909
|
-
return ct;
|
|
910
|
-
}
|
|
911
|
-
open(aad, ct) {
|
|
912
|
-
const pt = (0, import_chacha.chacha20poly1305)(this.key, this.computeNonce(), aad).decrypt(ct);
|
|
913
|
-
this.seq += 1;
|
|
914
|
-
return pt;
|
|
915
|
-
}
|
|
916
|
-
export(exporterContext, length) {
|
|
917
|
-
return labeledExpand(this.exporterSecret, bytes("sec"), exporterContext, length, SUITE_ID);
|
|
918
|
-
}
|
|
919
|
-
};
|
|
920
|
-
function keySchedule(sharedSecret, info) {
|
|
921
|
-
const empty = new Uint8Array(0);
|
|
922
|
-
const pskIdHash = labeledExtract(empty, bytes("psk_id_hash"), empty, SUITE_ID);
|
|
923
|
-
const infoHash = labeledExtract(empty, bytes("info_hash"), info, SUITE_ID);
|
|
924
|
-
const keyScheduleContext = concat(new Uint8Array([0]), pskIdHash, infoHash);
|
|
925
|
-
const secret = labeledExtract(sharedSecret, bytes("secret"), empty, SUITE_ID);
|
|
926
|
-
const key = labeledExpand(secret, bytes("key"), keyScheduleContext, NK, SUITE_ID);
|
|
927
|
-
const baseNonce = labeledExpand(secret, bytes("base_nonce"), keyScheduleContext, NN, SUITE_ID);
|
|
928
|
-
const exporterSecret = labeledExpand(secret, bytes("exp"), keyScheduleContext, NH, SUITE_ID);
|
|
929
|
-
return new Context(key, baseNonce, exporterSecret);
|
|
930
|
-
}
|
|
931
|
-
function setupBaseS(pkR, info, skE) {
|
|
932
|
-
const [sharedSecret, enc] = encap(pkR, skE);
|
|
933
|
-
return { enc, ctx: keySchedule(sharedSecret, info) };
|
|
934
|
-
}
|
|
935
|
-
function setupBaseR(skR, enc, info) {
|
|
936
|
-
const sharedSecret = decap(enc, skR);
|
|
937
|
-
return keySchedule(sharedSecret, info);
|
|
938
|
-
}
|
|
939
|
-
function generateX25519Keypair() {
|
|
940
|
-
const priv = import_ed25519.x25519.utils.randomSecretKey();
|
|
941
|
-
return { priv, pub: import_ed25519.x25519.getPublicKey(priv) };
|
|
942
|
-
}
|
|
943
|
-
function randomBytes(n) {
|
|
944
|
-
return (0, import_utils.randomBytes)(n);
|
|
945
|
-
}
|
|
946
|
-
function sha256Hex(data) {
|
|
947
|
-
return Array.from((0, import_sha2.sha256)(data)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
948
|
-
}
|
|
949
|
-
|
|
950
|
-
// src/_privateInference.ts
|
|
951
|
-
var import_chacha2 = require("@noble/ciphers/chacha.js");
|
|
952
|
-
var import_hkdf2 = require("@noble/hashes/hkdf.js");
|
|
953
|
-
var ENVELOPE_VERSION = 1;
|
|
954
|
-
var TEXT_ENCODER2 = new TextEncoder();
|
|
955
|
-
var TEXT_DECODER = new TextDecoder();
|
|
956
|
-
var SUITE_INFO = TEXT_ENCODER2.encode("pendra-pi-v1");
|
|
957
|
-
var RESPONSE_INFO = TEXT_ENCODER2.encode("pendra-pi-v1:response");
|
|
958
|
-
var RESPONSE_EXPORT_CTX = TEXT_ENCODER2.encode("pendra-pi-v1:rdek");
|
|
959
|
-
var AFFINITY_SALT_INFO = TEXT_ENCODER2.encode("pendra-affinity-salt-v1");
|
|
960
|
-
function utf8(s) {
|
|
961
|
-
return TEXT_ENCODER2.encode(s);
|
|
962
|
-
}
|
|
963
|
-
function b64(b) {
|
|
964
|
-
if (typeof Buffer !== "undefined") {
|
|
965
|
-
return Buffer.from(b).toString("base64");
|
|
966
|
-
}
|
|
967
|
-
let binary = "";
|
|
968
|
-
for (let i = 0; i < b.length; i++) binary += String.fromCharCode(b[i]);
|
|
969
|
-
return btoa(binary);
|
|
970
|
-
}
|
|
971
|
-
function b64d(s) {
|
|
972
|
-
if (typeof Buffer !== "undefined") {
|
|
973
|
-
return new Uint8Array(Buffer.from(s, "base64"));
|
|
974
|
-
}
|
|
975
|
-
const binary = atob(s);
|
|
976
|
-
const out = new Uint8Array(binary.length);
|
|
977
|
-
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
978
|
-
return out;
|
|
979
|
-
}
|
|
980
|
-
function toHex(b) {
|
|
981
|
-
return Array.from(b).map((x) => x.toString(16).padStart(2, "0")).join("");
|
|
982
|
-
}
|
|
983
|
-
function fingerprint(pub) {
|
|
984
|
-
return sha256Hex(pub);
|
|
985
|
-
}
|
|
986
|
-
function buildAad(model, stream, taskType, responsePkB64) {
|
|
987
|
-
const streamBit = stream ? utf8("1") : utf8("0");
|
|
988
|
-
const sep = new Uint8Array([0]);
|
|
989
|
-
const parts = [utf8("pendra-pi-v1"), utf8(model), streamBit, utf8(taskType), utf8(responsePkB64)];
|
|
990
|
-
let total = 0;
|
|
991
|
-
for (let i = 0; i < parts.length; i++) {
|
|
992
|
-
if (i > 0) total += 1;
|
|
993
|
-
total += parts[i].length;
|
|
994
|
-
}
|
|
995
|
-
const out = new Uint8Array(total);
|
|
996
|
-
let off = 0;
|
|
997
|
-
for (let i = 0; i < parts.length; i++) {
|
|
998
|
-
if (i > 0) {
|
|
999
|
-
out.set(sep, off);
|
|
1000
|
-
off += 1;
|
|
1001
|
-
}
|
|
1002
|
-
out.set(parts[i], off);
|
|
1003
|
-
off += parts[i].length;
|
|
1004
|
-
}
|
|
1005
|
-
return out;
|
|
1006
|
-
}
|
|
1007
|
-
function seqNonce(seq) {
|
|
1008
|
-
const nonce = new Uint8Array(12);
|
|
1009
|
-
let n = BigInt(seq);
|
|
1010
|
-
for (let i = 11; i >= 4; i--) {
|
|
1011
|
-
nonce[i] = Number(n & 0xffn);
|
|
1012
|
-
n >>= 8n;
|
|
1013
|
-
}
|
|
1014
|
-
return nonce;
|
|
1015
|
-
}
|
|
1016
|
-
function sealRequest(orgPubs, body, opts) {
|
|
1017
|
-
const pubs = Array.isArray(orgPubs) ? orgPubs : [orgPubs];
|
|
1018
|
-
if (pubs.length === 0) {
|
|
1019
|
-
throw new Error("sealRequest: no org public keys to seal to");
|
|
1013
|
+
return await response.json();
|
|
1020
1014
|
}
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
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();
|
|
1028
1030
|
}
|
|
1031
|
+
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
1032
|
+
return JSON.parse(DECODER3.decode(plain));
|
|
1029
1033
|
}
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
for (const pub of uniquePubs) {
|
|
1038
|
-
const { enc, ctx: sealer } = setupBaseS(pub, SUITE_INFO);
|
|
1039
|
-
const sealedDek = sealer.seal(new Uint8Array(0), dek);
|
|
1040
|
-
recipients.push({ kid: fingerprint(pub), enc: b64(enc), sealed_dek: b64(sealedDek) });
|
|
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");
|
|
1041
1041
|
}
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
recipients,
|
|
1045
|
-
nonce: b64(nonce),
|
|
1046
|
-
ciphertext: b64(ciphertext),
|
|
1047
|
-
response_pk: respPkB64
|
|
1048
|
-
};
|
|
1049
|
-
if (opts.affinityKey != null) {
|
|
1050
|
-
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");
|
|
1051
1044
|
}
|
|
1052
|
-
if (
|
|
1053
|
-
|
|
1054
|
-
envelope.binary_nonce = b64(binaryNonce);
|
|
1055
|
-
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')");
|
|
1056
1047
|
}
|
|
1057
|
-
return { envelope, responsePriv: respPriv };
|
|
1058
1048
|
}
|
|
1059
|
-
var
|
|
1060
|
-
constructor(
|
|
1061
|
-
this.
|
|
1062
|
-
this.nextSeq = 0;
|
|
1063
|
-
this.respPriv = responsePrivateKey;
|
|
1049
|
+
var Generations = class {
|
|
1050
|
+
constructor(client) {
|
|
1051
|
+
this.client = client;
|
|
1064
1052
|
}
|
|
1065
|
-
|
|
1066
|
-
if (this.
|
|
1067
|
-
|
|
1068
|
-
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");
|
|
1069
1056
|
}
|
|
1070
|
-
|
|
1071
|
-
|
|
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();
|
|
1072
1077
|
}
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1078
|
+
};
|
|
1079
|
+
|
|
1080
|
+
// src/resources/images/index.ts
|
|
1081
|
+
var Images = class {
|
|
1082
|
+
constructor(client) {
|
|
1083
|
+
this.generations = new Generations(client);
|
|
1077
1084
|
}
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
this.
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
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;
|
|
1090
1098
|
}
|
|
1091
1099
|
};
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
function
|
|
1097
|
-
if (
|
|
1098
|
-
|
|
1099
|
-
if (t === "boolean") return value ? "true" : "false";
|
|
1100
|
-
if (t === "number") {
|
|
1101
|
-
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");
|
|
1102
1107
|
}
|
|
1103
|
-
if (
|
|
1104
|
-
|
|
1105
|
-
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");
|
|
1106
1110
|
}
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
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");
|
|
1112
1117
|
}
|
|
1113
|
-
return "null";
|
|
1114
1118
|
}
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
out += s[i];
|
|
1146
|
-
}
|
|
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);
|
|
1147
1149
|
}
|
|
1150
|
+
const { response } = await this.client._fetch(
|
|
1151
|
+
"/api/v1/rerank",
|
|
1152
|
+
{ method: "POST", body, headers }
|
|
1153
|
+
);
|
|
1154
|
+
return await response.json();
|
|
1148
1155
|
}
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
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();
|
|
1164
1171
|
}
|
|
1172
|
+
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
1173
|
+
return JSON.parse(DECODER4.decode(plain));
|
|
1165
1174
|
}
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
}
|
|
1175
|
+
};
|
|
1176
|
+
|
|
1177
|
+
// src/version.ts
|
|
1178
|
+
var VERSION = "0.14.0";
|
|
1179
|
+
var USER_AGENT = `pendra-node/${VERSION}`;
|
|
1171
1180
|
|
|
1172
1181
|
// src/_privateInferenceEngine.ts
|
|
1173
1182
|
var PrivateInferenceError = class extends Error {
|
|
@@ -1342,7 +1351,7 @@ var PrivateInferenceEngine = class {
|
|
|
1342
1351
|
if (args.messages != null) {
|
|
1343
1352
|
affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
|
|
1344
1353
|
}
|
|
1345
|
-
const { envelope,
|
|
1354
|
+
const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
|
|
1346
1355
|
model: args.model,
|
|
1347
1356
|
stream: args.stream,
|
|
1348
1357
|
taskType: args.taskType,
|
|
@@ -1353,7 +1362,7 @@ var PrivateInferenceEngine = class {
|
|
|
1353
1362
|
stream: args.stream,
|
|
1354
1363
|
pendra_encrypted: envelope
|
|
1355
1364
|
};
|
|
1356
|
-
return { topLevel, decryptor: new ResponseDecryptor(
|
|
1365
|
+
return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
|
|
1357
1366
|
}
|
|
1358
1367
|
get keyFetchUrl() {
|
|
1359
1368
|
return `${this.baseUrl}/v1/private-inference/key`;
|