pendra 0.15.2 → 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/dist/index.js CHANGED
@@ -59,21 +59,23 @@ var APIConnectionError = class extends APIError {
59
59
  }
60
60
  };
61
61
  var APIStatusError = class extends APIError {
62
- constructor(message, status) {
62
+ constructor(message, status, options = {}) {
63
63
  super(message, status);
64
64
  this.name = "APIStatusError";
65
65
  this.status = status;
66
+ this.body = options.body;
67
+ this.detail = options.detail;
66
68
  }
67
69
  };
68
70
  var AuthenticationError = class extends APIStatusError {
69
- constructor(message = "Invalid API key \u2014 check your PENDRA_API_KEY") {
70
- super(message, 401);
71
+ constructor(message = "Invalid API key \u2014 check your PENDRA_API_KEY", options = {}) {
72
+ super(message, 401, options);
71
73
  this.name = "AuthenticationError";
72
74
  }
73
75
  };
74
76
  var RateLimitError = class extends APIStatusError {
75
- constructor(message = "Rate limit exceeded") {
76
- super(message, 429);
77
+ constructor(message = "Rate limit exceeded", options = {}) {
78
+ super(message, 429, options);
77
79
  this.name = "RateLimitError";
78
80
  }
79
81
  };
@@ -104,6 +106,80 @@ var APIStreamError = class extends APIError {
104
106
  this.workerName = options.workerName;
105
107
  }
106
108
  };
109
+ var LOC_SOURCES = /* @__PURE__ */ new Set(["body", "query", "path", "header", "cookie"]);
110
+ function isRecord(value) {
111
+ return typeof value === "object" && value !== null && !Array.isArray(value);
112
+ }
113
+ function nonEmptyString(value) {
114
+ return typeof value === "string" && value ? value : void 0;
115
+ }
116
+ function compactJson(value) {
117
+ try {
118
+ return JSON.stringify(value) ?? String(value);
119
+ } catch {
120
+ return String(value);
121
+ }
122
+ }
123
+ function messageFromItem(item) {
124
+ if (isRecord(item)) {
125
+ const msg = nonEmptyString(item.msg) ?? nonEmptyString(item.message);
126
+ if (msg) {
127
+ let field = typeof item.field === "string" ? item.field : void 0;
128
+ if (field === void 0) {
129
+ const loc = Array.isArray(item.loc) ? [...item.loc] : [];
130
+ if (loc.length && LOC_SOURCES.has(String(loc[0]))) loc.shift();
131
+ field = loc.map(String).join(".");
132
+ }
133
+ return field ? `${field}: ${msg}` : msg;
134
+ }
135
+ }
136
+ return messageFromDetail(item);
137
+ }
138
+ function messageFromDetail(detail) {
139
+ if (detail === void 0 || detail === null) return void 0;
140
+ if (typeof detail === "string") return detail || void 0;
141
+ if (Array.isArray(detail)) {
142
+ const parts = detail.map(messageFromItem).filter((p) => !!p);
143
+ return parts.length ? parts.join("; ") : void 0;
144
+ }
145
+ if (isRecord(detail)) {
146
+ const err = detail.error;
147
+ const nested = isRecord(err) ? nonEmptyString(err.message) : void 0;
148
+ const msg = nested ?? nonEmptyString(detail.message) ?? nonEmptyString(detail.msg);
149
+ if (msg) return msg;
150
+ return Object.keys(detail).length ? compactJson(detail) : void 0;
151
+ }
152
+ return compactJson(detail);
153
+ }
154
+ async function readErrorBody(response) {
155
+ let raw;
156
+ try {
157
+ raw = await response.text();
158
+ } catch {
159
+ return void 0;
160
+ }
161
+ if (!raw) return void 0;
162
+ try {
163
+ return JSON.parse(raw);
164
+ } catch {
165
+ return raw;
166
+ }
167
+ }
168
+ function statusErrorFromBody(status, body, fallback) {
169
+ const detail = isRecord(body) ? body.detail : void 0;
170
+ const err = isRecord(body) ? body.error : void 0;
171
+ let message = (isRecord(err) ? nonEmptyString(err.message) : void 0) ?? messageFromDetail(detail) ?? (isRecord(body) ? nonEmptyString(body.message) : void 0);
172
+ if (message === void 0) {
173
+ if (typeof body === "string") message = body || fallback;
174
+ else if (Array.isArray(body) ? body.length : isRecord(body) && Object.keys(body).length) {
175
+ message = compactJson(body);
176
+ } else message = fallback;
177
+ }
178
+ const options = { body, detail };
179
+ if (status === 401) return new AuthenticationError(message, options);
180
+ if (status === 429) return new RateLimitError(message, options);
181
+ return new APIStatusError(message, status, options);
182
+ }
107
183
 
108
184
  // src/_privateInference.ts
109
185
  var import_chacha2 = require("@noble/ciphers/chacha.js");
@@ -331,12 +407,23 @@ function sealRequest(orgPubs, body, opts) {
331
407
  }
332
408
  return { envelope, responseKeys };
333
409
  }
334
- var API_TIMING_CHUNK_KEYS = /* @__PURE__ */ new Set(["id", "object", "created", "model", "choices", "pendra"]);
335
- function isApiTimingChunk(frame) {
410
+ var API_TRAILER_CHUNK_KEYS = /* @__PURE__ */ new Set(["id", "object", "created", "model", "choices", "pendra"]);
411
+ var API_TRAILER_PENDRA_KEYS = /* @__PURE__ */ new Set(["timing", "worker", "request_id"]);
412
+ function isApiTrailerChunk(frame) {
336
413
  if (frame === null || typeof frame !== "object" || Array.isArray(frame)) return false;
337
414
  const obj = frame;
338
415
  const pendra = obj.pendra;
339
- 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;
416
+ 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)) {
417
+ return false;
418
+ }
419
+ const block = pendra;
420
+ const keys = Object.keys(block);
421
+ if (keys.length === 0 || !keys.every((k) => API_TRAILER_PENDRA_KEYS.has(k))) return false;
422
+ if ("worker" in block && (block.worker === null || typeof block.worker !== "object" || Array.isArray(block.worker))) {
423
+ return false;
424
+ }
425
+ if ("request_id" in block && typeof block.request_id !== "string") return false;
426
+ return true;
340
427
  }
