pendra 0.16.0 → 0.17.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/README.md +61 -0
- package/dist/index.d.mts +180 -62
- package/dist/index.d.ts +180 -62
- package/dist/index.js +478 -238
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +478 -238
- 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) {
|
|
@@ -599,9 +611,10 @@ async function readSealedReply(response) {
|
|
|
599
611
|
});
|
|
600
612
|
}
|
|
601
613
|
throwIfInBandError(parsed, "The server reported an error");
|
|
602
|
-
const
|
|
614
|
+
const wrapper = typeof parsed === "object" && parsed !== null ? parsed : void 0;
|
|
615
|
+
const inner = wrapper?.pendra_encrypted;
|
|
603
616
|
if (!inner) throw unsealedReplyError();
|
|
604
|
-
return inner;
|
|
617
|
+
return { inner, placement: wrapper.pendra };
|
|
605
618
|
}
|
|
606
619
|
function parseDecryptedJson(json, status) {
|
|
607
620
|
try {
|
|
@@ -614,6 +627,392 @@ function parseDecryptedJson(json, status) {
|
|
|
614
627
|
}
|
|
615
628
|
}
|
|
616
629
|
|
|
630
|
+
// src/_placement.ts
|
|
631
|
+
var UTF8_EXT_PREFIX = "utf-8''";
|
|
632
|
+
function isPlainObject(v) {
|
|
633
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
634
|
+
}
|
|
635
|
+
function parseWorker(v) {
|
|
636
|
+
if (!isPlainObject(v) || typeof v.id !== "string" || !v.id) return void 0;
|
|
637
|
+
return {
|
|
638
|
+
id: v.id,
|
|
639
|
+
name: typeof v.name === "string" && v.name ? v.name : null,
|
|
640
|
+
version: typeof v.version === "string" && v.version ? v.version : null
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
function placementFromBlock(block) {
|
|
644
|
+
if (!isPlainObject(block)) return void 0;
|
|
645
|
+
const worker = parseWorker(block.worker);
|
|
646
|
+
if (!worker) return void 0;
|
|
647
|
+
const requestId = block.request_id;
|
|
648
|
+
return typeof requestId === "string" && requestId ? { worker, request_id: requestId } : { worker };
|
|
649
|
+
}
|
|
650
|
+
function decodeWorkerNameHeader(raw) {
|
|
651
|
+
if (raw.slice(0, UTF8_EXT_PREFIX.length).toLowerCase() !== UTF8_EXT_PREFIX) return raw;
|
|
652
|
+
try {
|
|
653
|
+
return decodeURIComponent(raw.slice(UTF8_EXT_PREFIX.length));
|
|
654
|
+
} catch {
|
|
655
|
+
return raw;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
function header(headers, name) {
|
|
659
|
+
if (!headers || typeof headers.get !== "function") return void 0;
|
|
660
|
+
return headers.get(name) || void 0;
|
|
661
|
+
}
|
|
662
|
+
function placementFromHeaders(headers) {
|
|
663
|
+
const id = header(headers, "X-Worker-Id");
|
|
664
|
+
if (!id) return void 0;
|
|
665
|
+
const rawName = header(headers, "X-Worker-Name");
|
|
666
|
+
const requestId = header(headers, "X-Request-Id");
|
|
667
|
+
const worker = {
|
|
668
|
+
id,
|
|
669
|
+
name: rawName ? decodeWorkerNameHeader(rawName) : null,
|
|
670
|
+
version: null
|
|
671
|
+
};
|
|
672
|
+
return requestId ? { worker, request_id: requestId } : { worker };
|
|
673
|
+
}
|
|
674
|
+
function sanitise(block) {
|
|
675
|
+
if ("worker" in block && block.worker !== null) {
|
|
676
|
+
const worker = parseWorker(block.worker);
|
|
677
|
+
if (worker) block.worker = worker;
|
|
678
|
+
else delete block.worker;
|
|
679
|
+
}
|
|
680
|
+
if ("request_id" in block && block.request_id !== null && typeof block.request_id !== "string") {
|
|
681
|
+
delete block.request_id;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
function withPlacement(result, headers, ...blocks) {
|
|
685
|
+
if (!isPlainObject(result)) return result;
|
|
686
|
+
const own = isPlainObject(result.pendra) ? result.pendra : void 0;
|
|
687
|
+
if (own) sanitise(own);
|
|
688
|
+
let placement;
|
|
689
|
+
for (const block of blocks) {
|
|
690
|
+
placement = placementFromBlock(block);
|
|
691
|
+
if (placement) break;
|
|
692
|
+
}
|
|
693
|
+
placement ?? (placement = placementFromHeaders(headers));
|
|
694
|
+
if (!placement) return result;
|
|
695
|
+
const merged = { ...own ?? {}, worker: placement.worker };
|
|
696
|
+
if (placement.request_id) merged.request_id = placement.request_id;
|
|
697
|
+
else delete merged.request_id;
|
|
698
|
+
result.pendra = merged;
|
|
699
|
+
return result;
|
|
700
|
+
}
|
|
701
|
+
function chunkPlacement(chunk) {
|
|
702
|
+
const block = chunk.pendra;
|
|
703
|
+
if (!isPlainObject(block)) return {};
|
|
704
|
+
sanitise(block);
|
|
705
|
+
const worker = block.worker;
|
|
706
|
+
const requestId = block.request_id;
|
|
707
|
+
return { worker: worker ?? void 0, requestId: requestId || void 0 };
|
|
708
|
+
}
|
|
709
|
+
var PLACEMENT_OPT_IN_HEADER = "X-Pendra-Placement";
|
|
710
|
+
|
|
711
|
+
// src/_privateInferenceEngine.ts
|
|
712
|
+
var PrivateInferenceError = class extends Error {
|
|
713
|
+
constructor(message) {
|
|
714
|
+
super(message);
|
|
715
|
+
this.name = "PrivateInferenceError";
|
|
716
|
+
}
|
|
717
|
+
};
|
|
718
|
+
var FINGERPRINT_RE = /^[0-9a-f]{64}$/;
|
|
719
|
+
function parsePinnedFingerprints(pin) {
|
|
720
|
+
if (typeof pin !== "string") {
|
|
721
|
+
throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);
|
|
722
|
+
}
|
|
723
|
+
const fps = pin.split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
|
|
724
|
+
if (fps.length === 0) {
|
|
725
|
+
throw new PrivateInferenceError(
|
|
726
|
+
"pinnedFingerprint was set but contains no fingerprint. Pass the 64-character fingerprint shown in the console, or leave it unset to use automatic trust."
|
|
727
|
+
);
|
|
728
|
+
}
|
|
729
|
+
const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();
|
|
730
|
+
if (bad.length > 0) {
|
|
731
|
+
throw new PrivateInferenceError(
|
|
732
|
+
`pinnedFingerprint "${bad[0]}" is not a valid fingerprint: expected 64 hexadecimal characters, as shown in the console.`
|
|
733
|
+
);
|
|
734
|
+
}
|
|
735
|
+
return new Set(fps);
|
|
736
|
+
}
|
|
737
|
+
function defaultTofuPath() {
|
|
738
|
+
const env = typeof process !== "undefined" ? process.env : void 0;
|
|
739
|
+
if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
|
|
740
|
+
const home = env?.HOME || env?.USERPROFILE || ".";
|
|
741
|
+
return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
|
|
742
|
+
}
|
|
743
|
+
function b64d2(s) {
|
|
744
|
+
if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
|
|
745
|
+
const binary = atob(s);
|
|
746
|
+
const out = new Uint8Array(binary.length);
|
|
747
|
+
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
748
|
+
return out;
|
|
749
|
+
}
|
|
750
|
+
var PrivateInferenceEngine = class {
|
|
751
|
+
constructor(opts) {
|
|
752
|
+
this.orgPubs = null;
|
|
753
|
+
this.baseUrl = opts.baseUrl.replace(/\/$/, "");
|
|
754
|
+
this.apiKey = opts.apiKey;
|
|
755
|
+
const pin = opts.pinnedFingerprint;
|
|
756
|
+
this.pinnedFingerprints = pin === null || pin === void 0 ? null : parsePinnedFingerprints(pin);
|
|
757
|
+
this.affinitySalt = opts.affinitySalt ?? null;
|
|
758
|
+
this.tofuPath = opts.tofuPath || defaultTofuPath();
|
|
759
|
+
}
|
|
760
|
+
// --- key resolution ---
|
|
761
|
+
cachedOrgPublicKeys() {
|
|
762
|
+
return this.orgPubs;
|
|
763
|
+
}
|
|
764
|
+
cachedOrgPublicKey() {
|
|
765
|
+
return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;
|
|
766
|
+
}
|
|
767
|
+
tofuIdentity() {
|
|
768
|
+
const digest = sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);
|
|
769
|
+
return `${this.baseUrl}|${digest}`;
|
|
770
|
+
}
|
|
771
|
+
/**
|
|
772
|
+
* Drop the cached key set so the next call re-fetches it.
|
|
773
|
+
*
|
|
774
|
+
* The cache is otherwise held for the whole process lifetime, which is
|
|
775
|
+
* correct while a fleet keeps one key but fatal when it re-keys: a
|
|
776
|
+
* long-running server would go on sealing to a fingerprint no worker holds
|
|
777
|
+
* and fail EVERY request until someone restarted it. The API signals a re-key
|
|
778
|
+
* with `X-Pendra-Error-Code: no_private_inference_worker`, and this is what
|
|
779
|
+
* lets the client recover on its own.
|
|
780
|
+
*
|
|
781
|
+
* Pinned clients are deliberately NOT re-fetched on that signal — a pin is an
|
|
782
|
+
* allowlist, so a fetch could only return fingerprints the pin already
|
|
783
|
+
* rejects. They surface the error instead, which is what pinning means.
|
|
784
|
+
*/
|
|
785
|
+
invalidateOrgKey() {
|
|
786
|
+
this.orgPubs = null;
|
|
787
|
+
}
|
|
788
|
+
/** Whether this client seals only to an explicit fingerprint allowlist. */
|
|
789
|
+
get isPinned() {
|
|
790
|
+
return this.pinnedFingerprints !== null;
|
|
791
|
+
}
|
|
792
|
+
/**
|
|
793
|
+
* Validate the key(s) returned by GET /v1/private-inference/key, apply the pin
|
|
794
|
+
* allowlist (or auto-trust TOFU), cache the accepted public keys, and return
|
|
795
|
+
* them (newest-seen first). The client seals to **all** of the returned keys
|
|
796
|
+
* so any worker holding any of them can serve the request. Throws
|
|
797
|
+
* PrivateInferenceError on absence, a malformed key, or (when pinned) an empty
|
|
798
|
+
* intersection with the pin set.
|
|
799
|
+
*/
|
|
800
|
+
async resolveOrgKey(fetchedKeys) {
|
|
801
|
+
if (this.orgPubs !== null) return this.orgPubs;
|
|
802
|
+
if (!fetchedKeys || fetchedKeys.length === 0) {
|
|
803
|
+
throw new PrivateInferenceError(
|
|
804
|
+
"No encryption key is registered for this organisation. Start a worker and it will be issued one automatically."
|
|
805
|
+
);
|
|
806
|
+
}
|
|
807
|
+
const pubs = [];
|
|
808
|
+
const fps = [];
|
|
809
|
+
for (const entry of fetchedKeys) {
|
|
810
|
+
let pub;
|
|
811
|
+
try {
|
|
812
|
+
pub = b64d2(entry.public_key);
|
|
813
|
+
} catch (e) {
|
|
814
|
+
throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
|
|
815
|
+
}
|
|
816
|
+
if (pub.length !== 32) {
|
|
817
|
+
throw new PrivateInferenceError(
|
|
818
|
+
`Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`
|
|
819
|
+
);
|
|
820
|
+
}
|
|
821
|
+
pubs.push(pub);
|
|
822
|
+
fps.push(fingerprint(pub));
|
|
823
|
+
}
|
|
824
|
+
let accepted;
|
|
825
|
+
if (this.pinnedFingerprints !== null) {
|
|
826
|
+
accepted = pubs.filter((_p, i) => this.pinnedFingerprints.has(fps[i]));
|
|
827
|
+
if (accepted.length === 0) {
|
|
828
|
+
const pinned = Array.from(this.pinnedFingerprints).sort().join(", ");
|
|
829
|
+
throw new PrivateInferenceError(
|
|
830
|
+
`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.`
|
|
831
|
+
);
|
|
832
|
+
}
|
|
833
|
+
} else {
|
|
834
|
+
await this.tofuTrust(fps);
|
|
835
|
+
accepted = pubs;
|
|
836
|
+
}
|
|
837
|
+
this.orgPubs = accepted;
|
|
838
|
+
return accepted;
|
|
839
|
+
}
|
|
840
|
+
async tofuTrust(fps) {
|
|
841
|
+
const store = await this.loadTofu();
|
|
842
|
+
const identity = this.tofuIdentity();
|
|
843
|
+
const known = store[identity];
|
|
844
|
+
const trusted = /* @__PURE__ */ new Set();
|
|
845
|
+
if (typeof known === "string") {
|
|
846
|
+
trusted.add(known);
|
|
847
|
+
} else if (Array.isArray(known)) {
|
|
848
|
+
for (const f of known) if (typeof f === "string") trusted.add(f);
|
|
849
|
+
}
|
|
850
|
+
const before = trusted.size;
|
|
851
|
+
for (const f of fps) trusted.add(f);
|
|
852
|
+
if (trusted.size !== before || !Array.isArray(known)) {
|
|
853
|
+
store[identity] = Array.from(trusted).sort();
|
|
854
|
+
await this.saveTofu(store);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
async loadTofu() {
|
|
858
|
+
try {
|
|
859
|
+
const fs = await import("fs");
|
|
860
|
+
const raw = fs.readFileSync(this.tofuPath, "utf-8");
|
|
861
|
+
const data = JSON.parse(raw);
|
|
862
|
+
return data && typeof data === "object" && !Array.isArray(data) ? data : {};
|
|
863
|
+
} catch {
|
|
864
|
+
return {};
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
async saveTofu(store) {
|
|
868
|
+
const fs = await import("fs");
|
|
869
|
+
const path = await import("path");
|
|
870
|
+
const directory = path.dirname(this.tofuPath) || ".";
|
|
871
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
872
|
+
const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);
|
|
873
|
+
try {
|
|
874
|
+
fs.writeFileSync(tmp, JSON.stringify(store), { mode: 384 });
|
|
875
|
+
try {
|
|
876
|
+
fs.chmodSync(tmp, 384);
|
|
877
|
+
} catch {
|
|
878
|
+
}
|
|
879
|
+
fs.renameSync(tmp, this.tofuPath);
|
|
880
|
+
} catch (e) {
|
|
881
|
+
try {
|
|
882
|
+
fs.unlinkSync(tmp);
|
|
883
|
+
} catch {
|
|
884
|
+
}
|
|
885
|
+
throw e;
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
// --- sealing ---
|
|
889
|
+
/**
|
|
890
|
+
* Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
|
|
891
|
+
* `messages` (chat only) drives the affinity token; pass undefined for non-chat.
|
|
892
|
+
* `binary` (audio only) is sealed under the same data key as the body.
|
|
893
|
+
*/
|
|
894
|
+
seal(args) {
|
|
895
|
+
if (this.orgPubs === null || this.orgPubs.length === 0) {
|
|
896
|
+
throw new PrivateInferenceError(
|
|
897
|
+
"private inference: org key not resolved yet (call resolveOrgKey first)"
|
|
898
|
+
);
|
|
899
|
+
}
|
|
900
|
+
let affinity = null;
|
|
901
|
+
if (args.messages != null) {
|
|
902
|
+
affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
|
|
903
|
+
}
|
|
904
|
+
const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
|
|
905
|
+
model: args.model,
|
|
906
|
+
stream: args.stream,
|
|
907
|
+
taskType: args.taskType,
|
|
908
|
+
affinityKey: affinity,
|
|
909
|
+
binary: args.binary ?? null
|
|
910
|
+
});
|
|
911
|
+
const topLevel = {
|
|
912
|
+
model: args.model,
|
|
913
|
+
stream: args.stream,
|
|
914
|
+
pendra_encrypted: envelope
|
|
915
|
+
};
|
|
916
|
+
return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
|
|
917
|
+
}
|
|
918
|
+
get keyFetchUrl() {
|
|
919
|
+
return `${this.baseUrl}/v1/private-inference/key`;
|
|
920
|
+
}
|
|
921
|
+
};
|
|
922
|
+
|
|
923
|
+
// src/resources/audio/speech.ts
|
|
924
|
+
var BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
925
|
+
function decodeAudio(value) {
|
|
926
|
+
if (typeof value !== "string") return void 0;
|
|
927
|
+
const s = value.replace(/\s+/g, "");
|
|
928
|
+
if (!s || !BASE64_RE.test(s) || s.replace(/=+$/, "").length % 4 === 1) return void 0;
|
|
929
|
+
if (s.includes("=") && s.length % 4 !== 0) return void 0;
|
|
930
|
+
let bytes2;
|
|
931
|
+
try {
|
|
932
|
+
bytes2 = _internal.b64d(s);
|
|
933
|
+
} catch {
|
|
934
|
+
return void 0;
|
|
935
|
+
}
|
|
936
|
+
return bytes2.length > 0 ? bytes2 : void 0;
|
|
937
|
+
}
|
|
938
|
+
function isRecord2(v) {
|
|
939
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
940
|
+
}
|
|
941
|
+
var Speech = class {
|
|
942
|
+
constructor(client) {
|
|
943
|
+
this.client = client;
|
|
944
|
+
}
|
|
945
|
+
/**
|
|
946
|
+
* Turn text into spoken audio (OpenAI-compatible).
|
|
947
|
+
*
|
|
948
|
+
* @example
|
|
949
|
+
* ```ts
|
|
950
|
+
* import { writeFileSync } from "node:fs";
|
|
951
|
+
*
|
|
952
|
+
* const speech = await client.audio.speech.create({
|
|
953
|
+
* model: "qwen3-tts",
|
|
954
|
+
* input: "Hello from Pendra.",
|
|
955
|
+
* });
|
|
956
|
+
* writeFileSync("speech.wav", speech.audio);
|
|
957
|
+
* ```
|
|
958
|
+
*/
|
|
959
|
+
async create(params) {
|
|
960
|
+
if (!params.model || typeof params.model !== "string") {
|
|
961
|
+
throw new Error("model must be a non-empty string");
|
|
962
|
+
}
|
|
963
|
+
if (typeof params.input !== "string" || !params.input.trim()) {
|
|
964
|
+
throw new Error("input must be a non-empty string");
|
|
965
|
+
}
|
|
966
|
+
if (this.client.privateInferenceEnabled) {
|
|
967
|
+
throw new PrivateInferenceError("Private inference does not support speech synthesis yet.");
|
|
968
|
+
}
|
|
969
|
+
const body = { model: params.model, input: params.input };
|
|
970
|
+
if (params.voice != null) body.voice = params.voice;
|
|
971
|
+
if (params.response_format != null) body.response_format = params.response_format;
|
|
972
|
+
const headers = { Accept: "application/json" };
|
|
973
|
+
if (params.worker_id) headers["X-Pendra-Worker-Id"] = params.worker_id;
|
|
974
|
+
const timeout = Math.max(this.client.timeout ?? 0, 3e5);
|
|
975
|
+
const { response } = await this.client._fetch("/api/v1/audio/speech", {
|
|
976
|
+
method: "POST",
|
|
977
|
+
body,
|
|
978
|
+
headers,
|
|
979
|
+
timeout
|
|
980
|
+
});
|
|
981
|
+
const text = await response.text();
|
|
982
|
+
let parsed;
|
|
983
|
+
try {
|
|
984
|
+
parsed = JSON.parse(text);
|
|
985
|
+
} catch {
|
|
986
|
+
throw new APIResponseValidationError("Response was not valid JSON", {
|
|
987
|
+
status: response.status,
|
|
988
|
+
body: text
|
|
989
|
+
});
|
|
990
|
+
}
|
|
991
|
+
throwIfInBandError(parsed, "The server reported an error");
|
|
992
|
+
if (!isRecord2(parsed)) {
|
|
993
|
+
throw new APIResponseValidationError("Response was not a speech result", {
|
|
994
|
+
status: response.status,
|
|
995
|
+
body: text
|
|
996
|
+
});
|
|
997
|
+
}
|
|
998
|
+
const audio = decodeAudio(parsed.audio);
|
|
999
|
+
if (!audio) {
|
|
1000
|
+
throw new APIResponseValidationError("Response did not contain decodable audio", {
|
|
1001
|
+
status: response.status,
|
|
1002
|
+
body: text
|
|
1003
|
+
});
|
|
1004
|
+
}
|
|
1005
|
+
const result = {
|
|
1006
|
+
audio,
|
|
1007
|
+
format: typeof parsed.format === "string" && parsed.format ? parsed.format : params.response_format ?? "wav",
|
|
1008
|
+
duration_ms: typeof parsed.duration_ms === "number" && Number.isFinite(parsed.duration_ms) ? parsed.duration_ms : null,
|
|
1009
|
+
arrayBuffer: async () => audio.slice().buffer
|
|
1010
|
+
};
|
|
1011
|
+
if (isRecord2(parsed.pendra)) result.pendra = parsed.pendra;
|
|
1012
|
+
return withPlacement(result, response.headers, result.pendra);
|
|
1013
|
+
}
|
|
1014
|
+
};
|
|
1015
|
+
|
|
617
1016
|
// src/resources/audio/transcriptions.ts
|
|
618
1017
|
var ENCODER = new TextEncoder();
|
|
619
1018
|
var DECODER = new TextDecoder();
|
|
@@ -713,9 +1112,10 @@ var Transcriptions = class {
|
|
|
713
1112
|
const format = params.response_format;
|
|
714
1113
|
if (format === "text" || format === "srt" || format === "vtt") {
|
|
715
1114
|
const text = await response.text();
|
|
716
|
-
return { text };
|
|
1115
|
+
return withPlacement({ text }, response.headers);
|
|
717
1116
|
}
|
|
718
|
-
|
|
1117
|
+
const result = await response.json();
|
|
1118
|
+
return withPlacement(result, response.headers, result.pendra);
|
|
719
1119
|
}
|
|
720
1120
|
/**
|
|
721
1121
|
* Private-inference transcription. There is no multipart upload: the audio
|
|
@@ -750,9 +1150,11 @@ var Transcriptions = class {
|
|
|
750
1150
|
timeout
|
|
751
1151
|
}
|
|
752
1152
|
);
|
|
753
|
-
const
|
|
1153
|
+
const { inner, placement } = await readSealedReply(response);
|
|
1154
|
+
const raw = DECODER.decode(decryptor.openResult(inner));
|
|
754
1155
|
const parsed = parseDecryptedJson(raw, response.status);
|
|
755
|
-
|
|
1156
|
+
const place = (r) => withPlacement(r, response.headers, r.pendra, placement);
|
|
1157
|
+
if (typeof parsed === "string") return place({ text: parsed });
|
|
756
1158
|
if (typeof parsed === "object" && parsed !== null) {
|
|
757
1159
|
if (typeof parsed.text !== "string") {
|
|
758
1160
|
throw new APIResponseValidationError("Decrypted response was not a transcription", {
|
|
@@ -760,9 +1162,9 @@ var Transcriptions = class {
|
|
|
760
1162
|
body: raw
|
|
761
1163
|
});
|
|
762
1164
|
}
|
|
763
|
-
return parsed;
|
|
1165
|
+
return place(parsed);
|
|
764
1166
|
}
|
|
765
|
-
return { text: raw };
|
|
1167
|
+
return place({ text: raw });
|
|
766
1168
|
}
|
|
767
1169
|
};
|
|
768
1170
|
|
|
@@ -770,6 +1172,7 @@ var Transcriptions = class {
|
|
|
770
1172
|
var Audio = class {
|
|
771
1173
|
constructor(client) {
|
|
772
1174
|
this.transcriptions = new Transcriptions(client);
|
|
1175
|
+
this.speech = new Speech(client);
|
|
773
1176
|
}
|
|
774
1177
|
};
|
|
775
1178
|
|
|
@@ -846,6 +1249,7 @@ var Stream = class {
|
|
|
846
1249
|
this.decoder = new TextDecoder();
|
|
847
1250
|
this.sse = new SseDecoder();
|
|
848
1251
|
this.done = false;
|
|
1252
|
+
this.placement = new PlacementTracker();
|
|
849
1253
|
if (!response.body) {
|
|
850
1254
|
throw new Error("Response body is null \u2014 streaming not supported");
|
|
851
1255
|
}
|
|
@@ -866,7 +1270,7 @@ var Stream = class {
|
|
|
866
1270
|
this.done = true;
|
|
867
1271
|
return;
|
|
868
1272
|
}
|
|
869
|
-
yield parseStreamFrame(data);
|
|
1273
|
+
yield this.placement.observe(parseStreamFrame(data));
|
|
870
1274
|
}
|
|
871
1275
|
if (readerDone) {
|
|
872
1276
|
this.done = true;
|
|
@@ -877,11 +1281,39 @@ var Stream = class {
|
|
|
877
1281
|
releaseReader(this.reader, this.controller, this.done);
|
|
878
1282
|
}
|
|
879
1283
|
}
|
|
1284
|
+
/**
|
|
1285
|
+
* The worker that served this stream, or `null` until the chunk reporting it
|
|
1286
|
+
* — the trailer, just before `[DONE]` — has been iterated (and on an API too
|
|
1287
|
+
* old to report it). Same as that chunk's `pendra.worker`.
|
|
1288
|
+
*/
|
|
1289
|
+
get worker() {
|
|
1290
|
+
return this.placement.worker;
|
|
1291
|
+
}
|
|
1292
|
+
/**
|
|
1293
|
+
* Pendra's id for this request, reported alongside {@link Stream.worker};
|
|
1294
|
+
* `null` until then.
|
|
1295
|
+
*/
|
|
1296
|
+
get requestId() {
|
|
1297
|
+
return this.placement.requestId;
|
|
1298
|
+
}
|
|
880
1299
|
abort() {
|
|
881
1300
|
this.done = true;
|
|
882
1301
|
this.controller.abort();
|
|
883
1302
|
}
|
|
884
1303
|
};
|
|
1304
|
+
var PlacementTracker = class {
|
|
1305
|
+
constructor() {
|
|
1306
|
+
this.worker = null;
|
|
1307
|
+
this.requestId = null;
|
|
1308
|
+
}
|
|
1309
|
+
/** Record `chunk`'s placement, if it carries any, and hand it back. */
|
|
1310
|
+
observe(chunk) {
|
|
1311
|
+
const { worker, requestId } = chunkPlacement(chunk);
|
|
1312
|
+
if (worker) this.worker = worker;
|
|
1313
|
+
if (requestId) this.requestId = requestId;
|
|
1314
|
+
return chunk;
|
|
1315
|
+
}
|
|
1316
|
+
};
|
|
885
1317
|
async function readWithIdleTimeout(reader, idleTimeoutMs) {
|
|
886
1318
|
if (!idleTimeoutMs) return reader.read();
|
|
887
1319
|
let timer;
|
|
@@ -917,6 +1349,7 @@ var EncryptedStream = class {
|
|
|
917
1349
|
this.openedAny = false;
|
|
918
1350
|
this.declared = false;
|
|
919
1351
|
this.terminated = false;
|
|
1352
|
+
this.placement = new PlacementTracker();
|
|
920
1353
|
if (!response.body) {
|
|
921
1354
|
throw new Error("Response body is null \u2014 streaming not supported");
|
|
922
1355
|
}
|
|
@@ -958,9 +1391,9 @@ var EncryptedStream = class {
|
|
|
958
1391
|
}
|
|
959
1392
|
const inner = frame?.pendra_encrypted;
|
|
960
1393
|
if (!inner) {
|
|
961
|
-
if (
|
|
1394
|
+
if (isApiTrailerChunk(frame)) {
|
|
962
1395
|
this.checkEnded();
|
|
963
|
-
yield parseStreamFrame(data);
|
|
1396
|
+
yield this.placement.observe(parseStreamFrame(data));
|
|
964
1397
|
continue;
|
|
965
1398
|
}
|
|
966
1399
|
parseStreamFrame(data);
|
|
@@ -988,7 +1421,7 @@ var EncryptedStream = class {
|
|
|
988
1421
|
return;
|
|
989
1422
|
}
|
|
990
1423
|
if (!chunkJson) continue;
|
|
991
|
-
yield parseStreamFrame(chunkJson, "Decrypted stream frame");
|
|
1424
|
+
yield this.placement.observe(parseStreamFrame(chunkJson, "Decrypted stream frame"));
|
|
992
1425
|
}
|
|
993
1426
|
if (readerDone) {
|
|
994
1427
|
this.checkEnded();
|
|
@@ -1010,6 +1443,14 @@ var EncryptedStream = class {
|
|
|
1010
1443
|
throw truncatedStreamError();
|
|
1011
1444
|
}
|
|
1012
1445
|
}
|
|
1446
|
+
/** Same as `Stream.worker`: set once the trailer chunk has been iterated. */
|
|
1447
|
+
get worker() {
|
|
1448
|
+
return this.placement.worker;
|
|
1449
|
+
}
|
|
1450
|
+
/** Same as `Stream.requestId`. */
|
|
1451
|
+
get requestId() {
|
|
1452
|
+
return this.placement.requestId;
|
|
1453
|
+
}
|
|
1013
1454
|
abort() {
|
|
1014
1455
|
this.aborted = true;
|
|
1015
1456
|
this.done = true;
|
|
@@ -1030,7 +1471,9 @@ var Completions = class {
|
|
|
1030
1471
|
for (const [key, value] of Object.entries(rest)) {
|
|
1031
1472
|
if (value != null) body[key] = value;
|
|
1032
1473
|
}
|
|
1033
|
-
const headers =
|
|
1474
|
+
const headers = {};
|
|
1475
|
+
if (params.worker_id) headers["X-Pendra-Worker-Id"] = params.worker_id;
|
|
1476
|
+
if (params.stream) headers[PLACEMENT_OPT_IN_HEADER] = "1";
|
|
1034
1477
|
if (this.client.privateInferenceEnabled) {
|
|
1035
1478
|
return this.createEncrypted(params, body, headers);
|
|
1036
1479
|
}
|
|
@@ -1045,7 +1488,8 @@ var Completions = class {
|
|
|
1045
1488
|
"/api/v1/chat/completions",
|
|
1046
1489
|
{ method: "POST", body, headers }
|
|
1047
1490
|
);
|
|
1048
|
-
|
|
1491
|
+
const completion = await parseCompletion(response);
|
|
1492
|
+
return withPlacement(completion, response.headers, completion.pendra);
|
|
1049
1493
|
}
|
|
1050
1494
|
async createEncrypted(params, body, headers) {
|
|
1051
1495
|
const engine = await this.client._privateEngine();
|
|
@@ -1085,7 +1529,8 @@ var Completions = class {
|
|
|
1085
1529
|
throw unsealedReplyError();
|
|
1086
1530
|
}
|
|
1087
1531
|
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
1088
|
-
|
|
1532
|
+
const completion = parseDecryptedCompletion(DECODER3.decode(plain), response.status);
|
|
1533
|
+
return withPlacement(completion, response.headers, completion.pendra, wrapper.pendra);
|
|
1089
1534
|
}
|
|
1090
1535
|
};
|
|
1091
1536
|
|
|
@@ -1154,7 +1599,8 @@ var Embeddings = class {
|
|
|
1154
1599
|
"/api/v1/embeddings",
|
|
1155
1600
|
{ method: "POST", body, headers }
|
|
1156
1601
|
);
|
|
1157
|
-
|
|
1602
|
+
const result = await response.json();
|
|
1603
|
+
return withPlacement(result, response.headers, result.pendra);
|
|
1158
1604
|
}
|
|
1159
1605
|
async createEncrypted(model, body, headers) {
|
|
1160
1606
|
const engine = await this.client._privateEngine();
|
|
@@ -1173,7 +1619,8 @@ var Embeddings = class {
|
|
|
1173
1619
|
throw unsealedReplyError();
|
|
1174
1620
|
}
|
|
1175
1621
|
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
1176
|
-
|
|
1622
|
+
const result = JSON.parse(DECODER4.decode(plain));
|
|
1623
|
+
return withPlacement(result, response.headers, result.pendra, wrapper.pendra);
|
|
1177
1624
|
}
|
|
1178
1625
|
};
|
|
1179
1626
|
|
|
@@ -1216,7 +1663,8 @@ var Generations = class {
|
|
|
1216
1663
|
"/api/v1/images/generations",
|
|
1217
1664
|
{ method: "POST", body, headers }
|
|
1218
1665
|
);
|
|
1219
|
-
|
|
1666
|
+
const result = await response.json();
|
|
1667
|
+
return withPlacement(result, response.headers, result.pendra);
|
|
1220
1668
|
}
|
|
1221
1669
|
async createEncrypted(model, body, headers) {
|
|
1222
1670
|
const engine = await this.client._privateEngine();
|
|
@@ -1230,7 +1678,8 @@ var Generations = class {
|
|
|
1230
1678
|
"/api/v1/images/generations",
|
|
1231
1679
|
{ method: "POST", body: topLevel, headers }
|
|
1232
1680
|
);
|
|
1233
|
-
const
|
|
1681
|
+
const { inner, placement } = await readSealedReply(response);
|
|
1682
|
+
const plain = decryptor.openResult(inner);
|
|
1234
1683
|
const parsed = parseDecryptedJson(DECODER5.decode(plain), response.status);
|
|
1235
1684
|
if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.data)) {
|
|
1236
1685
|
throw new APIResponseValidationError("Decrypted response was not an image generation", {
|
|
@@ -1238,7 +1687,8 @@ var Generations = class {
|
|
|
1238
1687
|
body: DECODER5.decode(plain)
|
|
1239
1688
|
});
|
|
1240
1689
|
}
|
|
1241
|
-
|
|
1690
|
+
const result = parsed;
|
|
1691
|
+
return withPlacement(result, response.headers, result.pendra, placement);
|
|
1242
1692
|
}
|
|
1243
1693
|
};
|
|
1244
1694
|
|
|
@@ -1316,7 +1766,8 @@ var Rerank = class {
|
|
|
1316
1766
|
"/api/v1/rerank",
|
|
1317
1767
|
{ method: "POST", body, headers }
|
|
1318
1768
|
);
|
|
1319
|
-
|
|
1769
|
+
const result = await response.json();
|
|
1770
|
+
return withPlacement(result, response.headers, result.pendra);
|
|
1320
1771
|
}
|
|
1321
1772
|
async createEncrypted(model, body, headers) {
|
|
1322
1773
|
const engine = await this.client._privateEngine();
|
|
@@ -1335,226 +1786,15 @@ var Rerank = class {
|
|
|
1335
1786
|
throw unsealedReplyError();
|
|
1336
1787
|
}
|
|
1337
1788
|
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
1338
|
-
|
|
1789
|
+
const result = JSON.parse(DECODER6.decode(plain));
|
|
1790
|
+
return withPlacement(result, response.headers, result.pendra, wrapper.pendra);
|
|
1339
1791
|
}
|
|
1340
1792
|
};
|
|
1341
1793
|
|
|
1342
1794
|
// src/version.ts
|
|
1343
|
-
var VERSION = "0.
|
|
1795
|
+
var VERSION = "0.17.0";
|
|
1344
1796
|
var USER_AGENT = `pendra-node/${VERSION}`;
|
|
1345
1797
|
|
|
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
1798
|
// src/client.ts
|
|
1559
1799
|
function envTruthy(v) {
|
|
1560
1800
|
if (!v) return false;
|