pendra 0.14.0 → 0.15.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/dist/index.d.mts +12 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +795 -630
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +795 -630
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -59,350 +59,6 @@ var APIStreamError = class extends APIError {
|
|
|
59
59
|
}
|
|
60
60
|
};
|
|
61
61
|
|
|
62
|
-
// src/resources/audio/transcriptions.ts
|
|
63
|
-
var MAX_FILE_SIZE = 25 * 1024 * 1024;
|
|
64
|
-
var MIME_EXT = {
|
|
65
|
-
"audio/mpeg": "mp3",
|
|
66
|
-
"audio/mp3": "mp3",
|
|
67
|
-
"audio/mp4": "m4a",
|
|
68
|
-
"audio/x-m4a": "m4a",
|
|
69
|
-
"audio/wav": "wav",
|
|
70
|
-
"audio/wave": "wav",
|
|
71
|
-
"audio/x-wav": "wav",
|
|
72
|
-
"audio/webm": "webm",
|
|
73
|
-
"audio/ogg": "ogg",
|
|
74
|
-
"audio/flac": "flac",
|
|
75
|
-
"audio/x-flac": "flac"
|
|
76
|
-
};
|
|
77
|
-
function extFromMime(type) {
|
|
78
|
-
if (!type) return "mp3";
|
|
79
|
-
const base = type.split(";")[0].trim().toLowerCase();
|
|
80
|
-
return MIME_EXT[base] ?? "mp3";
|
|
81
|
-
}
|
|
82
|
-
function asBlob(file) {
|
|
83
|
-
if (file instanceof Blob) {
|
|
84
|
-
const asFile = file;
|
|
85
|
-
if (asFile.name) {
|
|
86
|
-
return { blob: file, filename: asFile.name };
|
|
87
|
-
}
|
|
88
|
-
return { blob: file, filename: `audio.${extFromMime(file.type)}` };
|
|
89
|
-
}
|
|
90
|
-
const { filename, content } = file;
|
|
91
|
-
if (content instanceof Blob) {
|
|
92
|
-
return { blob: content, filename };
|
|
93
|
-
}
|
|
94
|
-
return { blob: new Blob([content]), filename };
|
|
95
|
-
}
|
|
96
|
-
async function extractErrorDetail(response) {
|
|
97
|
-
let raw = "";
|
|
98
|
-
try {
|
|
99
|
-
raw = await response.text();
|
|
100
|
-
} catch {
|
|
101
|
-
return response.statusText;
|
|
102
|
-
}
|
|
103
|
-
if (!raw) return response.statusText;
|
|
104
|
-
try {
|
|
105
|
-
const body = JSON.parse(raw);
|
|
106
|
-
return body.detail ?? body.error?.message ?? raw;
|
|
107
|
-
} catch {
|
|
108
|
-
return raw;
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
var Transcriptions = class {
|
|
112
|
-
constructor(client) {
|
|
113
|
-
this.client = client;
|
|
114
|
-
}
|
|
115
|
-
async create(params) {
|
|
116
|
-
if (this.client.privateInferenceEnabled) {
|
|
117
|
-
throw new Error("private inference is not yet supported for images/audio");
|
|
118
|
-
}
|
|
119
|
-
if (!params.model) {
|
|
120
|
-
throw new Error("model is required");
|
|
121
|
-
}
|
|
122
|
-
const { blob, filename } = asBlob(params.file);
|
|
123
|
-
if (blob.size === 0) {
|
|
124
|
-
throw new Error("audio file is empty");
|
|
125
|
-
}
|
|
126
|
-
if (blob.size > MAX_FILE_SIZE) {
|
|
127
|
-
throw new Error(`audio file exceeds ${MAX_FILE_SIZE / (1024 * 1024)}MB limit`);
|
|
128
|
-
}
|
|
129
|
-
const form = new FormData();
|
|
130
|
-
form.append("file", blob, filename);
|
|
131
|
-
form.append("model", params.model);
|
|
132
|
-
if (params.language) form.append("language", params.language);
|
|
133
|
-
if (params.prompt) form.append("prompt", params.prompt);
|
|
134
|
-
if (params.response_format) form.append("response_format", params.response_format);
|
|
135
|
-
if (params.temperature != null) form.append("temperature", String(params.temperature));
|
|
136
|
-
if (params.beam_size != null) form.append("beam_size", String(params.beam_size));
|
|
137
|
-
if (params.timestamp_granularities) {
|
|
138
|
-
for (const g of params.timestamp_granularities) {
|
|
139
|
-
form.append("timestamp_granularities[]", g);
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
const timeout = Math.max(this.client.timeout ?? 0, 3e5);
|
|
143
|
-
const controller = new AbortController();
|
|
144
|
-
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
145
|
-
let response;
|
|
146
|
-
try {
|
|
147
|
-
response = await fetch(`${this.client.baseURL}/api/v1/audio/transcriptions`, {
|
|
148
|
-
method: "POST",
|
|
149
|
-
headers: {
|
|
150
|
-
Authorization: `Bearer ${this.client.apiKey}`,
|
|
151
|
-
...params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : {}
|
|
152
|
-
},
|
|
153
|
-
body: form,
|
|
154
|
-
signal: controller.signal
|
|
155
|
-
});
|
|
156
|
-
} catch (err) {
|
|
157
|
-
clearTimeout(timeoutId);
|
|
158
|
-
if (err instanceof DOMException && err.name === "AbortError") {
|
|
159
|
-
throw new APIConnectionError("Transcription request timed out");
|
|
160
|
-
}
|
|
161
|
-
throw new APIConnectionError(String(err));
|
|
162
|
-
}
|
|
163
|
-
clearTimeout(timeoutId);
|
|
164
|
-
if (response.status >= 400) {
|
|
165
|
-
const detail = await extractErrorDetail(response);
|
|
166
|
-
if (response.status === 401) {
|
|
167
|
-
throw new AuthenticationError(detail);
|
|
168
|
-
}
|
|
169
|
-
if (response.status === 429) {
|
|
170
|
-
throw new RateLimitError(detail);
|
|
171
|
-
}
|
|
172
|
-
throw new APIStatusError(detail, response.status);
|
|
173
|
-
}
|
|
174
|
-
const format = params.response_format;
|
|
175
|
-
if (format === "text" || format === "srt" || format === "vtt") {
|
|
176
|
-
const text = await response.text();
|
|
177
|
-
return { text };
|
|
178
|
-
}
|
|
179
|
-
return await response.json();
|
|
180
|
-
}
|
|
181
|
-
};
|
|
182
|
-
|
|
183
|
-
// src/resources/audio/index.ts
|
|
184
|
-
var Audio = class {
|
|
185
|
-
constructor(client) {
|
|
186
|
-
this.transcriptions = new Transcriptions(client);
|
|
187
|
-
}
|
|
188
|
-
};
|
|
189
|
-
|
|
190
|
-
// src/_parsing.ts
|
|
191
|
-
function asString(v) {
|
|
192
|
-
return typeof v === "string" ? v : void 0;
|
|
193
|
-
}
|
|
194
|
-
function throwIfInBandError(parsed) {
|
|
195
|
-
if (typeof parsed !== "object" || parsed === null) return;
|
|
196
|
-
const err = parsed.error;
|
|
197
|
-
if (typeof err !== "object" || err === null || Array.isArray(err)) return;
|
|
198
|
-
const e = err;
|
|
199
|
-
throw new APIStreamError(
|
|
200
|
-
asString(e.message) ?? "The server reported an error mid-stream",
|
|
201
|
-
{
|
|
202
|
-
type: asString(e.type),
|
|
203
|
-
code: typeof e.code === "number" ? e.code : void 0,
|
|
204
|
-
requestId: asString(e.request_id),
|
|
205
|
-
workerId: asString(e.worker_id),
|
|
206
|
-
workerName: asString(e.worker_name)
|
|
207
|
-
}
|
|
208
|
-
);
|
|
209
|
-
}
|
|
210
|
-
function isChunkShaped(parsed) {
|
|
211
|
-
if (typeof parsed !== "object" || parsed === null) return false;
|
|
212
|
-
const c = parsed;
|
|
213
|
-
return typeof c.id === "string" && typeof c.model === "string" && Array.isArray(c.choices);
|
|
214
|
-
}
|
|
215
|
-
function parseStreamFrame(data, label = "Stream frame") {
|
|
216
|
-
let parsed;
|
|
217
|
-
try {
|
|
218
|
-
parsed = JSON.parse(data);
|
|
219
|
-
} catch {
|
|
220
|
-
throw new APIResponseValidationError(`${label} was not valid JSON`, { body: data });
|
|
221
|
-
}
|
|
222
|
-
throwIfInBandError(parsed);
|
|
223
|
-
if (!isChunkShaped(parsed)) {
|
|
224
|
-
throw new APIResponseValidationError(`${label} was not a chat completion chunk`, {
|
|
225
|
-
body: data
|
|
226
|
-
});
|
|
227
|
-
}
|
|
228
|
-
return parsed;
|
|
229
|
-
}
|
|
230
|
-
function completionFrom(parsed, body, status) {
|
|
231
|
-
if (typeof parsed !== "object" || parsed === null) {
|
|
232
|
-
throw new APIResponseValidationError("Response was not a chat completion", { status, body });
|
|
233
|
-
}
|
|
234
|
-
const c = parsed;
|
|
235
|
-
if (typeof c.id !== "string" || typeof c.model !== "string" || !Array.isArray(c.choices)) {
|
|
236
|
-
throw new APIResponseValidationError("Response was not a chat completion", { status, body });
|
|
237
|
-
}
|
|
238
|
-
return parsed;
|
|
239
|
-
}
|
|
240
|
-
async function parseCompletion(response) {
|
|
241
|
-
const body = await response.text();
|
|
242
|
-
let parsed;
|
|
243
|
-
try {
|
|
244
|
-
parsed = JSON.parse(body);
|
|
245
|
-
} catch {
|
|
246
|
-
throw new APIResponseValidationError("Response was not valid JSON", {
|
|
247
|
-
status: response.status,
|
|
248
|
-
body
|
|
249
|
-
});
|
|
250
|
-
}
|
|
251
|
-
return completionFrom(parsed, body, response.status);
|
|
252
|
-
}
|
|
253
|
-
function parseDecryptedCompletion(json, status) {
|
|
254
|
-
let parsed;
|
|
255
|
-
try {
|
|
256
|
-
parsed = JSON.parse(json);
|
|
257
|
-
} catch {
|
|
258
|
-
throw new APIResponseValidationError("Decrypted response was not valid JSON", {
|
|
259
|
-
status,
|
|
260
|
-
body: json
|
|
261
|
-
});
|
|
262
|
-
}
|
|
263
|
-
try {
|
|
264
|
-
return completionFrom(parsed, json, status);
|
|
265
|
-
} catch {
|
|
266
|
-
throw new APIResponseValidationError("Decrypted response was not a chat completion", {
|
|
267
|
-
status,
|
|
268
|
-
body: json
|
|
269
|
-
});
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
// src/_sse.ts
|
|
274
|
-
var DEFAULT_EVENT = "message";
|
|
275
|
-
function fieldValue(line, name) {
|
|
276
|
-
const value = line.slice(name.length + 1);
|
|
277
|
-
return value.startsWith(" ") ? value.slice(1) : value;
|
|
278
|
-
}
|
|
279
|
-
var SseDecoder = class {
|
|
280
|
-
constructor() {
|
|
281
|
-
this.buffer = "";
|
|
282
|
-
this.event = "";
|
|
283
|
-
this.data = [];
|
|
284
|
-
}
|
|
285
|
-
/** Feed a chunk of decoded text; returns the payloads it completed. */
|
|
286
|
-
push(text) {
|
|
287
|
-
this.buffer += text;
|
|
288
|
-
const lines = this.buffer.split("\n");
|
|
289
|
-
this.buffer = lines.pop() ?? "";
|
|
290
|
-
const out = [];
|
|
291
|
-
for (const line of lines) {
|
|
292
|
-
const payload = this.pushLine(line);
|
|
293
|
-
if (payload !== null) out.push(payload);
|
|
294
|
-
}
|
|
295
|
-
return out;
|
|
296
|
-
}
|
|
297
|
-
/**
|
|
298
|
-
* Release what the stream ended without terminating: the held-back partial
|
|
299
|
-
* line, plus any frame that never got its blank line.
|
|
300
|
-
*
|
|
301
|
-
* The spec discards an unterminated final block; we keep it, so a connection
|
|
302
|
-
* that drops after the last `data:` line but before its blank line still
|
|
303
|
-
* delivers that payload rather than silently losing it.
|
|
304
|
-
*/
|
|
305
|
-
flush() {
|
|
306
|
-
const out = [];
|
|
307
|
-
if (this.buffer !== "") {
|
|
308
|
-
const payload = this.pushLine(this.buffer);
|
|
309
|
-
this.buffer = "";
|
|
310
|
-
if (payload !== null) out.push(payload);
|
|
311
|
-
}
|
|
312
|
-
const tail = this.endFrame();
|
|
313
|
-
if (tail !== null) out.push(tail);
|
|
314
|
-
return out;
|
|
315
|
-
}
|
|
316
|
-
pushLine(rawLine) {
|
|
317
|
-
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
|
|
318
|
-
if (line === "") return this.endFrame();
|
|
319
|
-
if (line.startsWith(":")) return null;
|
|
320
|
-
if (line.startsWith("event:")) {
|
|
321
|
-
this.event = fieldValue(line, "event");
|
|
322
|
-
return null;
|
|
323
|
-
}
|
|
324
|
-
if (line.startsWith("data:")) {
|
|
325
|
-
this.data.push(fieldValue(line, "data"));
|
|
326
|
-
return null;
|
|
327
|
-
}
|
|
328
|
-
return null;
|
|
329
|
-
}
|
|
330
|
-
endFrame() {
|
|
331
|
-
const { data, event } = this;
|
|
332
|
-
this.data = [];
|
|
333
|
-
this.event = "";
|
|
334
|
-
if (data.length === 0) return null;
|
|
335
|
-
if (event !== "" && event !== DEFAULT_EVENT) return null;
|
|
336
|
-
return data.join("\n");
|
|
337
|
-
}
|
|
338
|
-
};
|
|
339
|
-
|
|
340
|
-
// src/streaming.ts
|
|
341
|
-
var Stream = class {
|
|
342
|
-
constructor(response, controller, idleTimeoutMs) {
|
|
343
|
-
this.decoder = new TextDecoder();
|
|
344
|
-
this.sse = new SseDecoder();
|
|
345
|
-
this.done = false;
|
|
346
|
-
if (!response.body) {
|
|
347
|
-
throw new Error("Response body is null \u2014 streaming not supported");
|
|
348
|
-
}
|
|
349
|
-
this.reader = response.body.getReader();
|
|
350
|
-
this.controller = controller;
|
|
351
|
-
this.idleTimeoutMs = idleTimeoutMs;
|
|
352
|
-
}
|
|
353
|
-
async *[Symbol.asyncIterator]() {
|
|
354
|
-
try {
|
|
355
|
-
while (!this.done) {
|
|
356
|
-
const { value, done: readerDone } = await readWithIdleTimeout(
|
|
357
|
-
this.reader,
|
|
358
|
-
this.idleTimeoutMs
|
|
359
|
-
);
|
|
360
|
-
const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
|
|
361
|
-
for (const data of payloads) {
|
|
362
|
-
if (data === "[DONE]") {
|
|
363
|
-
this.done = true;
|
|
364
|
-
return;
|
|
365
|
-
}
|
|
366
|
-
yield parseStreamFrame(data);
|
|
367
|
-
}
|
|
368
|
-
if (readerDone) {
|
|
369
|
-
this.done = true;
|
|
370
|
-
break;
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
} finally {
|
|
374
|
-
releaseReader(this.reader, this.controller, this.done);
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
abort() {
|
|
378
|
-
this.done = true;
|
|
379
|
-
this.controller.abort();
|
|
380
|
-
}
|
|
381
|
-
};
|
|
382
|
-
async function readWithIdleTimeout(reader, idleTimeoutMs) {
|
|
383
|
-
if (!idleTimeoutMs) return reader.read();
|
|
384
|
-
let timer;
|
|
385
|
-
const idle = new Promise((_, reject) => {
|
|
386
|
-
timer = setTimeout(
|
|
387
|
-
() => reject(new APIConnectionError(`Stream received no data for ${idleTimeoutMs}ms`)),
|
|
388
|
-
idleTimeoutMs
|
|
389
|
-
);
|
|
390
|
-
});
|
|
391
|
-
try {
|
|
392
|
-
return await Promise.race([reader.read(), idle]);
|
|
393
|
-
} finally {
|
|
394
|
-
clearTimeout(timer);
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
function releaseReader(reader, controller, finished) {
|
|
398
|
-
if (!finished) {
|
|
399
|
-
controller.abort();
|
|
400
|
-
reader.cancel().catch(() => {
|
|
401
|
-
});
|
|
402
|
-
}
|
|
403
|
-
reader.releaseLock();
|
|
404
|
-
}
|
|
405
|
-
|
|
406
62
|
// src/_privateInference.ts
|
|
407
63
|
import { chacha20poly1305 as chacha20poly13052 } from "@noble/ciphers/chacha.js";
|
|
408
64
|
import { extract as extract2, expand as expand2 } from "@noble/hashes/hkdf.js";
|
|
@@ -461,311 +117,751 @@ function labeledExpand(prk, label, info, length, suiteId) {
|
|
|
461
117
|
const labeledInfo = concat(i2osp(length, 2), HPKE_VERSION, suiteId, label, info);
|
|
462
118
|
return hkdfExpand(prk, labeledInfo, length);
|
|
463
119
|
}
|
|
464
|
-
function extractAndExpand(dh, kemContext) {
|
|
465
|
-
const eaePrk = labeledExtract(new Uint8Array(0), bytes("eae_prk"), dh, KEM_SUITE_ID);
|
|
466
|
-
return labeledExpand(eaePrk, bytes("shared_secret"), kemContext, NSECRET, KEM_SUITE_ID);
|
|
120
|
+
function extractAndExpand(dh, kemContext) {
|
|
121
|
+
const eaePrk = labeledExtract(new Uint8Array(0), bytes("eae_prk"), dh, KEM_SUITE_ID);
|
|
122
|
+
return labeledExpand(eaePrk, bytes("shared_secret"), kemContext, NSECRET, KEM_SUITE_ID);
|
|
123
|
+
}
|
|
124
|
+
function encap(pkR, skE) {
|
|
125
|
+
const skEObj = skE ?? x25519.utils.randomSecretKey();
|
|
126
|
+
const enc = x25519.getPublicKey(skEObj);
|
|
127
|
+
const dh = x25519.getSharedSecret(skEObj, pkR);
|
|
128
|
+
const kemContext = concat(enc, pkR);
|
|
129
|
+
return [extractAndExpand(dh, kemContext), enc];
|
|
130
|
+
}
|
|
131
|
+
var Context = class {
|
|
132
|
+
constructor(key, baseNonce, exporterSecret) {
|
|
133
|
+
this.seq = 0;
|
|
134
|
+
this.key = key;
|
|
135
|
+
this.baseNonce = baseNonce;
|
|
136
|
+
this.exporterSecret = exporterSecret;
|
|
137
|
+
}
|
|
138
|
+
computeNonce() {
|
|
139
|
+
const seqBytes = i2osp(this.seq, NN);
|
|
140
|
+
const nonce = new Uint8Array(NN);
|
|
141
|
+
for (let i = 0; i < NN; i++) {
|
|
142
|
+
nonce[i] = this.baseNonce[i] ^ seqBytes[i];
|
|
143
|
+
}
|
|
144
|
+
return nonce;
|
|
145
|
+
}
|
|
146
|
+
seal(aad, pt) {
|
|
147
|
+
const ct = chacha20poly1305(this.key, this.computeNonce(), aad).encrypt(pt);
|
|
148
|
+
this.seq += 1;
|
|
149
|
+
return ct;
|
|
150
|
+
}
|
|
151
|
+
open(aad, ct) {
|
|
152
|
+
const pt = chacha20poly1305(this.key, this.computeNonce(), aad).decrypt(ct);
|
|
153
|
+
this.seq += 1;
|
|
154
|
+
return pt;
|
|
155
|
+
}
|
|
156
|
+
export(exporterContext, length) {
|
|
157
|
+
return labeledExpand(this.exporterSecret, bytes("sec"), exporterContext, length, SUITE_ID);
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
function keySchedule(sharedSecret, info) {
|
|
161
|
+
const empty = new Uint8Array(0);
|
|
162
|
+
const pskIdHash = labeledExtract(empty, bytes("psk_id_hash"), empty, SUITE_ID);
|
|
163
|
+
const infoHash = labeledExtract(empty, bytes("info_hash"), info, SUITE_ID);
|
|
164
|
+
const keyScheduleContext = concat(new Uint8Array([0]), pskIdHash, infoHash);
|
|
165
|
+
const secret = labeledExtract(sharedSecret, bytes("secret"), empty, SUITE_ID);
|
|
166
|
+
const key = labeledExpand(secret, bytes("key"), keyScheduleContext, NK, SUITE_ID);
|
|
167
|
+
const baseNonce = labeledExpand(secret, bytes("base_nonce"), keyScheduleContext, NN, SUITE_ID);
|
|
168
|
+
const exporterSecret = labeledExpand(secret, bytes("exp"), keyScheduleContext, NH, SUITE_ID);
|
|
169
|
+
return new Context(key, baseNonce, exporterSecret);
|
|
170
|
+
}
|
|
171
|
+
function setupBaseS(pkR, info, skE) {
|
|
172
|
+
const [sharedSecret, enc] = encap(pkR, skE);
|
|
173
|
+
return { enc, ctx: keySchedule(sharedSecret, info) };
|
|
174
|
+
}
|
|
175
|
+
function randomBytes(n) {
|
|
176
|
+
return nobleRandomBytes(n);
|
|
177
|
+
}
|
|
178
|
+
function sha256Hex(data) {
|
|
179
|
+
return Array.from(sha256(data)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// src/_privateInference.ts
|
|
183
|
+
var ENVELOPE_VERSION = 2;
|
|
184
|
+
var TEXT_ENCODER2 = new TextEncoder();
|
|
185
|
+
var TEXT_DECODER = new TextDecoder();
|
|
186
|
+
var SUITE_INFO = TEXT_ENCODER2.encode("pendra-pi-v1");
|
|
187
|
+
var RESPONSE_EXPORT_CTX = TEXT_ENCODER2.encode("pendra-pi-v1:rdek");
|
|
188
|
+
var AFFINITY_SALT_INFO = TEXT_ENCODER2.encode("pendra-affinity-salt-v1");
|
|
189
|
+
function utf8(s) {
|
|
190
|
+
return TEXT_ENCODER2.encode(s);
|
|
191
|
+
}
|
|
192
|
+
function b64(b) {
|
|
193
|
+
if (typeof Buffer !== "undefined") {
|
|
194
|
+
return Buffer.from(b).toString("base64");
|
|
195
|
+
}
|
|
196
|
+
let binary = "";
|
|
197
|
+
for (let i = 0; i < b.length; i++) binary += String.fromCharCode(b[i]);
|
|
198
|
+
return btoa(binary);
|
|
199
|
+
}
|
|
200
|
+
function b64d(s) {
|
|
201
|
+
if (typeof Buffer !== "undefined") {
|
|
202
|
+
return new Uint8Array(Buffer.from(s, "base64"));
|
|
203
|
+
}
|
|
204
|
+
const binary = atob(s);
|
|
205
|
+
const out = new Uint8Array(binary.length);
|
|
206
|
+
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
207
|
+
return out;
|
|
208
|
+
}
|
|
209
|
+
function toHex(b) {
|
|
210
|
+
return Array.from(b).map((x) => x.toString(16).padStart(2, "0")).join("");
|
|
211
|
+
}
|
|
212
|
+
function fingerprint(pub) {
|
|
213
|
+
return sha256Hex(pub);
|
|
214
|
+
}
|
|
215
|
+
function buildAad(model, stream, taskType) {
|
|
216
|
+
const streamBit = stream ? utf8("1") : utf8("0");
|
|
217
|
+
const sep = new Uint8Array([0]);
|
|
218
|
+
const parts = [utf8("pendra-pi-v1"), utf8(model), streamBit, utf8(taskType), new Uint8Array(0)];
|
|
219
|
+
let total = 0;
|
|
220
|
+
for (let i = 0; i < parts.length; i++) {
|
|
221
|
+
if (i > 0) total += 1;
|
|
222
|
+
total += parts[i].length;
|
|
223
|
+
}
|
|
224
|
+
const out = new Uint8Array(total);
|
|
225
|
+
let off = 0;
|
|
226
|
+
for (let i = 0; i < parts.length; i++) {
|
|
227
|
+
if (i > 0) {
|
|
228
|
+
out.set(sep, off);
|
|
229
|
+
off += 1;
|
|
230
|
+
}
|
|
231
|
+
out.set(parts[i], off);
|
|
232
|
+
off += parts[i].length;
|
|
233
|
+
}
|
|
234
|
+
return out;
|
|
235
|
+
}
|
|
236
|
+
function seqNonce(seq) {
|
|
237
|
+
const nonce = new Uint8Array(12);
|
|
238
|
+
let n = BigInt(seq);
|
|
239
|
+
for (let i = 11; i >= 4; i--) {
|
|
240
|
+
nonce[i] = Number(n & 0xffn);
|
|
241
|
+
n >>= 8n;
|
|
242
|
+
}
|
|
243
|
+
return nonce;
|
|
244
|
+
}
|
|
245
|
+
function sealRequest(orgPubs, body, opts) {
|
|
246
|
+
const pubs = Array.isArray(orgPubs) ? orgPubs : [orgPubs];
|
|
247
|
+
if (pubs.length === 0) {
|
|
248
|
+
throw new Error("sealRequest: no org public keys to seal to");
|
|
249
|
+
}
|
|
250
|
+
const seen = /* @__PURE__ */ new Set();
|
|
251
|
+
const uniquePubs = [];
|
|
252
|
+
for (const p of pubs) {
|
|
253
|
+
const fp = fingerprint(p);
|
|
254
|
+
if (!seen.has(fp)) {
|
|
255
|
+
seen.add(fp);
|
|
256
|
+
uniquePubs.push(p);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
const dek = randomBytes(32);
|
|
260
|
+
const nonce = randomBytes(12);
|
|
261
|
+
const aad = buildAad(opts.model, opts.stream, opts.taskType);
|
|
262
|
+
const ciphertext = chacha20poly13052(dek, nonce, aad).encrypt(body);
|
|
263
|
+
const recipients = [];
|
|
264
|
+
const responseKeys = /* @__PURE__ */ new Map();
|
|
265
|
+
for (const pub of uniquePubs) {
|
|
266
|
+
const { enc, ctx: sealer } = setupBaseS(pub, SUITE_INFO);
|
|
267
|
+
const sealedDek = sealer.seal(new Uint8Array(0), dek);
|
|
268
|
+
const kid = fingerprint(pub);
|
|
269
|
+
responseKeys.set(kid, sealer.export(RESPONSE_EXPORT_CTX, 32));
|
|
270
|
+
recipients.push({ kid, enc: b64(enc), sealed_dek: b64(sealedDek) });
|
|
271
|
+
}
|
|
272
|
+
const envelope = {
|
|
273
|
+
v: ENVELOPE_VERSION,
|
|
274
|
+
recipients,
|
|
275
|
+
nonce: b64(nonce),
|
|
276
|
+
ciphertext: b64(ciphertext)
|
|
277
|
+
};
|
|
278
|
+
if (opts.affinityKey != null) {
|
|
279
|
+
envelope.affinity_key = opts.affinityKey;
|
|
280
|
+
}
|
|
281
|
+
if (opts.binary != null) {
|
|
282
|
+
const binaryNonce = randomBytes(12);
|
|
283
|
+
envelope.binary_nonce = b64(binaryNonce);
|
|
284
|
+
envelope.binary_ciphertext = b64(chacha20poly13052(dek, binaryNonce, aad).encrypt(opts.binary));
|
|
285
|
+
}
|
|
286
|
+
return { envelope, responseKeys };
|
|
287
|
+
}
|
|
288
|
+
var API_TIMING_CHUNK_KEYS = /* @__PURE__ */ new Set(["id", "object", "created", "model", "choices", "pendra"]);
|
|
289
|
+
function isApiTimingChunk(frame) {
|
|
290
|
+
if (frame === null || typeof frame !== "object" || Array.isArray(frame)) return false;
|
|
291
|
+
const obj = frame;
|
|
292
|
+
const pendra = obj.pendra;
|
|
293
|
+
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;
|
|
294
|
+
}
|
|
295
|
+
function unsealedReplyError() {
|
|
296
|
+
return new Error(
|
|
297
|
+
"private_inference: refusing an unencrypted reply to an encrypted request (it could have been forged in transit)"
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
var STREAM_TERMINATOR_KEY = "pendra_stream_terminator";
|
|
301
|
+
function isStreamTerminatorDeclaration(plaintext) {
|
|
302
|
+
try {
|
|
303
|
+
const obj = JSON.parse(plaintext);
|
|
304
|
+
return obj !== null && typeof obj === "object" && !Array.isArray(obj) && Object.keys(obj).length === 1 && obj[STREAM_TERMINATOR_KEY] === 1;
|
|
305
|
+
} catch {
|
|
306
|
+
return false;
|
|
307
|
+
}
|
|
467
308
|
}
|
|
468
|
-
function
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
const kemContext = concat(enc, pkR);
|
|
473
|
-
return [extractAndExpand(dh, kemContext), enc];
|
|
309
|
+
function truncatedStreamError() {
|
|
310
|
+
return new Error(
|
|
311
|
+
"private_inference: the stream ended before the worker's sealed end-of-stream marker; the response may have been truncated in transit"
|
|
312
|
+
);
|
|
474
313
|
}
|
|
475
|
-
var
|
|
476
|
-
constructor(
|
|
477
|
-
this.
|
|
478
|
-
this.
|
|
479
|
-
this.
|
|
480
|
-
this.exporterSecret = exporterSecret;
|
|
314
|
+
var ResponseDecryptor = class {
|
|
315
|
+
constructor(responseKeys) {
|
|
316
|
+
this.dek = null;
|
|
317
|
+
this.nextSeq = 0;
|
|
318
|
+
this.keys = responseKeys;
|
|
481
319
|
}
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
320
|
+
ensureDek(inner) {
|
|
321
|
+
if (inner.v !== ENVELOPE_VERSION || inner.enc !== void 0) {
|
|
322
|
+
throw new Error(
|
|
323
|
+
"private_inference: refusing a response that is not in v2 form (it could have been forged in transit)"
|
|
324
|
+
);
|
|
487
325
|
}
|
|
488
|
-
return
|
|
326
|
+
if (this.dek !== null) return;
|
|
327
|
+
const dek = inner.kid === void 0 ? void 0 : this.keys.get(inner.kid);
|
|
328
|
+
if (dek === void 0) {
|
|
329
|
+
throw new Error("private_inference: first response frame names no key this request was sealed to");
|
|
330
|
+
}
|
|
331
|
+
this.dek = dek;
|
|
489
332
|
}
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
this.
|
|
493
|
-
return
|
|
333
|
+
/** Decrypt a non-streaming result envelope `{v, kid, seq, ciphertext}`. */
|
|
334
|
+
openResult(inner) {
|
|
335
|
+
this.ensureDek(inner);
|
|
336
|
+
return chacha20poly13052(this.dek, seqNonce(Number(inner.seq))).decrypt(b64d(inner.ciphertext));
|
|
494
337
|
}
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
338
|
+
/** Decrypt one streaming chunk envelope, enforcing monotonic `seq`. */
|
|
339
|
+
openChunk(inner) {
|
|
340
|
+
const seq = Number(inner.seq);
|
|
341
|
+
if (seq !== this.nextSeq) {
|
|
342
|
+
throw new Error(
|
|
343
|
+
`private_inference: out-of-order response chunk (seq ${seq}, expected ${this.nextSeq})`
|
|
344
|
+
);
|
|
345
|
+
}
|
|
346
|
+
this.ensureDek(inner);
|
|
347
|
+
const pt = chacha20poly13052(this.dek, seqNonce(seq)).decrypt(b64d(inner.ciphertext));
|
|
348
|
+
this.nextSeq += 1;
|
|
498
349
|
return pt;
|
|
499
350
|
}
|
|
500
|
-
export(exporterContext, length) {
|
|
501
|
-
return labeledExpand(this.exporterSecret, bytes("sec"), exporterContext, length, SUITE_ID);
|
|
502
|
-
}
|
|
503
351
|
};
|
|
504
|
-
function
|
|
505
|
-
const
|
|
506
|
-
|
|
507
|
-
const infoHash = labeledExtract(empty, bytes("info_hash"), info, SUITE_ID);
|
|
508
|
-
const keyScheduleContext = concat(new Uint8Array([0]), pskIdHash, infoHash);
|
|
509
|
-
const secret = labeledExtract(sharedSecret, bytes("secret"), empty, SUITE_ID);
|
|
510
|
-
const key = labeledExpand(secret, bytes("key"), keyScheduleContext, NK, SUITE_ID);
|
|
511
|
-
const baseNonce = labeledExpand(secret, bytes("base_nonce"), keyScheduleContext, NN, SUITE_ID);
|
|
512
|
-
const exporterSecret = labeledExpand(secret, bytes("exp"), keyScheduleContext, NH, SUITE_ID);
|
|
513
|
-
return new Context(key, baseNonce, exporterSecret);
|
|
352
|
+
function deriveSalt(rawApiKey) {
|
|
353
|
+
const prk = extract2(sha256, utf8(rawApiKey), new Uint8Array(32));
|
|
354
|
+
return expand2(sha256, prk, AFFINITY_SALT_INFO, 32);
|
|
514
355
|
}
|
|
515
|
-
function
|
|
516
|
-
|
|
517
|
-
|
|
356
|
+
function canonicalJson(value) {
|
|
357
|
+
if (value === null) return "null";
|
|
358
|
+
const t = typeof value;
|
|
359
|
+
if (t === "boolean") return value ? "true" : "false";
|
|
360
|
+
if (t === "number") {
|
|
361
|
+
return String(value);
|
|
362
|
+
}
|
|
363
|
+
if (t === "string") return encodeString(value);
|
|
364
|
+
if (Array.isArray(value)) {
|
|
365
|
+
return "[" + value.map((v) => canonicalJson(v)).join(",") + "]";
|
|
366
|
+
}
|
|
367
|
+
if (t === "object") {
|
|
368
|
+
const obj = value;
|
|
369
|
+
const keys = Object.keys(obj).sort();
|
|
370
|
+
const items = keys.map((k) => encodeString(k) + ":" + canonicalJson(obj[k]));
|
|
371
|
+
return "{" + items.join(",") + "}";
|
|
372
|
+
}
|
|
373
|
+
return "null";
|
|
518
374
|
}
|
|
519
|
-
function
|
|
520
|
-
|
|
375
|
+
function encodeString(s) {
|
|
376
|
+
let out = '"';
|
|
377
|
+
for (let i = 0; i < s.length; i++) {
|
|
378
|
+
const code = s.charCodeAt(i);
|
|
379
|
+
switch (code) {
|
|
380
|
+
case 34:
|
|
381
|
+
out += '\\"';
|
|
382
|
+
break;
|
|
383
|
+
case 92:
|
|
384
|
+
out += "\\\\";
|
|
385
|
+
break;
|
|
386
|
+
case 8:
|
|
387
|
+
out += "\\b";
|
|
388
|
+
break;
|
|
389
|
+
case 9:
|
|
390
|
+
out += "\\t";
|
|
391
|
+
break;
|
|
392
|
+
case 10:
|
|
393
|
+
out += "\\n";
|
|
394
|
+
break;
|
|
395
|
+
case 12:
|
|
396
|
+
out += "\\f";
|
|
397
|
+
break;
|
|
398
|
+
case 13:
|
|
399
|
+
out += "\\r";
|
|
400
|
+
break;
|
|
401
|
+
default:
|
|
402
|
+
if (code < 32 || code > 126) {
|
|
403
|
+
out += "\\u" + code.toString(16).padStart(4, "0");
|
|
404
|
+
} else {
|
|
405
|
+
out += s[i];
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
return out + '"';
|
|
521
410
|
}
|
|
522
|
-
function
|
|
523
|
-
|
|
411
|
+
function flattenContent(content) {
|
|
412
|
+
if (typeof content === "string") return content;
|
|
413
|
+
return canonicalJson(content);
|
|
414
|
+
}
|
|
415
|
+
function affinityKey(rawApiKey, model, messages, saltOverride) {
|
|
416
|
+
const parts = ["model=" + model];
|
|
417
|
+
let sawUser = false;
|
|
418
|
+
for (const m of messages ?? []) {
|
|
419
|
+
const role = m.role ?? "";
|
|
420
|
+
parts.push(role + ":" + flattenContent(m.content));
|
|
421
|
+
if (role === "user") {
|
|
422
|
+
sawUser = true;
|
|
423
|
+
break;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
if (!sawUser) return null;
|
|
427
|
+
const salt = saltOverride != null ? saltOverride : deriveSalt(rawApiKey);
|
|
428
|
+
const mac = hmac(sha256, salt, utf8(parts.join("\0")));
|
|
429
|
+
return toHex(mac);
|
|
524
430
|
}
|
|
525
431
|
|
|
526
|
-
// src/
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
var TEXT_DECODER = new TextDecoder();
|
|
530
|
-
var SUITE_INFO = TEXT_ENCODER2.encode("pendra-pi-v1");
|
|
531
|
-
var RESPONSE_EXPORT_CTX = TEXT_ENCODER2.encode("pendra-pi-v1:rdek");
|
|
532
|
-
var AFFINITY_SALT_INFO = TEXT_ENCODER2.encode("pendra-affinity-salt-v1");
|
|
533
|
-
function utf8(s) {
|
|
534
|
-
return TEXT_ENCODER2.encode(s);
|
|
432
|
+
// src/_parsing.ts
|
|
433
|
+
function asString(v) {
|
|
434
|
+
return typeof v === "string" ? v : void 0;
|
|
535
435
|
}
|
|
536
|
-
function
|
|
537
|
-
if (typeof
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
436
|
+
function throwIfInBandError(parsed, fallback = "The server reported an error mid-stream") {
|
|
437
|
+
if (typeof parsed !== "object" || parsed === null) return;
|
|
438
|
+
const err = parsed.error;
|
|
439
|
+
if (typeof err !== "object" || err === null || Array.isArray(err)) return;
|
|
440
|
+
const e = err;
|
|
441
|
+
throw new APIStreamError(
|
|
442
|
+
asString(e.message) ?? fallback,
|
|
443
|
+
{
|
|
444
|
+
type: asString(e.type),
|
|
445
|
+
code: typeof e.code === "number" ? e.code : void 0,
|
|
446
|
+
requestId: asString(e.request_id),
|
|
447
|
+
workerId: asString(e.worker_id),
|
|
448
|
+
workerName: asString(e.worker_name)
|
|
449
|
+
}
|
|
450
|
+
);
|
|
543
451
|
}
|
|
544
|
-
function
|
|
545
|
-
if (typeof
|
|
546
|
-
|
|
452
|
+
function isChunkShaped(parsed) {
|
|
453
|
+
if (typeof parsed !== "object" || parsed === null) return false;
|
|
454
|
+
const c = parsed;
|
|
455
|
+
return typeof c.id === "string" && typeof c.model === "string" && Array.isArray(c.choices);
|
|
456
|
+
}
|
|
457
|
+
function parseStreamFrame(data, label = "Stream frame") {
|
|
458
|
+
let parsed;
|
|
459
|
+
try {
|
|
460
|
+
parsed = JSON.parse(data);
|
|
461
|
+
} catch {
|
|
462
|
+
throw new APIResponseValidationError(`${label} was not valid JSON`, { body: data });
|
|
547
463
|
}
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
464
|
+
throwIfInBandError(parsed);
|
|
465
|
+
if (!isChunkShaped(parsed)) {
|
|
466
|
+
throw new APIResponseValidationError(`${label} was not a chat completion chunk`, {
|
|
467
|
+
body: data
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
return parsed;
|
|
552
471
|
}
|
|
553
|
-
function
|
|
554
|
-
|
|
472
|
+
function completionFrom(parsed, body, status) {
|
|
473
|
+
if (typeof parsed !== "object" || parsed === null) {
|
|
474
|
+
throw new APIResponseValidationError("Response was not a chat completion", { status, body });
|
|
475
|
+
}
|
|
476
|
+
const c = parsed;
|
|
477
|
+
if (typeof c.id !== "string" || typeof c.model !== "string" || !Array.isArray(c.choices)) {
|
|
478
|
+
throw new APIResponseValidationError("Response was not a chat completion", { status, body });
|
|
479
|
+
}
|
|
480
|
+
return parsed;
|
|
555
481
|
}
|
|
556
|
-
function
|
|
557
|
-
|
|
482
|
+
async function parseCompletion(response) {
|
|
483
|
+
const body = await response.text();
|
|
484
|
+
let parsed;
|
|
485
|
+
try {
|
|
486
|
+
parsed = JSON.parse(body);
|
|
487
|
+
} catch {
|
|
488
|
+
throw new APIResponseValidationError("Response was not valid JSON", {
|
|
489
|
+
status: response.status,
|
|
490
|
+
body
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
return completionFrom(parsed, body, response.status);
|
|
558
494
|
}
|
|
559
|
-
function
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
495
|
+
function parseDecryptedCompletion(json, status) {
|
|
496
|
+
let parsed;
|
|
497
|
+
try {
|
|
498
|
+
parsed = JSON.parse(json);
|
|
499
|
+
} catch {
|
|
500
|
+
throw new APIResponseValidationError("Decrypted response was not valid JSON", {
|
|
501
|
+
status,
|
|
502
|
+
body: json
|
|
503
|
+
});
|
|
567
504
|
}
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
}
|
|
575
|
-
out.set(parts[i], off);
|
|
576
|
-
off += parts[i].length;
|
|
505
|
+
try {
|
|
506
|
+
return completionFrom(parsed, json, status);
|
|
507
|
+
} catch {
|
|
508
|
+
throw new APIResponseValidationError("Decrypted response was not a chat completion", {
|
|
509
|
+
status,
|
|
510
|
+
body: json
|
|
511
|
+
});
|
|
577
512
|
}
|
|
578
|
-
return out;
|
|
579
513
|
}
|
|
580
|
-
function
|
|
581
|
-
const
|
|
582
|
-
let
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
514
|
+
async function readSealedReply(response) {
|
|
515
|
+
const body = await response.text();
|
|
516
|
+
let parsed;
|
|
517
|
+
try {
|
|
518
|
+
parsed = JSON.parse(body);
|
|
519
|
+
} catch {
|
|
520
|
+
throw new APIResponseValidationError("Response was not valid JSON", {
|
|
521
|
+
status: response.status,
|
|
522
|
+
body
|
|
523
|
+
});
|
|
586
524
|
}
|
|
587
|
-
|
|
525
|
+
throwIfInBandError(parsed, "The server reported an error");
|
|
526
|
+
const inner = typeof parsed === "object" && parsed !== null ? parsed.pendra_encrypted : void 0;
|
|
527
|
+
if (!inner) throw unsealedReplyError();
|
|
528
|
+
return inner;
|
|
588
529
|
}
|
|
589
|
-
function
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
530
|
+
function parseDecryptedJson(json, status) {
|
|
531
|
+
try {
|
|
532
|
+
return JSON.parse(json);
|
|
533
|
+
} catch {
|
|
534
|
+
throw new APIResponseValidationError("Decrypted response was not valid JSON", {
|
|
535
|
+
status,
|
|
536
|
+
body: json
|
|
537
|
+
});
|
|
593
538
|
}
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
// src/resources/audio/transcriptions.ts
|
|
542
|
+
var ENCODER = new TextEncoder();
|
|
543
|
+
var DECODER = new TextDecoder();
|
|
544
|
+
var MAX_FILE_SIZE = 25 * 1024 * 1024;
|
|
545
|
+
var MIME_EXT = {
|
|
546
|
+
"audio/mpeg": "mp3",
|
|
547
|
+
"audio/mp3": "mp3",
|
|
548
|
+
"audio/mp4": "m4a",
|
|
549
|
+
"audio/x-m4a": "m4a",
|
|
550
|
+
"audio/wav": "wav",
|
|
551
|
+
"audio/wave": "wav",
|
|
552
|
+
"audio/x-wav": "wav",
|
|
553
|
+
"audio/webm": "webm",
|
|
554
|
+
"audio/ogg": "ogg",
|
|
555
|
+
"audio/flac": "flac",
|
|
556
|
+
"audio/x-flac": "flac"
|
|
557
|
+
};
|
|
558
|
+
function extFromMime(type) {
|
|
559
|
+
if (!type) return "mp3";
|
|
560
|
+
const base = type.split(";")[0].trim().toLowerCase();
|
|
561
|
+
return MIME_EXT[base] ?? "mp3";
|
|
562
|
+
}
|
|
563
|
+
function asBlob(file) {
|
|
564
|
+
if (file instanceof Blob) {
|
|
565
|
+
const asFile = file;
|
|
566
|
+
if (asFile.name) {
|
|
567
|
+
return { blob: file, filename: asFile.name };
|
|
601
568
|
}
|
|
569
|
+
return { blob: file, filename: `audio.${extFromMime(file.type)}` };
|
|
602
570
|
}
|
|
603
|
-
const
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
const ciphertext = chacha20poly13052(dek, nonce, aad).encrypt(body);
|
|
607
|
-
const recipients = [];
|
|
608
|
-
const responseKeys = /* @__PURE__ */ new Map();
|
|
609
|
-
for (const pub of uniquePubs) {
|
|
610
|
-
const { enc, ctx: sealer } = setupBaseS(pub, SUITE_INFO);
|
|
611
|
-
const sealedDek = sealer.seal(new Uint8Array(0), dek);
|
|
612
|
-
const kid = fingerprint(pub);
|
|
613
|
-
responseKeys.set(kid, sealer.export(RESPONSE_EXPORT_CTX, 32));
|
|
614
|
-
recipients.push({ kid, enc: b64(enc), sealed_dek: b64(sealedDek) });
|
|
571
|
+
const { filename, content } = file;
|
|
572
|
+
if (content instanceof Blob) {
|
|
573
|
+
return { blob: content, filename };
|
|
615
574
|
}
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
575
|
+
return { blob: new Blob([content]), filename };
|
|
576
|
+
}
|
|
577
|
+
async function extractErrorDetail(response) {
|
|
578
|
+
let raw = "";
|
|
579
|
+
try {
|
|
580
|
+
raw = await response.text();
|
|
581
|
+
} catch {
|
|
582
|
+
return response.statusText;
|
|
624
583
|
}
|
|
625
|
-
if (
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
584
|
+
if (!raw) return response.statusText;
|
|
585
|
+
try {
|
|
586
|
+
const body = JSON.parse(raw);
|
|
587
|
+
return body.detail ?? body.error?.message ?? raw;
|
|
588
|
+
} catch {
|
|
589
|
+
return raw;
|
|
629
590
|
}
|
|
630
|
-
return { envelope, responseKeys };
|
|
631
|
-
}
|
|
632
|
-
var API_TIMING_CHUNK_KEYS = /* @__PURE__ */ new Set(["id", "object", "created", "model", "choices", "pendra"]);
|
|
633
|
-
function isApiTimingChunk(frame) {
|
|
634
|
-
if (frame === null || typeof frame !== "object" || Array.isArray(frame)) return false;
|
|
635
|
-
const obj = frame;
|
|
636
|
-
const pendra = obj.pendra;
|
|
637
|
-
return Object.keys(obj).every((k) => API_TIMING_CHUNK_KEYS.has(k)) && Array.isArray(obj.choices) && obj.choices.length === 0 && pendra !== null && typeof pendra === "object" && Object.keys(pendra).length === 1 && "timing" in pendra;
|
|
638
|
-
}
|
|
639
|
-
function unsealedReplyError() {
|
|
640
|
-
return new Error(
|
|
641
|
-
"private_inference: refusing an unencrypted reply to an encrypted request (it could have been forged in transit)"
|
|
642
|
-
);
|
|
643
591
|
}
|
|
644
|
-
var
|
|
645
|
-
constructor(
|
|
646
|
-
this.
|
|
647
|
-
this.nextSeq = 0;
|
|
648
|
-
this.keys = responseKeys;
|
|
592
|
+
var Transcriptions = class {
|
|
593
|
+
constructor(client) {
|
|
594
|
+
this.client = client;
|
|
649
595
|
}
|
|
650
|
-
|
|
651
|
-
if (
|
|
652
|
-
throw new Error(
|
|
653
|
-
"private_inference: refusing a response that is not in v2 form (it could have been forged in transit)"
|
|
654
|
-
);
|
|
596
|
+
async create(params) {
|
|
597
|
+
if (!params.model) {
|
|
598
|
+
throw new Error("model is required");
|
|
655
599
|
}
|
|
656
|
-
if (
|
|
657
|
-
|
|
658
|
-
if (dek === void 0) {
|
|
659
|
-
throw new Error("private_inference: first response frame names no key this request was sealed to");
|
|
600
|
+
if (params.beam_size != null && !(Number.isInteger(params.beam_size) && params.beam_size >= 1 && params.beam_size <= 8)) {
|
|
601
|
+
throw new Error(`beam_size must be an integer between 1 and 8 (got ${params.beam_size})`);
|
|
660
602
|
}
|
|
661
|
-
|
|
603
|
+
const { blob, filename } = asBlob(params.file);
|
|
604
|
+
if (blob.size === 0) {
|
|
605
|
+
throw new Error("audio file is empty");
|
|
606
|
+
}
|
|
607
|
+
if (blob.size > MAX_FILE_SIZE) {
|
|
608
|
+
throw new Error(`audio file exceeds ${MAX_FILE_SIZE / (1024 * 1024)}MB limit`);
|
|
609
|
+
}
|
|
610
|
+
const timeout = Math.max(this.client.timeout ?? 0, 3e5);
|
|
611
|
+
if (this.client.privateInferenceEnabled) {
|
|
612
|
+
return this.createEncrypted(params, blob, timeout);
|
|
613
|
+
}
|
|
614
|
+
const form = new FormData();
|
|
615
|
+
form.append("file", blob, filename);
|
|
616
|
+
form.append("model", params.model);
|
|
617
|
+
if (params.language) form.append("language", params.language);
|
|
618
|
+
if (params.prompt) form.append("prompt", params.prompt);
|
|
619
|
+
if (params.response_format) form.append("response_format", params.response_format);
|
|
620
|
+
if (params.temperature != null) form.append("temperature", String(params.temperature));
|
|
621
|
+
if (params.beam_size != null) form.append("beam_size", String(params.beam_size));
|
|
622
|
+
if (params.timestamp_granularities) {
|
|
623
|
+
for (const g of params.timestamp_granularities) {
|
|
624
|
+
form.append("timestamp_granularities[]", g);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
const controller = new AbortController();
|
|
628
|
+
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
629
|
+
let response;
|
|
630
|
+
try {
|
|
631
|
+
response = await fetch(`${this.client.baseURL}/api/v1/audio/transcriptions`, {
|
|
632
|
+
method: "POST",
|
|
633
|
+
headers: {
|
|
634
|
+
Authorization: `Bearer ${this.client.apiKey}`,
|
|
635
|
+
...params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : {}
|
|
636
|
+
},
|
|
637
|
+
body: form,
|
|
638
|
+
signal: controller.signal
|
|
639
|
+
});
|
|
640
|
+
} catch (err) {
|
|
641
|
+
clearTimeout(timeoutId);
|
|
642
|
+
if (err instanceof DOMException && err.name === "AbortError") {
|
|
643
|
+
throw new APIConnectionError("Transcription request timed out");
|
|
644
|
+
}
|
|
645
|
+
throw new APIConnectionError(String(err));
|
|
646
|
+
}
|
|
647
|
+
clearTimeout(timeoutId);
|
|
648
|
+
if (response.status >= 400) {
|
|
649
|
+
const detail = await extractErrorDetail(response);
|
|
650
|
+
if (response.status === 401) {
|
|
651
|
+
throw new AuthenticationError(detail);
|
|
652
|
+
}
|
|
653
|
+
if (response.status === 429) {
|
|
654
|
+
throw new RateLimitError(detail);
|
|
655
|
+
}
|
|
656
|
+
throw new APIStatusError(detail, response.status);
|
|
657
|
+
}
|
|
658
|
+
const format = params.response_format;
|
|
659
|
+
if (format === "text" || format === "srt" || format === "vtt") {
|
|
660
|
+
const text = await response.text();
|
|
661
|
+
return { text };
|
|
662
|
+
}
|
|
663
|
+
return await response.json();
|
|
664
|
+
}
|
|
665
|
+
/**
|
|
666
|
+
* Private-inference transcription. There is no multipart upload: the audio
|
|
667
|
+
* bytes ride inside the envelope (sealed under the request's data key) and
|
|
668
|
+
* the request options are the sealed JSON body, POSTed as JSON to the same
|
|
669
|
+
* route.
|
|
670
|
+
*/
|
|
671
|
+
async createEncrypted(params, blob, timeout) {
|
|
672
|
+
const body = { model: params.model };
|
|
673
|
+
if (params.language) body.language = params.language;
|
|
674
|
+
if (params.prompt) body.prompt = params.prompt;
|
|
675
|
+
if (params.response_format) body.response_format = params.response_format;
|
|
676
|
+
if (params.temperature != null) body.temperature = params.temperature;
|
|
677
|
+
if (params.beam_size != null) body.beam_size = params.beam_size;
|
|
678
|
+
if (params.timestamp_granularities) {
|
|
679
|
+
body.timestamp_granularities = params.timestamp_granularities;
|
|
680
|
+
}
|
|
681
|
+
const engine = await this.client._privateEngine();
|
|
682
|
+
const { topLevel, decryptor } = engine.seal({
|
|
683
|
+
model: params.model,
|
|
684
|
+
stream: false,
|
|
685
|
+
taskType: "transcription",
|
|
686
|
+
body: ENCODER.encode(JSON.stringify(body)),
|
|
687
|
+
binary: new Uint8Array(await blob.arrayBuffer())
|
|
688
|
+
});
|
|
689
|
+
const { response } = await this.client._fetch(
|
|
690
|
+
"/api/v1/audio/transcriptions",
|
|
691
|
+
{
|
|
692
|
+
method: "POST",
|
|
693
|
+
body: topLevel,
|
|
694
|
+
headers: params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0,
|
|
695
|
+
timeout
|
|
696
|
+
}
|
|
697
|
+
);
|
|
698
|
+
const raw = DECODER.decode(decryptor.openResult(await readSealedReply(response)));
|
|
699
|
+
const parsed = parseDecryptedJson(raw, response.status);
|
|
700
|
+
if (typeof parsed === "string") return { text: parsed };
|
|
701
|
+
if (typeof parsed === "object" && parsed !== null) {
|
|
702
|
+
if (typeof parsed.text !== "string") {
|
|
703
|
+
throw new APIResponseValidationError("Decrypted response was not a transcription", {
|
|
704
|
+
status: response.status,
|
|
705
|
+
body: raw
|
|
706
|
+
});
|
|
707
|
+
}
|
|
708
|
+
return parsed;
|
|
709
|
+
}
|
|
710
|
+
return { text: raw };
|
|
711
|
+
}
|
|
712
|
+
};
|
|
713
|
+
|
|
714
|
+
// src/resources/audio/index.ts
|
|
715
|
+
var Audio = class {
|
|
716
|
+
constructor(client) {
|
|
717
|
+
this.transcriptions = new Transcriptions(client);
|
|
718
|
+
}
|
|
719
|
+
};
|
|
720
|
+
|
|
721
|
+
// src/_sse.ts
|
|
722
|
+
var DEFAULT_EVENT = "message";
|
|
723
|
+
function fieldValue(line, name) {
|
|
724
|
+
const value = line.slice(name.length + 1);
|
|
725
|
+
return value.startsWith(" ") ? value.slice(1) : value;
|
|
726
|
+
}
|
|
727
|
+
var SseDecoder = class {
|
|
728
|
+
constructor() {
|
|
729
|
+
this.buffer = "";
|
|
730
|
+
this.event = "";
|
|
731
|
+
this.data = [];
|
|
662
732
|
}
|
|
663
|
-
/**
|
|
664
|
-
|
|
665
|
-
this.
|
|
666
|
-
|
|
733
|
+
/** Feed a chunk of decoded text; returns the payloads it completed. */
|
|
734
|
+
push(text) {
|
|
735
|
+
this.buffer += text;
|
|
736
|
+
const lines = this.buffer.split("\n");
|
|
737
|
+
this.buffer = lines.pop() ?? "";
|
|
738
|
+
const out = [];
|
|
739
|
+
for (const line of lines) {
|
|
740
|
+
const payload = this.pushLine(line);
|
|
741
|
+
if (payload !== null) out.push(payload);
|
|
742
|
+
}
|
|
743
|
+
return out;
|
|
667
744
|
}
|
|
668
|
-
/**
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
745
|
+
/**
|
|
746
|
+
* Release what the stream ended without terminating: the held-back partial
|
|
747
|
+
* line, plus any frame that never got its blank line.
|
|
748
|
+
*
|
|
749
|
+
* The spec discards an unterminated final block; we keep it, so a connection
|
|
750
|
+
* that drops after the last `data:` line but before its blank line still
|
|
751
|
+
* delivers that payload rather than silently losing it.
|
|
752
|
+
*/
|
|
753
|
+
flush() {
|
|
754
|
+
const out = [];
|
|
755
|
+
if (this.buffer !== "") {
|
|
756
|
+
const payload = this.pushLine(this.buffer);
|
|
757
|
+
this.buffer = "";
|
|
758
|
+
if (payload !== null) out.push(payload);
|
|
675
759
|
}
|
|
676
|
-
this.
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
return pt;
|
|
760
|
+
const tail = this.endFrame();
|
|
761
|
+
if (tail !== null) out.push(tail);
|
|
762
|
+
return out;
|
|
680
763
|
}
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
764
|
+
pushLine(rawLine) {
|
|
765
|
+
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
|
|
766
|
+
if (line === "") return this.endFrame();
|
|
767
|
+
if (line.startsWith(":")) return null;
|
|
768
|
+
if (line.startsWith("event:")) {
|
|
769
|
+
this.event = fieldValue(line, "event");
|
|
770
|
+
return null;
|
|
771
|
+
}
|
|
772
|
+
if (line.startsWith("data:")) {
|
|
773
|
+
this.data.push(fieldValue(line, "data"));
|
|
774
|
+
return null;
|
|
775
|
+
}
|
|
776
|
+
return null;
|
|
692
777
|
}
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
778
|
+
endFrame() {
|
|
779
|
+
const { data, event } = this;
|
|
780
|
+
this.data = [];
|
|
781
|
+
this.event = "";
|
|
782
|
+
if (data.length === 0) return null;
|
|
783
|
+
if (event !== "" && event !== DEFAULT_EVENT) return null;
|
|
784
|
+
return data.join("\n");
|
|
696
785
|
}
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
786
|
+
};
|
|
787
|
+
|
|
788
|
+
// src/streaming.ts
|
|
789
|
+
var Stream = class {
|
|
790
|
+
constructor(response, controller, idleTimeoutMs) {
|
|
791
|
+
this.decoder = new TextDecoder();
|
|
792
|
+
this.sse = new SseDecoder();
|
|
793
|
+
this.done = false;
|
|
794
|
+
if (!response.body) {
|
|
795
|
+
throw new Error("Response body is null \u2014 streaming not supported");
|
|
796
|
+
}
|
|
797
|
+
this.reader = response.body.getReader();
|
|
798
|
+
this.controller = controller;
|
|
799
|
+
this.idleTimeoutMs = idleTimeoutMs;
|
|
702
800
|
}
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
break;
|
|
722
|
-
case 10:
|
|
723
|
-
out += "\\n";
|
|
724
|
-
break;
|
|
725
|
-
case 12:
|
|
726
|
-
out += "\\f";
|
|
727
|
-
break;
|
|
728
|
-
case 13:
|
|
729
|
-
out += "\\r";
|
|
730
|
-
break;
|
|
731
|
-
default:
|
|
732
|
-
if (code < 32 || code > 126) {
|
|
733
|
-
out += "\\u" + code.toString(16).padStart(4, "0");
|
|
734
|
-
} else {
|
|
735
|
-
out += s[i];
|
|
801
|
+
async *[Symbol.asyncIterator]() {
|
|
802
|
+
try {
|
|
803
|
+
while (!this.done) {
|
|
804
|
+
const { value, done: readerDone } = await readWithIdleTimeout(
|
|
805
|
+
this.reader,
|
|
806
|
+
this.idleTimeoutMs
|
|
807
|
+
);
|
|
808
|
+
const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
|
|
809
|
+
for (const data of payloads) {
|
|
810
|
+
if (data === "[DONE]") {
|
|
811
|
+
this.done = true;
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
yield parseStreamFrame(data);
|
|
815
|
+
}
|
|
816
|
+
if (readerDone) {
|
|
817
|
+
this.done = true;
|
|
818
|
+
break;
|
|
736
819
|
}
|
|
820
|
+
}
|
|
821
|
+
} finally {
|
|
822
|
+
releaseReader(this.reader, this.controller, this.done);
|
|
737
823
|
}
|
|
738
824
|
}
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
825
|
+
abort() {
|
|
826
|
+
this.done = true;
|
|
827
|
+
this.controller.abort();
|
|
828
|
+
}
|
|
829
|
+
};
|
|
830
|
+
async function readWithIdleTimeout(reader, idleTimeoutMs) {
|
|
831
|
+
if (!idleTimeoutMs) return reader.read();
|
|
832
|
+
let timer;
|
|
833
|
+
const idle = new Promise((_, reject) => {
|
|
834
|
+
timer = setTimeout(
|
|
835
|
+
() => reject(new APIConnectionError(`Stream received no data for ${idleTimeoutMs}ms`)),
|
|
836
|
+
idleTimeoutMs
|
|
837
|
+
);
|
|
838
|
+
});
|
|
839
|
+
try {
|
|
840
|
+
return await Promise.race([reader.read(), idle]);
|
|
841
|
+
} finally {
|
|
842
|
+
clearTimeout(timer);
|
|
843
|
+
}
|
|
744
844
|
}
|
|
745
|
-
function
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
parts.push(role + ":" + flattenContent(m.content));
|
|
751
|
-
if (role === "user") {
|
|
752
|
-
sawUser = true;
|
|
753
|
-
break;
|
|
754
|
-
}
|
|
845
|
+
function releaseReader(reader, controller, finished) {
|
|
846
|
+
if (!finished) {
|
|
847
|
+
controller.abort();
|
|
848
|
+
reader.cancel().catch(() => {
|
|
849
|
+
});
|
|
755
850
|
}
|
|
756
|
-
|
|
757
|
-
const salt = saltOverride != null ? saltOverride : deriveSalt(rawApiKey);
|
|
758
|
-
const mac = hmac(sha256, salt, utf8(parts.join("\0")));
|
|
759
|
-
return toHex(mac);
|
|
851
|
+
reader.releaseLock();
|
|
760
852
|
}
|
|
761
853
|
|
|
762
854
|
// src/_privateStreaming.ts
|
|
763
|
-
var
|
|
855
|
+
var DECODER2 = new TextDecoder();
|
|
764
856
|
var EncryptedStream = class {
|
|
765
857
|
constructor(response, controller, decryptor, idleTimeoutMs) {
|
|
766
858
|
this.decoder = new TextDecoder();
|
|
767
859
|
this.sse = new SseDecoder();
|
|
768
860
|
this.done = false;
|
|
861
|
+
this.aborted = false;
|
|
862
|
+
this.openedAny = false;
|
|
863
|
+
this.declared = false;
|
|
864
|
+
this.terminated = false;
|
|
769
865
|
if (!response.body) {
|
|
770
866
|
throw new Error("Response body is null \u2014 streaming not supported");
|
|
771
867
|
}
|
|
@@ -777,13 +873,18 @@ var EncryptedStream = class {
|
|
|
777
873
|
async *[Symbol.asyncIterator]() {
|
|
778
874
|
try {
|
|
779
875
|
while (!this.done) {
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
this.idleTimeoutMs
|
|
783
|
-
)
|
|
876
|
+
let read;
|
|
877
|
+
try {
|
|
878
|
+
read = await readWithIdleTimeout(this.reader, this.idleTimeoutMs);
|
|
879
|
+
} catch (e) {
|
|
880
|
+
if (this.terminated) return;
|
|
881
|
+
throw e;
|
|
882
|
+
}
|
|
883
|
+
const { value, done: readerDone } = read;
|
|
784
884
|
const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
|
|
785
885
|
for (const data of payloads) {
|
|
786
886
|
if (data === "[DONE]") {
|
|
887
|
+
this.checkEnded();
|
|
787
888
|
this.done = true;
|
|
788
889
|
return;
|
|
789
890
|
}
|
|
@@ -791,6 +892,11 @@ var EncryptedStream = class {
|
|
|
791
892
|
try {
|
|
792
893
|
frame = JSON.parse(data);
|
|
793
894
|
} catch {
|
|
895
|
+
if (this.aborted) continue;
|
|
896
|
+
if (readerDone) {
|
|
897
|
+
if (this.terminated) continue;
|
|
898
|
+
this.checkEnded();
|
|
899
|
+
}
|
|
794
900
|
throw new APIResponseValidationError("Stream frame was not valid JSON", {
|
|
795
901
|
body: data
|
|
796
902
|
});
|
|
@@ -798,24 +904,39 @@ var EncryptedStream = class {
|
|
|
798
904
|
const inner = frame?.pendra_encrypted;
|
|
799
905
|
if (!inner) {
|
|
800
906
|
if (isApiTimingChunk(frame)) {
|
|
907
|
+
this.checkEnded();
|
|
801
908
|
yield parseStreamFrame(data);
|
|
802
909
|
continue;
|
|
803
910
|
}
|
|
804
911
|
parseStreamFrame(data);
|
|
805
912
|
throw unsealedReplyError();
|
|
806
913
|
}
|
|
914
|
+
if (this.terminated) {
|
|
915
|
+
throw new Error(
|
|
916
|
+
"private_inference: refusing a frame after the worker's sealed end of stream"
|
|
917
|
+
);
|
|
918
|
+
}
|
|
807
919
|
const plain = this.decryptor.openChunk(inner);
|
|
808
|
-
const chunkJson =
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
}
|
|
920
|
+
const chunkJson = DECODER2.decode(plain).trim();
|
|
921
|
+
const first = !this.openedAny;
|
|
922
|
+
this.openedAny = true;
|
|
923
|
+
if (first && isStreamTerminatorDeclaration(chunkJson)) {
|
|
924
|
+
this.declared = true;
|
|
814
925
|
continue;
|
|
815
926
|
}
|
|
927
|
+
if (chunkJson === "[DONE]") {
|
|
928
|
+
if (this.declared) {
|
|
929
|
+
this.terminated = true;
|
|
930
|
+
continue;
|
|
931
|
+
}
|
|
932
|
+
this.done = true;
|
|
933
|
+
return;
|
|
934
|
+
}
|
|
935
|
+
if (!chunkJson) continue;
|
|
816
936
|
yield parseStreamFrame(chunkJson, "Decrypted stream frame");
|
|
817
937
|
}
|
|
818
938
|
if (readerDone) {
|
|
939
|
+
this.checkEnded();
|
|
819
940
|
this.done = true;
|
|
820
941
|
break;
|
|
821
942
|
}
|
|
@@ -824,15 +945,26 @@ var EncryptedStream = class {
|
|
|
824
945
|
releaseReader(this.reader, this.controller, this.done);
|
|
825
946
|
}
|
|
826
947
|
}
|
|
948
|
+
/**
|
|
949
|
+
* The server ended the stream: it must have carried a sealed frame, and after
|
|
950
|
+
* a declaration, it must have ended on the sealed `[DONE]`.
|
|
951
|
+
*/
|
|
952
|
+
checkEnded() {
|
|
953
|
+
if (this.aborted) return;
|
|
954
|
+
if (!this.openedAny || this.declared && !this.terminated) {
|
|
955
|
+
throw truncatedStreamError();
|
|
956
|
+
}
|
|
957
|
+
}
|
|
827
958
|
abort() {
|
|
959
|
+
this.aborted = true;
|
|
828
960
|
this.done = true;
|
|
829
961
|
this.controller.abort();
|
|
830
962
|
}
|
|
831
963
|
};
|
|
832
964
|
|
|
833
965
|
// src/resources/chat/completions.ts
|
|
834
|
-
var
|
|
835
|
-
var
|
|
966
|
+
var ENCODER2 = new TextEncoder();
|
|
967
|
+
var DECODER3 = new TextDecoder();
|
|
836
968
|
var Completions = class {
|
|
837
969
|
constructor(client) {
|
|
838
970
|
this.client = client;
|
|
@@ -867,7 +999,10 @@ var Completions = class {
|
|
|
867
999
|
model: params.model,
|
|
868
1000
|
stream,
|
|
869
1001
|
taskType: "chat",
|
|
870
|
-
|
|
1002
|
+
// The terminator request rides inside the sealed body, so the relay can
|
|
1003
|
+
// neither strip nor add it: it asks the worker to seal the end of the
|
|
1004
|
+
// stream (#2157).
|
|
1005
|
+
body: ENCODER2.encode(JSON.stringify(stream ? { ...body, [STREAM_TERMINATOR_KEY]: 1 } : body)),
|
|
871
1006
|
messages: params.messages
|
|
872
1007
|
});
|
|
873
1008
|
if (stream) {
|
|
@@ -895,7 +1030,7 @@ var Completions = class {
|
|
|
895
1030
|
throw unsealedReplyError();
|
|
896
1031
|
}
|
|
897
1032
|
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
898
|
-
return parseDecryptedCompletion(
|
|
1033
|
+
return parseDecryptedCompletion(DECODER3.decode(plain), response.status);
|
|
899
1034
|
}
|
|
900
1035
|
};
|
|
901
1036
|
|
|
@@ -907,8 +1042,8 @@ var Chat = class {
|
|
|
907
1042
|
};
|
|
908
1043
|
|
|
909
1044
|
// src/resources/embeddings.ts
|
|
910
|
-
var
|
|
911
|
-
var
|
|
1045
|
+
var ENCODER3 = new TextEncoder();
|
|
1046
|
+
var DECODER4 = new TextDecoder();
|
|
912
1047
|
function validateParams(params) {
|
|
913
1048
|
if (!params.model || typeof params.model !== "string") {
|
|
914
1049
|
throw new Error("model must be a non-empty string");
|
|
@@ -972,7 +1107,7 @@ var Embeddings = class {
|
|
|
972
1107
|
model,
|
|
973
1108
|
stream: false,
|
|
974
1109
|
taskType: "embeddings",
|
|
975
|
-
body:
|
|
1110
|
+
body: ENCODER3.encode(JSON.stringify(body))
|
|
976
1111
|
});
|
|
977
1112
|
const { response } = await this.client._fetch(
|
|
978
1113
|
"/api/v1/embeddings",
|
|
@@ -983,11 +1118,13 @@ var Embeddings = class {
|
|
|
983
1118
|
throw unsealedReplyError();
|
|
984
1119
|
}
|
|
985
1120
|
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
986
|
-
return JSON.parse(
|
|
1121
|
+
return JSON.parse(DECODER4.decode(plain));
|
|
987
1122
|
}
|
|
988
1123
|
};
|
|
989
1124
|
|
|
990
1125
|
// src/resources/images/generations.ts
|
|
1126
|
+
var ENCODER4 = new TextEncoder();
|
|
1127
|
+
var DECODER5 = new TextDecoder();
|
|
991
1128
|
var SIZE_RE = /^\d+x\d+$/;
|
|
992
1129
|
function validateParams2(params) {
|
|
993
1130
|
if (!params.prompt || !params.prompt.trim()) {
|
|
@@ -1005,9 +1142,6 @@ var Generations = class {
|
|
|
1005
1142
|
this.client = client;
|
|
1006
1143
|
}
|
|
1007
1144
|
async create(params) {
|
|
1008
|
-
if (this.client.privateInferenceEnabled) {
|
|
1009
|
-
throw new Error("private inference is not yet supported for images/audio");
|
|
1010
|
-
}
|
|
1011
1145
|
validateParams2(params);
|
|
1012
1146
|
const body = {
|
|
1013
1147
|
model: params.model,
|
|
@@ -1019,16 +1153,38 @@ var Generations = class {
|
|
|
1019
1153
|
if (params.num_inference_steps != null) body.num_inference_steps = params.num_inference_steps;
|
|
1020
1154
|
if (params.seed != null) body.seed = params.seed;
|
|
1021
1155
|
if (params.negative_prompt != null) body.negative_prompt = params.negative_prompt;
|
|
1156
|
+
const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
|
|
1157
|
+
if (this.client.privateInferenceEnabled) {
|
|
1158
|
+
return this.createEncrypted(params.model, body, headers);
|
|
1159
|
+
}
|
|
1022
1160
|
const { response } = await this.client._fetch(
|
|
1023
1161
|
"/api/v1/images/generations",
|
|
1024
|
-
{
|
|
1025
|
-
method: "POST",
|
|
1026
|
-
body,
|
|
1027
|
-
headers: params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0
|
|
1028
|
-
}
|
|
1162
|
+
{ method: "POST", body, headers }
|
|
1029
1163
|
);
|
|
1030
1164
|
return await response.json();
|
|
1031
1165
|
}
|
|
1166
|
+
async createEncrypted(model, body, headers) {
|
|
1167
|
+
const engine = await this.client._privateEngine();
|
|
1168
|
+
const { topLevel, decryptor } = engine.seal({
|
|
1169
|
+
model,
|
|
1170
|
+
stream: false,
|
|
1171
|
+
taskType: "image_generation",
|
|
1172
|
+
body: ENCODER4.encode(JSON.stringify(body))
|
|
1173
|
+
});
|
|
1174
|
+
const { response } = await this.client._fetch(
|
|
1175
|
+
"/api/v1/images/generations",
|
|
1176
|
+
{ method: "POST", body: topLevel, headers }
|
|
1177
|
+
);
|
|
1178
|
+
const plain = decryptor.openResult(await readSealedReply(response));
|
|
1179
|
+
const parsed = parseDecryptedJson(DECODER5.decode(plain), response.status);
|
|
1180
|
+
if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.data)) {
|
|
1181
|
+
throw new APIResponseValidationError("Decrypted response was not an image generation", {
|
|
1182
|
+
status: response.status,
|
|
1183
|
+
body: DECODER5.decode(plain)
|
|
1184
|
+
});
|
|
1185
|
+
}
|
|
1186
|
+
return parsed;
|
|
1187
|
+
}
|
|
1032
1188
|
};
|
|
1033
1189
|
|
|
1034
1190
|
// src/resources/images/index.ts
|
|
@@ -1053,8 +1209,8 @@ var Models = class {
|
|
|
1053
1209
|
};
|
|
1054
1210
|
|
|
1055
1211
|
// src/resources/rerank.ts
|
|
1056
|
-
var
|
|
1057
|
-
var
|
|
1212
|
+
var ENCODER5 = new TextEncoder();
|
|
1213
|
+
var DECODER6 = new TextDecoder();
|
|
1058
1214
|
function validateParams3(params) {
|
|
1059
1215
|
if (!params.model || typeof params.model !== "string") {
|
|
1060
1216
|
throw new Error("model must be a non-empty string");
|
|
@@ -1113,7 +1269,7 @@ var Rerank = class {
|
|
|
1113
1269
|
model,
|
|
1114
1270
|
stream: false,
|
|
1115
1271
|
taskType: "rerank",
|
|
1116
|
-
body:
|
|
1272
|
+
body: ENCODER5.encode(JSON.stringify(body))
|
|
1117
1273
|
});
|
|
1118
1274
|
const { response } = await this.client._fetch(
|
|
1119
1275
|
"/api/v1/rerank",
|
|
@@ -1124,12 +1280,12 @@ var Rerank = class {
|
|
|
1124
1280
|
throw unsealedReplyError();
|
|
1125
1281
|
}
|
|
1126
1282
|
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
1127
|
-
return JSON.parse(
|
|
1283
|
+
return JSON.parse(DECODER6.decode(plain));
|
|
1128
1284
|
}
|
|
1129
1285
|
};
|
|
1130
1286
|
|
|
1131
1287
|
// src/version.ts
|
|
1132
|
-
var VERSION = "0.
|
|
1288
|
+
var VERSION = "0.15.1";
|
|
1133
1289
|
var USER_AGENT = `pendra-node/${VERSION}`;
|
|
1134
1290
|
|
|
1135
1291
|
// src/_privateInferenceEngine.ts
|
|
@@ -1294,6 +1450,7 @@ var PrivateInferenceEngine = class {
|
|
|
1294
1450
|
/**
|
|
1295
1451
|
* Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
|
|
1296
1452
|
* `messages` (chat only) drives the affinity token; pass undefined for non-chat.
|
|
1453
|
+
* `binary` (audio only) is sealed under the same data key as the body.
|
|
1297
1454
|
*/
|
|
1298
1455
|
seal(args) {
|
|
1299
1456
|
if (this.orgPubs === null || this.orgPubs.length === 0) {
|
|
@@ -1309,7 +1466,8 @@ var PrivateInferenceEngine = class {
|
|
|
1309
1466
|
model: args.model,
|
|
1310
1467
|
stream: args.stream,
|
|
1311
1468
|
taskType: args.taskType,
|
|
1312
|
-
affinityKey: affinity
|
|
1469
|
+
affinityKey: affinity,
|
|
1470
|
+
binary: args.binary ?? null
|
|
1313
1471
|
});
|
|
1314
1472
|
const topLevel = {
|
|
1315
1473
|
model: args.model,
|
|
@@ -1428,7 +1586,10 @@ var Pendra = class {
|
|
|
1428
1586
|
let message;
|
|
1429
1587
|
try {
|
|
1430
1588
|
const body = await response.json();
|
|
1431
|
-
|
|
1589
|
+
if (typeof body.detail === "string") message = body.detail;
|
|
1590
|
+
else if (typeof body.error?.message === "string") message = body.error.message;
|
|
1591
|
+
else if (body.detail != null) message = JSON.stringify(body.detail);
|
|
1592
|
+
else message = response.statusText;
|
|
1432
1593
|
} catch {
|
|
1433
1594
|
message = response.statusText;
|
|
1434
1595
|
}
|
|
@@ -1441,8 +1602,9 @@ var Pendra = class {
|
|
|
1441
1602
|
}
|
|
1442
1603
|
/** @internal */
|
|
1443
1604
|
async _fetch(path, options) {
|
|
1605
|
+
const timeout = options.timeout ?? this.timeout;
|
|
1444
1606
|
const controller = new AbortController();
|
|
1445
|
-
const timeoutId = setTimeout(() => controller.abort(),
|
|
1607
|
+
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
1446
1608
|
const headers = {
|
|
1447
1609
|
Authorization: `Bearer ${this.apiKey}`,
|
|
1448
1610
|
"Content-Type": "application/json",
|
|
@@ -1461,7 +1623,7 @@ var Pendra = class {
|
|
|
1461
1623
|
clearTimeout(timeoutId);
|
|
1462
1624
|
if (err instanceof DOMException && err.name === "AbortError") {
|
|
1463
1625
|
throw new APIConnectionError(
|
|
1464
|
-
`Request timed out after ${
|
|
1626
|
+
`Request timed out after ${timeout}ms`
|
|
1465
1627
|
);
|
|
1466
1628
|
}
|
|
1467
1629
|
throw new APIConnectionError(
|
|
@@ -1474,7 +1636,10 @@ var Pendra = class {
|
|
|
1474
1636
|
let message;
|
|
1475
1637
|
try {
|
|
1476
1638
|
const body = await response.json();
|
|
1477
|
-
|
|
1639
|
+
if (typeof body.detail === "string") message = body.detail;
|
|
1640
|
+
else if (typeof body.error?.message === "string") message = body.error.message;
|
|
1641
|
+
else if (body.detail != null) message = JSON.stringify(body.detail);
|
|
1642
|
+
else message = response.statusText;
|
|
1478
1643
|
} catch {
|
|
1479
1644
|
message = response.statusText;
|
|
1480
1645
|
}
|