341
428
  function unsealedReplyError() {
342
429
  return new Error(
@@ -474,6 +561,7 @@ function affinityKey(rawApiKey, model, messages, saltOverride) {
474
561
  const mac = import_hmac.hmac(import_sha2.sha256, salt, utf8(parts.join("\0")));
475
562
  return toHex(mac);
476
563
  }
564
+ var _internal = { b64, b64d, utf8, TEXT_DECODER };
477
565
 
478
566
  // src/_parsing.ts
479
567
  function asString(v) {
@@ -569,9 +657,10 @@ async function readSealedReply(response) {
569
657
  });
570
658
  }
571
659
  throwIfInBandError(parsed, "The server reported an error");
572
- const inner = typeof parsed === "object" && parsed !== null ? parsed.pendra_encrypted : void 0;
660
+ const wrapper = typeof parsed === "object" && parsed !== null ? parsed : void 0;
661
+ const inner = wrapper?.pendra_encrypted;
573
662
  if (!inner) throw unsealedReplyError();
574
- return inner;
663
+ return { inner, placement: wrapper.pendra };
575
664
  }
576
665
  function parseDecryptedJson(json, status) {
577
666
  try {
@@ -582,7 +671,393 @@ function parseDecryptedJson(json, status) {
582
671
  body: json
583
672
  });
584
673
  }
