pendra 0.13.1 → 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 +21 -6
- package/dist/index.d.ts +21 -6
- package/dist/index.js +745 -628
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +745 -628
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -105,7 +105,474 @@ var APIStreamError = class extends APIError {
|
|
|
105
105
|
}
|
|
106
106
|
};
|
|
107
107
|
|
|
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);
|
|
131
|
+
}
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
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;
|
|
146
|
+
}
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
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;
|
|
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 ResponseDecryptor = class {
|
|
347
|
+
constructor(responseKeys) {
|
|
348
|
+
this.dek = null;
|
|
349
|
+
this.nextSeq = 0;
|
|
350
|
+
this.keys = responseKeys;
|
|
351
|
+
}
|
|
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
|
+
);
|
|
357
|
+
}
|
|
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");
|
|
362
|
+
}
|
|
363
|
+
this.dek = dek;
|
|
364
|
+
}
|
|
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));
|
|
369
|
+
}
|
|
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
|
+
);
|
|
377
|
+
}
|
|
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;
|
|
382
|
+
}
|
|
383
|
+
};
|
|
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);
|
|
394
|
+
}
|
|
395
|
+
if (t === "string") return encodeString(value);
|
|
396
|
+
if (Array.isArray(value)) {
|
|
397
|
+
return "[" + value.map((v) => canonicalJson(v)).join(",") + "]";
|
|
398
|
+
}
|
|
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(",") + "}";
|
|
404
|
+
}
|
|
405
|
+
return "null";
|
|
406
|
+
}
|
|
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
|
+
}
|
|
440
|
+
}
|
|
441
|
+
return out + '"';
|
|
442
|
+
}
|
|
443
|
+
function flattenContent(content) {
|
|
444
|
+
if (typeof content === "string") return content;
|
|
445
|
+
return canonicalJson(content);
|
|
446
|
+
}
|
|
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);
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// src/_parsing.ts
|
|
465
|
+
function asString(v) {
|
|
466
|
+
return typeof v === "string" ? v : void 0;
|
|
467
|
+
}
|
|
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
|
+
);
|
|
483
|
+
}
|
|
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);
|
|
488
|
+
}
|
|
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 });
|
|
495
|
+
}
|
|
496
|
+
throwIfInBandError(parsed);
|
|
497
|
+
if (!isChunkShaped(parsed)) {
|
|
498
|
+
throw new APIResponseValidationError(`${label} was not a chat completion chunk`, {
|
|
499
|
+
body: data
|
|
500
|
+
});
|
|
501
|
+
}
|
|
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 });
|
|
507
|
+
}
|
|
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 });
|
|
511
|
+
}
|
|
512
|
+
return parsed;
|
|
513
|
+
}
|
|
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);
|
|
526
|
+
}
|
|
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
|
+
});
|
|
544
|
+
}
|
|
545
|
+
}
|
|
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
|
+
});
|
|
556
|
+
}
|
|
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;
|
|
561
|
+
}
|
|
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
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
108
573
|
// src/resources/audio/transcriptions.ts
|
|
574
|
+
var ENCODER = new TextEncoder();
|
|
575
|
+
var DECODER = new TextDecoder();
|
|
109
576
|
var MAX_FILE_SIZE = 25 * 1024 * 1024;
|
|
110
577
|
var MIME_EXT = {
|
|
111
578
|
"audio/mpeg": "mp3",
|
|
@@ -159,12 +626,12 @@ var Transcriptions = class {
|
|
|
159
626
|
this.client = client;
|
|
160
627
|
}
|
|
161
628
|
async create(params) {
|
|
162
|
-
if (this.client.privateInferenceEnabled) {
|
|
163
|
-
throw new Error("private inference is not yet supported for images/audio");
|
|
164
|
-
}
|
|
165
629
|
if (!params.model) {
|
|
166
630
|
throw new Error("model is required");
|
|
167
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
|
+
}
|
|
168
635
|
const { blob, filename } = asBlob(params.file);
|
|
169
636
|
if (blob.size === 0) {
|
|
170
637
|
throw new Error("audio file is empty");
|
|
@@ -172,6 +639,10 @@ var Transcriptions = class {
|
|
|
172
639
|
if (blob.size > MAX_FILE_SIZE) {
|
|
173
640
|
throw new Error(`audio file exceeds ${MAX_FILE_SIZE / (1024 * 1024)}MB limit`);
|
|
174
641
|
}
|
|
642
|
+
const timeout = Math.max(this.client.timeout ?? 0, 3e5);
|
|
643
|
+
if (this.client.privateInferenceEnabled) {
|
|
644
|
+
return this.createEncrypted(params, blob, timeout);
|
|
645
|
+
}
|
|
175
646
|
const form = new FormData();
|
|
176
647
|
form.append("file", blob, filename);
|
|
177
648
|
form.append("model", params.model);
|
|
@@ -185,7 +656,6 @@ var Transcriptions = class {
|
|
|
185
656
|
form.append("timestamp_granularities[]", g);
|
|
186
657
|
}
|
|
187
658
|
}
|
|
188
|
-
const timeout = Math.max(this.client.timeout ?? 0, 3e5);
|
|
189
659
|
const controller = new AbortController();
|
|
190
660
|
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
191
661
|
let response;
|
|
@@ -224,6 +694,53 @@ var Transcriptions = class {
|
|
|
224
694
|
}
|
|
225
695
|
return await response.json();
|
|
226
696
|
}
|
|
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 };
|
|
743
|
+
}
|
|
227
744
|
};
|
|
228
745
|
|
|
229
746
|
// src/resources/audio/index.ts
|
|
@@ -233,89 +750,6 @@ var Audio = class {
|
|
|
233
750
|
}
|
|
234
751
|
};
|
|
235
752
|
|
|
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
753
|
// src/_sse.ts
|
|
320
754
|
var DEFAULT_EVENT = "message";
|
|
321
755
|
function fieldValue(line, name) {
|
|
@@ -450,7 +884,7 @@ function releaseReader(reader, controller, finished) {
|
|
|
450
884
|
}
|
|
451
885
|
|
|
452
886
|
// src/_privateStreaming.ts
|
|
453
|
-
var
|
|
887
|
+
var DECODER2 = new TextDecoder();
|
|
454
888
|
var EncryptedStream = class {
|
|
455
889
|
constructor(response, controller, decryptor, idleTimeoutMs) {
|
|
456
890
|
this.decoder = new TextDecoder();
|
|
@@ -477,20 +911,25 @@ var EncryptedStream = class {
|
|
|
477
911
|
this.done = true;
|
|
478
912
|
return;
|
|
479
913
|
}
|
|
480
|
-
let
|
|
914
|
+
let frame;
|
|
481
915
|
try {
|
|
482
|
-
|
|
916
|
+
frame = JSON.parse(data);
|
|
483
917
|
} catch {
|
|
484
918
|
throw new APIResponseValidationError("Stream frame was not valid JSON", {
|
|
485
919
|
body: data
|
|
486
920
|
});
|
|
487
921
|
}
|
|
922
|
+
const inner = frame?.pendra_encrypted;
|
|
488
923
|
if (!inner) {
|
|
489
|
-
|
|
490
|
-
|
|
924
|
+
if (isApiTimingChunk(frame)) {
|
|
925
|
+
yield parseStreamFrame(data);
|
|
926
|
+
continue;
|
|
927
|
+
}
|
|
928
|
+
parseStreamFrame(data);
|
|
929
|
+
throw unsealedReplyError();
|
|
491
930
|
}
|
|
492
931
|
const plain = this.decryptor.openChunk(inner);
|
|
493
|
-
const chunkJson =
|
|
932
|
+
const chunkJson = DECODER2.decode(plain).trim();
|
|
494
933
|
if (!chunkJson || chunkJson === "[DONE]") {
|
|
495
934
|
if (chunkJson === "[DONE]") {
|
|
496
935
|
this.done = true;
|
|
@@ -516,8 +955,8 @@ var EncryptedStream = class {
|
|
|
516
955
|
};
|
|
517
956
|
|
|
518
957
|
// src/resources/chat/completions.ts
|
|
519
|
-
var
|
|
520
|
-
var
|
|
958
|
+
var ENCODER2 = new TextEncoder();
|
|
959
|
+
var DECODER3 = new TextDecoder();
|
|
521
960
|
var Completions = class {
|
|
522
961
|
constructor(client) {
|
|
523
962
|
this.client = client;
|
|
@@ -552,7 +991,7 @@ var Completions = class {
|
|
|
552
991
|
model: params.model,
|
|
553
992
|
stream,
|
|
554
993
|
taskType: "chat",
|
|
555
|
-
body:
|
|
994
|
+
body: ENCODER2.encode(JSON.stringify(body)),
|
|
556
995
|
messages: params.messages
|
|
557
996
|
});
|
|
558
997
|
if (stream) {
|
|
@@ -577,10 +1016,10 @@ var Completions = class {
|
|
|
577
1016
|
});
|
|
578
1017
|
}
|
|
579
1018
|
if (!wrapper.pendra_encrypted) {
|
|
580
|
-
|
|
1019
|
+
throw unsealedReplyError();
|
|
581
1020
|
}
|
|
582
1021
|
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
583
|
-
return parseDecryptedCompletion(
|
|
1022
|
+
return parseDecryptedCompletion(DECODER3.decode(plain), response.status);
|
|
584
1023
|
}
|
|
585
1024
|
};
|
|
586
1025
|
|
|
@@ -592,582 +1031,251 @@ var Chat = class {
|
|
|
592
1031
|
};
|
|
593
1032
|
|
|
594
1033
|
// src/resources/embeddings.ts
|
|
595
|
-
var
|
|
596
|
-
var
|
|
1034
|
+
var ENCODER3 = new TextEncoder();
|
|
1035
|
+
var DECODER4 = new TextDecoder();
|
|
597
1036
|
function validateParams(params) {
|
|
598
1037
|
if (!params.model || typeof params.model !== "string") {
|
|
599
1038
|
throw new Error("model must be a non-empty string");
|
|
600
1039
|
}
|
|
601
1040
|
const { input } = params;
|
|
602
1041
|
if (typeof input === "string") {
|
|
603
|
-
if (input.length === 0) {
|
|
604
|
-
throw new Error("input must be a non-empty string or non-empty array of strings");
|
|
605
|
-
}
|
|
606
|
-
return;
|
|
607
|
-
}
|
|
608
|
-
if (Array.isArray(input)) {
|
|
609
|
-
if (input.length === 0) {
|
|
610
|
-
throw new Error("input must be a non-empty string or non-empty array of strings");
|
|
611
|
-
}
|
|
612
|
-
if (!input.every((s) => typeof s === "string" && s.length > 0)) {
|
|
613
|
-
throw new Error("input array entries must all be non-empty strings");
|
|
614
|
-
}
|
|
615
|
-
return;
|
|
616
|
-
}
|
|
617
|
-
throw new Error("input must be a string or an array of strings");
|
|
618
|
-
}
|
|
619
|
-
var Embeddings = class {
|
|
620
|
-
constructor(client) {
|
|
621
|
-
this.client = client;
|
|
622
|
-
}
|
|
623
|
-
/**
|
|
624
|
-
* Create embeddings for the given input.
|
|
625
|
-
*
|
|
626
|
-
* @example
|
|
627
|
-
* ```ts
|
|
628
|
-
* const result = await client.embeddings.create({
|
|
629
|
-
* model: "nomic-embed-text:latest",
|
|
630
|
-
* input: "Hello world",
|
|
631
|
-
* });
|
|
632
|
-
* console.log(result.data[0].embedding);
|
|
633
|
-
* ```
|
|
634
|
-
*/
|
|
635
|
-
async create(params) {
|
|
636
|
-
validateParams(params);
|
|
637
|
-
const body = {
|
|
638
|
-
model: params.model,
|
|
639
|
-
input: params.input
|
|
640
|
-
};
|
|
641
|
-
if (params.encoding_format != null) body.encoding_format = params.encoding_format;
|
|
642
|
-
if (params.dimensions != null) body.dimensions = params.dimensions;
|
|
643
|
-
if (params.user != null) body.user = params.user;
|
|
644
|
-
const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
|
|
645
|
-
if (this.client.privateInferenceEnabled) {
|
|
646
|
-
return this.createEncrypted(params.model, body, headers);
|
|
647
|
-
}
|
|
648
|
-
const { response } = await this.client._fetch(
|
|
649
|
-
"/api/v1/embeddings",
|
|
650
|
-
{ method: "POST", body, headers }
|
|
651
|
-
);
|
|
652
|
-
return await response.json();
|
|
653
|
-
}
|
|
654
|
-
async createEncrypted(model, body, headers) {
|
|
655
|
-
const engine = await this.client._privateEngine();
|
|
656
|
-
const { topLevel, decryptor } = engine.seal({
|
|
657
|
-
model,
|
|
658
|
-
stream: false,
|
|
659
|
-
taskType: "embeddings",
|
|
660
|
-
body: ENCODER2.encode(JSON.stringify(body))
|
|
661
|
-
});
|
|
662
|
-
const { response } = await this.client._fetch(
|
|
663
|
-
"/api/v1/embeddings",
|
|
664
|
-
{ method: "POST", body: topLevel, headers }
|
|
665
|
-
);
|
|
666
|
-
const wrapper = await response.json();
|
|
667
|
-
if (!wrapper.pendra_encrypted) {
|
|
668
|
-
return wrapper;
|
|
669
|
-
}
|
|
670
|
-
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
671
|
-
return JSON.parse(DECODER3.decode(plain));
|
|
672
|
-
}
|
|
673
|
-
};
|
|
674
|
-
|
|
675
|
-
// src/resources/images/generations.ts
|
|
676
|
-
var SIZE_RE = /^\d+x\d+$/;
|
|
677
|
-
function validateParams2(params) {
|
|
678
|
-
if (!params.prompt || !params.prompt.trim()) {
|
|
679
|
-
throw new Error("prompt must be a non-empty string");
|
|
680
|
-
}
|
|
681
|
-
if (params.n != null && (params.n < 1 || params.n > 4)) {
|
|
682
|
-
throw new Error("n must be between 1 and 4");
|
|
683
|
-
}
|
|
684
|
-
if (params.size != null && !SIZE_RE.test(params.size)) {
|
|
685
|
-
throw new Error("size must be in the form WIDTHxHEIGHT (e.g. '1024x1024')");
|
|
686
|
-
}
|
|
687
|
-
}
|
|
688
|
-
var Generations = class {
|
|
689
|
-
constructor(client) {
|
|
690
|
-
this.client = client;
|
|
691
|
-
}
|
|
692
|
-
async create(params) {
|
|
693
|
-
if (this.client.privateInferenceEnabled) {
|
|
694
|
-
throw new Error("private inference is not yet supported for images/audio");
|
|
695
|
-
}
|
|
696
|
-
validateParams2(params);
|
|
697
|
-
const body = {
|
|
698
|
-
model: params.model,
|
|
699
|
-
prompt: params.prompt
|
|
700
|
-
};
|
|
701
|
-
if (params.n != null) body.n = params.n;
|
|
702
|
-
if (params.size != null) body.size = params.size;
|
|
703
|
-
if (params.response_format != null) body.response_format = params.response_format;
|
|
704
|
-
if (params.num_inference_steps != null) body.num_inference_steps = params.num_inference_steps;
|
|
705
|
-
if (params.seed != null) body.seed = params.seed;
|
|
706
|
-
if (params.negative_prompt != null) body.negative_prompt = params.negative_prompt;
|
|
707
|
-
const { response } = await this.client._fetch(
|
|
708
|
-
"/api/v1/images/generations",
|
|
709
|
-
{
|
|
710
|
-
method: "POST",
|
|
711
|
-
body,
|
|
712
|
-
headers: params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0
|
|
713
|
-
}
|
|
714
|
-
);
|
|
715
|
-
return await response.json();
|
|
716
|
-
}
|
|
717
|
-
};
|
|
718
|
-
|
|
719
|
-
// src/resources/images/index.ts
|
|
720
|
-
var Images = class {
|
|
721
|
-
constructor(client) {
|
|
722
|
-
this.generations = new Generations(client);
|
|
723
|
-
}
|
|
724
|
-
};
|
|
725
|
-
|
|
726
|
-
// src/resources/models.ts
|
|
727
|
-
var Models = class {
|
|
728
|
-
constructor(client) {
|
|
729
|
-
this.client = client;
|
|
730
|
-
}
|
|
731
|
-
async list() {
|
|
732
|
-
const { response } = await this.client._fetch("/api/v1/models", {
|
|
733
|
-
method: "GET"
|
|
734
|
-
});
|
|
735
|
-
const data = await response.json();
|
|
736
|
-
return data.data;
|
|
737
|
-
}
|
|
738
|
-
};
|
|
739
|
-
|
|
740
|
-
// src/resources/rerank.ts
|
|
741
|
-
var ENCODER3 = new TextEncoder();
|
|
742
|
-
var DECODER4 = new TextDecoder();
|
|
743
|
-
function validateParams3(params) {
|
|
744
|
-
if (!params.model || typeof params.model !== "string") {
|
|
745
|
-
throw new Error("model must be a non-empty string");
|
|
746
|
-
}
|
|
747
|
-
if (!params.query || typeof params.query !== "string") {
|
|
748
|
-
throw new Error("query must be a non-empty string");
|
|
749
|
-
}
|
|
750
|
-
const { documents } = params;
|
|
751
|
-
if (!Array.isArray(documents) || documents.length === 0 || !documents.every((d) => typeof d === "string" && d.length > 0)) {
|
|
752
|
-
throw new Error("documents must be a non-empty array of non-empty strings");
|
|
1042
|
+
if (input.length === 0) {
|
|
1043
|
+
throw new Error("input must be a non-empty string or non-empty array of strings");
|
|
1044
|
+
}
|
|
1045
|
+
return;
|
|
753
1046
|
}
|
|
754
|
-
if (
|
|
755
|
-
|
|
1047
|
+
if (Array.isArray(input)) {
|
|
1048
|
+
if (input.length === 0) {
|
|
1049
|
+
throw new Error("input must be a non-empty string or non-empty array of strings");
|
|
1050
|
+
}
|
|
1051
|
+
if (!input.every((s) => typeof s === "string" && s.length > 0)) {
|
|
1052
|
+
throw new Error("input array entries must all be non-empty strings");
|
|
1053
|
+
}
|
|
1054
|
+
return;
|
|
756
1055
|
}
|
|
1056
|
+
throw new Error("input must be a string or an array of strings");
|
|
757
1057
|
}
|
|
758
|
-
var
|
|
1058
|
+
var Embeddings = class {
|
|
759
1059
|
constructor(client) {
|
|
760
1060
|
this.client = client;
|
|
761
1061
|
}
|
|
762
1062
|
/**
|
|
763
|
-
*
|
|
1063
|
+
* Create embeddings for the given input.
|
|
764
1064
|
*
|
|
765
1065
|
* @example
|
|
766
1066
|
* ```ts
|
|
767
|
-
* const result = await client.
|
|
768
|
-
* model: "
|
|
769
|
-
*
|
|
770
|
-
* documents: ["Paris is the capital of France.", "Berlin is in Germany."],
|
|
771
|
-
* top_n: 1,
|
|
1067
|
+
* const result = await client.embeddings.create({
|
|
1068
|
+
* model: "nomic-embed-text:latest",
|
|
1069
|
+
* input: "Hello world",
|
|
772
1070
|
* });
|
|
773
|
-
* console.log(result.
|
|
1071
|
+
* console.log(result.data[0].embedding);
|
|
774
1072
|
* ```
|
|
775
1073
|
*/
|
|
776
1074
|
async create(params) {
|
|
777
|
-
|
|
1075
|
+
validateParams(params);
|
|
778
1076
|
const body = {
|
|
779
1077
|
model: params.model,
|
|
780
|
-
|
|
781
|
-
documents: params.documents,
|
|
782
|
-
return_documents: params.return_documents ?? false
|
|
1078
|
+
input: params.input
|
|
783
1079
|
};
|
|
784
|
-
if (params.
|
|
1080
|
+
if (params.encoding_format != null) body.encoding_format = params.encoding_format;
|
|
1081
|
+
if (params.dimensions != null) body.dimensions = params.dimensions;
|
|
1082
|
+
if (params.user != null) body.user = params.user;
|
|
785
1083
|
const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
|
|
786
1084
|
if (this.client.privateInferenceEnabled) {
|
|
787
1085
|
return this.createEncrypted(params.model, body, headers);
|
|
788
1086
|
}
|
|
789
1087
|
const { response } = await this.client._fetch(
|
|
790
|
-
"/api/v1/
|
|
1088
|
+
"/api/v1/embeddings",
|
|
791
1089
|
{ method: "POST", body, headers }
|
|
792
1090
|
);
|
|
793
1091
|
return await response.json();
|
|
794
1092
|
}
|
|
795
1093
|
async createEncrypted(model, body, headers) {
|
|
796
|
-
const engine = await this.client._privateEngine();
|
|
797
|
-
const { topLevel, decryptor } = engine.seal({
|
|
798
|
-
model,
|
|
799
|
-
stream: false,
|
|
800
|
-
taskType: "
|
|
801
|
-
body: ENCODER3.encode(JSON.stringify(body))
|
|
802
|
-
});
|
|
803
|
-
const { response } = await this.client._fetch(
|
|
804
|
-
"/api/v1/
|
|
805
|
-
{ method: "POST", body: topLevel, headers }
|
|
806
|
-
);
|
|
807
|
-
const wrapper = await response.json();
|
|
808
|
-
if (!wrapper.pendra_encrypted) {
|
|
809
|
-
|
|
810
|
-
}
|
|
811
|
-
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
812
|
-
return JSON.parse(DECODER4.decode(plain));
|
|
813
|
-
}
|
|
814
|
-
};
|
|
815
|
-
|
|
816
|
-
// src/version.ts
|
|
817
|
-
var VERSION = "0.13.1";
|
|
818
|
-
var USER_AGENT = `pendra-node/${VERSION}`;
|
|
819
|
-
|
|
820
|
-
// src/_hpke.ts
|
|
821
|
-
var import_ed25519 = require("@noble/curves/ed25519.js");
|
|
822
|
-
var import_chacha = require("@noble/ciphers/chacha.js");
|
|
823
|
-
var import_sha2 = require("@noble/hashes/sha2.js");
|
|
824
|
-
var import_hmac = require("@noble/hashes/hmac.js");
|
|
825
|
-
var import_hkdf = require("@noble/hashes/hkdf.js");
|
|
826
|
-
var import_utils = require("@noble/hashes/utils.js");
|
|
827
|
-
var KEM_ID = 32;
|
|
828
|
-
var KDF_ID = 1;
|
|
829
|
-
var AEAD_ID = 3;
|
|
830
|
-
var NH = 32;
|
|
831
|
-
var NK = 32;
|
|
832
|
-
var NN = 12;
|
|
833
|
-
var NSECRET = 32;
|
|
834
|
-
function i2osp(n, len) {
|
|
835
|
-
const out = new Uint8Array(len);
|
|
836
|
-
for (let i = len - 1; i >= 0; i--) {
|
|
837
|
-
out[i] = n & 255;
|
|
838
|
-
n = Math.floor(n / 256);
|
|
839
|
-
}
|
|
840
|
-
return out;
|
|
841
|
-
}
|
|
842
|
-
var TEXT_ENCODER = new TextEncoder();
|
|
843
|
-
function bytes(s) {
|
|
844
|
-
return TEXT_ENCODER.encode(s);
|
|
845
|
-
}
|
|
846
|
-
function concat(...parts) {
|
|
847
|
-
let total = 0;
|
|
848
|
-
for (const p of parts) total += p.length;
|
|
849
|
-
const out = new Uint8Array(total);
|
|
850
|
-
let off = 0;
|
|
851
|
-
for (const p of parts) {
|
|
852
|
-
out.set(p, off);
|
|
853
|
-
off += p.length;
|
|
854
|
-
}
|
|
855
|
-
return out;
|
|
856
|
-
}
|
|
857
|
-
var SUITE_ID = concat(bytes("HPKE"), i2osp(KEM_ID, 2), i2osp(KDF_ID, 2), i2osp(AEAD_ID, 2));
|
|
858
|
-
var KEM_SUITE_ID = concat(bytes("KEM"), i2osp(KEM_ID, 2));
|
|
859
|
-
var HPKE_VERSION = bytes("HPKE-v1");
|
|
860
|
-
function hkdfExtract(salt, ikm) {
|
|
861
|
-
const effectiveSalt = salt.length === 0 ? new Uint8Array(NH) : salt;
|
|
862
|
-
return (0, import_hkdf.extract)(import_sha2.sha256, ikm, effectiveSalt);
|
|
863
|
-
}
|
|
864
|
-
function hkdfExpand(prk, info, length) {
|
|
865
|
-
return (0, import_hkdf.expand)(import_sha2.sha256, prk, info, length);
|
|
866
|
-
}
|
|
867
|
-
function labeledExtract(salt, label, ikm, suiteId) {
|
|
868
|
-
return hkdfExtract(salt, concat(HPKE_VERSION, suiteId, label, ikm));
|
|
869
|
-
}
|
|
870
|
-
function labeledExpand(prk, label, info, length, suiteId) {
|
|
871
|
-
const labeledInfo = concat(i2osp(length, 2), HPKE_VERSION, suiteId, label, info);
|
|
872
|
-
return hkdfExpand(prk, labeledInfo, length);
|
|
873
|
-
}
|
|
874
|
-
function extractAndExpand(dh, kemContext) {
|
|
875
|
-
const eaePrk = labeledExtract(new Uint8Array(0), bytes("eae_prk"), dh, KEM_SUITE_ID);
|
|
876
|
-
return labeledExpand(eaePrk, bytes("shared_secret"), kemContext, NSECRET, KEM_SUITE_ID);
|
|
877
|
-
}
|
|
878
|
-
function encap(pkR, skE) {
|
|
879
|
-
const skEObj = skE ?? import_ed25519.x25519.utils.randomSecretKey();
|
|
880
|
-
const enc = import_ed25519.x25519.getPublicKey(skEObj);
|
|
881
|
-
const dh = import_ed25519.x25519.getSharedSecret(skEObj, pkR);
|
|
882
|
-
const kemContext = concat(enc, pkR);
|
|
883
|
-
return [extractAndExpand(dh, kemContext), enc];
|
|
884
|
-
}
|
|
885
|
-
function decap(enc, skR) {
|
|
886
|
-
const dh = import_ed25519.x25519.getSharedSecret(skR, enc);
|
|
887
|
-
const pkRm = import_ed25519.x25519.getPublicKey(skR);
|
|
888
|
-
const kemContext = concat(enc, pkRm);
|
|
889
|
-
return extractAndExpand(dh, kemContext);
|
|
890
|
-
}
|
|
891
|
-
var Context = class {
|
|
892
|
-
constructor(key, baseNonce, exporterSecret) {
|
|
893
|
-
this.seq = 0;
|
|
894
|
-
this.key = key;
|
|
895
|
-
this.baseNonce = baseNonce;
|
|
896
|
-
this.exporterSecret = exporterSecret;
|
|
897
|
-
}
|
|
898
|
-
computeNonce() {
|
|
899
|
-
const seqBytes = i2osp(this.seq, NN);
|
|
900
|
-
const nonce = new Uint8Array(NN);
|
|
901
|
-
for (let i = 0; i < NN; i++) {
|
|
902
|
-
nonce[i] = this.baseNonce[i] ^ seqBytes[i];
|
|
903
|
-
}
|
|
904
|
-
return nonce;
|
|
905
|
-
}
|
|
906
|
-
seal(aad, pt) {
|
|
907
|
-
const ct = (0, import_chacha.chacha20poly1305)(this.key, this.computeNonce(), aad).encrypt(pt);
|
|
908
|
-
this.seq += 1;
|
|
909
|
-
return ct;
|
|
910
|
-
}
|
|
911
|
-
open(aad, ct) {
|
|
912
|
-
const pt = (0, import_chacha.chacha20poly1305)(this.key, this.computeNonce(), aad).decrypt(ct);
|
|
913
|
-
this.seq += 1;
|
|
914
|
-
return pt;
|
|
915
|
-
}
|
|
916
|
-
export(exporterContext, length) {
|
|
917
|
-
return labeledExpand(this.exporterSecret, bytes("sec"), exporterContext, length, SUITE_ID);
|
|
918
|
-
}
|
|
919
|
-
};
|
|
920
|
-
function keySchedule(sharedSecret, info) {
|
|
921
|
-
const empty = new Uint8Array(0);
|
|
922
|
-
const pskIdHash = labeledExtract(empty, bytes("psk_id_hash"), empty, SUITE_ID);
|
|
923
|
-
const infoHash = labeledExtract(empty, bytes("info_hash"), info, SUITE_ID);
|
|
924
|
-
const keyScheduleContext = concat(new Uint8Array([0]), pskIdHash, infoHash);
|
|
925
|
-
const secret = labeledExtract(sharedSecret, bytes("secret"), empty, SUITE_ID);
|
|
926
|
-
const key = labeledExpand(secret, bytes("key"), keyScheduleContext, NK, SUITE_ID);
|
|
927
|
-
const baseNonce = labeledExpand(secret, bytes("base_nonce"), keyScheduleContext, NN, SUITE_ID);
|
|
928
|
-
const exporterSecret = labeledExpand(secret, bytes("exp"), keyScheduleContext, NH, SUITE_ID);
|
|
929
|
-
return new Context(key, baseNonce, exporterSecret);
|
|
930
|
-
}
|
|
931
|
-
function setupBaseS(pkR, info, skE) {
|
|
932
|
-
const [sharedSecret, enc] = encap(pkR, skE);
|
|
933
|
-
return { enc, ctx: keySchedule(sharedSecret, info) };
|
|
934
|
-
}
|
|
935
|
-
function setupBaseR(skR, enc, info) {
|
|
936
|
-
const sharedSecret = decap(enc, skR);
|
|
937
|
-
return keySchedule(sharedSecret, info);
|
|
938
|
-
}
|
|
939
|
-
function generateX25519Keypair() {
|
|
940
|
-
const priv = import_ed25519.x25519.utils.randomSecretKey();
|
|
941
|
-
return { priv, pub: import_ed25519.x25519.getPublicKey(priv) };
|
|
942
|
-
}
|
|
943
|
-
function randomBytes(n) {
|
|
944
|
-
return (0, import_utils.randomBytes)(n);
|
|
945
|
-
}
|
|
946
|
-
function sha256Hex(data) {
|
|
947
|
-
return Array.from((0, import_sha2.sha256)(data)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
948
|
-
}
|
|
949
|
-
|
|
950
|
-
// src/_privateInference.ts
|
|
951
|
-
var import_chacha2 = require("@noble/ciphers/chacha.js");
|
|
952
|
-
var import_hkdf2 = require("@noble/hashes/hkdf.js");
|
|
953
|
-
var ENVELOPE_VERSION = 1;
|
|
954
|
-
var TEXT_ENCODER2 = new TextEncoder();
|
|
955
|
-
var TEXT_DECODER = new TextDecoder();
|
|
956
|
-
var SUITE_INFO = TEXT_ENCODER2.encode("pendra-pi-v1");
|
|
957
|
-
var RESPONSE_INFO = TEXT_ENCODER2.encode("pendra-pi-v1:response");
|
|
958
|
-
var RESPONSE_EXPORT_CTX = TEXT_ENCODER2.encode("pendra-pi-v1:rdek");
|
|
959
|
-
var AFFINITY_SALT_INFO = TEXT_ENCODER2.encode("pendra-affinity-salt-v1");
|
|
960
|
-
function utf8(s) {
|
|
961
|
-
return TEXT_ENCODER2.encode(s);
|
|
962
|
-
}
|
|
963
|
-
function b64(b) {
|
|
964
|
-
if (typeof Buffer !== "undefined") {
|
|
965
|
-
return Buffer.from(b).toString("base64");
|
|
966
|
-
}
|
|
967
|
-
let binary = "";
|
|
968
|
-
for (let i = 0; i < b.length; i++) binary += String.fromCharCode(b[i]);
|
|
969
|
-
return btoa(binary);
|
|
970
|
-
}
|
|
971
|
-
function b64d(s) {
|
|
972
|
-
if (typeof Buffer !== "undefined") {
|
|
973
|
-
return new Uint8Array(Buffer.from(s, "base64"));
|
|
974
|
-
}
|
|
975
|
-
const binary = atob(s);
|
|
976
|
-
const out = new Uint8Array(binary.length);
|
|
977
|
-
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
978
|
-
return out;
|
|
979
|
-
}
|
|
980
|
-
function toHex(b) {
|
|
981
|
-
return Array.from(b).map((x) => x.toString(16).padStart(2, "0")).join("");
|
|
982
|
-
}
|
|
983
|
-
function fingerprint(pub) {
|
|
984
|
-
return sha256Hex(pub);
|
|
985
|
-
}
|
|
986
|
-
function buildAad(model, stream, taskType, responsePkB64) {
|
|
987
|
-
const streamBit = stream ? utf8("1") : utf8("0");
|
|
988
|
-
const sep = new Uint8Array([0]);
|
|
989
|
-
const parts = [utf8("pendra-pi-v1"), utf8(model), streamBit, utf8(taskType), utf8(responsePkB64)];
|
|
990
|
-
let total = 0;
|
|
991
|
-
for (let i = 0; i < parts.length; i++) {
|
|
992
|
-
if (i > 0) total += 1;
|
|
993
|
-
total += parts[i].length;
|
|
994
|
-
}
|
|
995
|
-
const out = new Uint8Array(total);
|
|
996
|
-
let off = 0;
|
|
997
|
-
for (let i = 0; i < parts.length; i++) {
|
|
998
|
-
if (i > 0) {
|
|
999
|
-
out.set(sep, off);
|
|
1000
|
-
off += 1;
|
|
1001
|
-
}
|
|
1002
|
-
out.set(parts[i], off);
|
|
1003
|
-
off += parts[i].length;
|
|
1004
|
-
}
|
|
1005
|
-
return out;
|
|
1006
|
-
}
|
|
1007
|
-
function seqNonce(seq) {
|
|
1008
|
-
const nonce = new Uint8Array(12);
|
|
1009
|
-
let n = BigInt(seq);
|
|
1010
|
-
for (let i = 11; i >= 4; i--) {
|
|
1011
|
-
nonce[i] = Number(n & 0xffn);
|
|
1012
|
-
n >>= 8n;
|
|
1013
|
-
}
|
|
1014
|
-
return nonce;
|
|
1015
|
-
}
|
|
1016
|
-
function sealRequest(orgPubs, body, opts) {
|
|
1017
|
-
const pubs = Array.isArray(orgPubs) ? orgPubs : [orgPubs];
|
|
1018
|
-
if (pubs.length === 0) {
|
|
1019
|
-
throw new Error("sealRequest: no org public keys to seal to");
|
|
1020
|
-
}
|
|
1021
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1022
|
-
const uniquePubs = [];
|
|
1023
|
-
for (const p of pubs) {
|
|
1024
|
-
const fp = fingerprint(p);
|
|
1025
|
-
if (!seen.has(fp)) {
|
|
1026
|
-
seen.add(fp);
|
|
1027
|
-
uniquePubs.push(p);
|
|
1094
|
+
const engine = await this.client._privateEngine();
|
|
1095
|
+
const { topLevel, decryptor } = engine.seal({
|
|
1096
|
+
model,
|
|
1097
|
+
stream: false,
|
|
1098
|
+
taskType: "embeddings",
|
|
1099
|
+
body: ENCODER3.encode(JSON.stringify(body))
|
|
1100
|
+
});
|
|
1101
|
+
const { response } = await this.client._fetch(
|
|
1102
|
+
"/api/v1/embeddings",
|
|
1103
|
+
{ method: "POST", body: topLevel, headers }
|
|
1104
|
+
);
|
|
1105
|
+
const wrapper = await response.json();
|
|
1106
|
+
if (!wrapper.pendra_encrypted) {
|
|
1107
|
+
throw unsealedReplyError();
|
|
1028
1108
|
}
|
|
1109
|
+
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
1110
|
+
return JSON.parse(DECODER4.decode(plain));
|
|
1029
1111
|
}
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
const sealedDek = sealer.seal(new Uint8Array(0), dek);
|
|
1040
|
-
recipients.push({ kid: fingerprint(pub), enc: b64(enc), sealed_dek: b64(sealedDek) });
|
|
1112
|
+
};
|
|
1113
|
+
|
|
1114
|
+
// src/resources/images/generations.ts
|
|
1115
|
+
var ENCODER4 = new TextEncoder();
|
|
1116
|
+
var DECODER5 = new TextDecoder();
|
|
1117
|
+
var SIZE_RE = /^\d+x\d+$/;
|
|
1118
|
+
function validateParams2(params) {
|
|
1119
|
+
if (!params.prompt || !params.prompt.trim()) {
|
|
1120
|
+
throw new Error("prompt must be a non-empty string");
|
|
1041
1121
|
}
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
recipients,
|
|
1045
|
-
nonce: b64(nonce),
|
|
1046
|
-
ciphertext: b64(ciphertext),
|
|
1047
|
-
response_pk: respPkB64
|
|
1048
|
-
};
|
|
1049
|
-
if (opts.affinityKey != null) {
|
|
1050
|
-
envelope.affinity_key = opts.affinityKey;
|
|
1122
|
+
if (params.n != null && (params.n < 1 || params.n > 4)) {
|
|
1123
|
+
throw new Error("n must be between 1 and 4");
|
|
1051
1124
|
}
|
|
1052
|
-
if (
|
|
1053
|
-
|
|
1054
|
-
envelope.binary_nonce = b64(binaryNonce);
|
|
1055
|
-
envelope.binary_ciphertext = b64((0, import_chacha2.chacha20poly1305)(dek, binaryNonce, aad).encrypt(opts.binary));
|
|
1125
|
+
if (params.size != null && !SIZE_RE.test(params.size)) {
|
|
1126
|
+
throw new Error("size must be in the form WIDTHxHEIGHT (e.g. '1024x1024')");
|
|
1056
1127
|
}
|
|
1057
|
-
return { envelope, responsePriv: respPriv };
|
|
1058
1128
|
}
|
|
1059
|
-
var
|
|
1060
|
-
constructor(
|
|
1061
|
-
this.
|
|
1062
|
-
this.nextSeq = 0;
|
|
1063
|
-
this.respPriv = responsePrivateKey;
|
|
1129
|
+
var Generations = class {
|
|
1130
|
+
constructor(client) {
|
|
1131
|
+
this.client = client;
|
|
1064
1132
|
}
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1133
|
+
async create(params) {
|
|
1134
|
+
validateParams2(params);
|
|
1135
|
+
const body = {
|
|
1136
|
+
model: params.model,
|
|
1137
|
+
prompt: params.prompt
|
|
1138
|
+
};
|
|
1139
|
+
if (params.n != null) body.n = params.n;
|
|
1140
|
+
if (params.size != null) body.size = params.size;
|
|
1141
|
+
if (params.response_format != null) body.response_format = params.response_format;
|
|
1142
|
+
if (params.num_inference_steps != null) body.num_inference_steps = params.num_inference_steps;
|
|
1143
|
+
if (params.seed != null) body.seed = params.seed;
|
|
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);
|
|
1069
1148
|
}
|
|
1070
|
-
const
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
this.ensureDek(inner.enc);
|
|
1076
|
-
return (0, import_chacha2.chacha20poly1305)(this.dek, seqNonce(Number(inner.seq))).decrypt(b64d(inner.ciphertext));
|
|
1149
|
+
const { response } = await this.client._fetch(
|
|
1150
|
+
"/api/v1/images/generations",
|
|
1151
|
+
{ method: "POST", body, headers }
|
|
1152
|
+
);
|
|
1153
|
+
return await response.json();
|
|
1077
1154
|
}
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
const
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
)
|
|
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
|
+
});
|
|
1085
1174
|
}
|
|
1086
|
-
|
|
1087
|
-
const pt = (0, import_chacha2.chacha20poly1305)(this.dek, seqNonce(seq)).decrypt(b64d(inner.ciphertext));
|
|
1088
|
-
this.nextSeq += 1;
|
|
1089
|
-
return pt;
|
|
1175
|
+
return parsed;
|
|
1090
1176
|
}
|
|
1091
1177
|
};
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
if (value === null) return "null";
|
|
1098
|
-
const t = typeof value;
|
|
1099
|
-
if (t === "boolean") return value ? "true" : "false";
|
|
1100
|
-
if (t === "number") {
|
|
1101
|
-
return String(value);
|
|
1178
|
+
|
|
1179
|
+
// src/resources/images/index.ts
|
|
1180
|
+
var Images = class {
|
|
1181
|
+
constructor(client) {
|
|
1182
|
+
this.generations = new Generations(client);
|
|
1102
1183
|
}
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1184
|
+
};
|
|
1185
|
+
|
|
1186
|
+
// src/resources/models.ts
|
|
1187
|
+
var Models = class {
|
|
1188
|
+
constructor(client) {
|
|
1189
|
+
this.client = client;
|
|
1106
1190
|
}
|
|
1107
|
-
|
|
1108
|
-
const
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1191
|
+
async list() {
|
|
1192
|
+
const { response } = await this.client._fetch("/api/v1/models", {
|
|
1193
|
+
method: "GET"
|
|
1194
|
+
});
|
|
1195
|
+
const data = await response.json();
|
|
1196
|
+
return data.data;
|
|
1197
|
+
}
|
|
1198
|
+
};
|
|
1199
|
+
|
|
1200
|
+
// src/resources/rerank.ts
|
|
1201
|
+
var ENCODER5 = new TextEncoder();
|
|
1202
|
+
var DECODER6 = new TextDecoder();
|
|
1203
|
+
function validateParams3(params) {
|
|
1204
|
+
if (!params.model || typeof params.model !== "string") {
|
|
1205
|
+
throw new Error("model must be a non-empty string");
|
|
1206
|
+
}
|
|
1207
|
+
if (!params.query || typeof params.query !== "string") {
|
|
1208
|
+
throw new Error("query must be a non-empty string");
|
|
1209
|
+
}
|
|
1210
|
+
const { documents } = params;
|
|
1211
|
+
if (!Array.isArray(documents) || documents.length === 0 || !documents.every((d) => typeof d === "string" && d.length > 0)) {
|
|
1212
|
+
throw new Error("documents must be a non-empty array of non-empty strings");
|
|
1213
|
+
}
|
|
1214
|
+
if (params.top_n != null && params.top_n < 1) {
|
|
1215
|
+
throw new Error("top_n must be >= 1 when provided");
|
|
1112
1216
|
}
|
|
1113
|
-
return "null";
|
|
1114
1217
|
}
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
out += s[i];
|
|
1146
|
-
}
|
|
1218
|
+
var Rerank = class {
|
|
1219
|
+
constructor(client) {
|
|
1220
|
+
this.client = client;
|
|
1221
|
+
}
|
|
1222
|
+
/**
|
|
1223
|
+
* Rerank `documents` by relevance to `query` (Cohere-compatible).
|
|
1224
|
+
*
|
|
1225
|
+
* @example
|
|
1226
|
+
* ```ts
|
|
1227
|
+
* const result = await client.rerank.create({
|
|
1228
|
+
* model: "bge-reranker-v2-m3",
|
|
1229
|
+
* query: "What is the capital of France?",
|
|
1230
|
+
* documents: ["Paris is the capital of France.", "Berlin is in Germany."],
|
|
1231
|
+
* top_n: 1,
|
|
1232
|
+
* });
|
|
1233
|
+
* console.log(result.results[0].index, result.results[0].relevance_score);
|
|
1234
|
+
* ```
|
|
1235
|
+
*/
|
|
1236
|
+
async create(params) {
|
|
1237
|
+
validateParams3(params);
|
|
1238
|
+
const body = {
|
|
1239
|
+
model: params.model,
|
|
1240
|
+
query: params.query,
|
|
1241
|
+
documents: params.documents,
|
|
1242
|
+
return_documents: params.return_documents ?? false
|
|
1243
|
+
};
|
|
1244
|
+
if (params.top_n != null) body.top_n = params.top_n;
|
|
1245
|
+
const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
|
|
1246
|
+
if (this.client.privateInferenceEnabled) {
|
|
1247
|
+
return this.createEncrypted(params.model, body, headers);
|
|
1147
1248
|
}
|
|
1249
|
+
const { response } = await this.client._fetch(
|
|
1250
|
+
"/api/v1/rerank",
|
|
1251
|
+
{ method: "POST", body, headers }
|
|
1252
|
+
);
|
|
1253
|
+
return await response.json();
|
|
1148
1254
|
}
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1255
|
+
async createEncrypted(model, body, headers) {
|
|
1256
|
+
const engine = await this.client._privateEngine();
|
|
1257
|
+
const { topLevel, decryptor } = engine.seal({
|
|
1258
|
+
model,
|
|
1259
|
+
stream: false,
|
|
1260
|
+
taskType: "rerank",
|
|
1261
|
+
body: ENCODER5.encode(JSON.stringify(body))
|
|
1262
|
+
});
|
|
1263
|
+
const { response } = await this.client._fetch(
|
|
1264
|
+
"/api/v1/rerank",
|
|
1265
|
+
{ method: "POST", body: topLevel, headers }
|
|
1266
|
+
);
|
|
1267
|
+
const wrapper = await response.json();
|
|
1268
|
+
if (!wrapper.pendra_encrypted) {
|
|
1269
|
+
throw unsealedReplyError();
|
|
1164
1270
|
}
|
|
1271
|
+
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
1272
|
+
return JSON.parse(DECODER6.decode(plain));
|
|
1165
1273
|
}
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
}
|
|
1274
|
+
};
|
|
1275
|
+
|
|
1276
|
+
// src/version.ts
|
|
1277
|
+
var VERSION = "0.15.0";
|
|
1278
|
+
var USER_AGENT = `pendra-node/${VERSION}`;
|
|
1171
1279
|
|
|
1172
1280
|
// src/_privateInferenceEngine.ts
|
|
1173
1281
|
var PrivateInferenceError = class extends Error {
|
|
@@ -1331,6 +1439,7 @@ var PrivateInferenceEngine = class {
|
|
|
1331
1439
|
/**
|
|
1332
1440
|
* Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
|
|
1333
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.
|
|
1334
1443
|
*/
|
|
1335
1444
|
seal(args) {
|
|
1336
1445
|
if (this.orgPubs === null || this.orgPubs.length === 0) {
|
|
@@ -1342,18 +1451,19 @@ var PrivateInferenceEngine = class {
|
|
|
1342
1451
|
if (args.messages != null) {
|
|
1343
1452
|
affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
|
|
1344
1453
|
}
|
|
1345
|
-
const { envelope,
|
|
1454
|
+
const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
|
|
1346
1455
|
model: args.model,
|
|
1347
1456
|
stream: args.stream,
|
|
1348
1457
|
taskType: args.taskType,
|
|
1349
|
-
affinityKey: affinity
|
|
1458
|
+
affinityKey: affinity,
|
|
1459
|
+
binary: args.binary ?? null
|
|
1350
1460
|
});
|
|
1351
1461
|
const topLevel = {
|
|
1352
1462
|
model: args.model,
|
|
1353
1463
|
stream: args.stream,
|
|
1354
1464
|
pendra_encrypted: envelope
|
|
1355
1465
|
};
|
|
1356
|
-
return { topLevel, decryptor: new ResponseDecryptor(
|
|
1466
|
+
return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
|
|
1357
1467
|
}
|
|
1358
1468
|
get keyFetchUrl() {
|
|
1359
1469
|
return `${this.baseUrl}/v1/private-inference/key`;
|
|
@@ -1465,7 +1575,10 @@ var Pendra = class {
|
|
|
1465
1575
|
let message;
|
|
1466
1576
|
try {
|
|
1467
1577
|
const body = await response.json();
|
|
1468
|
-
|
|
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;
|
|
1469
1582
|
} catch {
|
|
1470
1583
|
message = response.statusText;
|
|
1471
1584
|
}
|
|
@@ -1478,8 +1591,9 @@ var Pendra = class {
|
|
|
1478
1591
|
}
|
|
1479
1592
|
/** @internal */
|
|
1480
1593
|
async _fetch(path, options) {
|
|
1594
|
+
const timeout = options.timeout ?? this.timeout;
|
|
1481
1595
|
const controller = new AbortController();
|
|
1482
|
-
const timeoutId = setTimeout(() => controller.abort(),
|
|
1596
|
+
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
1483
1597
|
const headers = {
|
|
1484
1598
|
Authorization: `Bearer ${this.apiKey}`,
|
|
1485
1599
|
"Content-Type": "application/json",
|
|
@@ -1498,7 +1612,7 @@ var Pendra = class {
|
|
|
1498
1612
|
clearTimeout(timeoutId);
|
|
1499
1613
|
if (err instanceof DOMException && err.name === "AbortError") {
|
|
1500
1614
|
throw new APIConnectionError(
|
|
1501
|
-
`Request timed out after ${
|
|
1615
|
+
`Request timed out after ${timeout}ms`
|
|
1502
1616
|
);
|
|
1503
1617
|
}
|
|
1504
1618
|
throw new APIConnectionError(
|
|
@@ -1511,7 +1625,10 @@ var Pendra = class {
|
|
|
1511
1625
|
let message;
|
|
1512
1626
|
try {
|
|
1513
1627
|
const body = await response.json();
|
|
1514
|
-
|
|
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;
|
|
1515
1632
|
} catch {
|
|
1516
1633
|
message = response.statusText;
|
|
1517
1634
|
}
|