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