585
- }
674
+ }
675
+
676
+ // src/_placement.ts
677
+ var UTF8_EXT_PREFIX = "utf-8''";
678
+ function isPlainObject(v) {
679
+ return typeof v === "object" && v !== null && !Array.isArray(v);
680
+ }
681
+ function parseWorker(v) {
682
+ if (!isPlainObject(v) || typeof v.id !== "string" || !v.id) return void 0;
683
+ return {
684
+ id: v.id,
685
+ name: typeof v.name === "string" && v.name ? v.name : null,
686
+ version: typeof v.version === "string" && v.version ? v.version : null
687
+ };
688
+ }
689
+ function placementFromBlock(block) {
690
+ if (!isPlainObject(block)) return void 0;
691
+ const worker = parseWorker(block.worker);
692
+ if (!worker) return void 0;
693
+ const requestId = block.request_id;
694
+ return typeof requestId === "string" && requestId ? { worker, request_id: requestId } : { worker };
695
+ }
696
+ function decodeWorkerNameHeader(raw) {
697
+ if (raw.slice(0, UTF8_EXT_PREFIX.length).toLowerCase() !== UTF8_EXT_PREFIX) return raw;
698
+ try {
699
+ return decodeURIComponent(raw.slice(UTF8_EXT_PREFIX.length));
700
+ } catch {
701
+ return raw;
702
+ }
703
+ }
704
+ function header(headers, name) {
705
+ if (!headers || typeof headers.get !== "function") return void 0;
706
+ return headers.get(name) || void 0;
707
+ }
708
+ function placementFromHeaders(headers) {
709
+ const id = header(headers, "X-Worker-Id");
710
+ if (!id) return void 0;
711
+ const rawName = header(headers, "X-Worker-Name");
712
+ const requestId = header(headers, "X-Request-Id");
713
+ const worker = {
714
+ id,
715
+ name: rawName ? decodeWorkerNameHeader(rawName) : null,
716
+ version: null
717
+ };
718
+ return requestId ? { worker, request_id: requestId } : { worker };
719
+ }
720
+ function sanitise(block) {
721
+ if ("worker" in block && block.worker !== null) {
722
+ const worker = parseWorker(block.worker);
723
+ if (worker) block.worker = worker;
724
+ else delete block.worker;
725
+ }
726
+ if ("request_id" in block && block.request_id !== null && typeof block.request_id !== "string") {
727
+ delete block.request_id;
728
+ }
729
+ }
730
+ function withPlacement(result, headers, ...blocks) {
731
+ if (!isPlainObject(result)) return result;
732
+ const own = isPlainObject(result.pendra) ? result.pendra : void 0;
733
+ if (own) sanitise(own);
734
+ let placement;
735
+ for (const block of blocks) {
736
+ placement = placementFromBlock(block);
737
+ if (placement) break;
738
+ }
739
+ placement ?? (placement = placementFromHeaders(headers));
740
+ if (!placement) return result;
741
+ const merged = { ...own ?? {}, worker: placement.worker };
742
+ if (placement.request_id) merged.request_id = placement.request_id;
743
+ else delete merged.request_id;
744
+ result.pendra = merged;
745
+ return result;
746
+ }
747
+ function chunkPlacement(chunk) {
748
+ const block = chunk.pendra;
749
+ if (!isPlainObject(block)) return {};
750
+ sanitise(block);
751
+ const worker = block.worker;
752
+ const requestId = block.request_id;
753
+ return { worker: worker ?? void 0, requestId: requestId || void 0 };
754
+ }
755
+ var PLACEMENT_OPT_IN_HEADER = "X-Pendra-Placement";
756
+
757
+ // src/_privateInferenceEngine.ts
758
+ var PrivateInferenceError = class extends Error {
759
+ constructor(message) {
760
+ super(message);
761
+ this.name = "PrivateInferenceError";
762
+ }
763
+ };
764
+ var FINGERPRINT_RE = /^[0-9a-f]{64}$/;
765
+ function parsePinnedFingerprints(pin) {
766
+ if (typeof pin !== "string") {
767
+ throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);
768
+ }
769
+ const fps = pin.split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
770
+ if (fps.length === 0) {
771
+ throw new PrivateInferenceError(
772
+ "pinnedFingerprint was set but contains no fingerprint. Pass the 64-character fingerprint shown in the console, or leave it unset to use automatic trust."
773
+ );
774
+ }
775
+ const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();
776
+ if (bad.length > 0) {
777
+ throw new PrivateInferenceError(
778
+ `pinnedFingerprint "${bad[0]}" is not a valid fingerprint: expected 64 hexadecimal characters, as shown in the console.`
779
+ );
780
+ }
781
+ return new Set(fps);
782
+ }
783
+ function defaultTofuPath() {
784
+ const env = typeof process !== "undefined" ? process.env : void 0;
785
+ if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
786
+ const home = env?.HOME || env?.USERPROFILE || ".";
787
+ return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
788
+ }
789
+ function b64d2(s) {
790
+ if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
791
+ const binary = atob(s);
792
+ const out = new Uint8Array(binary.length);
793
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
794
+ return out;
795
+ }
796
+ var PrivateInferenceEngine = class {
797
+ constructor(opts) {
798
+ this.orgPubs = null;
799
+ this.baseUrl = opts.baseUrl.replace(/\/$/, "");
800
+ this.apiKey = opts.apiKey;
801
+ const pin = opts.pinnedFingerprint;
802
+ this.pinnedFingerprints = pin === null || pin === void 0 ? null : parsePinnedFingerprints(pin);
803
+ this.affinitySalt = opts.affinitySalt ?? null;
804
+ this.tofuPath = opts.tofuPath || defaultTofuPath();
805
+ }
806
+ // --- key resolution ---
807
+ cachedOrgPublicKeys() {
808
+ return this.orgPubs;
809
+ }
810
+ cachedOrgPublicKey() {
811
+ return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;
812
+ }
813
+ tofuIdentity() {
814
+ const digest = sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);
815
+ return `${this.baseUrl}|${digest}`;
816
+ }
817
+ /**
818
+ * Drop the cached key set so the next call re-fetches it.
819
+ *
820
+ * The cache is otherwise held for the whole process lifetime, which is
821
+ * correct while a fleet keeps one key but fatal when it re-keys: a
822
+ * long-running server would go on sealing to a fingerprint no worker holds
823
+ * and fail EVERY request until someone restarted it. The API signals a re-key
824
+ * with `X-Pendra-Error-Code: no_private_inference_worker`, and this is what
825
+ * lets the client recover on its own.
826
+ *
827
+ * Pinned clients are deliberately NOT re-fetched on that signal — a pin is an
828
+ * allowlist, so a fetch could only return fingerprints the pin already
829
+ * rejects. They surface the error instead, which is what pinning means.
830
+ */
831
+ invalidateOrgKey() {
832
+ this.orgPubs = null;
833
+ }
834
+ /** Whether this client seals only to an explicit fingerprint allowlist. */
835
+ get isPinned() {
836
+ return this.pinnedFingerprints !== null;
837
+ }
838
+ /**
839
+ * Validate the key(s) returned by GET /v1/private-inference/key, apply the pin
840
+ * allowlist (or auto-trust TOFU), cache the accepted public keys, and return
841
+ * them (newest-seen first). The client seals to **all** of the returned keys
842
+ * so any worker holding any of them can serve the request. Throws
843
+ * PrivateInferenceError on absence, a malformed key, or (when pinned) an empty
844
+ * intersection with the pin set.
845
+ */
846
+ async resolveOrgKey(fetchedKeys) {
847
+ if (this.orgPubs !== null) return this.orgPubs;
848
+ if (!fetchedKeys || fetchedKeys.length === 0) {
849
+ throw new PrivateInferenceError(
850
+ "No encryption key is registered for this organisation. Start a worker and it will be issued one automatically."
851
+ );
852
+ }
853
+ const pubs = [];
854
+ const fps = [];
855
+ for (const entry of fetchedKeys) {
856
+ let pub;
857
+ try {
858
+ pub = b64d2(entry.public_key);
859
+ } catch (e) {
860
+ throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
861
+ }
862
+ if (pub.length !== 32) {
863
+ throw new PrivateInferenceError(
864
+ `Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`
865
+ );
866
+ }
867
+ pubs.push(pub);
868
+ fps.push(fingerprint(pub));
869
+ }
870
+ let accepted;
871
+ if (this.pinnedFingerprints !== null) {
872
+ accepted = pubs.filter((_p, i) => this.pinnedFingerprints.has(fps[i]));
873
+ if (accepted.length === 0) {
874
+ const pinned = Array.from(this.pinnedFingerprints).sort().join(", ");
875
+ throw new PrivateInferenceError(
876
+ `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.`
877
+ );
878
+ }
879
+ } else {
880
+ await this.tofuTrust(fps);
881
+ accepted = pubs;
882
+ }
883
+ this.orgPubs = accepted;
884
+ return accepted;
885
+ }
886
+ async tofuTrust(fps) {
887
+ const store = await this.loadTofu();
888
+ const identity = this.tofuIdentity();
889
+ const known = store[identity];
890
+ const trusted = /* @__PURE__ */ new Set();
891
+ if (typeof known === "string") {
892
+ trusted.add(known);
893
+ } else if (Array.isArray(known)) {
894
+ for (const f of known) if (typeof f === "string") trusted.add(f);
895
+ }
896
+ const before = trusted.size;
897
+ for (const f of fps) trusted.add(f);
898
+ if (trusted.size !== before || !Array.isArray(known)) {
899
+ store[identity] = Array.from(trusted).sort();
900
+ await this.saveTofu(store);
901
+ }
902
+ }
903
+ async loadTofu() {
904
+ try {
905
+ const fs = await import("fs");
906
+ const raw = fs.readFileSync(this.tofuPath, "utf-8");
907
+ const data = JSON.parse(raw);
908
+ return data && typeof data === "object" && !Array.isArray(data) ? data : {};
909
+ } catch {
910
+ return {};
911
+ }
912
+ }
913
+ async saveTofu(store) {
914
+ const fs = await import("fs");
915
+ const path = await import("path");
916
+ const directory = path.dirname(this.tofuPath) || ".";
917
+ fs.mkdirSync(directory, { recursive: true });
918
+ const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);
919
+ try {
920
+ fs.writeFileSync(tmp, JSON.stringify(store), { mode: 384 });
921
+ try {
922
+ fs.chmodSync(tmp, 384);
923
+ } catch {
924
+ }
925
+ fs.renameSync(tmp, this.tofuPath);
926
+ } catch (e) {
927
+ try {
928
+ fs.unlinkSync(tmp);
929
+ } catch {
930
+ }
931
+ throw e;
932
+ }
933
+ }
934
+ // --- sealing ---
935
+ /**
936
+ * Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
937
+ * `messages` (chat only) drives the affinity token; pass undefined for non-chat.
938
+ * `binary` (audio only) is sealed under the same data key as the body.
939
+ */
940
+ seal(args) {
941
+ if (this.orgPubs === null || this.orgPubs.length === 0) {
942
+ throw new PrivateInferenceError(
943
+ "private inference: org key not resolved yet (call resolveOrgKey first)"
944
+ );
945
+ }
946
+ let affinity = null;
947
+ if (args.messages != null) {
948
+ affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
949
+ }
950
+ const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
951
+ model: args.model,
952
+ stream: args.stream,
953
+ taskType: args.taskType,
954
+ affinityKey: affinity,
955
+ binary: args.binary ?? null
956
+ });
957
+ const topLevel = {
958
+ model: args.model,
959
+ stream: args.stream,
960
+ pendra_encrypted: envelope
961
+ };
962
+ return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
963
+ }
964
+ get keyFetchUrl() {
965
+ return `${this.baseUrl}/v1/private-inference/key`;
966
+ }
967
+ };
968
+
969
+ // src/resources/audio/speech.ts
970
+ var BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
971
+ function decodeAudio(value) {
972
+ if (typeof value !== "string") return void 0;
973
+ const s = value.replace(/\s+/g, "");
974
+ if (!s || !BASE64_RE.test(s) || s.replace(/=+$/, "").length % 4 === 1) return void 0;
975
+ if (s.includes("=") && s.length % 4 !== 0) return void 0;
976
+ let bytes2;
977
+ try {
978
+ bytes2 = _internal.b64d(s);
979
+ } catch {
980
+ return void 0;
981
+ }
982
+ return bytes2.length > 0 ? bytes2 : void 0;
983
+ }
984
+ function isRecord2(v) {
985
+ return typeof v === "object" && v !== null && !Array.isArray(v);
986
+ }
987
+ var Speech = class {
988
+ constructor(client) {
989
+ this.client = client;
990
+ }
991
+ /**
992
+ * Turn text into spoken audio (OpenAI-compatible).
993
+ *
994
+ * @example
995
+ * ```ts
996
+ * import { writeFileSync } from "node:fs";
997
+ *
998
+ * const speech = await client.audio.speech.create({
999
+ * model: "qwen3-tts",
1000
+ * input: "Hello from Pendra.",
1001
+ * });
1002
+ * writeFileSync("speech.wav", speech.audio);
1003
+ * ```
1004
+ */
1005
+ async create(params) {
1006
+ if (!params.model || typeof params.model !== "string") {
1007
+ throw new Error("model must be a non-empty string");
1008
+ }
1009
+ if (typeof params.input !== "string" || !params.input.trim()) {
1010
+ throw new Error("input must be a non-empty string");
1011
+ }
1012
+ if (this.client.privateInferenceEnabled) {
1013
+ throw new PrivateInferenceError("Private inference does not support speech synthesis yet.");
1014
+ }
1015
+ const body = { model: params.model, input: params.input };
1016
+ if (params.voice != null) body.voice = params.voice;
1017
+ if (params.response_format != null) body.response_format = params.response_format;
1018
+ const headers = { Accept: "application/json" };
1019
+ if (params.worker_id) headers["X-Pendra-Worker-Id"] = params.worker_id;
1020
+ const timeout = Math.max(this.client.timeout ?? 0, 3e5);
1021
+ const { response } = await this.client._fetch("/api/v1/audio/speech", {
1022
+ method: "POST",
1023
+ body,
1024
+ headers,
1025
+ timeout
1026
+ });
1027
+ const text = await response.text();
1028
+ let parsed;
1029
+ try {
1030
+ parsed = JSON.parse(text);
1031
+ } catch {
1032
+ throw new APIResponseValidationError("Response was not valid JSON", {
1033
+ status: response.status,
1034
+ body: text
1035
+ });
1036
+ }
1037
+ throwIfInBandError(parsed, "The server reported an error");
1038
+ if (!isRecord2(parsed)) {
1039
+ throw new APIResponseValidationError("Response was not a speech result", {
1040
+ status: response.status,
1041
+ body: text
1042
+ });
1043
+ }
1044
+ const audio = decodeAudio(parsed.audio);
1045
+ if (!audio) {
1046
+ throw new APIResponseValidationError("Response did not contain decodable audio", {
1047
+ status: response.status,
1048
+ body: text
1049
+ });
1050
+ }
1051
+ const result = {
1052
+ audio,
1053
+ format: typeof parsed.format === "string" && parsed.format ? parsed.format : params.response_format ?? "wav",
1054
+ duration_ms: typeof parsed.duration_ms === "number" && Number.isFinite(parsed.duration_ms) ? parsed.duration_ms : null,
1055
+ arrayBuffer: async () => audio.slice().buffer
1056
+ };
1057
+ if (isRecord2(parsed.pendra)) result.pendra = parsed.pendra;
1058
+ return withPlacement(result, response.headers, result.pendra);
1059
+ }
1060
+ };
586
1061
 
