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