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