587
1062
  // src/resources/audio/transcriptions.ts
588
1063
  var ENCODER = new TextEncoder();
@@ -620,21 +1095,6 @@ function asBlob(file) {
620
1095
  }
621
1096
  return { blob: new Blob([content]), filename };
622
1097
  }
623
- async function extractErrorDetail(response) {
624
- let raw = "";
625
- try {
626
- raw = await response.text();
627
- } catch {
628
- return response.statusText;
629
- }
630
- if (!raw) return response.statusText;
631
- try {
632
- const body = JSON.parse(raw);
633
- return body.detail ?? body.error?.message ?? raw;
634
- } catch {
635
- return raw;
636
- }
637
- }
638
1098
  var Transcriptions = class {
639
1099
  constructor(client) {
640
1100
  this.client = client;
@@ -692,21 +1152,16 @@ var Transcriptions = class {
692
1152
  }
693
1153
  clearTimeout(timeoutId);
694
1154
  if (response.status >= 400) {
695
- const detail = await extractErrorDetail(response);
696
- if (response.status === 401) {
697
- throw new AuthenticationError(detail);
698
- }
699
- if (response.status === 429) {
700
- throw new RateLimitError(detail);
701
- }
702
- throw new APIStatusError(detail, response.status);
1155
+ const body = await readErrorBody(response);
1156
+ throw statusErrorFromBody(response.status, body, response.statusText);
703
1157
  }
704
1158
  const format = params.response_format;
705
1159
  if (format === "text" || format === "srt" || format === "vtt") {
706
1160
  const text = await response.text();
707
- return { text };
1161
+ return withPlacement({ text }, response.headers);
708
1162
  }
709
- return await response.json();
1163
+ const result = await response.json();
1164
+ return withPlacement(result, response.headers, result.pendra);
710
1165
  }
711
1166
  /**
712
1167
  * Private-inference transcription. There is no multipart upload: the audio
@@ -741,9 +1196,11 @@ var Transcriptions = class {
741
1196
  timeout
742
1197
  }
743
1198
  );
744
- const raw = DECODER.decode(decryptor.openResult(await readSealedReply(response)));
1199
+ const { inner, placement } = await readSealedReply(response);
1200
+ const raw = DECODER.decode(decryptor.openResult(inner));
745
1201
  const parsed = parseDecryptedJson(raw, response.status);
746
- if (typeof parsed === "string") return { text: parsed };
1202
+ const place = (r) => withPlacement(r, response.headers, r.pendra, placement);
1203
+ if (typeof parsed === "string") return place({ text: parsed });
747
1204
  if (typeof parsed === "object" && parsed !== null) {
748
1205
  if (typeof parsed.text !== "string") {
749
1206
  throw new APIResponseValidationError("Decrypted response was not a transcription", {
@@ -751,9 +1208,9 @@ var Transcriptions = class {
751
1208
  body: raw
752
1209
  });
753
1210
  }
754
- return parsed;
1211
+ return place(parsed);
755
1212
  }
756
- return { text: raw };
1213
+ return place({ text: raw });
757
1214
  }
758
1215
  };
759
1216
 
@@ -761,6 +1218,7 @@ var Transcriptions = class {
761
1218
  var Audio = class {
762
1219
  constructor(client) {
763
1220
  this.transcriptions = new Transcriptions(client);
1221
+ this.speech = new Speech(client);
764
1222
  }
765
1223
  };
766
1224
 
@@ -837,6 +1295,7 @@ var Stream = class {
837
1295
  this.decoder = new TextDecoder();
838
1296
  this.sse = new SseDecoder();
839
1297
  this.done = false;
1298
+ this.placement = new PlacementTracker();
840
1299
  if (!response.body) {
841
1300
  throw new Error("Response body is null \u2014 streaming not supported");
842
1301
  }
@@ -857,7 +1316,7 @@ var Stream = class {
857
1316
  this.done = true;
858
1317
  return;
859
1318
  }
860
- yield parseStreamFrame(data);
1319
+ yield this.placement.observe(parseStreamFrame(data));
861
1320
  }
862
1321
  if (readerDone) {
863
1322
  this.done = true;
@@ -868,11 +1327,39 @@ var Stream = class {
868
1327
  releaseReader(this.reader, this.controller, this.done);
869
1328
  }
870
1329
  }
1330
+ /**
1331
+ * The worker that served this stream, or `null` until the chunk reporting it
1332
+ * — the trailer, just before `[DONE]` — has been iterated (and on an API too
1333
+ * old to report it). Same as that chunk's `pendra.worker`.
1334
+ */
1335
+ get worker() {
1336
+ return this.placement.worker;
1337
+ }
1338
+ /**
1339
+ * Pendra's id for this request, reported alongside {@link Stream.worker};
1340
+ * `null` until then.
1341
+ */
1342
+ get requestId() {
1343
+ return this.placement.requestId;
1344
+ }
871
1345
  abort() {
872
1346
  this.done = true;
873
1347
  this.controller.abort();
874
1348
  }
875
1349
  };
