pendra 0.3.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -3
- package/dist/index.d.mts +224 -1
- package/dist/index.d.ts +224 -1
- package/dist/index.js +965 -29
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +954 -29
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -2
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,164 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var APIError = class extends Error {
|
|
3
|
+
constructor(message, status) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.name = "APIError";
|
|
6
|
+
this.status = status;
|
|
7
|
+
}
|
|
8
|
+
};
|
|
9
|
+
var APIConnectionError = class extends APIError {
|
|
10
|
+
constructor(message = "Failed to connect to the Pendra API") {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = "APIConnectionError";
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
var APIStatusError = class extends APIError {
|
|
16
|
+
constructor(message, status) {
|
|
17
|
+
super(message, status);
|
|
18
|
+
this.name = "APIStatusError";
|
|
19
|
+
this.status = status;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
var AuthenticationError = class extends APIStatusError {
|
|
23
|
+
constructor(message = "Invalid API key \u2014 check your PENDRA_API_KEY") {
|
|
24
|
+
super(message, 401);
|
|
25
|
+
this.name = "AuthenticationError";
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
var RateLimitError = class extends APIStatusError {
|
|
29
|
+
constructor(message = "Rate limit exceeded") {
|
|
30
|
+
super(message, 429);
|
|
31
|
+
this.name = "RateLimitError";
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
// src/resources/audio/transcriptions.ts
|
|
36
|
+
var MAX_FILE_SIZE = 25 * 1024 * 1024;
|
|
37
|
+
var MIME_EXT = {
|
|
38
|
+
"audio/mpeg": "mp3",
|
|
39
|
+
"audio/mp3": "mp3",
|
|
40
|
+
"audio/mp4": "m4a",
|
|
41
|
+
"audio/x-m4a": "m4a",
|
|
42
|
+
"audio/wav": "wav",
|
|
43
|
+
"audio/wave": "wav",
|
|
44
|
+
"audio/x-wav": "wav",
|
|
45
|
+
"audio/webm": "webm",
|
|
46
|
+
"audio/ogg": "ogg",
|
|
47
|
+
"audio/flac": "flac",
|
|
48
|
+
"audio/x-flac": "flac"
|
|
49
|
+
};
|
|
50
|
+
function extFromMime(type) {
|
|
51
|
+
if (!type) return "mp3";
|
|
52
|
+
const base = type.split(";")[0].trim().toLowerCase();
|
|
53
|
+
return MIME_EXT[base] ?? "mp3";
|
|
54
|
+
}
|
|
55
|
+
function asBlob(file) {
|
|
56
|
+
if (file instanceof Blob) {
|
|
57
|
+
const asFile = file;
|
|
58
|
+
if (asFile.name) {
|
|
59
|
+
return { blob: file, filename: asFile.name };
|
|
60
|
+
}
|
|
61
|
+
return { blob: file, filename: `audio.${extFromMime(file.type)}` };
|
|
62
|
+
}
|
|
63
|
+
const { filename, content } = file;
|
|
64
|
+
if (content instanceof Blob) {
|
|
65
|
+
return { blob: content, filename };
|
|
66
|
+
}
|
|
67
|
+
return { blob: new Blob([content]), filename };
|
|
68
|
+
}
|
|
69
|
+
async function extractErrorDetail(response) {
|
|
70
|
+
let raw = "";
|
|
71
|
+
try {
|
|
72
|
+
raw = await response.text();
|
|
73
|
+
} catch {
|
|
74
|
+
return response.statusText;
|
|
75
|
+
}
|
|
76
|
+
if (!raw) return response.statusText;
|
|
77
|
+
try {
|
|
78
|
+
const body = JSON.parse(raw);
|
|
79
|
+
return body.detail ?? body.error?.message ?? raw;
|
|
80
|
+
} catch {
|
|
81
|
+
return raw;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
var Transcriptions = class {
|
|
85
|
+
constructor(client) {
|
|
86
|
+
this.client = client;
|
|
87
|
+
}
|
|
88
|
+
async create(params) {
|
|
89
|
+
if (this.client.privateInferenceEnabled) {
|
|
90
|
+
throw new Error("private inference is not yet supported for images/audio");
|
|
91
|
+
}
|
|
92
|
+
if (!params.model) {
|
|
93
|
+
throw new Error("model is required");
|
|
94
|
+
}
|
|
95
|
+
const { blob, filename } = asBlob(params.file);
|
|
96
|
+
if (blob.size === 0) {
|
|
97
|
+
throw new Error("audio file is empty");
|
|
98
|
+
}
|
|
99
|
+
if (blob.size > MAX_FILE_SIZE) {
|
|
100
|
+
throw new Error(`audio file exceeds ${MAX_FILE_SIZE / (1024 * 1024)}MB limit`);
|
|
101
|
+
}
|
|
102
|
+
const form = new FormData();
|
|
103
|
+
form.append("file", blob, filename);
|
|
104
|
+
form.append("model", params.model);
|
|
105
|
+
if (params.language) form.append("language", params.language);
|
|
106
|
+
if (params.prompt) form.append("prompt", params.prompt);
|
|
107
|
+
if (params.response_format) form.append("response_format", params.response_format);
|
|
108
|
+
if (params.temperature != null) form.append("temperature", String(params.temperature));
|
|
109
|
+
if (params.timestamp_granularities) {
|
|
110
|
+
for (const g of params.timestamp_granularities) {
|
|
111
|
+
form.append("timestamp_granularities[]", g);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
const timeout = Math.max(this.client.timeout ?? 0, 3e5);
|
|
115
|
+
const controller = new AbortController();
|
|
116
|
+
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
117
|
+
let response;
|
|
118
|
+
try {
|
|
119
|
+
response = await fetch(`${this.client.baseURL}/api/v1/audio/transcriptions`, {
|
|
120
|
+
method: "POST",
|
|
121
|
+
headers: {
|
|
122
|
+
Authorization: `Bearer ${this.client.apiKey}`,
|
|
123
|
+
...params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : {}
|
|
124
|
+
},
|
|
125
|
+
body: form,
|
|
126
|
+
signal: controller.signal
|
|
127
|
+
});
|
|
128
|
+
} catch (err) {
|
|
129
|
+
clearTimeout(timeoutId);
|
|
130
|
+
if (err instanceof DOMException && err.name === "AbortError") {
|
|
131
|
+
throw new APIConnectionError("Transcription request timed out");
|
|
132
|
+
}
|
|
133
|
+
throw new APIConnectionError(String(err));
|
|
134
|
+
}
|
|
135
|
+
clearTimeout(timeoutId);
|
|
136
|
+
if (response.status >= 400) {
|
|
137
|
+
const detail = await extractErrorDetail(response);
|
|
138
|
+
if (response.status === 401) {
|
|
139
|
+
throw new AuthenticationError(detail);
|
|
140
|
+
}
|
|
141
|
+
if (response.status === 429) {
|
|
142
|
+
throw new RateLimitError(detail);
|
|
143
|
+
}
|
|
144
|
+
throw new APIStatusError(detail, response.status);
|
|
145
|
+
}
|
|
146
|
+
const format = params.response_format;
|
|
147
|
+
if (format === "text" || format === "srt" || format === "vtt") {
|
|
148
|
+
const text = await response.text();
|
|
149
|
+
return { text };
|
|
150
|
+
}
|
|
151
|
+
return await response.json();
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
// src/resources/audio/index.ts
|
|
156
|
+
var Audio = class {
|
|
157
|
+
constructor(client) {
|
|
158
|
+
this.transcriptions = new Transcriptions(client);
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
|
|
1
162
|
// src/streaming.ts
|
|
2
163
|
var Stream = class {
|
|
3
164
|
constructor(response, controller) {
|
|
@@ -46,7 +207,78 @@ var Stream = class {
|
|
|
46
207
|
}
|
|
47
208
|
};
|
|
48
209
|
|
|
210
|
+
// src/_privateStreaming.ts
|
|
211
|
+
var DECODER = new TextDecoder();
|
|
212
|
+
var EncryptedStream = class {
|
|
213
|
+
constructor(response, controller, decryptor) {
|
|
214
|
+
this.buffer = "";
|
|
215
|
+
this.done = false;
|
|
216
|
+
if (!response.body) {
|
|
217
|
+
throw new Error("Response body is null \u2014 streaming not supported");
|
|
218
|
+
}
|
|
219
|
+
this.reader = response.body.getReader();
|
|
220
|
+
this.controller = controller;
|
|
221
|
+
this.decryptor = decryptor;
|
|
222
|
+
}
|
|
223
|
+
async *[Symbol.asyncIterator]() {
|
|
224
|
+
try {
|
|
225
|
+
while (!this.done) {
|
|
226
|
+
const { value, done: readerDone } = await this.reader.read();
|
|
227
|
+
if (readerDone) {
|
|
228
|
+
this.done = true;
|
|
229
|
+
break;
|
|
230
|
+
}
|
|
231
|
+
this.buffer += DECODER.decode(value, { stream: true });
|
|
232
|
+
const lines = this.buffer.split("\n");
|
|
233
|
+
this.buffer = lines.pop() ?? "";
|
|
234
|
+
for (const line of lines) {
|
|
235
|
+
const trimmed = line.trim();
|
|
236
|
+
if (!trimmed || trimmed.startsWith(":") || trimmed.startsWith("event:")) continue;
|
|
237
|
+
if (!trimmed.startsWith("data:")) continue;
|
|
238
|
+
const data = trimmed.slice("data:".length).trimStart();
|
|
239
|
+
if (data === "[DONE]") {
|
|
240
|
+
this.done = true;
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
let parsed;
|
|
244
|
+
try {
|
|
245
|
+
parsed = JSON.parse(data);
|
|
246
|
+
} catch {
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
const inner = parsed.pendra_encrypted;
|
|
250
|
+
if (!inner) {
|
|
251
|
+
yield parsed;
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
const plain = this.decryptor.openChunk(inner);
|
|
255
|
+
const chunkJson = DECODER.decode(plain).trim();
|
|
256
|
+
if (!chunkJson || chunkJson === "[DONE]") {
|
|
257
|
+
if (chunkJson === "[DONE]") {
|
|
258
|
+
this.done = true;
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
try {
|
|
264
|
+
yield JSON.parse(chunkJson);
|
|
265
|
+
} catch {
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
} finally {
|
|
270
|
+
this.reader.releaseLock();
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
abort() {
|
|
274
|
+
this.done = true;
|
|
275
|
+
this.controller.abort();
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
|
|
49
279
|
// src/resources/chat/completions.ts
|
|
280
|
+
var ENCODER = new TextEncoder();
|
|
281
|
+
var DECODER2 = new TextDecoder();
|
|
50
282
|
var Completions = class {
|
|
51
283
|
constructor(client) {
|
|
52
284
|
this.client = client;
|
|
@@ -61,19 +293,51 @@ var Completions = class {
|
|
|
61
293
|
if (params.max_tokens != null) body.max_tokens = params.max_tokens;
|
|
62
294
|
if (params.top_p != null) body.top_p = params.top_p;
|
|
63
295
|
if (params.stop != null) body.stop = params.stop;
|
|
296
|
+
const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
|
|
297
|
+
if (this.client.privateInferenceEnabled) {
|
|
298
|
+
return this.createEncrypted(params, body, headers);
|
|
299
|
+
}
|
|
64
300
|
if (params.stream) {
|
|
65
301
|
const { response: response2, controller } = await this.client._fetch(
|
|
66
302
|
"/api/v1/chat/completions",
|
|
67
|
-
{ method: "POST", body, stream: true }
|
|
303
|
+
{ method: "POST", body, stream: true, headers }
|
|
68
304
|
);
|
|
69
305
|
return new Stream(response2, controller);
|
|
70
306
|
}
|
|
71
307
|
const { response } = await this.client._fetch(
|
|
72
308
|
"/api/v1/chat/completions",
|
|
73
|
-
{ method: "POST", body }
|
|
309
|
+
{ method: "POST", body, headers }
|
|
74
310
|
);
|
|
75
311
|
return await response.json();
|
|
76
312
|
}
|
|
313
|
+
async createEncrypted(params, body, headers) {
|
|
314
|
+
const engine = await this.client._privateEngine();
|
|
315
|
+
const stream = Boolean(params.stream);
|
|
316
|
+
const { topLevel, decryptor } = engine.seal({
|
|
317
|
+
model: params.model,
|
|
318
|
+
stream,
|
|
319
|
+
taskType: "chat",
|
|
320
|
+
body: ENCODER.encode(JSON.stringify(body)),
|
|
321
|
+
messages: params.messages
|
|
322
|
+
});
|
|
323
|
+
if (stream) {
|
|
324
|
+
const { response: response2, controller } = await this.client._fetch(
|
|
325
|
+
"/api/v1/chat/completions",
|
|
326
|
+
{ method: "POST", body: topLevel, stream: true, headers }
|
|
327
|
+
);
|
|
328
|
+
return new EncryptedStream(response2, controller, decryptor);
|
|
329
|
+
}
|
|
330
|
+
const { response } = await this.client._fetch(
|
|
331
|
+
"/api/v1/chat/completions",
|
|
332
|
+
{ method: "POST", body: topLevel, headers }
|
|
333
|
+
);
|
|
334
|
+
const wrapper = await response.json();
|
|
335
|
+
if (!wrapper.pendra_encrypted) {
|
|
336
|
+
return wrapper;
|
|
337
|
+
}
|
|
338
|
+
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
339
|
+
return JSON.parse(DECODER2.decode(plain));
|
|
340
|
+
}
|
|
77
341
|
};
|
|
78
342
|
|
|
79
343
|
// src/resources/chat/index.ts
|
|
@@ -84,6 +348,8 @@ var Chat = class {
|
|
|
84
348
|
};
|
|
85
349
|
|
|
86
350
|
// src/resources/embeddings.ts
|
|
351
|
+
var ENCODER2 = new TextEncoder();
|
|
352
|
+
var DECODER3 = new TextDecoder();
|
|
87
353
|
function validateParams(params) {
|
|
88
354
|
if (!params.model || typeof params.model !== "string") {
|
|
89
355
|
throw new Error("model must be a non-empty string");
|
|
@@ -131,12 +397,35 @@ var Embeddings = class {
|
|
|
131
397
|
if (params.encoding_format != null) body.encoding_format = params.encoding_format;
|
|
132
398
|
if (params.dimensions != null) body.dimensions = params.dimensions;
|
|
133
399
|
if (params.user != null) body.user = params.user;
|
|
400
|
+
const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
|
|
401
|
+
if (this.client.privateInferenceEnabled) {
|
|
402
|
+
return this.createEncrypted(params.model, body, headers);
|
|
403
|
+
}
|
|
134
404
|
const { response } = await this.client._fetch(
|
|
135
405
|
"/api/v1/embeddings",
|
|
136
|
-
{ method: "POST", body }
|
|
406
|
+
{ method: "POST", body, headers }
|
|
137
407
|
);
|
|
138
408
|
return await response.json();
|
|
139
409
|
}
|
|
410
|
+
async createEncrypted(model, body, headers) {
|
|
411
|
+
const engine = await this.client._privateEngine();
|
|
412
|
+
const { topLevel, decryptor } = engine.seal({
|
|
413
|
+
model,
|
|
414
|
+
stream: false,
|
|
415
|
+
taskType: "embeddings",
|
|
416
|
+
body: ENCODER2.encode(JSON.stringify(body))
|
|
417
|
+
});
|
|
418
|
+
const { response } = await this.client._fetch(
|
|
419
|
+
"/api/v1/embeddings",
|
|
420
|
+
{ method: "POST", body: topLevel, headers }
|
|
421
|
+
);
|
|
422
|
+
const wrapper = await response.json();
|
|
423
|
+
if (!wrapper.pendra_encrypted) {
|
|
424
|
+
return wrapper;
|
|
425
|
+
}
|
|
426
|
+
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
427
|
+
return JSON.parse(DECODER3.decode(plain));
|
|
428
|
+
}
|
|
140
429
|
};
|
|
141
430
|
|
|
142
431
|
// src/resources/images/generations.ts
|
|
@@ -157,6 +446,9 @@ var Generations = class {
|
|
|
157
446
|
this.client = client;
|
|
158
447
|
}
|
|
159
448
|
async create(params) {
|
|
449
|
+
if (this.client.privateInferenceEnabled) {
|
|
450
|
+
throw new Error("private inference is not yet supported for images/audio");
|
|
451
|
+
}
|
|
160
452
|
validateParams2(params);
|
|
161
453
|
const body = {
|
|
162
454
|
model: params.model,
|
|
@@ -170,7 +462,11 @@ var Generations = class {
|
|
|
170
462
|
if (params.negative_prompt != null) body.negative_prompt = params.negative_prompt;
|
|
171
463
|
const { response } = await this.client._fetch(
|
|
172
464
|
"/api/v1/images/generations",
|
|
173
|
-
{
|
|
465
|
+
{
|
|
466
|
+
method: "POST",
|
|
467
|
+
body,
|
|
468
|
+
headers: params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0
|
|
469
|
+
}
|
|
174
470
|
);
|
|
175
471
|
return await response.json();
|
|
176
472
|
}
|
|
@@ -197,44 +493,583 @@ var Models = class {
|
|
|
197
493
|
}
|
|
198
494
|
};
|
|
199
495
|
|
|
200
|
-
// src/
|
|
201
|
-
var
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
496
|
+
// src/resources/rerank.ts
|
|
497
|
+
var ENCODER3 = new TextEncoder();
|
|
498
|
+
var DECODER4 = new TextDecoder();
|
|
499
|
+
function validateParams3(params) {
|
|
500
|
+
if (!params.model || typeof params.model !== "string") {
|
|
501
|
+
throw new Error("model must be a non-empty string");
|
|
502
|
+
}
|
|
503
|
+
if (!params.query || typeof params.query !== "string") {
|
|
504
|
+
throw new Error("query must be a non-empty string");
|
|
505
|
+
}
|
|
506
|
+
const { documents } = params;
|
|
507
|
+
if (!Array.isArray(documents) || documents.length === 0 || !documents.every((d) => typeof d === "string" && d.length > 0)) {
|
|
508
|
+
throw new Error("documents must be a non-empty array of non-empty strings");
|
|
509
|
+
}
|
|
510
|
+
if (params.top_n != null && params.top_n < 1) {
|
|
511
|
+
throw new Error("top_n must be >= 1 when provided");
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
var Rerank = class {
|
|
515
|
+
constructor(client) {
|
|
516
|
+
this.client = client;
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Rerank `documents` by relevance to `query` (Cohere-compatible).
|
|
520
|
+
*
|
|
521
|
+
* @example
|
|
522
|
+
* ```ts
|
|
523
|
+
* const result = await client.rerank.create({
|
|
524
|
+
* model: "bge-reranker-v2-m3",
|
|
525
|
+
* query: "What is the capital of France?",
|
|
526
|
+
* documents: ["Paris is the capital of France.", "Berlin is in Germany."],
|
|
527
|
+
* top_n: 1,
|
|
528
|
+
* });
|
|
529
|
+
* console.log(result.results[0].index, result.results[0].relevance_score);
|
|
530
|
+
* ```
|
|
531
|
+
*/
|
|
532
|
+
async create(params) {
|
|
533
|
+
validateParams3(params);
|
|
534
|
+
const body = {
|
|
535
|
+
model: params.model,
|
|
536
|
+
query: params.query,
|
|
537
|
+
documents: params.documents,
|
|
538
|
+
return_documents: params.return_documents ?? false
|
|
539
|
+
};
|
|
540
|
+
if (params.top_n != null) body.top_n = params.top_n;
|
|
541
|
+
const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
|
|
542
|
+
if (this.client.privateInferenceEnabled) {
|
|
543
|
+
return this.createEncrypted(params.model, body, headers);
|
|
544
|
+
}
|
|
545
|
+
const { response } = await this.client._fetch(
|
|
546
|
+
"/api/v1/rerank",
|
|
547
|
+
{ method: "POST", body, headers }
|
|
548
|
+
);
|
|
549
|
+
return await response.json();
|
|
550
|
+
}
|
|
551
|
+
async createEncrypted(model, body, headers) {
|
|
552
|
+
const engine = await this.client._privateEngine();
|
|
553
|
+
const { topLevel, decryptor } = engine.seal({
|
|
554
|
+
model,
|
|
555
|
+
stream: false,
|
|
556
|
+
taskType: "rerank",
|
|
557
|
+
body: ENCODER3.encode(JSON.stringify(body))
|
|
558
|
+
});
|
|
559
|
+
const { response } = await this.client._fetch(
|
|
560
|
+
"/api/v1/rerank",
|
|
561
|
+
{ method: "POST", body: topLevel, headers }
|
|
562
|
+
);
|
|
563
|
+
const wrapper = await response.json();
|
|
564
|
+
if (!wrapper.pendra_encrypted) {
|
|
565
|
+
return wrapper;
|
|
566
|
+
}
|
|
567
|
+
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
568
|
+
return JSON.parse(DECODER4.decode(plain));
|
|
206
569
|
}
|
|
207
570
|
};
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
571
|
+
|
|
572
|
+
// src/_hpke.ts
|
|
573
|
+
import { x25519 } from "@noble/curves/ed25519";
|
|
574
|
+
import { chacha20poly1305 } from "@noble/ciphers/chacha";
|
|
575
|
+
import { sha256 } from "@noble/hashes/sha256";
|
|
576
|
+
import { hmac } from "@noble/hashes/hmac";
|
|
577
|
+
import { extract, expand } from "@noble/hashes/hkdf";
|
|
578
|
+
import { randomBytes as nobleRandomBytes } from "@noble/hashes/utils";
|
|
579
|
+
var KEM_ID = 32;
|
|
580
|
+
var KDF_ID = 1;
|
|
581
|
+
var AEAD_ID = 3;
|
|
582
|
+
var NH = 32;
|
|
583
|
+
var NK = 32;
|
|
584
|
+
var NN = 12;
|
|
585
|
+
var NSECRET = 32;
|
|
586
|
+
function i2osp(n, len) {
|
|
587
|
+
const out = new Uint8Array(len);
|
|
588
|
+
for (let i = len - 1; i >= 0; i--) {
|
|
589
|
+
out[i] = n & 255;
|
|
590
|
+
n = Math.floor(n / 256);
|
|
591
|
+
}
|
|
592
|
+
return out;
|
|
593
|
+
}
|
|
594
|
+
var TEXT_ENCODER = new TextEncoder();
|
|
595
|
+
function bytes(s) {
|
|
596
|
+
return TEXT_ENCODER.encode(s);
|
|
597
|
+
}
|
|
598
|
+
function concat(...parts) {
|
|
599
|
+
let total = 0;
|
|
600
|
+
for (const p of parts) total += p.length;
|
|
601
|
+
const out = new Uint8Array(total);
|
|
602
|
+
let off = 0;
|
|
603
|
+
for (const p of parts) {
|
|
604
|
+
out.set(p, off);
|
|
605
|
+
off += p.length;
|
|
606
|
+
}
|
|
607
|
+
return out;
|
|
608
|
+
}
|
|
609
|
+
var SUITE_ID = concat(bytes("HPKE"), i2osp(KEM_ID, 2), i2osp(KDF_ID, 2), i2osp(AEAD_ID, 2));
|
|
610
|
+
var KEM_SUITE_ID = concat(bytes("KEM"), i2osp(KEM_ID, 2));
|
|
611
|
+
var HPKE_VERSION = bytes("HPKE-v1");
|
|
612
|
+
function hkdfExtract(salt, ikm) {
|
|
613
|
+
const effectiveSalt = salt.length === 0 ? new Uint8Array(NH) : salt;
|
|
614
|
+
return extract(sha256, ikm, effectiveSalt);
|
|
615
|
+
}
|
|
616
|
+
function hkdfExpand(prk, info, length) {
|
|
617
|
+
return expand(sha256, prk, info, length);
|
|
618
|
+
}
|
|
619
|
+
function labeledExtract(salt, label, ikm, suiteId) {
|
|
620
|
+
return hkdfExtract(salt, concat(HPKE_VERSION, suiteId, label, ikm));
|
|
621
|
+
}
|
|
622
|
+
function labeledExpand(prk, label, info, length, suiteId) {
|
|
623
|
+
const labeledInfo = concat(i2osp(length, 2), HPKE_VERSION, suiteId, label, info);
|
|
624
|
+
return hkdfExpand(prk, labeledInfo, length);
|
|
625
|
+
}
|
|
626
|
+
function extractAndExpand(dh, kemContext) {
|
|
627
|
+
const eaePrk = labeledExtract(new Uint8Array(0), bytes("eae_prk"), dh, KEM_SUITE_ID);
|
|
628
|
+
return labeledExpand(eaePrk, bytes("shared_secret"), kemContext, NSECRET, KEM_SUITE_ID);
|
|
629
|
+
}
|
|
630
|
+
function encap(pkR, skE) {
|
|
631
|
+
const skEObj = skE ?? x25519.utils.randomPrivateKey();
|
|
632
|
+
const enc = x25519.getPublicKey(skEObj);
|
|
633
|
+
const dh = x25519.getSharedSecret(skEObj, pkR);
|
|
634
|
+
const kemContext = concat(enc, pkR);
|
|
635
|
+
return [extractAndExpand(dh, kemContext), enc];
|
|
636
|
+
}
|
|
637
|
+
function decap(enc, skR) {
|
|
638
|
+
const dh = x25519.getSharedSecret(skR, enc);
|
|
639
|
+
const pkRm = x25519.getPublicKey(skR);
|
|
640
|
+
const kemContext = concat(enc, pkRm);
|
|
641
|
+
return extractAndExpand(dh, kemContext);
|
|
642
|
+
}
|
|
643
|
+
var Context = class {
|
|
644
|
+
constructor(key, baseNonce, exporterSecret) {
|
|
645
|
+
this.seq = 0;
|
|
646
|
+
this.key = key;
|
|
647
|
+
this.baseNonce = baseNonce;
|
|
648
|
+
this.exporterSecret = exporterSecret;
|
|
649
|
+
}
|
|
650
|
+
computeNonce() {
|
|
651
|
+
const seqBytes = i2osp(this.seq, NN);
|
|
652
|
+
const nonce = new Uint8Array(NN);
|
|
653
|
+
for (let i = 0; i < NN; i++) {
|
|
654
|
+
nonce[i] = this.baseNonce[i] ^ seqBytes[i];
|
|
655
|
+
}
|
|
656
|
+
return nonce;
|
|
657
|
+
}
|
|
658
|
+
seal(aad, pt) {
|
|
659
|
+
const ct = chacha20poly1305(this.key, this.computeNonce(), aad).encrypt(pt);
|
|
660
|
+
this.seq += 1;
|
|
661
|
+
return ct;
|
|
662
|
+
}
|
|
663
|
+
open(aad, ct) {
|
|
664
|
+
const pt = chacha20poly1305(this.key, this.computeNonce(), aad).decrypt(ct);
|
|
665
|
+
this.seq += 1;
|
|
666
|
+
return pt;
|
|
667
|
+
}
|
|
668
|
+
export(exporterContext, length) {
|
|
669
|
+
return labeledExpand(this.exporterSecret, bytes("sec"), exporterContext, length, SUITE_ID);
|
|
212
670
|
}
|
|
213
671
|
};
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
672
|
+
function keySchedule(sharedSecret, info) {
|
|
673
|
+
const empty = new Uint8Array(0);
|
|
674
|
+
const pskIdHash = labeledExtract(empty, bytes("psk_id_hash"), empty, SUITE_ID);
|
|
675
|
+
const infoHash = labeledExtract(empty, bytes("info_hash"), info, SUITE_ID);
|
|
676
|
+
const keyScheduleContext = concat(new Uint8Array([0]), pskIdHash, infoHash);
|
|
677
|
+
const secret = labeledExtract(sharedSecret, bytes("secret"), empty, SUITE_ID);
|
|
678
|
+
const key = labeledExpand(secret, bytes("key"), keyScheduleContext, NK, SUITE_ID);
|
|
679
|
+
const baseNonce = labeledExpand(secret, bytes("base_nonce"), keyScheduleContext, NN, SUITE_ID);
|
|
680
|
+
const exporterSecret = labeledExpand(secret, bytes("exp"), keyScheduleContext, NH, SUITE_ID);
|
|
681
|
+
return new Context(key, baseNonce, exporterSecret);
|
|
682
|
+
}
|
|
683
|
+
function setupBaseS(pkR, info, skE) {
|
|
684
|
+
const [sharedSecret, enc] = encap(pkR, skE);
|
|
685
|
+
return { enc, ctx: keySchedule(sharedSecret, info) };
|
|
686
|
+
}
|
|
687
|
+
function setupBaseR(skR, enc, info) {
|
|
688
|
+
const sharedSecret = decap(enc, skR);
|
|
689
|
+
return keySchedule(sharedSecret, info);
|
|
690
|
+
}
|
|
691
|
+
function generateX25519Keypair() {
|
|
692
|
+
const priv = x25519.utils.randomPrivateKey();
|
|
693
|
+
return { priv, pub: x25519.getPublicKey(priv) };
|
|
694
|
+
}
|
|
695
|
+
function randomBytes(n) {
|
|
696
|
+
return nobleRandomBytes(n);
|
|
697
|
+
}
|
|
698
|
+
function sha256Hex(data) {
|
|
699
|
+
return Array.from(sha256(data)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
// src/_privateInference.ts
|
|
703
|
+
import { chacha20poly1305 as chacha20poly13052 } from "@noble/ciphers/chacha";
|
|
704
|
+
import { extract as extract2, expand as expand2 } from "@noble/hashes/hkdf";
|
|
705
|
+
var ENVELOPE_VERSION = 1;
|
|
706
|
+
var TEXT_ENCODER2 = new TextEncoder();
|
|
707
|
+
var TEXT_DECODER = new TextDecoder();
|
|
708
|
+
var SUITE_INFO = TEXT_ENCODER2.encode("pendra-pi-v1");
|
|
709
|
+
var RESPONSE_INFO = TEXT_ENCODER2.encode("pendra-pi-v1:response");
|
|
710
|
+
var RESPONSE_EXPORT_CTX = TEXT_ENCODER2.encode("pendra-pi-v1:rdek");
|
|
711
|
+
var AFFINITY_SALT_INFO = TEXT_ENCODER2.encode("pendra-affinity-salt-v1");
|
|
712
|
+
function utf8(s) {
|
|
713
|
+
return TEXT_ENCODER2.encode(s);
|
|
714
|
+
}
|
|
715
|
+
function b64(b) {
|
|
716
|
+
if (typeof Buffer !== "undefined") {
|
|
717
|
+
return Buffer.from(b).toString("base64");
|
|
718
|
+
}
|
|
719
|
+
let binary = "";
|
|
720
|
+
for (let i = 0; i < b.length; i++) binary += String.fromCharCode(b[i]);
|
|
721
|
+
return btoa(binary);
|
|
722
|
+
}
|
|
723
|
+
function b64d(s) {
|
|
724
|
+
if (typeof Buffer !== "undefined") {
|
|
725
|
+
return new Uint8Array(Buffer.from(s, "base64"));
|
|
726
|
+
}
|
|
727
|
+
const binary = atob(s);
|
|
728
|
+
const out = new Uint8Array(binary.length);
|
|
729
|
+
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
730
|
+
return out;
|
|
731
|
+
}
|
|
732
|
+
function toHex(b) {
|
|
733
|
+
return Array.from(b).map((x) => x.toString(16).padStart(2, "0")).join("");
|
|
734
|
+
}
|
|
735
|
+
function fingerprint(pub) {
|
|
736
|
+
return sha256Hex(pub);
|
|
737
|
+
}
|
|
738
|
+
function buildAad(model, stream, taskType, responsePkB64) {
|
|
739
|
+
const streamBit = stream ? utf8("1") : utf8("0");
|
|
740
|
+
const sep = new Uint8Array([0]);
|
|
741
|
+
const parts = [utf8("pendra-pi-v1"), utf8(model), streamBit, utf8(taskType), utf8(responsePkB64)];
|
|
742
|
+
let total = 0;
|
|
743
|
+
for (let i = 0; i < parts.length; i++) {
|
|
744
|
+
if (i > 0) total += 1;
|
|
745
|
+
total += parts[i].length;
|
|
746
|
+
}
|
|
747
|
+
const out = new Uint8Array(total);
|
|
748
|
+
let off = 0;
|
|
749
|
+
for (let i = 0; i < parts.length; i++) {
|
|
750
|
+
if (i > 0) {
|
|
751
|
+
out.set(sep, off);
|
|
752
|
+
off += 1;
|
|
753
|
+
}
|
|
754
|
+
out.set(parts[i], off);
|
|
755
|
+
off += parts[i].length;
|
|
756
|
+
}
|
|
757
|
+
return out;
|
|
758
|
+
}
|
|
759
|
+
function seqNonce(seq) {
|
|
760
|
+
const nonce = new Uint8Array(12);
|
|
761
|
+
let n = BigInt(seq);
|
|
762
|
+
for (let i = 11; i >= 4; i--) {
|
|
763
|
+
nonce[i] = Number(n & 0xffn);
|
|
764
|
+
n >>= 8n;
|
|
765
|
+
}
|
|
766
|
+
return nonce;
|
|
767
|
+
}
|
|
768
|
+
function sealRequest(orgPub, body, opts) {
|
|
769
|
+
const { priv: respPriv, pub: respPub } = generateX25519Keypair();
|
|
770
|
+
const respPkB64 = b64(respPub);
|
|
771
|
+
const dek = randomBytes(32);
|
|
772
|
+
const nonce = randomBytes(12);
|
|
773
|
+
const aad = buildAad(opts.model, opts.stream, opts.taskType, respPkB64);
|
|
774
|
+
const ciphertext = chacha20poly13052(dek, nonce, aad).encrypt(body);
|
|
775
|
+
const { enc, ctx: sealer } = setupBaseS(orgPub, SUITE_INFO);
|
|
776
|
+
const sealedDek = sealer.seal(new Uint8Array(0), dek);
|
|
777
|
+
const envelope = {
|
|
778
|
+
v: ENVELOPE_VERSION,
|
|
779
|
+
recipients: [{ kid: fingerprint(orgPub), enc: b64(enc), sealed_dek: b64(sealedDek) }],
|
|
780
|
+
nonce: b64(nonce),
|
|
781
|
+
ciphertext: b64(ciphertext),
|
|
782
|
+
response_pk: respPkB64
|
|
783
|
+
};
|
|
784
|
+
if (opts.affinityKey != null) {
|
|
785
|
+
envelope.affinity_key = opts.affinityKey;
|
|
786
|
+
}
|
|
787
|
+
if (opts.binary != null) {
|
|
788
|
+
const binaryNonce = randomBytes(12);
|
|
789
|
+
envelope.binary_nonce = b64(binaryNonce);
|
|
790
|
+
envelope.binary_ciphertext = b64(chacha20poly13052(dek, binaryNonce, aad).encrypt(opts.binary));
|
|
791
|
+
}
|
|
792
|
+
return { envelope, responsePriv: respPriv };
|
|
793
|
+
}
|
|
794
|
+
var ResponseDecryptor = class {
|
|
795
|
+
constructor(responsePrivateKey) {
|
|
796
|
+
this.dek = null;
|
|
797
|
+
this.nextSeq = 0;
|
|
798
|
+
this.respPriv = responsePrivateKey;
|
|
799
|
+
}
|
|
800
|
+
ensureDek(encB64) {
|
|
801
|
+
if (this.dek !== null) return;
|
|
802
|
+
if (!encB64) {
|
|
803
|
+
throw new Error("private_inference: first response frame is missing the encapsulated key");
|
|
804
|
+
}
|
|
805
|
+
const ctx = setupBaseR(this.respPriv, b64d(encB64), RESPONSE_INFO);
|
|
806
|
+
this.dek = ctx.export(RESPONSE_EXPORT_CTX, 32);
|
|
807
|
+
}
|
|
808
|
+
/** Decrypt a non-streaming result envelope `{v, enc, seq, ciphertext}`. */
|
|
809
|
+
openResult(inner) {
|
|
810
|
+
this.ensureDek(inner.enc);
|
|
811
|
+
return chacha20poly13052(this.dek, seqNonce(Number(inner.seq))).decrypt(b64d(inner.ciphertext));
|
|
812
|
+
}
|
|
813
|
+
/** Decrypt one streaming chunk envelope, enforcing monotonic `seq`. */
|
|
814
|
+
openChunk(inner) {
|
|
815
|
+
const seq = Number(inner.seq);
|
|
816
|
+
if (seq !== this.nextSeq) {
|
|
817
|
+
throw new Error(
|
|
818
|
+
`private_inference: out-of-order response chunk (seq ${seq}, expected ${this.nextSeq})`
|
|
819
|
+
);
|
|
820
|
+
}
|
|
821
|
+
this.ensureDek(inner.enc);
|
|
822
|
+
const pt = chacha20poly13052(this.dek, seqNonce(seq)).decrypt(b64d(inner.ciphertext));
|
|
823
|
+
this.nextSeq += 1;
|
|
824
|
+
return pt;
|
|
219
825
|
}
|
|
220
826
|
};
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
827
|
+
function deriveSalt(rawApiKey) {
|
|
828
|
+
const prk = extract2(sha256, utf8(rawApiKey), new Uint8Array(32));
|
|
829
|
+
return expand2(sha256, prk, AFFINITY_SALT_INFO, 32);
|
|
830
|
+
}
|
|
831
|
+
function canonicalJson(value) {
|
|
832
|
+
if (value === null) return "null";
|
|
833
|
+
const t = typeof value;
|
|
834
|
+
if (t === "boolean") return value ? "true" : "false";
|
|
835
|
+
if (t === "number") {
|
|
836
|
+
return String(value);
|
|
837
|
+
}
|
|
838
|
+
if (t === "string") return encodeString(value);
|
|
839
|
+
if (Array.isArray(value)) {
|
|
840
|
+
return "[" + value.map((v) => canonicalJson(v)).join(",") + "]";
|
|
841
|
+
}
|
|
842
|
+
if (t === "object") {
|
|
843
|
+
const obj = value;
|
|
844
|
+
const keys = Object.keys(obj).sort();
|
|
845
|
+
const items = keys.map((k) => encodeString(k) + ":" + canonicalJson(obj[k]));
|
|
846
|
+
return "{" + items.join(",") + "}";
|
|
847
|
+
}
|
|
848
|
+
return "null";
|
|
849
|
+
}
|
|
850
|
+
function encodeString(s) {
|
|
851
|
+
let out = '"';
|
|
852
|
+
for (let i = 0; i < s.length; i++) {
|
|
853
|
+
const code = s.charCodeAt(i);
|
|
854
|
+
switch (code) {
|
|
855
|
+
case 34:
|
|
856
|
+
out += '\\"';
|
|
857
|
+
break;
|
|
858
|
+
case 92:
|
|
859
|
+
out += "\\\\";
|
|
860
|
+
break;
|
|
861
|
+
case 8:
|
|
862
|
+
out += "\\b";
|
|
863
|
+
break;
|
|
864
|
+
case 9:
|
|
865
|
+
out += "\\t";
|
|
866
|
+
break;
|
|
867
|
+
case 10:
|
|
868
|
+
out += "\\n";
|
|
869
|
+
break;
|
|
870
|
+
case 12:
|
|
871
|
+
out += "\\f";
|
|
872
|
+
break;
|
|
873
|
+
case 13:
|
|
874
|
+
out += "\\r";
|
|
875
|
+
break;
|
|
876
|
+
default:
|
|
877
|
+
if (code < 32 || code > 126) {
|
|
878
|
+
out += "\\u" + code.toString(16).padStart(4, "0");
|
|
879
|
+
} else {
|
|
880
|
+
out += s[i];
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
return out + '"';
|
|
885
|
+
}
|
|
886
|
+
function flattenContent(content) {
|
|
887
|
+
if (typeof content === "string") return content;
|
|
888
|
+
return canonicalJson(content);
|
|
889
|
+
}
|
|
890
|
+
function affinityKey(rawApiKey, model, messages, saltOverride) {
|
|
891
|
+
const parts = ["model=" + model];
|
|
892
|
+
let sawUser = false;
|
|
893
|
+
for (const m of messages ?? []) {
|
|
894
|
+
const role = m.role ?? "";
|
|
895
|
+
parts.push(role + ":" + flattenContent(m.content));
|
|
896
|
+
if (role === "user") {
|
|
897
|
+
sawUser = true;
|
|
898
|
+
break;
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
if (!sawUser) return null;
|
|
902
|
+
const salt = saltOverride != null ? saltOverride : deriveSalt(rawApiKey);
|
|
903
|
+
const mac = hmac(sha256, salt, utf8(parts.join("\0")));
|
|
904
|
+
return toHex(mac);
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
// src/_privateInferenceEngine.ts
|
|
908
|
+
var PrivateInferenceError = class extends Error {
|
|
909
|
+
constructor(message) {
|
|
910
|
+
super(message);
|
|
911
|
+
this.name = "PrivateInferenceError";
|
|
225
912
|
}
|
|
226
913
|
};
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
914
|
+
function defaultTofuPath() {
|
|
915
|
+
const env = typeof process !== "undefined" ? process.env : void 0;
|
|
916
|
+
if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
|
|
917
|
+
const home = env?.HOME || env?.USERPROFILE || ".";
|
|
918
|
+
return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
|
|
919
|
+
}
|
|
920
|
+
function b64d2(s) {
|
|
921
|
+
if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
|
|
922
|
+
const binary = atob(s);
|
|
923
|
+
const out = new Uint8Array(binary.length);
|
|
924
|
+
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
925
|
+
return out;
|
|
926
|
+
}
|
|
927
|
+
var PrivateInferenceEngine = class {
|
|
928
|
+
constructor(opts) {
|
|
929
|
+
this.orgPub = null;
|
|
930
|
+
this.baseUrl = opts.baseUrl.replace(/\/$/, "");
|
|
931
|
+
this.apiKey = opts.apiKey;
|
|
932
|
+
const pin = (opts.pinnedFingerprint || "").trim().toLowerCase();
|
|
933
|
+
this.pinnedFingerprint = pin || null;
|
|
934
|
+
this.affinitySalt = opts.affinitySalt ?? null;
|
|
935
|
+
this.tofuPath = opts.tofuPath || defaultTofuPath();
|
|
936
|
+
}
|
|
937
|
+
// --- key resolution ---
|
|
938
|
+
cachedOrgPublicKey() {
|
|
939
|
+
return this.orgPub;
|
|
940
|
+
}
|
|
941
|
+
tofuIdentity() {
|
|
942
|
+
const digest = sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);
|
|
943
|
+
return `${this.baseUrl}|${digest}`;
|
|
944
|
+
}
|
|
945
|
+
/**
|
|
946
|
+
* Validate the key(s) returned by GET /v1/private-inference/key against the
|
|
947
|
+
* pin or TOFU record, cache the accepted public key, and return it. Throws
|
|
948
|
+
* PrivateInferenceError on absence or a fingerprint mismatch.
|
|
949
|
+
*/
|
|
950
|
+
async resolveOrgKey(fetchedKeys) {
|
|
951
|
+
if (this.orgPub !== null) return this.orgPub;
|
|
952
|
+
if (!fetchedKeys || fetchedKeys.length === 0) {
|
|
953
|
+
throw new PrivateInferenceError(
|
|
954
|
+
"No private-inference workload key is registered for this organisation. Run `pendra keygen --save` on your worker(s), then reconnect them."
|
|
955
|
+
);
|
|
956
|
+
}
|
|
957
|
+
const newest = fetchedKeys[0];
|
|
958
|
+
let orgPub;
|
|
959
|
+
try {
|
|
960
|
+
orgPub = b64d2(newest.public_key);
|
|
961
|
+
} catch (e) {
|
|
962
|
+
throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
|
|
963
|
+
}
|
|
964
|
+
if (orgPub.length !== 32) {
|
|
965
|
+
throw new PrivateInferenceError(
|
|
966
|
+
`Workload key from the server is ${orgPub.length} bytes; expected a 32-byte X25519 key.`
|
|
967
|
+
);
|
|
968
|
+
}
|
|
969
|
+
const fp = fingerprint(orgPub);
|
|
970
|
+
if (this.pinnedFingerprint !== null) {
|
|
971
|
+
if (fp !== this.pinnedFingerprint) {
|
|
972
|
+
throw new PrivateInferenceError(
|
|
973
|
+
`Workload key fingerprint ${fp} does not match your pinned fingerprint ${this.pinnedFingerprint}. Refusing to use it (possible man-in-the-middle). Verify the fingerprint from \`pendra keygen\` and update the pin if you rotated keys.`
|
|
974
|
+
);
|
|
975
|
+
}
|
|
976
|
+
} else {
|
|
977
|
+
await this.checkTofu(fp);
|
|
978
|
+
}
|
|
979
|
+
this.orgPub = orgPub;
|
|
980
|
+
return orgPub;
|
|
981
|
+
}
|
|
982
|
+
async checkTofu(fp) {
|
|
983
|
+
const store = await this.loadTofu();
|
|
984
|
+
const identity = this.tofuIdentity();
|
|
985
|
+
const known = store[identity];
|
|
986
|
+
if (known === void 0) {
|
|
987
|
+
store[identity] = fp;
|
|
988
|
+
await this.saveTofu(store);
|
|
989
|
+
return;
|
|
990
|
+
}
|
|
991
|
+
if (known !== fp) {
|
|
992
|
+
throw new PrivateInferenceError(
|
|
993
|
+
`Workload key fingerprint changed for ${this.baseUrl}: pinned ${known}, server now returns ${fp}. If you rotated your org key this is expected \u2014 verify the new fingerprint out-of-band (from \`pendra keygen\`) and delete the entry in ${this.tofuPath} to re-pin. If you did NOT rotate, this may be a man-in-the-middle and the request has been refused.`
|
|
994
|
+
);
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
async loadTofu() {
|
|
998
|
+
try {
|
|
999
|
+
const fs = await import("fs");
|
|
1000
|
+
const raw = fs.readFileSync(this.tofuPath, "utf-8");
|
|
1001
|
+
const data = JSON.parse(raw);
|
|
1002
|
+
return data && typeof data === "object" && !Array.isArray(data) ? data : {};
|
|
1003
|
+
} catch {
|
|
1004
|
+
return {};
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
async saveTofu(store) {
|
|
1008
|
+
const fs = await import("fs");
|
|
1009
|
+
const path = await import("path");
|
|
1010
|
+
const directory = path.dirname(this.tofuPath) || ".";
|
|
1011
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
1012
|
+
const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);
|
|
1013
|
+
try {
|
|
1014
|
+
fs.writeFileSync(tmp, JSON.stringify(store), { mode: 384 });
|
|
1015
|
+
try {
|
|
1016
|
+
fs.chmodSync(tmp, 384);
|
|
1017
|
+
} catch {
|
|
1018
|
+
}
|
|
1019
|
+
fs.renameSync(tmp, this.tofuPath);
|
|
1020
|
+
} catch (e) {
|
|
1021
|
+
try {
|
|
1022
|
+
fs.unlinkSync(tmp);
|
|
1023
|
+
} catch {
|
|
1024
|
+
}
|
|
1025
|
+
throw e;
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
// --- sealing ---
|
|
1029
|
+
/**
|
|
1030
|
+
* Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
|
|
1031
|
+
* `messages` (chat only) drives the affinity token; pass undefined for non-chat.
|
|
1032
|
+
*/
|
|
1033
|
+
seal(args) {
|
|
1034
|
+
if (this.orgPub === null) {
|
|
1035
|
+
throw new PrivateInferenceError(
|
|
1036
|
+
"private inference: org key not resolved yet (call resolveOrgKey first)"
|
|
1037
|
+
);
|
|
1038
|
+
}
|
|
1039
|
+
let affinity = null;
|
|
1040
|
+
if (args.messages != null) {
|
|
1041
|
+
affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
|
|
1042
|
+
}
|
|
1043
|
+
const { envelope, responsePriv } = sealRequest(this.orgPub, args.body, {
|
|
1044
|
+
model: args.model,
|
|
1045
|
+
stream: args.stream,
|
|
1046
|
+
taskType: args.taskType,
|
|
1047
|
+
affinityKey: affinity
|
|
1048
|
+
});
|
|
1049
|
+
const topLevel = {
|
|
1050
|
+
model: args.model,
|
|
1051
|
+
stream: args.stream,
|
|
1052
|
+
pendra_encrypted: envelope
|
|
1053
|
+
};
|
|
1054
|
+
return { topLevel, decryptor: new ResponseDecryptor(responsePriv) };
|
|
1055
|
+
}
|
|
1056
|
+
get keyFetchUrl() {
|
|
1057
|
+
return `${this.baseUrl}/v1/private-inference/key`;
|
|
231
1058
|
}
|
|
232
1059
|
};
|
|
233
1060
|
|
|
234
1061
|
// src/client.ts
|
|
1062
|
+
function envTruthy(v) {
|
|
1063
|
+
if (!v) return false;
|
|
1064
|
+
return ["1", "true", "yes", "on"].includes(v.trim().toLowerCase());
|
|
1065
|
+
}
|
|
235
1066
|
var Pendra = class {
|
|
236
1067
|
constructor(options = {}) {
|
|
237
|
-
|
|
1068
|
+
this._piEngine = null;
|
|
1069
|
+
// Serialises the one-time key fetch across concurrent first calls.
|
|
1070
|
+
this._piKeyFetch = null;
|
|
1071
|
+
const env = typeof process !== "undefined" ? process.env : void 0;
|
|
1072
|
+
const apiKey = options.apiKey ?? env?.PENDRA_API_KEY;
|
|
238
1073
|
if (!apiKey) {
|
|
239
1074
|
throw new Error(
|
|
240
1075
|
"API key is required \u2014 pass apiKey or set the PENDRA_API_KEY environment variable"
|
|
@@ -246,10 +1081,98 @@ var Pendra = class {
|
|
|
246
1081
|
""
|
|
247
1082
|
);
|
|
248
1083
|
this.timeout = options.timeout ?? 12e4;
|
|
1084
|
+
let piOpt = options.privateInference;
|
|
1085
|
+
if (piOpt === void 0) {
|
|
1086
|
+
piOpt = envTruthy(env?.PENDRA_PRIVATE_INFERENCE);
|
|
1087
|
+
}
|
|
1088
|
+
let pinnedFingerprint;
|
|
1089
|
+
if (typeof piOpt === "object" && piOpt !== null) {
|
|
1090
|
+
this.privateInferenceEnabled = true;
|
|
1091
|
+
pinnedFingerprint = piOpt.pinnedFingerprint;
|
|
1092
|
+
} else {
|
|
1093
|
+
this.privateInferenceEnabled = Boolean(piOpt);
|
|
1094
|
+
}
|
|
1095
|
+
pinnedFingerprint = pinnedFingerprint ?? env?.PENDRA_PINNED_ORG_FINGERPRINT ?? void 0;
|
|
1096
|
+
if (this.privateInferenceEnabled) {
|
|
1097
|
+
const affinitySalt = env?.PENDRA_AFFINITY_SALT ? new TextEncoder().encode(env.PENDRA_AFFINITY_SALT) : null;
|
|
1098
|
+
this._piEngine = new PrivateInferenceEngine({
|
|
1099
|
+
baseUrl: this.baseURL,
|
|
1100
|
+
apiKey: this.apiKey,
|
|
1101
|
+
pinnedFingerprint: pinnedFingerprint ?? null,
|
|
1102
|
+
affinitySalt,
|
|
1103
|
+
tofuPath: env?.PENDRA_TOFU_PATH ?? null
|
|
1104
|
+
});
|
|
1105
|
+
}
|
|
249
1106
|
this.chat = new Chat(this);
|
|
250
1107
|
this.images = new Images(this);
|
|
251
1108
|
this.embeddings = new Embeddings(this);
|
|
252
1109
|
this.models = new Models(this);
|
|
1110
|
+
this.audio = new Audio(this);
|
|
1111
|
+
this.rerank = new Rerank(this);
|
|
1112
|
+
}
|
|
1113
|
+
/**
|
|
1114
|
+
* @internal
|
|
1115
|
+
* Return the private-inference engine with its org key resolved. Fetches
|
|
1116
|
+
* `GET {baseUrl}/v1/private-inference/key` exactly once (subsequent calls reuse
|
|
1117
|
+
* the cached key). Throws if private inference is not enabled.
|
|
1118
|
+
*/
|
|
1119
|
+
async _privateEngine() {
|
|
1120
|
+
if (!this._piEngine) {
|
|
1121
|
+
throw new PrivateInferenceError("private inference is not enabled on this client");
|
|
1122
|
+
}
|
|
1123
|
+
if (this._piEngine.cachedOrgPublicKey() !== null) {
|
|
1124
|
+
return this._piEngine;
|
|
1125
|
+
}
|
|
1126
|
+
if (!this._piKeyFetch) {
|
|
1127
|
+
this._piKeyFetch = this._fetchAndResolveOrgKey().catch((err) => {
|
|
1128
|
+
this._piKeyFetch = null;
|
|
1129
|
+
throw err;
|
|
1130
|
+
});
|
|
1131
|
+
}
|
|
1132
|
+
await this._piKeyFetch;
|
|
1133
|
+
return this._piEngine;
|
|
1134
|
+
}
|
|
1135
|
+
async _fetchAndResolveOrgKey() {
|
|
1136
|
+
const engine = this._piEngine;
|
|
1137
|
+
const url = `${this.baseURL}/v1/private-inference/key`;
|
|
1138
|
+
const controller = new AbortController();
|
|
1139
|
+
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
1140
|
+
let response;
|
|
1141
|
+
try {
|
|
1142
|
+
response = await fetch(url, {
|
|
1143
|
+
method: "GET",
|
|
1144
|
+
headers: { Authorization: `Bearer ${this.apiKey}` },
|
|
1145
|
+
signal: controller.signal
|
|
1146
|
+
});
|
|
1147
|
+
} catch (err) {
|
|
1148
|
+
if (err instanceof DOMException && err.name === "AbortError") {
|
|
1149
|
+
throw new APIConnectionError(`Request timed out after ${this.timeout}ms`);
|
|
1150
|
+
}
|
|
1151
|
+
throw new APIConnectionError(
|
|
1152
|
+
err instanceof Error ? err.message : "Failed to fetch the private-inference workload key"
|
|
1153
|
+
);
|
|
1154
|
+
} finally {
|
|
1155
|
+
clearTimeout(timeoutId);
|
|
1156
|
+
}
|
|
1157
|
+
if (response.status === 404) {
|
|
1158
|
+
throw new PrivateInferenceError(
|
|
1159
|
+
"No private-inference workload key is registered for this organisation. Run `pendra keygen --save` on your worker(s), then reconnect them."
|
|
1160
|
+
);
|
|
1161
|
+
}
|
|
1162
|
+
if (!response.ok) {
|
|
1163
|
+
let message;
|
|
1164
|
+
try {
|
|
1165
|
+
const body = await response.json();
|
|
1166
|
+
message = body.detail ?? response.statusText;
|
|
1167
|
+
} catch {
|
|
1168
|
+
message = response.statusText;
|
|
1169
|
+
}
|
|
1170
|
+
if (response.status === 401) throw new AuthenticationError(message);
|
|
1171
|
+
if (response.status === 429) throw new RateLimitError(message);
|
|
1172
|
+
throw new APIStatusError(message, response.status);
|
|
1173
|
+
}
|
|
1174
|
+
const json = await response.json();
|
|
1175
|
+
await engine.resolveOrgKey(json.keys ?? []);
|
|
253
1176
|
}
|
|
254
1177
|
/** @internal */
|
|
255
1178
|
async _fetch(path, options) {
|
|
@@ -257,7 +1180,8 @@ var Pendra = class {
|
|
|
257
1180
|
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
258
1181
|
const headers = {
|
|
259
1182
|
Authorization: `Bearer ${this.apiKey}`,
|
|
260
|
-
"Content-Type": "application/json"
|
|
1183
|
+
"Content-Type": "application/json",
|
|
1184
|
+
...options.headers ?? {}
|
|
261
1185
|
};
|
|
262
1186
|
let response;
|
|
263
1187
|
try {
|
|
@@ -306,6 +1230,7 @@ export {
|
|
|
306
1230
|
APIStatusError,
|
|
307
1231
|
AuthenticationError,
|
|
308
1232
|
Pendra,
|
|
1233
|
+
PrivateInferenceError,
|
|
309
1234
|
RateLimitError,
|
|
310
1235
|
Stream,
|
|
311
1236
|
index_default as default
|