pendra 0.16.0 → 0.17.1
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/README.md +61 -0
- package/dist/index.d.mts +180 -62
- package/dist/index.d.ts +180 -62
- package/dist/index.js +491 -263
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +491 -263
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -361,12 +361,23 @@ function sealRequest(orgPubs, body, opts) {
|
|
|
361
361
|
}
|
|
362
362
|
return { envelope, responseKeys };
|
|
363
363
|
}
|
|
364
|
-
var
|
|
365
|
-
|
|
364
|
+
var API_TRAILER_CHUNK_KEYS = /* @__PURE__ */ new Set(["id", "object", "created", "model", "choices", "pendra"]);
|
|
365
|
+
var API_TRAILER_PENDRA_KEYS = /* @__PURE__ */ new Set(["timing", "worker", "request_id"]);
|
|
366
|
+
function isApiTrailerChunk(frame) {
|
|
366
367
|
if (frame === null || typeof frame !== "object" || Array.isArray(frame)) return false;
|
|
367
368
|
const obj = frame;
|
|
368
369
|
const pendra = obj.pendra;
|
|
369
|
-
|
|
370
|
+
if (!Object.keys(obj).every((k) => API_TRAILER_CHUNK_KEYS.has(k)) || !Array.isArray(obj.choices) || obj.choices.length !== 0 || pendra === null || typeof pendra !== "object" || Array.isArray(pendra)) {
|
|
371
|
+
return false;
|
|
372
|
+
}
|
|
373
|
+
const block = pendra;
|
|
374
|
+
const keys = Object.keys(block);
|
|
375
|
+
if (keys.length === 0 || !keys.every((k) => API_TRAILER_PENDRA_KEYS.has(k))) return false;
|
|
376
|
+
if ("worker" in block && (block.worker === null || typeof block.worker !== "object" || Array.isArray(block.worker))) {
|
|
377
|
+
return false;
|
|
378
|
+
}
|
|
379
|
+
if ("request_id" in block && typeof block.request_id !== "string") return false;
|
|
380
|
+
return true;
|
|
370
381
|
}
|
|
371
382
|
function unsealedReplyError() {
|
|
372
383
|
return new Error(
|
|
@@ -504,6 +515,7 @@ function affinityKey(rawApiKey, model, messages, saltOverride) {
|
|
|
504
515
|
const mac = hmac(sha256, salt, utf8(parts.join("\0")));
|
|
505
516
|
return toHex(mac);
|
|
506
517
|
}
|
|
518
|
+
var _internal = { b64, b64d, utf8, TEXT_DECODER };
|
|
507
519
|
|
|
508
520
|
// src/_parsing.ts
|
|
509
521
|
function asString(v) {
|
|
@@ -566,8 +578,14 @@ async function parseCompletion(response) {
|
|
|
566
578
|
body
|
|
567
579
|
});
|
|
568
580
|
}
|
|
581
|
+
throwIfInBandError(parsed, "The server reported an error");
|
|
569
582
|
return completionFrom(parsed, body, response.status);
|
|
570
583
|
}
|
|
584
|
+
async function readJsonReply(response) {
|
|
585
|
+
const parsed = await response.json();
|
|
586
|
+
throwIfInBandError(parsed, "The server reported an error");
|
|
587
|
+
return parsed;
|
|
588
|
+
}
|
|
571
589
|
function parseDecryptedCompletion(json, status) {
|
|
572
590
|
let parsed;
|
|
573
591
|
try {
|
|
@@ -599,9 +617,10 @@ async function readSealedReply(response) {
|
|
|
599
617
|
});
|
|
600
618
|
}
|
|
601
619
|
throwIfInBandError(parsed, "The server reported an error");
|
|
602
|
-
const
|
|
620
|
+
const wrapper = typeof parsed === "object" && parsed !== null ? parsed : void 0;
|
|
621
|
+
const inner = wrapper?.pendra_encrypted;
|
|
603
622
|
if (!inner) throw unsealedReplyError();
|
|
604
|
-
return inner;
|
|
623
|
+
return { inner, placement: wrapper.pendra };
|
|
605
624
|
}
|
|
606
625
|
function parseDecryptedJson(json, status) {
|
|
607
626
|
try {
|
|
@@ -612,7 +631,393 @@ function parseDecryptedJson(json, status) {
|
|
|
612
631
|
body: json
|
|
613
632
|
});
|
|
614
633
|
}
|
|
615
|
-
}
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
// src/_placement.ts
|
|
637
|
+
var UTF8_EXT_PREFIX = "utf-8''";
|
|
638
|
+
function isPlainObject(v) {
|
|
639
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
640
|
+
}
|
|
641
|
+
function parseWorker(v) {
|
|
642
|
+
if (!isPlainObject(v) || typeof v.id !== "string" || !v.id) return void 0;
|
|
643
|
+
return {
|
|
644
|
+
id: v.id,
|
|
645
|
+
name: typeof v.name === "string" && v.name ? v.name : null,
|
|
646
|
+
version: typeof v.version === "string" && v.version ? v.version : null
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
function placementFromBlock(block) {
|
|
650
|
+
if (!isPlainObject(block)) return void 0;
|
|
651
|
+
const worker = parseWorker(block.worker);
|
|
652
|
+
if (!worker) return void 0;
|
|
653
|
+
const requestId = block.request_id;
|
|
654
|
+
return typeof requestId === "string" && requestId ? { worker, request_id: requestId } : { worker };
|
|
655
|
+
}
|
|
656
|
+
function decodeWorkerNameHeader(raw) {
|
|
657
|
+
if (raw.slice(0, UTF8_EXT_PREFIX.length).toLowerCase() !== UTF8_EXT_PREFIX) return raw;
|
|
658
|
+
try {
|
|
659
|
+
return decodeURIComponent(raw.slice(UTF8_EXT_PREFIX.length));
|
|
660
|
+
} catch {
|
|
661
|
+
return raw;
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
function header(headers, name) {
|
|
665
|
+
if (!headers || typeof headers.get !== "function") return void 0;
|
|
666
|
+
return headers.get(name) || void 0;
|
|
667
|
+
}
|
|
668
|
+
function placementFromHeaders(headers) {
|
|
669
|
+
const id = header(headers, "X-Worker-Id");
|
|
670
|
+
if (!id) return void 0;
|
|
671
|
+
const rawName = header(headers, "X-Worker-Name");
|
|
672
|
+
const requestId = header(headers, "X-Request-Id");
|
|
673
|
+
const worker = {
|
|
674
|
+
id,
|
|
675
|
+
name: rawName ? decodeWorkerNameHeader(rawName) : null,
|
|
676
|
+
version: null
|
|
677
|
+
};
|
|
678
|
+
return requestId ? { worker, request_id: requestId } : { worker };
|
|
679
|
+
}
|
|
680
|
+
function sanitise(block) {
|
|
681
|
+
if ("worker" in block && block.worker !== null) {
|
|
682
|
+
const worker = parseWorker(block.worker);
|
|
683
|
+
if (worker) block.worker = worker;
|
|
684
|
+
else delete block.worker;
|
|
685
|
+
}
|
|
686
|
+
if ("request_id" in block && block.request_id !== null && typeof block.request_id !== "string") {
|
|
687
|
+
delete block.request_id;
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
function withPlacement(result, headers, ...blocks) {
|
|
691
|
+
if (!isPlainObject(result)) return result;
|
|
692
|
+
const own = isPlainObject(result.pendra) ? result.pendra : void 0;
|
|
693
|
+
if (own) sanitise(own);
|
|
694
|
+
let placement;
|
|
695
|
+
for (const block of blocks) {
|
|
696
|
+
placement = placementFromBlock(block);
|
|
697
|
+
if (placement) break;
|
|
698
|
+
}
|
|
699
|
+
placement ?? (placement = placementFromHeaders(headers));
|
|
700
|
+
if (!placement) return result;
|
|
701
|
+
const merged = { ...own ?? {}, worker: placement.worker };
|
|
702
|
+
if (placement.request_id) merged.request_id = placement.request_id;
|
|
703
|
+
else delete merged.request_id;
|
|
704
|
+
result.pendra = merged;
|
|
705
|
+
return result;
|
|
706
|
+
}
|
|
707
|
+
function chunkPlacement(chunk) {
|
|
708
|
+
const block = chunk.pendra;
|
|
709
|
+
if (!isPlainObject(block)) return {};
|
|
710
|
+
sanitise(block);
|
|
711
|
+
const worker = block.worker;
|
|
712
|
+
const requestId = block.request_id;
|
|
713
|
+
return { worker: worker ?? void 0, requestId: requestId || void 0 };
|
|
714
|
+
}
|
|
715
|
+
var PLACEMENT_OPT_IN_HEADER = "X-Pendra-Placement";
|
|
716
|
+
|
|
717
|
+
// src/_privateInferenceEngine.ts
|
|
718
|
+
var PrivateInferenceError = class extends Error {
|
|
719
|
+
constructor(message) {
|
|
720
|
+
super(message);
|
|
721
|
+
this.name = "PrivateInferenceError";
|
|
722
|
+
}
|
|
723
|
+
};
|
|
724
|
+
var FINGERPRINT_RE = /^[0-9a-f]{64}$/;
|
|
725
|
+
function parsePinnedFingerprints(pin) {
|
|
726
|
+
if (typeof pin !== "string") {
|
|
727
|
+
throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);
|
|
728
|
+
}
|
|
729
|
+
const fps = pin.split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
|
|
730
|
+
if (fps.length === 0) {
|
|
731
|
+
throw new PrivateInferenceError(
|
|
732
|
+
"pinnedFingerprint was set but contains no fingerprint. Pass the 64-character fingerprint shown in the console, or leave it unset to use automatic trust."
|
|
733
|
+
);
|
|
734
|
+
}
|
|
735
|
+
const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();
|
|
736
|
+
if (bad.length > 0) {
|
|
737
|
+
throw new PrivateInferenceError(
|
|
738
|
+
`pinnedFingerprint "${bad[0]}" is not a valid fingerprint: expected 64 hexadecimal characters, as shown in the console.`
|
|
739
|
+
);
|
|
740
|
+
}
|
|
741
|
+
return new Set(fps);
|
|
742
|
+
}
|
|
743
|
+
function defaultTofuPath() {
|
|
744
|
+
const env = typeof process !== "undefined" ? process.env : void 0;
|
|
745
|
+
if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
|
|
746
|
+
const home = env?.HOME || env?.USERPROFILE || ".";
|
|
747
|
+
return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
|
|
748
|
+
}
|
|
749
|
+
function b64d2(s) {
|
|
750
|
+
if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
|
|
751
|
+
const binary = atob(s);
|
|
752
|
+
const out = new Uint8Array(binary.length);
|
|
753
|
+
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
754
|
+
return out;
|
|
755
|
+
}
|
|
756
|
+
var PrivateInferenceEngine = class {
|
|
757
|
+
constructor(opts) {
|
|
758
|
+
this.orgPubs = null;
|
|
759
|
+
this.baseUrl = opts.baseUrl.replace(/\/$/, "");
|
|
760
|
+
this.apiKey = opts.apiKey;
|
|
761
|
+
const pin = opts.pinnedFingerprint;
|
|
762
|
+
this.pinnedFingerprints = pin === null || pin === void 0 ? null : parsePinnedFingerprints(pin);
|
|
763
|
+
this.affinitySalt = opts.affinitySalt ?? null;
|
|
764
|
+
this.tofuPath = opts.tofuPath || defaultTofuPath();
|
|
765
|
+
}
|
|
766
|
+
// --- key resolution ---
|
|
767
|
+
cachedOrgPublicKeys() {
|
|
768
|
+
return this.orgPubs;
|
|
769
|
+
}
|
|
770
|
+
cachedOrgPublicKey() {
|
|
771
|
+
return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;
|
|
772
|
+
}
|
|
773
|
+
tofuIdentity() {
|
|
774
|
+
const digest = sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);
|
|
775
|
+
return `${this.baseUrl}|${digest}`;
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* Drop the cached key set so the next call re-fetches it.
|
|
779
|
+
*
|
|
780
|
+
* The cache is otherwise held for the whole process lifetime, which is
|
|
781
|
+
* correct while a fleet keeps one key but fatal when it re-keys: a
|
|
782
|
+
* long-running server would go on sealing to a fingerprint no worker holds
|
|
783
|
+
* and fail EVERY request until someone restarted it. The API signals a re-key
|
|
784
|
+
* with `X-Pendra-Error-Code: no_private_inference_worker`, and this is what
|
|
785
|
+
* lets the client recover on its own.
|
|
786
|
+
*
|
|
787
|
+
* Pinned clients are deliberately NOT re-fetched on that signal — a pin is an
|
|
788
|
+
* allowlist, so a fetch could only return fingerprints the pin already
|
|
789
|
+
* rejects. They surface the error instead, which is what pinning means.
|
|
790
|
+
*/
|
|
791
|
+
invalidateOrgKey() {
|
|
792
|
+
this.orgPubs = null;
|
|
793
|
+
}
|
|
794
|
+
/** Whether this client seals only to an explicit fingerprint allowlist. */
|
|
795
|
+
get isPinned() {
|
|
796
|
+
return this.pinnedFingerprints !== null;
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* Validate the key(s) returned by GET /v1/private-inference/key, apply the pin
|
|
800
|
+
* allowlist (or auto-trust TOFU), cache the accepted public keys, and return
|
|
801
|
+
* them (newest-seen first). The client seals to **all** of the returned keys
|
|
802
|
+
* so any worker holding any of them can serve the request. Throws
|
|
803
|
+
* PrivateInferenceError on absence, a malformed key, or (when pinned) an empty
|
|
804
|
+
* intersection with the pin set.
|
|
805
|
+
*/
|
|
806
|
+
async resolveOrgKey(fetchedKeys) {
|
|
807
|
+
if (this.orgPubs !== null) return this.orgPubs;
|
|
808
|
+
if (!fetchedKeys || fetchedKeys.length === 0) {
|
|
809
|
+
throw new PrivateInferenceError(
|
|
810
|
+
"No encryption key is registered for this organisation. Start a worker and it will be issued one automatically."
|
|
811
|
+
);
|
|
812
|
+
}
|
|
813
|
+
const pubs = [];
|
|
814
|
+
const fps = [];
|
|
815
|
+
for (const entry of fetchedKeys) {
|
|
816
|
+
let pub;
|
|
817
|
+
try {
|
|
818
|
+
pub = b64d2(entry.public_key);
|
|
819
|
+
} catch (e) {
|
|
820
|
+
throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
|
|
821
|
+
}
|
|
822
|
+
if (pub.length !== 32) {
|
|
823
|
+
throw new PrivateInferenceError(
|
|
824
|
+
`Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`
|
|
825
|
+
);
|
|
826
|
+
}
|
|
827
|
+
pubs.push(pub);
|
|
828
|
+
fps.push(fingerprint(pub));
|
|
829
|
+
}
|
|
830
|
+
let accepted;
|
|
831
|
+
if (this.pinnedFingerprints !== null) {
|
|
832
|
+
accepted = pubs.filter((_p, i) => this.pinnedFingerprints.has(fps[i]));
|
|
833
|
+
if (accepted.length === 0) {
|
|
834
|
+
const pinned = Array.from(this.pinnedFingerprints).sort().join(", ");
|
|
835
|
+
throw new PrivateInferenceError(
|
|
836
|
+
`None of the org's workload key fingerprints (${fps.join(", ")}) match your pinned fingerprint(s) (${pinned}). Refusing to seal (possible man-in-the-middle). If your fleet re-keyed \u2014 which happens when every worker goes offline at once \u2014 update the pin to a current fingerprint from the console.`
|
|
837
|
+
);
|
|
838
|
+
}
|
|
839
|
+
} else {
|
|
840
|
+
await this.tofuTrust(fps);
|
|
841
|
+
accepted = pubs;
|
|
842
|
+
}
|
|
843
|
+
this.orgPubs = accepted;
|
|
844
|
+
return accepted;
|
|
845
|
+
}
|
|
846
|
+
async tofuTrust(fps) {
|
|
847
|
+
const store = await this.loadTofu();
|
|
848
|
+
const identity = this.tofuIdentity();
|
|
849
|
+
const known = store[identity];
|
|
850
|
+
const trusted = /* @__PURE__ */ new Set();
|
|
851
|
+
if (typeof known === "string") {
|
|
852
|
+
trusted.add(known);
|
|
853
|
+
} else if (Array.isArray(known)) {
|
|
854
|
+
for (const f of known) if (typeof f === "string") trusted.add(f);
|
|
855
|
+
}
|
|
856
|
+
const before = trusted.size;
|
|
857
|
+
for (const f of fps) trusted.add(f);
|
|
858
|
+
if (trusted.size !== before || !Array.isArray(known)) {
|
|
859
|
+
store[identity] = Array.from(trusted).sort();
|
|
860
|
+
await this.saveTofu(store);
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
async loadTofu() {
|
|
864
|
+
try {
|
|
865
|
+
const fs = await import("fs");
|
|
866
|
+
const raw = fs.readFileSync(this.tofuPath, "utf-8");
|
|
867
|
+
const data = JSON.parse(raw);
|
|
868
|
+
return data && typeof data === "object" && !Array.isArray(data) ? data : {};
|
|
869
|
+
} catch {
|
|
870
|
+
return {};
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
async saveTofu(store) {
|
|
874
|
+
const fs = await import("fs");
|
|
875
|
+
const path = await import("path");
|
|
876
|
+
const directory = path.dirname(this.tofuPath) || ".";
|
|
877
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
878
|
+
const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);
|
|
879
|
+
try {
|
|
880
|
+
fs.writeFileSync(tmp, JSON.stringify(store), { mode: 384 });
|
|
881
|
+
try {
|
|
882
|
+
fs.chmodSync(tmp, 384);
|
|
883
|
+
} catch {
|
|
884
|
+
}
|
|
885
|
+
fs.renameSync(tmp, this.tofuPath);
|
|
886
|
+
} catch (e) {
|
|
887
|
+
try {
|
|
888
|
+
fs.unlinkSync(tmp);
|
|
889
|
+
} catch {
|
|
890
|
+
}
|
|
891
|
+
throw e;
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
// --- sealing ---
|
|
895
|
+
/**
|
|
896
|
+
* Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
|
|
897
|
+
* `messages` (chat only) drives the affinity token; pass undefined for non-chat.
|
|
898
|
+
* `binary` (audio only) is sealed under the same data key as the body.
|
|
899
|
+
*/
|
|
900
|
+
seal(args) {
|
|
901
|
+
if (this.orgPubs === null || this.orgPubs.length === 0) {
|
|
902
|
+
throw new PrivateInferenceError(
|
|
903
|
+
"private inference: org key not resolved yet (call resolveOrgKey first)"
|
|
904
|
+
);
|
|
905
|
+
}
|
|
906
|
+
let affinity = null;
|
|
907
|
+
if (args.messages != null) {
|
|
908
|
+
affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
|
|
909
|
+
}
|
|
910
|
+
const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
|
|
911
|
+
model: args.model,
|
|
912
|
+
stream: args.stream,
|
|
913
|
+
taskType: args.taskType,
|
|
914
|
+
affinityKey: affinity,
|
|
915
|
+
binary: args.binary ?? null
|
|
916
|
+
});
|
|
917
|
+
const topLevel = {
|
|
918
|
+
model: args.model,
|
|
919
|
+
stream: args.stream,
|
|
920
|
+
pendra_encrypted: envelope
|
|
921
|
+
};
|
|
922
|
+
return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
|
|
923
|
+
}
|
|
924
|
+
get keyFetchUrl() {
|
|
925
|
+
return `${this.baseUrl}/v1/private-inference/key`;
|
|
926
|
+
}
|
|
927
|
+
};
|
|
928
|
+
|
|
929
|
+
// src/resources/audio/speech.ts
|
|
930
|
+
var BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
931
|
+
function decodeAudio(value) {
|
|
932
|
+
if (typeof value !== "string") return void 0;
|
|
933
|
+
const s = value.replace(/\s+/g, "");
|
|
934
|
+
if (!s || !BASE64_RE.test(s) || s.replace(/=+$/, "").length % 4 === 1) return void 0;
|
|
935
|
+
if (s.includes("=") && s.length % 4 !== 0) return void 0;
|
|
936
|
+
let bytes2;
|
|
937
|
+
try {
|
|
938
|
+
bytes2 = _internal.b64d(s);
|
|
939
|
+
} catch {
|
|
940
|
+
return void 0;
|
|
941
|
+
}
|
|
942
|
+
return bytes2.length > 0 ? bytes2 : void 0;
|
|
943
|
+
}
|
|
944
|
+
function isRecord2(v) {
|
|
945
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
946
|
+
}
|
|
947
|
+
var Speech = class {
|
|
948
|
+
constructor(client) {
|
|
949
|
+
this.client = client;
|
|
950
|
+
}
|
|
951
|
+
/**
|
|
952
|
+
* Turn text into spoken audio (OpenAI-compatible).
|
|
953
|
+
*
|
|
954
|
+
* @example
|
|
955
|
+
* ```ts
|
|
956
|
+
* import { writeFileSync } from "node:fs";
|
|
957
|
+
*
|
|
958
|
+
* const speech = await client.audio.speech.create({
|
|
959
|
+
* model: "qwen3-tts",
|
|
960
|
+
* input: "Hello from Pendra.",
|
|
961
|
+
* });
|
|
962
|
+
* writeFileSync("speech.wav", speech.audio);
|
|
963
|
+
* ```
|
|
964
|
+
*/
|
|
965
|
+
async create(params) {
|
|
966
|
+
if (!params.model || typeof params.model !== "string") {
|
|
967
|
+
throw new Error("model must be a non-empty string");
|
|
968
|
+
}
|
|
969
|
+
if (typeof params.input !== "string" || !params.input.trim()) {
|
|
970
|
+
throw new Error("input must be a non-empty string");
|
|
971
|
+
}
|
|
972
|
+
if (this.client.privateInferenceEnabled) {
|
|
973
|
+
throw new PrivateInferenceError("Private inference does not support speech synthesis yet.");
|
|
974
|
+
}
|
|
975
|
+
const body = { model: params.model, input: params.input };
|
|
976
|
+
if (params.voice != null) body.voice = params.voice;
|
|
977
|
+
if (params.response_format != null) body.response_format = params.response_format;
|
|
978
|
+
const headers = { Accept: "application/json" };
|
|
979
|
+
if (params.worker_id) headers["X-Pendra-Worker-Id"] = params.worker_id;
|
|
980
|
+
const timeout = Math.max(this.client.timeout ?? 0, 3e5);
|
|
981
|
+
const { response } = await this.client._fetch("/api/v1/audio/speech", {
|
|
982
|
+
method: "POST",
|
|
983
|
+
body,
|
|
984
|
+
headers,
|
|
985
|
+
timeout
|
|
986
|
+
});
|
|
987
|
+
const text = await response.text();
|
|
988
|
+
let parsed;
|
|
989
|
+
try {
|
|
990
|
+
parsed = JSON.parse(text);
|
|
991
|
+
} catch {
|
|
992
|
+
throw new APIResponseValidationError("Response was not valid JSON", {
|
|
993
|
+
status: response.status,
|
|
994
|
+
body: text
|
|
995
|
+
});
|
|
996
|
+
}
|
|
997
|
+
throwIfInBandError(parsed, "The server reported an error");
|
|
998
|
+
if (!isRecord2(parsed)) {
|
|
999
|
+
throw new APIResponseValidationError("Response was not a speech result", {
|
|
1000
|
+
status: response.status,
|
|
1001
|
+
body: text
|
|
1002
|
+
});
|
|
1003
|
+
}
|
|
1004
|
+
const audio = decodeAudio(parsed.audio);
|
|
1005
|
+
if (!audio) {
|
|
1006
|
+
throw new APIResponseValidationError("Response did not contain decodable audio", {
|
|
1007
|
+
status: response.status,
|
|
1008
|
+
body: text
|
|
1009
|
+
});
|
|
1010
|
+
}
|
|
1011
|
+
const result = {
|
|
1012
|
+
audio,
|
|
1013
|
+
format: typeof parsed.format === "string" && parsed.format ? parsed.format : params.response_format ?? "wav",
|
|
1014
|
+
duration_ms: typeof parsed.duration_ms === "number" && Number.isFinite(parsed.duration_ms) ? parsed.duration_ms : null,
|
|
1015
|
+
arrayBuffer: async () => audio.slice().buffer
|
|
1016
|
+
};
|
|
1017
|
+
if (isRecord2(parsed.pendra)) result.pendra = parsed.pendra;
|
|
1018
|
+
return withPlacement(result, response.headers, result.pendra);
|
|
1019
|
+
}
|
|
1020
|
+
};
|
|
616
1021
|
|
|
617
1022
|
// src/resources/audio/transcriptions.ts
|
|
618
1023
|
var ENCODER = new TextEncoder();
|
|
@@ -713,9 +1118,10 @@ var Transcriptions = class {
|
|
|
713
1118
|
const format = params.response_format;
|
|
714
1119
|
if (format === "text" || format === "srt" || format === "vtt") {
|
|
715
1120
|
const text = await response.text();
|
|
716
|
-
return { text };
|
|
1121
|
+
return withPlacement({ text }, response.headers);
|
|
717
1122
|
}
|
|
718
|
-
|
|
1123
|
+
const result = await readJsonReply(response);
|
|
1124
|
+
return withPlacement(result, response.headers, result.pendra);
|
|
719
1125
|
}
|
|
720
1126
|
/**
|
|
721
1127
|
* Private-inference transcription. There is no multipart upload: the audio
|
|
@@ -750,9 +1156,11 @@ var Transcriptions = class {
|
|
|
750
1156
|
timeout
|
|
751
1157
|
}
|
|
752
1158
|
);
|
|
753
|
-
const
|
|
1159
|
+
const { inner, placement } = await readSealedReply(response);
|
|
1160
|
+
const raw = DECODER.decode(decryptor.openResult(inner));
|
|
754
1161
|
const parsed = parseDecryptedJson(raw, response.status);
|
|
755
|
-
|
|
1162
|
+
const place = (r) => withPlacement(r, response.headers, r.pendra, placement);
|
|
1163
|
+
if (typeof parsed === "string") return place({ text: parsed });
|
|
756
1164
|
if (typeof parsed === "object" && parsed !== null) {
|
|
757
1165
|
if (typeof parsed.text !== "string") {
|
|
758
1166
|
throw new APIResponseValidationError("Decrypted response was not a transcription", {
|
|
@@ -760,9 +1168,9 @@ var Transcriptions = class {
|
|
|
760
1168
|
body: raw
|
|
761
1169
|
});
|
|
762
1170
|
}
|
|
763
|
-
return parsed;
|
|
1171
|
+
return place(parsed);
|
|
764
1172
|
}
|
|
765
|
-
return { text: raw };
|
|
1173
|
+
return place({ text: raw });
|
|
766
1174
|
}
|
|
767
1175
|
};
|
|
768
1176
|
|
|
@@ -770,6 +1178,7 @@ var Transcriptions = class {
|
|
|
770
1178
|
var Audio = class {
|
|
771
1179
|
constructor(client) {
|
|
772
1180
|
this.transcriptions = new Transcriptions(client);
|
|
1181
|
+
this.speech = new Speech(client);
|
|
773
1182
|
}
|
|
774
1183
|
};
|
|
775
1184
|
|
|
@@ -846,6 +1255,7 @@ var Stream = class {
|
|
|
846
1255
|
this.decoder = new TextDecoder();
|
|
847
1256
|
this.sse = new SseDecoder();
|
|
848
1257
|
this.done = false;
|
|
1258
|
+
this.placement = new PlacementTracker();
|
|
849
1259
|
if (!response.body) {
|
|
850
1260
|
throw new Error("Response body is null \u2014 streaming not supported");
|
|
851
1261
|
}
|
|
@@ -866,7 +1276,7 @@ var Stream = class {
|
|
|
866
1276
|
this.done = true;
|
|
867
1277
|
return;
|
|
868
1278
|
}
|
|
869
|
-
yield parseStreamFrame(data);
|
|
1279
|
+
yield this.placement.observe(parseStreamFrame(data));
|
|
870
1280
|
}
|
|
871
1281
|
if (readerDone) {
|
|
872
1282
|
this.done = true;
|
|
@@ -877,11 +1287,39 @@ var Stream = class {
|
|
|
877
1287
|
releaseReader(this.reader, this.controller, this.done);
|
|
878
1288
|
}
|
|
879
1289
|
}
|
|
1290
|
+
/**
|
|
1291
|
+
* The worker that served this stream, or `null` until the chunk reporting it
|
|
1292
|
+
* — the trailer, just before `[DONE]` — has been iterated (and on an API too
|
|
1293
|
+
* old to report it). Same as that chunk's `pendra.worker`.
|
|
1294
|
+
*/
|
|
1295
|
+
get worker() {
|
|
1296
|
+
return this.placement.worker;
|
|
1297
|
+
}
|
|
1298
|
+
/**
|
|
1299
|
+
* Pendra's id for this request, reported alongside {@link Stream.worker};
|
|
1300
|
+
* `null` until then.
|
|
1301
|
+
*/
|
|
1302
|
+
get requestId() {
|
|
1303
|
+
return this.placement.requestId;
|
|
1304
|
+
}
|
|
880
1305
|
abort() {
|
|
881
1306
|
this.done = true;
|
|
882
1307
|
this.controller.abort();
|
|
883
1308
|
}
|
|
884
1309
|
};
|
|
1310
|
+
var PlacementTracker = class {
|
|
1311
|
+
constructor() {
|
|
1312
|
+
this.worker = null;
|
|
1313
|
+
this.requestId = null;
|
|
1314
|
+
}
|
|
1315
|
+
/** Record `chunk`'s placement, if it carries any, and hand it back. */
|
|
1316
|
+
observe(chunk) {
|
|
1317
|
+
const { worker, requestId } = chunkPlacement(chunk);
|
|
1318
|
+
if (worker) this.worker = worker;
|
|
1319
|
+
if (requestId) this.requestId = requestId;
|
|
1320
|
+
return chunk;
|
|
1321
|
+
}
|
|
1322
|
+
};
|
|
885
1323
|
async function readWithIdleTimeout(reader, idleTimeoutMs) {
|
|
886
1324
|
if (!idleTimeoutMs) return reader.read();
|
|
887
1325
|
let timer;
|
|
@@ -917,6 +1355,7 @@ var EncryptedStream = class {
|
|
|
917
1355
|
this.openedAny = false;
|
|
918
1356
|
this.declared = false;
|
|
919
1357
|
this.terminated = false;
|
|
1358
|
+
this.placement = new PlacementTracker();
|
|
920
1359
|
if (!response.body) {
|
|
921
1360
|
throw new Error("Response body is null \u2014 streaming not supported");
|
|
922
1361
|
}
|
|
@@ -958,9 +1397,9 @@ var EncryptedStream = class {
|
|
|
958
1397
|
}
|
|
959
1398
|
const inner = frame?.pendra_encrypted;
|
|
960
1399
|
if (!inner) {
|
|
961
|
-
if (
|
|
1400
|
+
if (isApiTrailerChunk(frame)) {
|
|
962
1401
|
this.checkEnded();
|
|
963
|
-
yield parseStreamFrame(data);
|
|
1402
|
+
yield this.placement.observe(parseStreamFrame(data));
|
|
964
1403
|
continue;
|
|
965
1404
|
}
|
|
966
1405
|
parseStreamFrame(data);
|
|
@@ -988,7 +1427,7 @@ var EncryptedStream = class {
|
|
|
988
1427
|
return;
|
|
989
1428
|
}
|
|
990
1429
|
if (!chunkJson) continue;
|
|
991
|
-
yield parseStreamFrame(chunkJson, "Decrypted stream frame");
|
|
1430
|
+
yield this.placement.observe(parseStreamFrame(chunkJson, "Decrypted stream frame"));
|
|
992
1431
|
}
|
|
993
1432
|
if (readerDone) {
|
|
994
1433
|
this.checkEnded();
|
|
@@ -1010,6 +1449,14 @@ var EncryptedStream = class {
|
|
|
1010
1449
|
throw truncatedStreamError();
|
|
1011
1450
|
}
|
|
1012
1451
|
}
|
|
1452
|
+
/** Same as `Stream.worker`: set once the trailer chunk has been iterated. */
|
|
1453
|
+
get worker() {
|
|
1454
|
+
return this.placement.worker;
|
|
1455
|
+
}
|
|
1456
|
+
/** Same as `Stream.requestId`. */
|
|
1457
|
+
get requestId() {
|
|
1458
|
+
return this.placement.requestId;
|
|
1459
|
+
}
|
|
1013
1460
|
abort() {
|
|
1014
1461
|
this.aborted = true;
|
|
1015
1462
|
this.done = true;
|
|
@@ -1030,7 +1477,9 @@ var Completions = class {
|
|
|
1030
1477
|
for (const [key, value] of Object.entries(rest)) {
|
|
1031
1478
|
if (value != null) body[key] = value;
|
|
1032
1479
|
}
|
|
1033
|
-
const headers =
|
|
1480
|
+
const headers = {};
|
|
1481
|
+
if (params.worker_id) headers["X-Pendra-Worker-Id"] = params.worker_id;
|
|
1482
|
+
if (params.stream) headers[PLACEMENT_OPT_IN_HEADER] = "1";
|
|
1034
1483
|
if (this.client.privateInferenceEnabled) {
|
|
1035
1484
|
return this.createEncrypted(params, body, headers);
|
|
1036
1485
|
}
|
|
@@ -1045,7 +1494,8 @@ var Completions = class {
|
|
|
1045
1494
|
"/api/v1/chat/completions",
|
|
1046
1495
|
{ method: "POST", body, headers }
|
|
1047
1496
|
);
|
|
1048
|
-
|
|
1497
|
+
const completion = await parseCompletion(response);
|
|
1498
|
+
return withPlacement(completion, response.headers, completion.pendra);
|
|
1049
1499
|
}
|
|
1050
1500
|
async createEncrypted(params, body, headers) {
|
|
1051
1501
|
const engine = await this.client._privateEngine();
|
|
@@ -1071,21 +1521,10 @@ var Completions = class {
|
|
|
1071
1521
|
"/api/v1/chat/completions",
|
|
1072
1522
|
{ method: "POST", body: topLevel, headers }
|
|
1073
1523
|
);
|
|
1074
|
-
const
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
} catch {
|
|
1079
|
-
throw new APIResponseValidationError("Response was not valid JSON", {
|
|
1080
|
-
status: response.status,
|
|
1081
|
-
body: raw
|
|
1082
|
-
});
|
|
1083
|
-
}
|
|
1084
|
-
if (!wrapper.pendra_encrypted) {
|
|
1085
|
-
throw unsealedReplyError();
|
|
1086
|
-
}
|
|
1087
|
-
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
1088
|
-
return parseDecryptedCompletion(DECODER3.decode(plain), response.status);
|
|
1524
|
+
const { inner, placement } = await readSealedReply(response);
|
|
1525
|
+
const plain = decryptor.openResult(inner);
|
|
1526
|
+
const completion = parseDecryptedCompletion(DECODER3.decode(plain), response.status);
|
|
1527
|
+
return withPlacement(completion, response.headers, completion.pendra, placement);
|
|
1089
1528
|
}
|
|
1090
1529
|
};
|
|
1091
1530
|
|
|
@@ -1154,7 +1593,8 @@ var Embeddings = class {
|
|
|
1154
1593
|
"/api/v1/embeddings",
|
|
1155
1594
|
{ method: "POST", body, headers }
|
|
1156
1595
|
);
|
|
1157
|
-
|
|
1596
|
+
const result = await readJsonReply(response);
|
|
1597
|
+
return withPlacement(result, response.headers, result.pendra);
|
|
1158
1598
|
}
|
|
1159
1599
|
async createEncrypted(model, body, headers) {
|
|
1160
1600
|
const engine = await this.client._privateEngine();
|
|
@@ -1168,12 +1608,10 @@ var Embeddings = class {
|
|
|
1168
1608
|
"/api/v1/embeddings",
|
|
1169
1609
|
{ method: "POST", body: topLevel, headers }
|
|
1170
1610
|
);
|
|
1171
|
-
const
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
1176
|
-
return JSON.parse(DECODER4.decode(plain));
|
|
1611
|
+
const { inner, placement } = await readSealedReply(response);
|
|
1612
|
+
const plain = decryptor.openResult(inner);
|
|
1613
|
+
const result = JSON.parse(DECODER4.decode(plain));
|
|
1614
|
+
return withPlacement(result, response.headers, result.pendra, placement);
|
|
1177
1615
|
}
|
|
1178
1616
|
};
|
|
1179
1617
|
|
|
@@ -1216,7 +1654,8 @@ var Generations = class {
|
|
|
1216
1654
|
"/api/v1/images/generations",
|
|
1217
1655
|
{ method: "POST", body, headers }
|
|
1218
1656
|
);
|
|
1219
|
-
|
|
1657
|
+
const result = await readJsonReply(response);
|
|
1658
|
+
return withPlacement(result, response.headers, result.pendra);
|
|
1220
1659
|
}
|
|
1221
1660
|
async createEncrypted(model, body, headers) {
|
|
1222
1661
|
const engine = await this.client._privateEngine();
|
|
@@ -1230,7 +1669,8 @@ var Generations = class {
|
|
|
1230
1669
|
"/api/v1/images/generations",
|
|
1231
1670
|
{ method: "POST", body: topLevel, headers }
|
|
1232
1671
|
);
|
|
1233
|
-
const
|
|
1672
|
+
const { inner, placement } = await readSealedReply(response);
|
|
1673
|
+
const plain = decryptor.openResult(inner);
|
|
1234
1674
|
const parsed = parseDecryptedJson(DECODER5.decode(plain), response.status);
|
|
1235
1675
|
if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.data)) {
|
|
1236
1676
|
throw new APIResponseValidationError("Decrypted response was not an image generation", {
|
|
@@ -1238,7 +1678,8 @@ var Generations = class {
|
|
|
1238
1678
|
body: DECODER5.decode(plain)
|
|
1239
1679
|
});
|
|
1240
1680
|
}
|
|
1241
|
-
|
|
1681
|
+
const result = parsed;
|
|
1682
|
+
return withPlacement(result, response.headers, result.pendra, placement);
|
|
1242
1683
|
}
|
|
1243
1684
|
};
|
|
1244
1685
|
|
|
@@ -1316,7 +1757,8 @@ var Rerank = class {
|
|
|
1316
1757
|
"/api/v1/rerank",
|
|
1317
1758
|
{ method: "POST", body, headers }
|
|
1318
1759
|
);
|
|
1319
|
-
|
|
1760
|
+
const result = await readJsonReply(response);
|
|
1761
|
+
return withPlacement(result, response.headers, result.pendra);
|
|
1320
1762
|
}
|
|
1321
1763
|
async createEncrypted(model, body, headers) {
|
|
1322
1764
|
const engine = await this.client._privateEngine();
|
|
@@ -1330,231 +1772,17 @@ var Rerank = class {
|
|
|
1330
1772
|
"/api/v1/rerank",
|
|
1331
1773
|
{ method: "POST", body: topLevel, headers }
|
|
1332
1774
|
);
|
|
1333
|
-
const
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
1338
|
-
return JSON.parse(DECODER6.decode(plain));
|
|
1775
|
+
const { inner, placement } = await readSealedReply(response);
|
|
1776
|
+
const plain = decryptor.openResult(inner);
|
|
1777
|
+
const result = JSON.parse(DECODER6.decode(plain));
|
|
1778
|
+
return withPlacement(result, response.headers, result.pendra, placement);
|
|
1339
1779
|
}
|
|
1340
1780
|
};
|
|
1341
1781
|
|
|
1342
1782
|
// src/version.ts
|
|
1343
|
-
var VERSION = "0.
|
|
1783
|
+
var VERSION = "0.17.1";
|
|
1344
1784
|
var USER_AGENT = `pendra-node/${VERSION}`;
|
|
1345
1785
|
|
|
1346
|
-
// src/_privateInferenceEngine.ts
|
|
1347
|
-
var PrivateInferenceError = class extends Error {
|
|
1348
|
-
constructor(message) {
|
|
1349
|
-
super(message);
|
|
1350
|
-
this.name = "PrivateInferenceError";
|
|
1351
|
-
}
|
|
1352
|
-
};
|
|
1353
|
-
var FINGERPRINT_RE = /^[0-9a-f]{64}$/;
|
|
1354
|
-
function parsePinnedFingerprints(pin) {
|
|
1355
|
-
if (typeof pin !== "string") {
|
|
1356
|
-
throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);
|
|
1357
|
-
}
|
|
1358
|
-
const fps = pin.split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
|
|
1359
|
-
if (fps.length === 0) {
|
|
1360
|
-
throw new PrivateInferenceError(
|
|
1361
|
-
"pinnedFingerprint was set but contains no fingerprint. Pass the 64-character fingerprint shown in the console, or leave it unset to use automatic trust."
|
|
1362
|
-
);
|
|
1363
|
-
}
|
|
1364
|
-
const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();
|
|
1365
|
-
if (bad.length > 0) {
|
|
1366
|
-
throw new PrivateInferenceError(
|
|
1367
|
-
`pinnedFingerprint "${bad[0]}" is not a valid fingerprint: expected 64 hexadecimal characters, as shown in the console.`
|
|
1368
|
-
);
|
|
1369
|
-
}
|
|
1370
|
-
return new Set(fps);
|
|
1371
|
-
}
|
|
1372
|
-
function defaultTofuPath() {
|
|
1373
|
-
const env = typeof process !== "undefined" ? process.env : void 0;
|
|
1374
|
-
if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
|
|
1375
|
-
const home = env?.HOME || env?.USERPROFILE || ".";
|
|
1376
|
-
return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
|
|
1377
|
-
}
|
|
1378
|
-
function b64d2(s) {
|
|
1379
|
-
if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
|
|
1380
|
-
const binary = atob(s);
|
|
1381
|
-
const out = new Uint8Array(binary.length);
|
|
1382
|
-
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
1383
|
-
return out;
|
|
1384
|
-
}
|
|
1385
|
-
var PrivateInferenceEngine = class {
|
|
1386
|
-
constructor(opts) {
|
|
1387
|
-
this.orgPubs = null;
|
|
1388
|
-
this.baseUrl = opts.baseUrl.replace(/\/$/, "");
|
|
1389
|
-
this.apiKey = opts.apiKey;
|
|
1390
|
-
const pin = opts.pinnedFingerprint;
|
|
1391
|
-
this.pinnedFingerprints = pin === null || pin === void 0 ? null : parsePinnedFingerprints(pin);
|
|
1392
|
-
this.affinitySalt = opts.affinitySalt ?? null;
|
|
1393
|
-
this.tofuPath = opts.tofuPath || defaultTofuPath();
|
|
1394
|
-
}
|
|
1395
|
-
// --- key resolution ---
|
|
1396
|
-
cachedOrgPublicKeys() {
|
|
1397
|
-
return this.orgPubs;
|
|
1398
|
-
}
|
|
1399
|
-
cachedOrgPublicKey() {
|
|
1400
|
-
return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;
|
|
1401
|
-
}
|
|
1402
|
-
tofuIdentity() {
|
|
1403
|
-
const digest = sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);
|
|
1404
|
-
return `${this.baseUrl}|${digest}`;
|
|
1405
|
-
}
|
|
1406
|
-
/**
|
|
1407
|
-
* Drop the cached key set so the next call re-fetches it.
|
|
1408
|
-
*
|
|
1409
|
-
* The cache is otherwise held for the whole process lifetime, which is
|
|
1410
|
-
* correct while a fleet keeps one key but fatal when it re-keys: a
|
|
1411
|
-
* long-running server would go on sealing to a fingerprint no worker holds
|
|
1412
|
-
* and fail EVERY request until someone restarted it. The API signals a re-key
|
|
1413
|
-
* with `X-Pendra-Error-Code: no_private_inference_worker`, and this is what
|
|
1414
|
-
* lets the client recover on its own.
|
|
1415
|
-
*
|
|
1416
|
-
* Pinned clients are deliberately NOT re-fetched on that signal — a pin is an
|
|
1417
|
-
* allowlist, so a fetch could only return fingerprints the pin already
|
|
1418
|
-
* rejects. They surface the error instead, which is what pinning means.
|
|
1419
|
-
*/
|
|
1420
|
-
invalidateOrgKey() {
|
|
1421
|
-
this.orgPubs = null;
|
|
1422
|
-
}
|
|
1423
|
-
/** Whether this client seals only to an explicit fingerprint allowlist. */
|
|
1424
|
-
get isPinned() {
|
|
1425
|
-
return this.pinnedFingerprints !== null;
|
|
1426
|
-
}
|
|
1427
|
-
/**
|
|
1428
|
-
* Validate the key(s) returned by GET /v1/private-inference/key, apply the pin
|
|
1429
|
-
* allowlist (or auto-trust TOFU), cache the accepted public keys, and return
|
|
1430
|
-
* them (newest-seen first). The client seals to **all** of the returned keys
|
|
1431
|
-
* so any worker holding any of them can serve the request. Throws
|
|
1432
|
-
* PrivateInferenceError on absence, a malformed key, or (when pinned) an empty
|
|
1433
|
-
* intersection with the pin set.
|
|
1434
|
-
*/
|
|
1435
|
-
async resolveOrgKey(fetchedKeys) {
|
|
1436
|
-
if (this.orgPubs !== null) return this.orgPubs;
|
|
1437
|
-
if (!fetchedKeys || fetchedKeys.length === 0) {
|
|
1438
|
-
throw new PrivateInferenceError(
|
|
1439
|
-
"No encryption key is registered for this organisation. Start a worker and it will be issued one automatically."
|
|
1440
|
-
);
|
|
1441
|
-
}
|
|
1442
|
-
const pubs = [];
|
|
1443
|
-
const fps = [];
|
|
1444
|
-
for (const entry of fetchedKeys) {
|
|
1445
|
-
let pub;
|
|
1446
|
-
try {
|
|
1447
|
-
pub = b64d2(entry.public_key);
|
|
1448
|
-
} catch (e) {
|
|
1449
|
-
throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
|
|
1450
|
-
}
|
|
1451
|
-
if (pub.length !== 32) {
|
|
1452
|
-
throw new PrivateInferenceError(
|
|
1453
|
-
`Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`
|
|
1454
|
-
);
|
|
1455
|
-
}
|
|
1456
|
-
pubs.push(pub);
|
|
1457
|
-
fps.push(fingerprint(pub));
|
|
1458
|
-
}
|
|
1459
|
-
let accepted;
|
|
1460
|
-
if (this.pinnedFingerprints !== null) {
|
|
1461
|
-
accepted = pubs.filter((_p, i) => this.pinnedFingerprints.has(fps[i]));
|
|
1462
|
-
if (accepted.length === 0) {
|
|
1463
|
-
const pinned = Array.from(this.pinnedFingerprints).sort().join(", ");
|
|
1464
|
-
throw new PrivateInferenceError(
|
|
1465
|
-
`None of the org's workload key fingerprints (${fps.join(", ")}) match your pinned fingerprint(s) (${pinned}). Refusing to seal (possible man-in-the-middle). If your fleet re-keyed \u2014 which happens when every worker goes offline at once \u2014 update the pin to a current fingerprint from the console.`
|
|
1466
|
-
);
|
|
1467
|
-
}
|
|
1468
|
-
} else {
|
|
1469
|
-
await this.tofuTrust(fps);
|
|
1470
|
-
accepted = pubs;
|
|
1471
|
-
}
|
|
1472
|
-
this.orgPubs = accepted;
|
|
1473
|
-
return accepted;
|
|
1474
|
-
}
|
|
1475
|
-
async tofuTrust(fps) {
|
|
1476
|
-
const store = await this.loadTofu();
|
|
1477
|
-
const identity = this.tofuIdentity();
|
|
1478
|
-
const known = store[identity];
|
|
1479
|
-
const trusted = /* @__PURE__ */ new Set();
|
|
1480
|
-
if (typeof known === "string") {
|
|
1481
|
-
trusted.add(known);
|
|
1482
|
-
} else if (Array.isArray(known)) {
|
|
1483
|
-
for (const f of known) if (typeof f === "string") trusted.add(f);
|
|
1484
|
-
}
|
|
1485
|
-
const before = trusted.size;
|
|
1486
|
-
for (const f of fps) trusted.add(f);
|
|
1487
|
-
if (trusted.size !== before || !Array.isArray(known)) {
|
|
1488
|
-
store[identity] = Array.from(trusted).sort();
|
|
1489
|
-
await this.saveTofu(store);
|
|
1490
|
-
}
|
|
1491
|
-
}
|
|
1492
|
-
async loadTofu() {
|
|
1493
|
-
try {
|
|
1494
|
-
const fs = await import("fs");
|
|
1495
|
-
const raw = fs.readFileSync(this.tofuPath, "utf-8");
|
|
1496
|
-
const data = JSON.parse(raw);
|
|
1497
|
-
return data && typeof data === "object" && !Array.isArray(data) ? data : {};
|
|
1498
|
-
} catch {
|
|
1499
|
-
return {};
|
|
1500
|
-
}
|
|
1501
|
-
}
|
|
1502
|
-
async saveTofu(store) {
|
|
1503
|
-
const fs = await import("fs");
|
|
1504
|
-
const path = await import("path");
|
|
1505
|
-
const directory = path.dirname(this.tofuPath) || ".";
|
|
1506
|
-
fs.mkdirSync(directory, { recursive: true });
|
|
1507
|
-
const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);
|
|
1508
|
-
try {
|
|
1509
|
-
fs.writeFileSync(tmp, JSON.stringify(store), { mode: 384 });
|
|
1510
|
-
try {
|
|
1511
|
-
fs.chmodSync(tmp, 384);
|
|
1512
|
-
} catch {
|
|
1513
|
-
}
|
|
1514
|
-
fs.renameSync(tmp, this.tofuPath);
|
|
1515
|
-
} catch (e) {
|
|
1516
|
-
try {
|
|
1517
|
-
fs.unlinkSync(tmp);
|
|
1518
|
-
} catch {
|
|
1519
|
-
}
|
|
1520
|
-
throw e;
|
|
1521
|
-
}
|
|
1522
|
-
}
|
|
1523
|
-
// --- sealing ---
|
|
1524
|
-
/**
|
|
1525
|
-
* Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
|
|
1526
|
-
* `messages` (chat only) drives the affinity token; pass undefined for non-chat.
|
|
1527
|
-
* `binary` (audio only) is sealed under the same data key as the body.
|
|
1528
|
-
*/
|
|
1529
|
-
seal(args) {
|
|
1530
|
-
if (this.orgPubs === null || this.orgPubs.length === 0) {
|
|
1531
|
-
throw new PrivateInferenceError(
|
|
1532
|
-
"private inference: org key not resolved yet (call resolveOrgKey first)"
|
|
1533
|
-
);
|
|
1534
|
-
}
|
|
1535
|
-
let affinity = null;
|
|
1536
|
-
if (args.messages != null) {
|
|
1537
|
-
affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
|
|
1538
|
-
}
|
|
1539
|
-
const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
|
|
1540
|
-
model: args.model,
|
|
1541
|
-
stream: args.stream,
|
|
1542
|
-
taskType: args.taskType,
|
|
1543
|
-
affinityKey: affinity,
|
|
1544
|
-
binary: args.binary ?? null
|
|
1545
|
-
});
|
|
1546
|
-
const topLevel = {
|
|
1547
|
-
model: args.model,
|
|
1548
|
-
stream: args.stream,
|
|
1549
|
-
pendra_encrypted: envelope
|
|
1550
|
-
};
|
|
1551
|
-
return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
|
|
1552
|
-
}
|
|
1553
|
-
get keyFetchUrl() {
|
|
1554
|
-
return `${this.baseUrl}/v1/private-inference/key`;
|
|
1555
|
-
}
|
|
1556
|
-
};
|
|
1557
|
-
|
|
1558
1786
|
// src/client.ts
|
|
1559
1787
|
function envTruthy(v) {
|
|
1560
1788
|
if (!v) return false;
|