1350
+ var PlacementTracker = class {
1351
+ constructor() {
1352
+ this.worker = null;
1353
+ this.requestId = null;
1354
+ }
1355
+ /** Record `chunk`'s placement, if it carries any, and hand it back. */
1356
+ observe(chunk) {
1357
+ const { worker, requestId } = chunkPlacement(chunk);
1358
+ if (worker) this.worker = worker;
1359
+ if (requestId) this.requestId = requestId;
1360
+ return chunk;
1361
+ }
1362
+ };
876
1363
  async function readWithIdleTimeout(reader, idleTimeoutMs) {
877
1364
  if (!idleTimeoutMs) return reader.read();
878
1365
  let timer;
@@ -908,6 +1395,7 @@ var EncryptedStream = class {
908
1395
  this.openedAny = false;
909
1396
  this.declared = false;
910
1397
  this.terminated = false;
1398
+ this.placement = new PlacementTracker();
911
1399
  if (!response.body) {
912
1400
  throw new Error("Response body is null \u2014 streaming not supported");
913
1401
  }
@@ -949,9 +1437,9 @@ var EncryptedStream = class {
949
1437
  }
950
1438
  const inner = frame?.pendra_encrypted;
951
1439
  if (!inner) {
952
- if (isApiTimingChunk(frame)) {
1440
+ if (isApiTrailerChunk(frame)) {
953
1441
  this.checkEnded();
954
- yield parseStreamFrame(data);
1442
+ yield this.placement.observe(parseStreamFrame(data));
955
1443
  continue;
956
1444
  }
957
1445
  parseStreamFrame(data);
@@ -979,7 +1467,7 @@ var EncryptedStream = class {
979
1467
  return;
980
1468
  }
981
1469
  if (!chunkJson) continue;
982
- yield parseStreamFrame(chunkJson, "Decrypted stream frame");
1470
+ yield this.placement.observe(parseStreamFrame(chunkJson, "Decrypted stream frame"));
983
1471
  }
984
1472
  if (readerDone) {
985
1473
  this.checkEnded();
@@ -1001,6 +1489,14 @@ var EncryptedStream = class {
1001
1489
  throw truncatedStreamError();
1002
1490
  }
1003
1491
  }
1492
+ /** Same as `Stream.worker`: set once the trailer chunk has been iterated. */
1493
+ get worker() {
1494
+ return this.placement.worker;
1495
+ }
1496
+ /** Same as `Stream.requestId`. */
1497
+ get requestId() {
1498
+ return this.placement.requestId;
1499
+ }
1004
1500
  abort() {
1005
1501
  this.aborted = true;
1006
1502
  this.done = true;
@@ -1021,7 +1517,9 @@ var Completions = class {
1021
1517
  for (const [key, value] of Object.entries(rest)) {
1022
1518
  if (value != null) body[key] = value;
1023
1519
  }
1024
- const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
1520
+ const headers = {};
1521
+ if (params.worker_id) headers["X-Pendra-Worker-Id"] = params.worker_id;
1522
+ if (params.stream) headers[PLACEMENT_OPT_IN_HEADER] = "1";
1025
1523
  if (this.client.privateInferenceEnabled) {
1026
1524
  return this.createEncrypted(params, body, headers);
1027
1525
  }
@@ -1036,7 +1534,8 @@ var Completions = class {
1036
1534
  "/api/v1/chat/completions",
1037
1535
  { method: "POST", body, headers }
1038
1536
  );
1039
- return parseCompletion(response);
1537
+ const completion = await parseCompletion(response);
1538
+ return withPlacement(completion, response.headers, completion.pendra);
1040
1539
  }
1041
1540
  async createEncrypted(params, body, headers) {
1042
1541
  const engine = await this.client._privateEngine();
@@ -1076,7 +1575,8 @@ var Completions = class {
1076
1575
  throw unsealedReplyError();
1077
1576
  }
1078
1577
  const plain = decryptor.openResult(wrapper.pendra_encrypted);
1079
- return parseDecryptedCompletion(DECODER3.decode(plain), response.status);
1578
+ const completion = parseDecryptedCompletion(DECODER3.decode(plain), response.status);
1579
+ return withPlacement(completion, response.headers, completion.pendra, wrapper.pendra);
1080
1580
  }
1081
1581
  };
1082
1582
 
@@ -1145,7 +1645,8 @@ var Embeddings = class {
1145
1645
  "/api/v1/embeddings",
1146
1646
  { method: "POST", body, headers }
1147
1647
  );
1148
- return await response.json();
1648
+ const result = await response.json();
1649
+ return withPlacement(result, response.headers, result.pendra);
1149
1650
  }
1150
1651
  async createEncrypted(model, body, headers) {
1151
1652
  const engine = await this.client._privateEngine();
@@ -1164,7 +1665,8 @@ var Embeddings = class {
1164
1665
  throw unsealedReplyError();
1165
1666
  }
1166
1667
  const plain = decryptor.openResult(wrapper.pendra_encrypted);
1167
- return JSON.parse(DECODER4.decode(plain));
1668
+ const result = JSON.parse(DECODER4.decode(plain));
1669
+ return withPlacement(result, response.headers, result.pendra, wrapper.pendra);
1168
1670
  }
1169
1671
  };
1170
1672
 
@@ -1207,7 +1709,8 @@ var Generations = class {
1207
1709
  "/api/v1/images/generations",
1208
1710
  { method: "POST", body, headers }
1209
1711
  );
1210
- return await response.json();
1712
+ const result = await response.json();
1713
+ return withPlacement(result, response.headers, result.pendra);
1211
1714
  }
