pendra 0.14.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +12 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +757 -649
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +757 -649
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -105,708 +105,786 @@ var APIStreamError = class extends APIError {
|
|
|
105
105
|
}
|
|
106
106
|
};
|
|
107
107
|
|
|
108
|
-
// src/
|
|
109
|
-
var
|
|
110
|
-
var
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
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 };
|
|
108
|
+
// src/_privateInference.ts
|
|
109
|
+
var import_chacha2 = require("@noble/ciphers/chacha.js");
|
|
110
|
+
var import_hkdf2 = require("@noble/hashes/hkdf.js");
|
|
111
|
+
|
|
112
|
+
// src/_hpke.ts
|
|
113
|
+
var import_ed25519 = require("@noble/curves/ed25519.js");
|
|
114
|
+
var import_chacha = require("@noble/ciphers/chacha.js");
|
|
115
|
+
var import_sha2 = require("@noble/hashes/sha2.js");
|
|
116
|
+
var import_hmac = require("@noble/hashes/hmac.js");
|
|
117
|
+
var import_hkdf = require("@noble/hashes/hkdf.js");
|
|
118
|
+
var import_utils = require("@noble/hashes/utils.js");
|
|
119
|
+
var KEM_ID = 32;
|
|
120
|
+
var KDF_ID = 1;
|
|
121
|
+
var AEAD_ID = 3;
|
|
122
|
+
var NH = 32;
|
|
123
|
+
var NK = 32;
|
|
124
|
+
var NN = 12;
|
|
125
|
+
var NSECRET = 32;
|
|
126
|
+
function i2osp(n, len) {
|
|
127
|
+
const out = new Uint8Array(len);
|
|
128
|
+
for (let i = len - 1; i >= 0; i--) {
|
|
129
|
+
out[i] = n & 255;
|
|
130
|
+
n = Math.floor(n / 256);
|
|
139
131
|
}
|
|
140
|
-
return
|
|
132
|
+
return out;
|
|
141
133
|
}
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
return raw;
|
|
134
|
+
var TEXT_ENCODER = new TextEncoder();
|
|
135
|
+
function bytes(s) {
|
|
136
|
+
return TEXT_ENCODER.encode(s);
|
|
137
|
+
}
|
|
138
|
+
function concat(...parts) {
|
|
139
|
+
let total = 0;
|
|
140
|
+
for (const p of parts) total += p.length;
|
|
141
|
+
const out = new Uint8Array(total);
|
|
142
|
+
let off = 0;
|
|
143
|
+
for (const p of parts) {
|
|
144
|
+
out.set(p, off);
|
|
145
|
+
off += p.length;
|
|
155
146
|
}
|
|
147
|
+
return out;
|
|
156
148
|
}
|
|
157
|
-
var
|
|
158
|
-
|
|
159
|
-
|
|
149
|
+
var SUITE_ID = concat(bytes("HPKE"), i2osp(KEM_ID, 2), i2osp(KDF_ID, 2), i2osp(AEAD_ID, 2));
|
|
150
|
+
var KEM_SUITE_ID = concat(bytes("KEM"), i2osp(KEM_ID, 2));
|
|
151
|
+
var HPKE_VERSION = bytes("HPKE-v1");
|
|
152
|
+
function hkdfExtract(salt, ikm) {
|
|
153
|
+
const effectiveSalt = salt.length === 0 ? new Uint8Array(NH) : salt;
|
|
154
|
+
return (0, import_hkdf.extract)(import_sha2.sha256, ikm, effectiveSalt);
|
|
155
|
+
}
|
|
156
|
+
function hkdfExpand(prk, info, length) {
|
|
157
|
+
return (0, import_hkdf.expand)(import_sha2.sha256, prk, info, length);
|
|
158
|
+
}
|
|
159
|
+
function labeledExtract(salt, label, ikm, suiteId) {
|
|
160
|
+
return hkdfExtract(salt, concat(HPKE_VERSION, suiteId, label, ikm));
|
|
161
|
+
}
|
|
162
|
+
function labeledExpand(prk, label, info, length, suiteId) {
|
|
163
|
+
const labeledInfo = concat(i2osp(length, 2), HPKE_VERSION, suiteId, label, info);
|
|
164
|
+
return hkdfExpand(prk, labeledInfo, length);
|
|
165
|
+
}
|
|
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;
|
|
160
183
|
}
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
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 };
|
|
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];
|
|
224
189
|
}
|
|
225
|
-
return
|
|
190
|
+
return nonce;
|
|
226
191
|
}
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
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);
|
|
233
204
|
}
|
|
234
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
|
+
}
|
|
235
227
|
|
|
236
|
-
// src/
|
|
237
|
-
|
|
238
|
-
|
|
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);
|
|
239
237
|
}
|
|
240
|
-
function
|
|
241
|
-
if (typeof
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
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
|
-
);
|
|
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);
|
|
255
245
|
}
|
|
256
|
-
function
|
|
257
|
-
if (typeof
|
|
258
|
-
|
|
259
|
-
|
|
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;
|
|
260
254
|
}
|
|
261
|
-
function
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
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;
|
|
267
279
|
}
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
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;
|
|
273
288
|
}
|
|
274
|
-
return
|
|
289
|
+
return nonce;
|
|
275
290
|
}
|
|
276
|
-
function
|
|
277
|
-
|
|
278
|
-
|
|
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");
|
|
279
295
|
}
|
|
280
|
-
const
|
|
281
|
-
|
|
282
|
-
|
|
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
|
+
}
|
|
283
304
|
}
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
const
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
});
|
|
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) });
|
|
296
317
|
}
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
status,
|
|
306
|
-
body: json
|
|
307
|
-
});
|
|
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;
|
|
308
326
|
}
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
status,
|
|
314
|
-
body: json
|
|
315
|
-
});
|
|
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));
|
|
316
331
|
}
|
|
332
|
+
return { envelope, responseKeys };
|
|
317
333
|
}
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
const
|
|
323
|
-
return
|
|
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;
|
|
324
340
|
}
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
this.
|
|
334
|
-
|
|
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;
|
|
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 ResponseDecryptor = class {
|
|
347
|
+
constructor(responseKeys) {
|
|
348
|
+
this.dek = null;
|
|
349
|
+
this.nextSeq = 0;
|
|
350
|
+
this.keys = responseKeys;
|
|
361
351
|
}
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
this.event = fieldValue(line, "event");
|
|
368
|
-
return null;
|
|
352
|
+
ensureDek(inner) {
|
|
353
|
+
if (inner.v !== ENVELOPE_VERSION || inner.enc !== void 0) {
|
|
354
|
+
throw new Error(
|
|
355
|
+
"private_inference: refusing a response that is not in v2 form (it could have been forged in transit)"
|
|
356
|
+
);
|
|
369
357
|
}
|
|
370
|
-
if (
|
|
371
|
-
|
|
372
|
-
|
|
358
|
+
if (this.dek !== null) return;
|
|
359
|
+
const dek = inner.kid === void 0 ? void 0 : this.keys.get(inner.kid);
|
|
360
|
+
if (dek === void 0) {
|
|
361
|
+
throw new Error("private_inference: first response frame names no key this request was sealed to");
|
|
373
362
|
}
|
|
374
|
-
|
|
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");
|
|
363
|
+
this.dek = dek;
|
|
383
364
|
}
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
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;
|
|
365
|
+
/** Decrypt a non-streaming result envelope `{v, kid, seq, ciphertext}`. */
|
|
366
|
+
openResult(inner) {
|
|
367
|
+
this.ensureDek(inner);
|
|
368
|
+
return (0, import_chacha2.chacha20poly1305)(this.dek, seqNonce(Number(inner.seq))).decrypt(b64d(inner.ciphertext));
|
|
398
369
|
}
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
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);
|
|
370
|
+
/** Decrypt one streaming chunk envelope, enforcing monotonic `seq`. */
|
|
371
|
+
openChunk(inner) {
|
|
372
|
+
const seq = Number(inner.seq);
|
|
373
|
+
if (seq !== this.nextSeq) {
|
|
374
|
+
throw new Error(
|
|
375
|
+
`private_inference: out-of-order response chunk (seq ${seq}, expected ${this.nextSeq})`
|
|
376
|
+
);
|
|
421
377
|
}
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
this.
|
|
425
|
-
|
|
378
|
+
this.ensureDek(inner);
|
|
379
|
+
const pt = (0, import_chacha2.chacha20poly1305)(this.dek, seqNonce(seq)).decrypt(b64d(inner.ciphertext));
|
|
380
|
+
this.nextSeq += 1;
|
|
381
|
+
return pt;
|
|
426
382
|
}
|
|
427
383
|
};
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
return await Promise.race([reader.read(), idle]);
|
|
439
|
-
} finally {
|
|
440
|
-
clearTimeout(timer);
|
|
384
|
+
function deriveSalt(rawApiKey) {
|
|
385
|
+
const prk = (0, import_hkdf2.extract)(import_sha2.sha256, utf8(rawApiKey), new Uint8Array(32));
|
|
386
|
+
return (0, import_hkdf2.expand)(import_sha2.sha256, prk, AFFINITY_SALT_INFO, 32);
|
|
387
|
+
}
|
|
388
|
+
function canonicalJson(value) {
|
|
389
|
+
if (value === null) return "null";
|
|
390
|
+
const t = typeof value;
|
|
391
|
+
if (t === "boolean") return value ? "true" : "false";
|
|
392
|
+
if (t === "number") {
|
|
393
|
+
return String(value);
|
|
441
394
|
}
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
controller.abort();
|
|
446
|
-
reader.cancel().catch(() => {
|
|
447
|
-
});
|
|
395
|
+
if (t === "string") return encodeString(value);
|
|
396
|
+
if (Array.isArray(value)) {
|
|
397
|
+
return "[" + value.map((v) => canonicalJson(v)).join(",") + "]";
|
|
448
398
|
}
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
var import_hkdf2 = require("@noble/hashes/hkdf.js");
|
|
455
|
-
|
|
456
|
-
// src/_hpke.ts
|
|
457
|
-
var import_ed25519 = require("@noble/curves/ed25519.js");
|
|
458
|
-
var import_chacha = require("@noble/ciphers/chacha.js");
|
|
459
|
-
var import_sha2 = require("@noble/hashes/sha2.js");
|
|
460
|
-
var import_hmac = require("@noble/hashes/hmac.js");
|
|
461
|
-
var import_hkdf = require("@noble/hashes/hkdf.js");
|
|
462
|
-
var import_utils = require("@noble/hashes/utils.js");
|
|
463
|
-
var KEM_ID = 32;
|
|
464
|
-
var KDF_ID = 1;
|
|
465
|
-
var AEAD_ID = 3;
|
|
466
|
-
var NH = 32;
|
|
467
|
-
var NK = 32;
|
|
468
|
-
var NN = 12;
|
|
469
|
-
var NSECRET = 32;
|
|
470
|
-
function i2osp(n, len) {
|
|
471
|
-
const out = new Uint8Array(len);
|
|
472
|
-
for (let i = len - 1; i >= 0; i--) {
|
|
473
|
-
out[i] = n & 255;
|
|
474
|
-
n = Math.floor(n / 256);
|
|
399
|
+
if (t === "object") {
|
|
400
|
+
const obj = value;
|
|
401
|
+
const keys = Object.keys(obj).sort();
|
|
402
|
+
const items = keys.map((k) => encodeString(k) + ":" + canonicalJson(obj[k]));
|
|
403
|
+
return "{" + items.join(",") + "}";
|
|
475
404
|
}
|
|
476
|
-
return
|
|
477
|
-
}
|
|
478
|
-
var TEXT_ENCODER = new TextEncoder();
|
|
479
|
-
function bytes(s) {
|
|
480
|
-
return TEXT_ENCODER.encode(s);
|
|
405
|
+
return "null";
|
|
481
406
|
}
|
|
482
|
-
function
|
|
483
|
-
let
|
|
484
|
-
for (
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
407
|
+
function encodeString(s) {
|
|
408
|
+
let out = '"';
|
|
409
|
+
for (let i = 0; i < s.length; i++) {
|
|
410
|
+
const code = s.charCodeAt(i);
|
|
411
|
+
switch (code) {
|
|
412
|
+
case 34:
|
|
413
|
+
out += '\\"';
|
|
414
|
+
break;
|
|
415
|
+
case 92:
|
|
416
|
+
out += "\\\\";
|
|
417
|
+
break;
|
|
418
|
+
case 8:
|
|
419
|
+
out += "\\b";
|
|
420
|
+
break;
|
|
421
|
+
case 9:
|
|
422
|
+
out += "\\t";
|
|
423
|
+
break;
|
|
424
|
+
case 10:
|
|
425
|
+
out += "\\n";
|
|
426
|
+
break;
|
|
427
|
+
case 12:
|
|
428
|
+
out += "\\f";
|
|
429
|
+
break;
|
|
430
|
+
case 13:
|
|
431
|
+
out += "\\r";
|
|
432
|
+
break;
|
|
433
|
+
default:
|
|
434
|
+
if (code < 32 || code > 126) {
|
|
435
|
+
out += "\\u" + code.toString(16).padStart(4, "0");
|
|
436
|
+
} else {
|
|
437
|
+
out += s[i];
|
|
438
|
+
}
|
|
439
|
+
}
|
|
490
440
|
}
|
|
491
|
-
return out;
|
|
492
|
-
}
|
|
493
|
-
var SUITE_ID = concat(bytes("HPKE"), i2osp(KEM_ID, 2), i2osp(KDF_ID, 2), i2osp(AEAD_ID, 2));
|
|
494
|
-
var KEM_SUITE_ID = concat(bytes("KEM"), i2osp(KEM_ID, 2));
|
|
495
|
-
var HPKE_VERSION = bytes("HPKE-v1");
|
|
496
|
-
function hkdfExtract(salt, ikm) {
|
|
497
|
-
const effectiveSalt = salt.length === 0 ? new Uint8Array(NH) : salt;
|
|
498
|
-
return (0, import_hkdf.extract)(import_sha2.sha256, ikm, effectiveSalt);
|
|
441
|
+
return out + '"';
|
|
499
442
|
}
|
|
500
|
-
function
|
|
501
|
-
|
|
443
|
+
function flattenContent(content) {
|
|
444
|
+
if (typeof content === "string") return content;
|
|
445
|
+
return canonicalJson(content);
|
|
502
446
|
}
|
|
503
|
-
function
|
|
504
|
-
|
|
447
|
+
function affinityKey(rawApiKey, model, messages, saltOverride) {
|
|
448
|
+
const parts = ["model=" + model];
|
|
449
|
+
let sawUser = false;
|
|
450
|
+
for (const m of messages ?? []) {
|
|
451
|
+
const role = m.role ?? "";
|
|
452
|
+
parts.push(role + ":" + flattenContent(m.content));
|
|
453
|
+
if (role === "user") {
|
|
454
|
+
sawUser = true;
|
|
455
|
+
break;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
if (!sawUser) return null;
|
|
459
|
+
const salt = saltOverride != null ? saltOverride : deriveSalt(rawApiKey);
|
|
460
|
+
const mac = import_hmac.hmac(import_sha2.sha256, salt, utf8(parts.join("\0")));
|
|
461
|
+
return toHex(mac);
|
|
505
462
|
}
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
463
|
+
|
|
464
|
+
// src/_parsing.ts
|
|
465
|
+
function asString(v) {
|
|
466
|
+
return typeof v === "string" ? v : void 0;
|
|
509
467
|
}
|
|
510
|
-
function
|
|
511
|
-
|
|
512
|
-
|
|
468
|
+
function throwIfInBandError(parsed, fallback = "The server reported an error mid-stream") {
|
|
469
|
+
if (typeof parsed !== "object" || parsed === null) return;
|
|
470
|
+
const err = parsed.error;
|
|
471
|
+
if (typeof err !== "object" || err === null || Array.isArray(err)) return;
|
|
472
|
+
const e = err;
|
|
473
|
+
throw new APIStreamError(
|
|
474
|
+
asString(e.message) ?? fallback,
|
|
475
|
+
{
|
|
476
|
+
type: asString(e.type),
|
|
477
|
+
code: typeof e.code === "number" ? e.code : void 0,
|
|
478
|
+
requestId: asString(e.request_id),
|
|
479
|
+
workerId: asString(e.worker_id),
|
|
480
|
+
workerName: asString(e.worker_name)
|
|
481
|
+
}
|
|
482
|
+
);
|
|
513
483
|
}
|
|
514
|
-
function
|
|
515
|
-
|
|
516
|
-
const
|
|
517
|
-
|
|
518
|
-
const kemContext = concat(enc, pkR);
|
|
519
|
-
return [extractAndExpand(dh, kemContext), enc];
|
|
484
|
+
function isChunkShaped(parsed) {
|
|
485
|
+
if (typeof parsed !== "object" || parsed === null) return false;
|
|
486
|
+
const c = parsed;
|
|
487
|
+
return typeof c.id === "string" && typeof c.model === "string" && Array.isArray(c.choices);
|
|
520
488
|
}
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
}
|
|
528
|
-
computeNonce() {
|
|
529
|
-
const seqBytes = i2osp(this.seq, NN);
|
|
530
|
-
const nonce = new Uint8Array(NN);
|
|
531
|
-
for (let i = 0; i < NN; i++) {
|
|
532
|
-
nonce[i] = this.baseNonce[i] ^ seqBytes[i];
|
|
533
|
-
}
|
|
534
|
-
return nonce;
|
|
489
|
+
function parseStreamFrame(data, label = "Stream frame") {
|
|
490
|
+
let parsed;
|
|
491
|
+
try {
|
|
492
|
+
parsed = JSON.parse(data);
|
|
493
|
+
} catch {
|
|
494
|
+
throw new APIResponseValidationError(`${label} was not valid JSON`, { body: data });
|
|
535
495
|
}
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
496
|
+
throwIfInBandError(parsed);
|
|
497
|
+
if (!isChunkShaped(parsed)) {
|
|
498
|
+
throw new APIResponseValidationError(`${label} was not a chat completion chunk`, {
|
|
499
|
+
body: data
|
|
500
|
+
});
|
|
540
501
|
}
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
502
|
+
return parsed;
|
|
503
|
+
}
|
|
504
|
+
function completionFrom(parsed, body, status) {
|
|
505
|
+
if (typeof parsed !== "object" || parsed === null) {
|
|
506
|
+
throw new APIResponseValidationError("Response was not a chat completion", { status, body });
|
|
545
507
|
}
|
|
546
|
-
|
|
547
|
-
|
|
508
|
+
const c = parsed;
|
|
509
|
+
if (typeof c.id !== "string" || typeof c.model !== "string" || !Array.isArray(c.choices)) {
|
|
510
|
+
throw new APIResponseValidationError("Response was not a chat completion", { status, body });
|
|
548
511
|
}
|
|
549
|
-
|
|
550
|
-
function keySchedule(sharedSecret, info) {
|
|
551
|
-
const empty = new Uint8Array(0);
|
|
552
|
-
const pskIdHash = labeledExtract(empty, bytes("psk_id_hash"), empty, SUITE_ID);
|
|
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);
|
|
560
|
-
}
|
|
561
|
-
function setupBaseS(pkR, info, skE) {
|
|
562
|
-
const [sharedSecret, enc] = encap(pkR, skE);
|
|
563
|
-
return { enc, ctx: keySchedule(sharedSecret, info) };
|
|
564
|
-
}
|
|
565
|
-
function randomBytes(n) {
|
|
566
|
-
return (0, import_utils.randomBytes)(n);
|
|
567
|
-
}
|
|
568
|
-
function sha256Hex(data) {
|
|
569
|
-
return Array.from((0, import_sha2.sha256)(data)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
512
|
+
return parsed;
|
|
570
513
|
}
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
514
|
+
async function parseCompletion(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
|
+
});
|
|
524
|
+
}
|
|
525
|
+
return completionFrom(parsed, body, response.status);
|
|
581
526
|
}
|
|
582
|
-
function
|
|
583
|
-
|
|
584
|
-
|
|
527
|
+
function parseDecryptedCompletion(json, status) {
|
|
528
|
+
let parsed;
|
|
529
|
+
try {
|
|
530
|
+
parsed = JSON.parse(json);
|
|
531
|
+
} catch {
|
|
532
|
+
throw new APIResponseValidationError("Decrypted response was not valid JSON", {
|
|
533
|
+
status,
|
|
534
|
+
body: json
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
try {
|
|
538
|
+
return completionFrom(parsed, json, status);
|
|
539
|
+
} catch {
|
|
540
|
+
throw new APIResponseValidationError("Decrypted response was not a chat completion", {
|
|
541
|
+
status,
|
|
542
|
+
body: json
|
|
543
|
+
});
|
|
585
544
|
}
|
|
586
|
-
let binary = "";
|
|
587
|
-
for (let i = 0; i < b.length; i++) binary += String.fromCharCode(b[i]);
|
|
588
|
-
return btoa(binary);
|
|
589
545
|
}
|
|
590
|
-
function
|
|
591
|
-
|
|
592
|
-
|
|
546
|
+
async function readSealedReply(response) {
|
|
547
|
+
const body = await response.text();
|
|
548
|
+
let parsed;
|
|
549
|
+
try {
|
|
550
|
+
parsed = JSON.parse(body);
|
|
551
|
+
} catch {
|
|
552
|
+
throw new APIResponseValidationError("Response was not valid JSON", {
|
|
553
|
+
status: response.status,
|
|
554
|
+
body
|
|
555
|
+
});
|
|
593
556
|
}
|
|
594
|
-
|
|
595
|
-
const
|
|
596
|
-
|
|
597
|
-
return
|
|
557
|
+
throwIfInBandError(parsed, "The server reported an error");
|
|
558
|
+
const inner = typeof parsed === "object" && parsed !== null ? parsed.pendra_encrypted : void 0;
|
|
559
|
+
if (!inner) throw unsealedReplyError();
|
|
560
|
+
return inner;
|
|
598
561
|
}
|
|
599
|
-
function
|
|
600
|
-
|
|
562
|
+
function parseDecryptedJson(json, status) {
|
|
563
|
+
try {
|
|
564
|
+
return JSON.parse(json);
|
|
565
|
+
} catch {
|
|
566
|
+
throw new APIResponseValidationError("Decrypted response was not valid JSON", {
|
|
567
|
+
status,
|
|
568
|
+
body: json
|
|
569
|
+
});
|
|
570
|
+
}
|
|
601
571
|
}
|
|
602
|
-
|
|
603
|
-
|
|
572
|
+
|
|
573
|
+
// src/resources/audio/transcriptions.ts
|
|
574
|
+
var ENCODER = new TextEncoder();
|
|
575
|
+
var DECODER = new TextDecoder();
|
|
576
|
+
var MAX_FILE_SIZE = 25 * 1024 * 1024;
|
|
577
|
+
var MIME_EXT = {
|
|
578
|
+
"audio/mpeg": "mp3",
|
|
579
|
+
"audio/mp3": "mp3",
|
|
580
|
+
"audio/mp4": "m4a",
|
|
581
|
+
"audio/x-m4a": "m4a",
|
|
582
|
+
"audio/wav": "wav",
|
|
583
|
+
"audio/wave": "wav",
|
|
584
|
+
"audio/x-wav": "wav",
|
|
585
|
+
"audio/webm": "webm",
|
|
586
|
+
"audio/ogg": "ogg",
|
|
587
|
+
"audio/flac": "flac",
|
|
588
|
+
"audio/x-flac": "flac"
|
|
589
|
+
};
|
|
590
|
+
function extFromMime(type) {
|
|
591
|
+
if (!type) return "mp3";
|
|
592
|
+
const base = type.split(";")[0].trim().toLowerCase();
|
|
593
|
+
return MIME_EXT[base] ?? "mp3";
|
|
604
594
|
}
|
|
605
|
-
function
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
for (let i = 0; i < parts.length; i++) {
|
|
611
|
-
if (i > 0) total += 1;
|
|
612
|
-
total += parts[i].length;
|
|
613
|
-
}
|
|
614
|
-
const out = new Uint8Array(total);
|
|
615
|
-
let off = 0;
|
|
616
|
-
for (let i = 0; i < parts.length; i++) {
|
|
617
|
-
if (i > 0) {
|
|
618
|
-
out.set(sep, off);
|
|
619
|
-
off += 1;
|
|
595
|
+
function asBlob(file) {
|
|
596
|
+
if (file instanceof Blob) {
|
|
597
|
+
const asFile = file;
|
|
598
|
+
if (asFile.name) {
|
|
599
|
+
return { blob: file, filename: asFile.name };
|
|
620
600
|
}
|
|
621
|
-
|
|
622
|
-
off += parts[i].length;
|
|
601
|
+
return { blob: file, filename: `audio.${extFromMime(file.type)}` };
|
|
623
602
|
}
|
|
624
|
-
|
|
603
|
+
const { filename, content } = file;
|
|
604
|
+
if (content instanceof Blob) {
|
|
605
|
+
return { blob: content, filename };
|
|
606
|
+
}
|
|
607
|
+
return { blob: new Blob([content]), filename };
|
|
625
608
|
}
|
|
626
|
-
function
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
609
|
+
async function extractErrorDetail(response) {
|
|
610
|
+
let raw = "";
|
|
611
|
+
try {
|
|
612
|
+
raw = await response.text();
|
|
613
|
+
} catch {
|
|
614
|
+
return response.statusText;
|
|
615
|
+
}
|
|
616
|
+
if (!raw) return response.statusText;
|
|
617
|
+
try {
|
|
618
|
+
const body = JSON.parse(raw);
|
|
619
|
+
return body.detail ?? body.error?.message ?? raw;
|
|
620
|
+
} catch {
|
|
621
|
+
return raw;
|
|
632
622
|
}
|
|
633
|
-
return nonce;
|
|
634
623
|
}
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
throw new Error("sealRequest: no org public keys to seal to");
|
|
624
|
+
var Transcriptions = class {
|
|
625
|
+
constructor(client) {
|
|
626
|
+
this.client = client;
|
|
639
627
|
}
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
const fp = fingerprint(p);
|
|
644
|
-
if (!seen.has(fp)) {
|
|
645
|
-
seen.add(fp);
|
|
646
|
-
uniquePubs.push(p);
|
|
628
|
+
async create(params) {
|
|
629
|
+
if (!params.model) {
|
|
630
|
+
throw new Error("model is required");
|
|
647
631
|
}
|
|
632
|
+
if (params.beam_size != null && !(Number.isInteger(params.beam_size) && params.beam_size >= 1 && params.beam_size <= 8)) {
|
|
633
|
+
throw new Error(`beam_size must be an integer between 1 and 8 (got ${params.beam_size})`);
|
|
634
|
+
}
|
|
635
|
+
const { blob, filename } = asBlob(params.file);
|
|
636
|
+
if (blob.size === 0) {
|
|
637
|
+
throw new Error("audio file is empty");
|
|
638
|
+
}
|
|
639
|
+
if (blob.size > MAX_FILE_SIZE) {
|
|
640
|
+
throw new Error(`audio file exceeds ${MAX_FILE_SIZE / (1024 * 1024)}MB limit`);
|
|
641
|
+
}
|
|
642
|
+
const timeout = Math.max(this.client.timeout ?? 0, 3e5);
|
|
643
|
+
if (this.client.privateInferenceEnabled) {
|
|
644
|
+
return this.createEncrypted(params, blob, timeout);
|
|
645
|
+
}
|
|
646
|
+
const form = new FormData();
|
|
647
|
+
form.append("file", blob, filename);
|
|
648
|
+
form.append("model", params.model);
|
|
649
|
+
if (params.language) form.append("language", params.language);
|
|
650
|
+
if (params.prompt) form.append("prompt", params.prompt);
|
|
651
|
+
if (params.response_format) form.append("response_format", params.response_format);
|
|
652
|
+
if (params.temperature != null) form.append("temperature", String(params.temperature));
|
|
653
|
+
if (params.beam_size != null) form.append("beam_size", String(params.beam_size));
|
|
654
|
+
if (params.timestamp_granularities) {
|
|
655
|
+
for (const g of params.timestamp_granularities) {
|
|
656
|
+
form.append("timestamp_granularities[]", g);
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
const controller = new AbortController();
|
|
660
|
+
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
661
|
+
let response;
|
|
662
|
+
try {
|
|
663
|
+
response = await fetch(`${this.client.baseURL}/api/v1/audio/transcriptions`, {
|
|
664
|
+
method: "POST",
|
|
665
|
+
headers: {
|
|
666
|
+
Authorization: `Bearer ${this.client.apiKey}`,
|
|
667
|
+
...params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : {}
|
|
668
|
+
},
|
|
669
|
+
body: form,
|
|
670
|
+
signal: controller.signal
|
|
671
|
+
});
|
|
672
|
+
} catch (err) {
|
|
673
|
+
clearTimeout(timeoutId);
|
|
674
|
+
if (err instanceof DOMException && err.name === "AbortError") {
|
|
675
|
+
throw new APIConnectionError("Transcription request timed out");
|
|
676
|
+
}
|
|
677
|
+
throw new APIConnectionError(String(err));
|
|
678
|
+
}
|
|
679
|
+
clearTimeout(timeoutId);
|
|
680
|
+
if (response.status >= 400) {
|
|
681
|
+
const detail = await extractErrorDetail(response);
|
|
682
|
+
if (response.status === 401) {
|
|
683
|
+
throw new AuthenticationError(detail);
|
|
684
|
+
}
|
|
685
|
+
if (response.status === 429) {
|
|
686
|
+
throw new RateLimitError(detail);
|
|
687
|
+
}
|
|
688
|
+
throw new APIStatusError(detail, response.status);
|
|
689
|
+
}
|
|
690
|
+
const format = params.response_format;
|
|
691
|
+
if (format === "text" || format === "srt" || format === "vtt") {
|
|
692
|
+
const text = await response.text();
|
|
693
|
+
return { text };
|
|
694
|
+
}
|
|
695
|
+
return await response.json();
|
|
648
696
|
}
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
const {
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
697
|
+
/**
|
|
698
|
+
* Private-inference transcription. There is no multipart upload: the audio
|
|
699
|
+
* bytes ride inside the envelope (sealed under the request's data key) and
|
|
700
|
+
* the request options are the sealed JSON body, POSTed as JSON to the same
|
|
701
|
+
* route.
|
|
702
|
+
*/
|
|
703
|
+
async createEncrypted(params, blob, timeout) {
|
|
704
|
+
const body = { model: params.model };
|
|
705
|
+
if (params.language) body.language = params.language;
|
|
706
|
+
if (params.prompt) body.prompt = params.prompt;
|
|
707
|
+
if (params.response_format) body.response_format = params.response_format;
|
|
708
|
+
if (params.temperature != null) body.temperature = params.temperature;
|
|
709
|
+
if (params.beam_size != null) body.beam_size = params.beam_size;
|
|
710
|
+
if (params.timestamp_granularities) {
|
|
711
|
+
body.timestamp_granularities = params.timestamp_granularities;
|
|
712
|
+
}
|
|
713
|
+
const engine = await this.client._privateEngine();
|
|
714
|
+
const { topLevel, decryptor } = engine.seal({
|
|
715
|
+
model: params.model,
|
|
716
|
+
stream: false,
|
|
717
|
+
taskType: "transcription",
|
|
718
|
+
body: ENCODER.encode(JSON.stringify(body)),
|
|
719
|
+
binary: new Uint8Array(await blob.arrayBuffer())
|
|
720
|
+
});
|
|
721
|
+
const { response } = await this.client._fetch(
|
|
722
|
+
"/api/v1/audio/transcriptions",
|
|
723
|
+
{
|
|
724
|
+
method: "POST",
|
|
725
|
+
body: topLevel,
|
|
726
|
+
headers: params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0,
|
|
727
|
+
timeout
|
|
728
|
+
}
|
|
729
|
+
);
|
|
730
|
+
const raw = DECODER.decode(decryptor.openResult(await readSealedReply(response)));
|
|
731
|
+
const parsed = parseDecryptedJson(raw, response.status);
|
|
732
|
+
if (typeof parsed === "string") return { text: parsed };
|
|
733
|
+
if (typeof parsed === "object" && parsed !== null) {
|
|
734
|
+
if (typeof parsed.text !== "string") {
|
|
735
|
+
throw new APIResponseValidationError("Decrypted response was not a transcription", {
|
|
736
|
+
status: response.status,
|
|
737
|
+
body: raw
|
|
738
|
+
});
|
|
739
|
+
}
|
|
740
|
+
return parsed;
|
|
741
|
+
}
|
|
742
|
+
return { text: raw };
|
|
670
743
|
}
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
744
|
+
};
|
|
745
|
+
|
|
746
|
+
// src/resources/audio/index.ts
|
|
747
|
+
var Audio = class {
|
|
748
|
+
constructor(client) {
|
|
749
|
+
this.transcriptions = new Transcriptions(client);
|
|
675
750
|
}
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
const
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
}
|
|
690
|
-
var ResponseDecryptor = class {
|
|
691
|
-
constructor(responseKeys) {
|
|
692
|
-
this.dek = null;
|
|
693
|
-
this.nextSeq = 0;
|
|
694
|
-
this.keys = responseKeys;
|
|
751
|
+
};
|
|
752
|
+
|
|
753
|
+
// src/_sse.ts
|
|
754
|
+
var DEFAULT_EVENT = "message";
|
|
755
|
+
function fieldValue(line, name) {
|
|
756
|
+
const value = line.slice(name.length + 1);
|
|
757
|
+
return value.startsWith(" ") ? value.slice(1) : value;
|
|
758
|
+
}
|
|
759
|
+
var SseDecoder = class {
|
|
760
|
+
constructor() {
|
|
761
|
+
this.buffer = "";
|
|
762
|
+
this.event = "";
|
|
763
|
+
this.data = [];
|
|
695
764
|
}
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
throw new Error("private_inference: first response frame names no key this request was sealed to");
|
|
765
|
+
/** Feed a chunk of decoded text; returns the payloads it completed. */
|
|
766
|
+
push(text) {
|
|
767
|
+
this.buffer += text;
|
|
768
|
+
const lines = this.buffer.split("\n");
|
|
769
|
+
this.buffer = lines.pop() ?? "";
|
|
770
|
+
const out = [];
|
|
771
|
+
for (const line of lines) {
|
|
772
|
+
const payload = this.pushLine(line);
|
|
773
|
+
if (payload !== null) out.push(payload);
|
|
706
774
|
}
|
|
707
|
-
|
|
708
|
-
}
|
|
709
|
-
/** Decrypt a non-streaming result envelope `{v, kid, seq, ciphertext}`. */
|
|
710
|
-
openResult(inner) {
|
|
711
|
-
this.ensureDek(inner);
|
|
712
|
-
return (0, import_chacha2.chacha20poly1305)(this.dek, seqNonce(Number(inner.seq))).decrypt(b64d(inner.ciphertext));
|
|
775
|
+
return out;
|
|
713
776
|
}
|
|
714
|
-
/**
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
777
|
+
/**
|
|
778
|
+
* Release what the stream ended without terminating: the held-back partial
|
|
779
|
+
* line, plus any frame that never got its blank line.
|
|
780
|
+
*
|
|
781
|
+
* The spec discards an unterminated final block; we keep it, so a connection
|
|
782
|
+
* that drops after the last `data:` line but before its blank line still
|
|
783
|
+
* delivers that payload rather than silently losing it.
|
|
784
|
+
*/
|
|
785
|
+
flush() {
|
|
786
|
+
const out = [];
|
|
787
|
+
if (this.buffer !== "") {
|
|
788
|
+
const payload = this.pushLine(this.buffer);
|
|
789
|
+
this.buffer = "";
|
|
790
|
+
if (payload !== null) out.push(payload);
|
|
721
791
|
}
|
|
722
|
-
this.
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
return pt;
|
|
792
|
+
const tail = this.endFrame();
|
|
793
|
+
if (tail !== null) out.push(tail);
|
|
794
|
+
return out;
|
|
726
795
|
}
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
796
|
+
pushLine(rawLine) {
|
|
797
|
+
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
|
|
798
|
+
if (line === "") return this.endFrame();
|
|
799
|
+
if (line.startsWith(":")) return null;
|
|
800
|
+
if (line.startsWith("event:")) {
|
|
801
|
+
this.event = fieldValue(line, "event");
|
|
802
|
+
return null;
|
|
803
|
+
}
|
|
804
|
+
if (line.startsWith("data:")) {
|
|
805
|
+
this.data.push(fieldValue(line, "data"));
|
|
806
|
+
return null;
|
|
807
|
+
}
|
|
808
|
+
return null;
|
|
738
809
|
}
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
810
|
+
endFrame() {
|
|
811
|
+
const { data, event } = this;
|
|
812
|
+
this.data = [];
|
|
813
|
+
this.event = "";
|
|
814
|
+
if (data.length === 0) return null;
|
|
815
|
+
if (event !== "" && event !== DEFAULT_EVENT) return null;
|
|
816
|
+
return data.join("\n");
|
|
742
817
|
}
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
818
|
+
};
|
|
819
|
+
|
|
820
|
+
// src/streaming.ts
|
|
821
|
+
var Stream = class {
|
|
822
|
+
constructor(response, controller, idleTimeoutMs) {
|
|
823
|
+
this.decoder = new TextDecoder();
|
|
824
|
+
this.sse = new SseDecoder();
|
|
825
|
+
this.done = false;
|
|
826
|
+
if (!response.body) {
|
|
827
|
+
throw new Error("Response body is null \u2014 streaming not supported");
|
|
828
|
+
}
|
|
829
|
+
this.reader = response.body.getReader();
|
|
830
|
+
this.controller = controller;
|
|
831
|
+
this.idleTimeoutMs = idleTimeoutMs;
|
|
748
832
|
}
|
|
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];
|
|
833
|
+
async *[Symbol.asyncIterator]() {
|
|
834
|
+
try {
|
|
835
|
+
while (!this.done) {
|
|
836
|
+
const { value, done: readerDone } = await readWithIdleTimeout(
|
|
837
|
+
this.reader,
|
|
838
|
+
this.idleTimeoutMs
|
|
839
|
+
);
|
|
840
|
+
const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
|
|
841
|
+
for (const data of payloads) {
|
|
842
|
+
if (data === "[DONE]") {
|
|
843
|
+
this.done = true;
|
|
844
|
+
return;
|
|
845
|
+
}
|
|
846
|
+
yield parseStreamFrame(data);
|
|
847
|
+
}
|
|
848
|
+
if (readerDone) {
|
|
849
|
+
this.done = true;
|
|
850
|
+
break;
|
|
782
851
|
}
|
|
852
|
+
}
|
|
853
|
+
} finally {
|
|
854
|
+
releaseReader(this.reader, this.controller, this.done);
|
|
783
855
|
}
|
|
784
856
|
}
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
857
|
+
abort() {
|
|
858
|
+
this.done = true;
|
|
859
|
+
this.controller.abort();
|
|
860
|
+
}
|
|
861
|
+
};
|
|
862
|
+
async function readWithIdleTimeout(reader, idleTimeoutMs) {
|
|
863
|
+
if (!idleTimeoutMs) return reader.read();
|
|
864
|
+
let timer;
|
|
865
|
+
const idle = new Promise((_, reject) => {
|
|
866
|
+
timer = setTimeout(
|
|
867
|
+
() => reject(new APIConnectionError(`Stream received no data for ${idleTimeoutMs}ms`)),
|
|
868
|
+
idleTimeoutMs
|
|
869
|
+
);
|
|
870
|
+
});
|
|
871
|
+
try {
|
|
872
|
+
return await Promise.race([reader.read(), idle]);
|
|
873
|
+
} finally {
|
|
874
|
+
clearTimeout(timer);
|
|
875
|
+
}
|
|
790
876
|
}
|
|
791
|
-
function
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
parts.push(role + ":" + flattenContent(m.content));
|
|
797
|
-
if (role === "user") {
|
|
798
|
-
sawUser = true;
|
|
799
|
-
break;
|
|
800
|
-
}
|
|
877
|
+
function releaseReader(reader, controller, finished) {
|
|
878
|
+
if (!finished) {
|
|
879
|
+
controller.abort();
|
|
880
|
+
reader.cancel().catch(() => {
|
|
881
|
+
});
|
|
801
882
|
}
|
|
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);
|
|
883
|
+
reader.releaseLock();
|
|
806
884
|
}
|
|
807
885
|
|
|
808
886
|
// src/_privateStreaming.ts
|
|
809
|
-
var
|
|
887
|
+
var DECODER2 = new TextDecoder();
|
|
810
888
|
var EncryptedStream = class {
|
|
811
889
|
constructor(response, controller, decryptor, idleTimeoutMs) {
|
|
812
890
|
this.decoder = new TextDecoder();
|
|
@@ -851,7 +929,7 @@ var EncryptedStream = class {
|
|
|
851
929
|
throw unsealedReplyError();
|
|
852
930
|
}
|
|
853
931
|
const plain = this.decryptor.openChunk(inner);
|
|
854
|
-
const chunkJson =
|
|
932
|
+
const chunkJson = DECODER2.decode(plain).trim();
|
|
855
933
|
if (!chunkJson || chunkJson === "[DONE]") {
|
|
856
934
|
if (chunkJson === "[DONE]") {
|
|
857
935
|
this.done = true;
|
|
@@ -877,8 +955,8 @@ var EncryptedStream = class {
|
|
|
877
955
|
};
|
|
878
956
|
|
|
879
957
|
// src/resources/chat/completions.ts
|
|
880
|
-
var
|
|
881
|
-
var
|
|
958
|
+
var ENCODER2 = new TextEncoder();
|
|
959
|
+
var DECODER3 = new TextDecoder();
|
|
882
960
|
var Completions = class {
|
|
883
961
|
constructor(client) {
|
|
884
962
|
this.client = client;
|
|
@@ -913,7 +991,7 @@ var Completions = class {
|
|
|
913
991
|
model: params.model,
|
|
914
992
|
stream,
|
|
915
993
|
taskType: "chat",
|
|
916
|
-
body:
|
|
994
|
+
body: ENCODER2.encode(JSON.stringify(body)),
|
|
917
995
|
messages: params.messages
|
|
918
996
|
});
|
|
919
997
|
if (stream) {
|
|
@@ -941,7 +1019,7 @@ var Completions = class {
|
|
|
941
1019
|
throw unsealedReplyError();
|
|
942
1020
|
}
|
|
943
1021
|
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
944
|
-
return parseDecryptedCompletion(
|
|
1022
|
+
return parseDecryptedCompletion(DECODER3.decode(plain), response.status);
|
|
945
1023
|
}
|
|
946
1024
|
};
|
|
947
1025
|
|
|
@@ -953,8 +1031,8 @@ var Chat = class {
|
|
|
953
1031
|
};
|
|
954
1032
|
|
|
955
1033
|
// src/resources/embeddings.ts
|
|
956
|
-
var
|
|
957
|
-
var
|
|
1034
|
+
var ENCODER3 = new TextEncoder();
|
|
1035
|
+
var DECODER4 = new TextDecoder();
|
|
958
1036
|
function validateParams(params) {
|
|
959
1037
|
if (!params.model || typeof params.model !== "string") {
|
|
960
1038
|
throw new Error("model must be a non-empty string");
|
|
@@ -1018,7 +1096,7 @@ var Embeddings = class {
|
|
|
1018
1096
|
model,
|
|
1019
1097
|
stream: false,
|
|
1020
1098
|
taskType: "embeddings",
|
|
1021
|
-
body:
|
|
1099
|
+
body: ENCODER3.encode(JSON.stringify(body))
|
|
1022
1100
|
});
|
|
1023
1101
|
const { response } = await this.client._fetch(
|
|
1024
1102
|
"/api/v1/embeddings",
|
|
@@ -1029,11 +1107,13 @@ var Embeddings = class {
|
|
|
1029
1107
|
throw unsealedReplyError();
|
|
1030
1108
|
}
|
|
1031
1109
|
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
1032
|
-
return JSON.parse(
|
|
1110
|
+
return JSON.parse(DECODER4.decode(plain));
|
|
1033
1111
|
}
|
|
1034
1112
|
};
|
|
1035
1113
|
|
|
1036
1114
|
// src/resources/images/generations.ts
|
|
1115
|
+
var ENCODER4 = new TextEncoder();
|
|
1116
|
+
var DECODER5 = new TextDecoder();
|
|
1037
1117
|
var SIZE_RE = /^\d+x\d+$/;
|
|
1038
1118
|
function validateParams2(params) {
|
|
1039
1119
|
if (!params.prompt || !params.prompt.trim()) {
|
|
@@ -1051,9 +1131,6 @@ var Generations = class {
|
|
|
1051
1131
|
this.client = client;
|
|
1052
1132
|
}
|
|
1053
1133
|
async create(params) {
|
|
1054
|
-
if (this.client.privateInferenceEnabled) {
|
|
1055
|
-
throw new Error("private inference is not yet supported for images/audio");
|
|
1056
|
-
}
|
|
1057
1134
|
validateParams2(params);
|
|
1058
1135
|
const body = {
|
|
1059
1136
|
model: params.model,
|
|
@@ -1065,16 +1142,38 @@ var Generations = class {
|
|
|
1065
1142
|
if (params.num_inference_steps != null) body.num_inference_steps = params.num_inference_steps;
|
|
1066
1143
|
if (params.seed != null) body.seed = params.seed;
|
|
1067
1144
|
if (params.negative_prompt != null) body.negative_prompt = params.negative_prompt;
|
|
1145
|
+
const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
|
|
1146
|
+
if (this.client.privateInferenceEnabled) {
|
|
1147
|
+
return this.createEncrypted(params.model, body, headers);
|
|
1148
|
+
}
|
|
1068
1149
|
const { response } = await this.client._fetch(
|
|
1069
1150
|
"/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
|
-
}
|
|
1151
|
+
{ method: "POST", body, headers }
|
|
1075
1152
|
);
|
|
1076
1153
|
return await response.json();
|
|
1077
1154
|
}
|
|
1155
|
+
async createEncrypted(model, body, headers) {
|
|
1156
|
+
const engine = await this.client._privateEngine();
|
|
1157
|
+
const { topLevel, decryptor } = engine.seal({
|
|
1158
|
+
model,
|
|
1159
|
+
stream: false,
|
|
1160
|
+
taskType: "image_generation",
|
|
1161
|
+
body: ENCODER4.encode(JSON.stringify(body))
|
|
1162
|
+
});
|
|
1163
|
+
const { response } = await this.client._fetch(
|
|
1164
|
+
"/api/v1/images/generations",
|
|
1165
|
+
{ method: "POST", body: topLevel, headers }
|
|
1166
|
+
);
|
|
1167
|
+
const plain = decryptor.openResult(await readSealedReply(response));
|
|
1168
|
+
const parsed = parseDecryptedJson(DECODER5.decode(plain), response.status);
|
|
1169
|
+
if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.data)) {
|
|
1170
|
+
throw new APIResponseValidationError("Decrypted response was not an image generation", {
|
|
1171
|
+
status: response.status,
|
|
1172
|
+
body: DECODER5.decode(plain)
|
|
1173
|
+
});
|
|
1174
|
+
}
|
|
1175
|
+
return parsed;
|
|
1176
|
+
}
|
|
1078
1177
|
};
|
|
1079
1178
|
|
|
1080
1179
|
// src/resources/images/index.ts
|
|
@@ -1099,8 +1198,8 @@ var Models = class {
|
|
|
1099
1198
|
};
|
|
1100
1199
|
|
|
1101
1200
|
// src/resources/rerank.ts
|
|
1102
|
-
var
|
|
1103
|
-
var
|
|
1201
|
+
var ENCODER5 = new TextEncoder();
|
|
1202
|
+
var DECODER6 = new TextDecoder();
|
|
1104
1203
|
function validateParams3(params) {
|
|
1105
1204
|
if (!params.model || typeof params.model !== "string") {
|
|
1106
1205
|
throw new Error("model must be a non-empty string");
|
|
@@ -1159,7 +1258,7 @@ var Rerank = class {
|
|
|
1159
1258
|
model,
|
|
1160
1259
|
stream: false,
|
|
1161
1260
|
taskType: "rerank",
|
|
1162
|
-
body:
|
|
1261
|
+
body: ENCODER5.encode(JSON.stringify(body))
|
|
1163
1262
|
});
|
|
1164
1263
|
const { response } = await this.client._fetch(
|
|
1165
1264
|
"/api/v1/rerank",
|
|
@@ -1170,12 +1269,12 @@ var Rerank = class {
|
|
|
1170
1269
|
throw unsealedReplyError();
|
|
1171
1270
|
}
|
|
1172
1271
|
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
1173
|
-
return JSON.parse(
|
|
1272
|
+
return JSON.parse(DECODER6.decode(plain));
|
|
1174
1273
|
}
|
|
1175
1274
|
};
|
|
1176
1275
|
|
|
1177
1276
|
// src/version.ts
|
|
1178
|
-
var VERSION = "0.
|
|
1277
|
+
var VERSION = "0.15.0";
|
|
1179
1278
|
var USER_AGENT = `pendra-node/${VERSION}`;
|
|
1180
1279
|
|
|
1181
1280
|
// src/_privateInferenceEngine.ts
|
|
@@ -1340,6 +1439,7 @@ var PrivateInferenceEngine = class {
|
|
|
1340
1439
|
/**
|
|
1341
1440
|
* Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
|
|
1342
1441
|
* `messages` (chat only) drives the affinity token; pass undefined for non-chat.
|
|
1442
|
+
* `binary` (audio only) is sealed under the same data key as the body.
|
|
1343
1443
|
*/
|
|
1344
1444
|
seal(args) {
|
|
1345
1445
|
if (this.orgPubs === null || this.orgPubs.length === 0) {
|
|
@@ -1355,7 +1455,8 @@ var PrivateInferenceEngine = class {
|
|
|
1355
1455
|
model: args.model,
|
|
1356
1456
|
stream: args.stream,
|
|
1357
1457
|
taskType: args.taskType,
|
|
1358
|
-
affinityKey: affinity
|
|
1458
|
+
affinityKey: affinity,
|
|
1459
|
+
binary: args.binary ?? null
|
|
1359
1460
|
});
|
|
1360
1461
|
const topLevel = {
|
|
1361
1462
|
model: args.model,
|
|
@@ -1474,7 +1575,10 @@ var Pendra = class {
|
|
|
1474
1575
|
let message;
|
|
1475
1576
|
try {
|
|
1476
1577
|
const body = await response.json();
|
|
1477
|
-
|
|
1578
|
+
if (typeof body.detail === "string") message = body.detail;
|
|
1579
|
+
else if (typeof body.error?.message === "string") message = body.error.message;
|
|
1580
|
+
else if (body.detail != null) message = JSON.stringify(body.detail);
|
|
1581
|
+
else message = response.statusText;
|
|
1478
1582
|
} catch {
|
|
1479
1583
|
message = response.statusText;
|
|
1480
1584
|
}
|
|
@@ -1487,8 +1591,9 @@ var Pendra = class {
|
|
|
1487
1591
|
}
|
|
1488
1592
|
/** @internal */
|
|
1489
1593
|
async _fetch(path, options) {
|
|
1594
|
+
const timeout = options.timeout ?? this.timeout;
|
|
1490
1595
|
const controller = new AbortController();
|
|
1491
|
-
const timeoutId = setTimeout(() => controller.abort(),
|
|
1596
|
+
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
1492
1597
|
const headers = {
|
|
1493
1598
|
Authorization: `Bearer ${this.apiKey}`,
|
|
1494
1599
|
"Content-Type": "application/json",
|
|
@@ -1507,7 +1612,7 @@ var Pendra = class {
|
|
|
1507
1612
|
clearTimeout(timeoutId);
|
|
1508
1613
|
if (err instanceof DOMException && err.name === "AbortError") {
|
|
1509
1614
|
throw new APIConnectionError(
|
|
1510
|
-
`Request timed out after ${
|
|
1615
|
+
`Request timed out after ${timeout}ms`
|
|
1511
1616
|
);
|
|
1512
1617
|
}
|
|
1513
1618
|
throw new APIConnectionError(
|
|
@@ -1520,7 +1625,10 @@ var Pendra = class {
|
|
|
1520
1625
|
let message;
|
|
1521
1626
|
try {
|
|
1522
1627
|
const body = await response.json();
|
|
1523
|
-
|
|
1628
|
+
if (typeof body.detail === "string") message = body.detail;
|
|
1629
|
+
else if (typeof body.error?.message === "string") message = body.error.message;
|
|
1630
|
+
else if (body.detail != null) message = JSON.stringify(body.detail);
|
|
1631
|
+
else message = response.statusText;
|
|
1524
1632
|
} catch {
|
|
1525
1633
|
message = response.statusText;
|
|
1526
1634
|
}
|