1212
1715
  async createEncrypted(model, body, headers) {
1213
1716
  const engine = await this.client._privateEngine();
@@ -1221,7 +1724,8 @@ var Generations = class {
1221
1724
  "/api/v1/images/generations",
1222
1725
  { method: "POST", body: topLevel, headers }
1223
1726
  );
1224
- const plain = decryptor.openResult(await readSealedReply(response));
1727
+ const { inner, placement } = await readSealedReply(response);
1728
+ const plain = decryptor.openResult(inner);
1225
1729
  const parsed = parseDecryptedJson(DECODER5.decode(plain), response.status);
1226
1730
  if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.data)) {
1227
1731
  throw new APIResponseValidationError("Decrypted response was not an image generation", {
@@ -1229,7 +1733,8 @@ var Generations = class {
1229
1733
  body: DECODER5.decode(plain)
1230
1734
  });
1231
1735
  }
1232
- return parsed;
1736
+ const result = parsed;
1737
+ return withPlacement(result, response.headers, result.pendra, placement);
1233
1738
  }
1234
1739
  };
1235
1740
 
@@ -1307,7 +1812,8 @@ var Rerank = class {
1307
1812
  "/api/v1/rerank",
1308
1813
  { method: "POST", body, headers }
1309
1814
  );
1310
- return await response.json();
1815
+ const result = await response.json();
1816
+ return withPlacement(result, response.headers, result.pendra);
1311
1817
  }
1312
1818
  async createEncrypted(model, body, headers) {
1313
1819
  const engine = await this.client._privateEngine();
@@ -1326,226 +1832,15 @@ var Rerank = class {
1326
1832
  throw unsealedReplyError();
1327
1833
  }
1328
1834
  const plain = decryptor.openResult(wrapper.pendra_encrypted);
1329
- return JSON.parse(DECODER6.decode(plain));
1835
+ const result = JSON.parse(DECODER6.decode(plain));
1836
+ return withPlacement(result, response.headers, result.pendra, wrapper.pendra);
1330
1837
  }
1331
1838
  };
1332
1839
 
1333
1840
  // src/version.ts
1334
- var VERSION = "0.15.2";
1841
+ var VERSION = "0.17.0";
1335
1842
  var USER_AGENT = `pendra-node/${VERSION}`;
1336
1843
 
1337
- // src/_privateInferenceEngine.ts
1338
- var PrivateInferenceError = class extends Error {
1339
- constructor(message) {
1340
- super(message);
1341
- this.name = "PrivateInferenceError";
1342
- }
1343
- };
1344
- var FINGERPRINT_RE = /^[0-9a-f]{64}$/;
1345
- function parsePinnedFingerprints(pin) {
1346
- if (typeof pin !== "string") {
1347
- throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);
1348
- }
1349
- const fps = pin.split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
1350
- if (fps.length === 0) {
1351
- throw new PrivateInferenceError(
1352
- "pinnedFingerprint was set but contains no fingerprint. Pass the 64-character fingerprint shown in the console, or leave it unset to use automatic trust."
1353
- );
1354
- }
1355
- const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();
1356
- if (bad.length > 0) {
1357
- throw new PrivateInferenceError(
1358
- `pinnedFingerprint "${bad[0]}" is not a valid fingerprint: expected 64 hexadecimal characters, as shown in the console.`
1359
- );
1360
- }
1361
- return new Set(fps);
1362
- }
1363
- function defaultTofuPath() {
1364
- const env = typeof process !== "undefined" ? process.env : void 0;
1365
- if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
1366
- const home = env?.HOME || env?.USERPROFILE || ".";
1367
- return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
1368
- }
1369
- function b64d2(s) {
1370
- if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
1371
- const binary = atob(s);
1372
- const out = new Uint8Array(binary.length);
1373
- for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
1374
- return out;
1375
- }
1376
- var PrivateInferenceEngine = class {
1377
- constructor(opts) {
1378
- this.orgPubs = null;
1379
- this.baseUrl = opts.baseUrl.replace(/\/$/, "");
1380
- this.apiKey = opts.apiKey;
1381
- const pin = opts.pinnedFingerprint;
1382
- this.pinnedFingerprints = pin === null || pin === void 0 ? null : parsePinnedFingerprints(pin);
1383
- this.affinitySalt = opts.affinitySalt ?? null;
1384
- this.tofuPath = opts.tofuPath || defaultTofuPath();
1385
- }
1386
- // --- key resolution ---
1387
- cachedOrgPublicKeys() {
1388
- return this.orgPubs;
1389
- }
1390
- cachedOrgPublicKey() {
1391
- return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;
1392
- }
1393
- tofuIdentity() {
1394
- const digest = sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);
1395
- return `${this.baseUrl}|${digest}`;
1396
- }
1397
- /**
1398
- * Drop the cached key set so the next call re-fetches it.
1399
- *
1400
- * The cache is otherwise held for the whole process lifetime, which is
1401
- * correct while a fleet keeps one key but fatal when it re-keys: a
1402
- * long-running server would go on sealing to a fingerprint no worker holds
1403
- * and fail EVERY request until someone restarted it. The API signals a re-key
1404
- * with `X-Pendra-Error-Code: no_private_inference_worker`, and this is what
1405
- * lets the client recover on its own.
1406
- *
1407
- * Pinned clients are deliberately NOT re-fetched on that signal — a pin is an
1408
- * allowlist, so a fetch could only return fingerprints the pin already
1409
- * rejects. They surface the error instead, which is what pinning means.
1410
- */
1411
- invalidateOrgKey() {
1412
- this.orgPubs = null;
1413
- }
1414
- /** Whether this client seals only to an explicit fingerprint allowlist. */
1415
- get isPinned() {
1416
- return this.pinnedFingerprints !== null;
1417
- }
1418
- /**
1419
- * Validate the key(s) returned by GET /v1/private-inference/key, apply the pin
1420
- * allowlist (or auto-trust TOFU), cache the accepted public keys, and return
1421
- * them (newest-seen first). The client seals to **all** of the returned keys
1422
- * so any worker holding any of them can serve the request. Throws
1423
- * PrivateInferenceError on absence, a malformed key, or (when pinned) an empty
1424
- * intersection with the pin set.
1425
- */
1426
- async resolveOrgKey(fetchedKeys) {
1427
- if (this.orgPubs !== null) return this.orgPubs;
1428
- if (!fetchedKeys || fetchedKeys.length === 0) {
1429
- throw new PrivateInferenceError(
1430
- "No encryption key is registered for this organisation. Start a worker and it will be issued one automatically."
1431
- );
1432
- }
1433
- const pubs = [];
1434
- const fps = [];
1435
- for (const entry of fetchedKeys) {
1436
- let pub;
1437
- try {
1438
- pub = b64d2(entry.public_key);
1439
- } catch (e) {
1440
- throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
1441
- }
1442
- if (pub.length !== 32) {
1443
- throw new PrivateInferenceError(
1444
- `Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`
1445
- );
1446
- }
1447
- pubs.push(pub);
1448
- fps.push(fingerprint(pub));
1449
- }
1450
- let accepted;
1451
- if (this.pinnedFingerprints !== null) {
1452
- accepted = pubs.filter((_p, i) => this.pinnedFingerprints.has(fps[i]));
1453
- if (accepted.length === 0) {
1454
- const pinned = Array.from(this.pinnedFingerprints).sort().join(", ");
1455
- throw new PrivateInferenceError(
1456
- `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.`
1457
- );
1458
- }
1459
- } else {
1460
- await this.tofuTrust(fps);
1461
- accepted = pubs;
1462
- }
1463
- this.orgPubs = accepted;
1464
- return accepted;
1465
- }
1466
- async tofuTrust(fps) {
1467
- const store = await this.loadTofu();
1468
- const identity = this.tofuIdentity();
1469
- const known = store[identity];
1470
- const trusted = /* @__PURE__ */ new Set();
1471
- if (typeof known === "string") {
1472
- trusted.add(known);
1473
- } else if (Array.isArray(known)) {
1474
- for (const f of known) if (typeof f === "string") trusted.add(f);
1475
- }
1476
- const before = trusted.size;
1477
- for (const f of fps) trusted.add(f);
1478
- if (trusted.size !== before || !Array.isArray(known)) {
1479
- store[identity] = Array.from(trusted).sort();
1480
- await this.saveTofu(store);
1481
- }
1482
- }
1483
- async loadTofu() {
1484
- try {
1485
- const fs = await import("fs");
1486
- const raw = fs.readFileSync(this.tofuPath, "utf-8");
1487
- const data = JSON.parse(raw);
1488
- return data && typeof data === "object" && !Array.isArray(data) ? data : {};
1489
- } catch {
1490
- return {};
1491
- }
1492
- }
1493
- async saveTofu(store) {
1494
- const fs = await import("fs");
1495
- const path = await import("path");
1496
- const directory = path.dirname(this.tofuPath) || ".";
1497
- fs.mkdirSync(directory, { recursive: true });
1498
- const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);
1499
- try {
1500
- fs.writeFileSync(tmp, JSON.stringify(store), { mode: 384 });
1501
- try {
1502
- fs.chmodSync(tmp, 384);
1503
- } catch {
1504
- }
1505
- fs.renameSync(tmp, this.tofuPath);
1506
- } catch (e) {
1507
- try {
1508
- fs.unlinkSync(tmp);
1509
- } catch {
1510
- }
1511
- throw e;
1512
- }
1513
- }
1514
- // --- sealing ---
1515
- /**
1516
- * Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
1517
- * `messages` (chat only) drives the affinity token; pass undefined for non-chat.
1518
- * `binary` (audio only) is sealed under the same data key as the body.
1519
- */
1520
- seal(args) {
1521
- if (this.orgPubs === null || this.orgPubs.length === 0) {
1522
- throw new PrivateInferenceError(
1523
- "private inference: org key not resolved yet (call resolveOrgKey first)"
1524
- );
1525
- }
1526
- let affinity = null;
1527
- if (args.messages != null) {
1528
- affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
1529
- }
1530
- const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
1531
- model: args.model,
1532
- stream: args.stream,
1533
- taskType: args.taskType,
1534
- affinityKey: affinity,
1535
- binary: args.binary ?? null
1536
- });
1537
- const topLevel = {
1538
- model: args.model,
1539
- stream: args.stream,
1540
- pendra_encrypted: envelope
1541
- };
1542
- return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
1543
- }
1544
- get keyFetchUrl() {
1545
- return `${this.baseUrl}/v1/private-inference/key`;
1546
- }
1547
- };
1548
-
1549
1844
  // src/client.ts
1550
1845
  function envTruthy(v) {
1551
1846
  if (!v) return false;
@@ -1655,19 +1950,7 @@ var Pendra = class {
1655
1950
  );
1656
1951
  }
1657
1952
  if (!response.ok) {
1658
- let message;
1659
- try {
1660
- const body = await response.json();
1661
- if (typeof body.detail === "string") message = body.detail;
1662
- else if (typeof body.error?.message === "string") message = body.error.message;
1663
- else if (body.detail != null) message = JSON.stringify(body.detail);
1664
- else message = response.statusText;
1665
- } catch {
1666
- message = response.statusText;
1667
- }
1668
- if (response.status === 401) throw new AuthenticationError(message);
1669
- if (response.status === 429) throw new RateLimitError(message);
1670
- throw new APIStatusError(message, response.status);
1953
+ throw statusErrorFromBody(response.status, await readErrorBody(response), response.statusText);
1671
1954
  }
1672
1955
  const json = await response.json();
1673
1956
  await engine.resolveOrgKey(json.keys ?? []);
@@ -1705,19 +1988,7 @@ var Pendra = class {
1705
1988
  clearTimeout(timeoutId);
1706
1989
  if (!response.ok) {
1707
1990
  this.invalidateKeyCacheIfRekeyed(response);
1708
- let message;
1709
- try {
1710
- const body = await response.json();
1711
- if (typeof body.detail === "string") message = body.detail;
1712
- else if (typeof body.error?.message === "string") message = body.error.message;
1713
- else if (body.detail != null) message = JSON.stringify(body.detail);
1714
- else message = response.statusText;
1715
- } catch {
1716
- message = response.statusText;
1717
- }
1718
- if (response.status === 401) throw new AuthenticationError(message);
1719
- if (response.status === 429) throw new RateLimitError(message);
1720
- throw new APIStatusError(message, response.status);
1991
+ throw statusErrorFromBody(response.status, await readErrorBody(response), response.statusText);
1721
1992
  }
1722
1993
  return { response, controller };
1723
1994
  }